For this tutorial, you’ll need:
- Ultrasonic Sensor HC-SR04
- Led 5MM Blue & Yellow
- Arduino UNO
- 2 x Resistor 330E
- BreadBoard
- Jumper Wires
- Battery 9V
- Snap to DC cable
Watch this full video:
Code:
long d; //distance variable
long DistanceSensor (int, int); //trigger echo
define T 8 // pin 8 is trigger for sensor
define E 7 //// pin 7 is echo for sensor
define ok 11 // ok digital pin
define no 12 // no digital pin
define sd 200 // safe distance = 200 cm
void setup() {
Serial.begin(9600);
pinMode(E, INPUT); //echo sensor
pinMode(T, OUTPUT); //trigger sensor
pinMode(ok, OUTPUT);
pinMode(no, OUTPUT);
digitalWrite(ok, LOW);
digitalWrite(no, LOW);
}
void loop() {
d=DistanceSensor(T,E);
Serial.println(d);
delay(1000);
if(d<sd)
{
digitalWrite(ok, LOW);
digitalWrite(no, HIGH);
}
else
{
digitalWrite(no, LOW);
digitalWrite(ok, HIGH);
}
}
long microsecondsToCentimeters(long microseconds) {
return microseconds / 29 / 2;
}
long DistanceSensor (int trigger, int echo)
{
long duration, inches, cm;
digitalWrite(trigger, HIGH); delayMicroseconds(5); digitalWrite(trigger, LOW); delayMicroseconds(5);
duration = pulseIn(echo, HIGH);
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
return cm;
}