materials:-
- Arduino uno
- Ultrasonic Sensor
- LED
- Jumper wires
- Bredboard
Connections
Ultrasonic vcc = Arduino 5V
Ultrasonic GND= Arduino GND
Ultrasonic Trig = Arduino Digital pin 12
Ultrasonic Echo = Arduino Digital pin 11
LED (-) = Arduino GND
LED(+) = Arduino Digital pin 13
code:-
//https://mrarduinoprojects.blogspot.com
#define trigPin 12 #define echoPin 11 #define led 13 //BLUE LED 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 < 30) { digitalWrite(led,HIGH); //distance is less than 30 so BLUE LED turns on } else { digitalWrite(led,LOW); //distance is more than 30 so BLUE LED turns off } if (distance >= 250 || distance <= 0){ //range is 100 cm for HC-SR04 sensor Serial.println("Out of range"); } else { Serial.print(distance); Serial.println(" cm"); //in centimeters } delay(1000); }