9.11 Example: SonarRanger

/* SonarRanger. This script uses the Velleman VMA 306 SONAR to 
determine the distance to an object. The round-trip time delay is 
displayed on the serial monitor. If the object distance is 
less than 1 m, the LED will glow. The wiring is as follows: 
Sonar to Arduino 
Vcc to 5V 
GND to GND 
TRIG to Pin 13 
ECHO to Pin 12 
Note that the OUTPUT pin of the SONAR is not used. */ 

#define TRIG 11 
#define ECHO 12 
#define LED 13 
long distance, duration; 

void setup(){ 
   Serial.begin(9600) 
   pinMode(TRIG, OUTPUT); 
   pinMode(ECHO, INPUT); 
   pinMode(LED, OUTPUT); 
} 

void loop(){ 
   digitalWrite(LED, LOW); 
   digitalWrite(TRIG, LOW); 
   digitalWrite(TRIG, HIGH);  
   delayMicroseconds(10); 
   digitalWrite(TRIG, LOW); 
   duration=pulseIn(ECHO, HIGH); 
   distance=duration * 0.017; 
   Serial.print("Time delay: "); 
   Serial.print(duration); 
   Serial.println(" uSec"); 
   if (distance < 100) { 
      digitalWrite(LED, HIGH);
   }
   delay(250); 
}

<PHOTO>

License

Icon for the Creative Commons Attribution 4.0 International License

Applied Electrical Engineering Fundamentals by David J. McLaughlin is licensed under a Creative Commons Attribution 4.0 International License, except where otherwise noted.

Share This Book