- Arduino uno
- Dot board
- Ultrasonic Sensor
- Jumper wires
- LED*5
Diagram:-
Connections:-
Ultrasonic to Arduino
- Ultrasonic VCC pin - Arduino 5V PIN
- Ultrasonic trig pin - Arduino digital pin 8
- Ultrasonic Echo pin- Arduino digital pin 7
- Ultrasonic GND - Arduino GND
LED to Arduino
- LED(1) - Arduino digital pin 13
- LED(2) - Arduino digital pin 12
- LED(3) - Arduino digital pin 11
- LED(4) - Arduino digital pin 10
- LED(5) - Arduino digital pin 9
Code :-
#define trigpin 8 //define pins
#define echopin 7
int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
void setup()
{
Serial.begin(9600);
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(led5, OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, LOW);
delay(1000);
}
void loop()
{
int duration, distance;
digitalWrite(trigpin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin,HIGH);
distance = ( duration / 2) / 29.1;
Serial.println("cm:");
Serial.println(distance);
if( (distance > 0) && (distance <= 4) ) //you can free to change this
{
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led5, HIGH);
} else
if( (distance > 4) && (distance <= 8) )
{
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led5, HIGH);
} else
if( (distance > 12) && (distance <= 16) )
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
digitalWrite(led4, HIGH);
digitalWrite(led5, HIGH);
} else
if( (distance > 16) && (distance <= 20) )
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
digitalWrite(led5, HIGH);
} else
if( (distance > 20) && (distance <= 25) )
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, HIGH);
} else
if( distance > 25 )
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
digitalWrite(led5, LOW);
}
}