Advertisement
Guest User

Untitled

a guest
Nov 29th, 2014
629
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #define ECHOPIN 12            //set pin 12 on the Arduino board as the ECHO pin
  2. #define TRIGPIN 13            //set pin 13 on the Arduino board as the TRIG pin
  3.  
  4.  
  5. int delaytime = 100;          //initialize variables for better performance of the code
  6. int duration = 0;             //
  7. int var = 10000;              //needed to convert the output in centimeters
  8. float distance = 0;           //
  9. float spread = 340;           //ultrasonic velocity spread in air in m/s
  10.  
  11. void setup()
  12. {
  13.   Serial.begin(9600);             //set the Baudrate to 9600, Baudrate - data rate in bits per second for serial data transmission
  14.   pinMode(ECHOPIN, INPUT);        //set the mode on the ECHO pin to INPUT
  15.   pinMode(TRIGPIN, OUTPUT);       //set the mode on the TRIG pin to OUTPUT
  16. }
  17.  
  18. void loop()
  19. {
  20.  
  21.   // Start Ranging - Generating a trigger of 10us burst
  22.  
  23.   digitalWrite(TRIGPIN, LOW);    //wipe the HIGH, just in case
  24.   delayMicroseconds(2);          //..........................
  25.   digitalWrite(TRIGPIN, HIGH);   //send HIGH pulse to the TRIG pin to activate it
  26.   delayMicroseconds(10);         //10 uS length of the HIGH pulse,   at this point the ECHO pin goes to HIGH until it receives the reflected signal
  27.   digitalWrite(TRIGPIN, LOW);    //kill the pulse
  28.  
  29.  
  30.   //Distance Calculation
  31.  
  32.   duration = pulseIn(ECHOPIN, HIGH);        //detects when the ECHO pin goes to HIGH and records the time until it goes back to LOW in uS
  33.   distance = duration*spread/(2*var);       //calculate the distance between the object and the sensor
  34.   Serial.println(distance);                 //print the calculated distance
  35.   delay(delaytime);                         //repeat every *delaytime* milliseconds
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement