Ultrasonic sensor

The following code outputs the distance:

  1. #define echoPin 11 // Echo Pin
  2. #define trigPin 12 // Trigger Pin
  3.  
  4. long duration, distance; // Duration used to calculate distance
  5.  
  6. void setup() {
  7.  Serial.begin (9600);
  8.  pinMode(trigPin, OUTPUT);
  9.  pinMode(echoPin, INPUT);
  10. }
  11.  
  12. void loop() {
  13.  digitalWrite(trigPin, LOW);
  14.  delayMicroseconds(2);
  15.  
  16.  digitalWrite(trigPin, HIGH);
  17.  delayMicroseconds(10);
  18.  
  19.  digitalWrite(trigPin, LOW);
  20.  duration = pulseIn(echoPin, HIGH);
  21.  
  22.  //Calculate the distance (in cm) based on the speed of sound.
  23.  distance = duration/58.2;
  24.  
  25.  Serial.println(distance);
  26.  
  27.  delay(50);
  28. }

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>