Get Started with interface of arduino uno with ultrasonic sensor

on Tuesday, February 14, 2017

               
Hi everyone,


I am vigneshraja. here i present the code for interfacing arduino uno with ultrasonic sensor like shown in above video.

The Code for view the value in serial monitor from ultrasonic sensor:



#define trigPin 8
#define echoPin 9


void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
 
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);

  distance = duration /74 /2;
 
  Serial.print(distance);
  Serial.println(" inch");
 
 
  delay(500);
}


Code for interface with buzzer and led to notify when the object near to the ultrasonic sensor as in the video:

#define trigPin 8
#define echoPin 9
#define led 13
#define buzzer 12

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzer, OUTPUT);
  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 /74 /2;
 
  Serial.print(distance);
  Serial.println(" inch");
 
   if(distance <= 12)
  {
  digitalWrite(buzzer, HIGH);
  digitalWrite(led, HIGH);
  }else
  {
    digitalWrite(buzzer, LOW);
    digitalWrite(led, LOW);
  }
 
  delay(500);
}











                                                       Thank you For Reading