It is a simple project to detect obstacles in various distances. The sonar sensor detects the distance between the object and the board and based on the distance from the board it lights up Red, Yellow and Green LED.
When the object is too close to the board (10 centimeters) it lights up Red LED as an indication of caution.
It lights up Yellow LED when the object is between 11-100 centimeter. If the object is detected outside of the 100-centimeter range, it lights up Green LED as an indication of the object in safe range.
Bill of Materials:- Arduino UNO (1)
- HC-SR04 Ultrasonic Sensor (1)
- Red LED (1)
- Yellow LED (1)
- Green LED (1)
- 220 Ohm Resistors (3)
- Breadboard (1)
- Male to Male Hookup wires (10)
- A Ruler that measures centimeters
Connect the components and wires as shown in the pictures.
* VCC connection of the sensor is attached to +5V
* GND connection of the sensor is attached to ground
* ECHO connection of the sensor is attached to digital pin 5
* TRIG connection of the sensor is attached to digital pin 6
* GREEN LED connection is attached to digital pin 2
* YELLOW LED connection is attached to digital pin 3
* RED LED connection is attached to digital pin 4
CODE:int green=2,yellow=3,red=4, echo=5, trig=6, duration, distance;
int call_distance(){
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
duration=pulseIn(echo,HIGH);
distance=(duration/2)*.0344;
return distance;
}
void fade(int pin){
for(int f=0; f<=255; f+=30){
analogWrite(pin, f);
delay(30);
}
for(int f=255; f>0; f-=30){
analogWrite(pin, f);
delay(30);
}
}
void setup(){
Serial.begin(9600);
pinMode(green, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(red, OUTPUT);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
}
void loop(){
call_distance();
while(distance<=10){
digitalWrite(yellow, LOW);
digitalWrite(green, LOW);
fade(red);
call_distance();
}
while(distance>10&&distance<=100){
digitalWrite(red, LOW);
digitalWrite(green, LOW);
fade(yellow);
call_distance();
}
while(distance>100){
digitalWrite(red, LOW);
digitalWrite(yellow, LOW);
fade(green);
call_distance();
}
delay(100);
}
Comments