Ultrasonic sensor in aurdino with code
Connection
*vcc of ultrasonic sonsor to +5v
*Gnd pin to Gnd pin of aurdino
*trigpin to pin no 13
*echopin to pin no 12
*led 1 to pin no 7
*led 2 to pin no 8
*Gnd of led to gnd pin of aurdino
Circuit Diagram
Procedure
*connect the circuit as shown in figure
*copy and paste the code given below
*upload the code
*then check it
Code
/*
connect ultrasonic sensor +vcc to 5v
connect echopin to pin no 12
connect trigpin to pin no 13
*/
#define trigPin 13
#define echoPin 12
#define led 7
#define led2 8
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(led2, 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 < 4) {
digitalWrite(led,HIGH);
digitalWrite(led2,LOW);
}
else {
digitalWrite(led,LOW);
digitalWrite(led2,HIGH);
}
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
}
else {
Serial.print(distance);
Serial.println(" cm");
}
delay(500);
}
Lets check how is it work;
This comment has been removed by a blog administrator.
ReplyDelete