Introduction: Ultrasonic Sensor

From: https://www.instructables.com/Simple-Project-With...

This is a simple example of using the ultrasonic sensor (HC-SR04) in Arduino where we will turn on a led with the variation of distance and print the distance from an object to the serial monitor.

I had made the time for the light to shine longer than the original one. This function made my idea of work better.

Supplies

1. Arduino Uno or Leonardo

2. Ultrasonic Sensor (HC-SR04).

3. Mini-BreadBoard

4. 1 kˇohm Resistor.

5. Jumpers.

6. Blue LED.

Step 1: All the Necessary Components

Step 2: Connect the Components

Step 3: Write Your Code

#define trigPin 13

#define echoPin 12

#define led 11

void setup()

{ Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(echoPin, INPUT);

pinMode(led, OUTPUT);

}

void loop()

{ long duration, distance;

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

if (distance < 10)

{ digitalWrite(led,HIGH);

}

else {

digitalWrite(led,LOW);

}

Serial.print(distance);

Serial.println(" cm");

delay(5000);

}

Step 4: Upload and Run