Ultra Sonic Application
Ultra Sonic Application

Ultra Sonic Application

Ultra Sonic sensor is a module that is widely used in automobiles. The HC-SR04 sensor is used to detect object approaches.
Youtube Channel:

The module we will use in this application has 4 pins. Supply pins, “trig” pin, “echo” pin.
With the help of codes, a signal is sent to the "trig" pin. The signal reflected from the object is received with the help of the "echo" pin. We convert the output-input time difference of the signals to cm.
In our example application, if the object brought closer to the sensor is closer than 10 cm, three red LEDs connected to the digital outputs start to light.

Codes:

#define trigPin 3
#define echoPin 4
void setup ( )  {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 
 // Red leds -------------------
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
 
}
void loop() {
 int duration, distance;
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(1000);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
    
 if (distance <=10){
  Serial.println("very close!!!");
  digitalWrite(13,HIGH); delay(100);digitalWrite(13,LOW);
  digitalWrite(12,HIGH); delay(100);digitalWrite(12,LOW);
  digitalWrite(11,HIGH); delay(100);digitalWrite(11,LOW);
 } else {
  Serial.print(distance);
  Serial.println(" cm");
 }
  delay(1000);
 }