Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define ECHOPIN 12 //set pin 12 on the Arduino board as the ECHO pin
- #define TRIGPIN 13 //set pin 13 on the Arduino board as the TRIG pin
- int delaytime = 100; //initialize variables for better performance of the code
- int duration = 0; //
- int var = 10000; //needed to convert the output in centimeters
- float distance = 0; //
- float spread = 340; //ultrasonic velocity spread in air in m/s
- void setup()
- {
- Serial.begin(9600); //set the Baudrate to 9600, Baudrate - data rate in bits per second for serial data transmission
- pinMode(ECHOPIN, INPUT); //set the mode on the ECHO pin to INPUT
- pinMode(TRIGPIN, OUTPUT); //set the mode on the TRIG pin to OUTPUT
- }
- void loop()
- {
- // Start Ranging - Generating a trigger of 10us burst
- digitalWrite(TRIGPIN, LOW); //wipe the HIGH, just in case
- delayMicroseconds(2); //..........................
- digitalWrite(TRIGPIN, HIGH); //send HIGH pulse to the TRIG pin to activate it
- delayMicroseconds(10); //10 uS length of the HIGH pulse, at this point the ECHO pin goes to HIGH until it receives the reflected signal
- digitalWrite(TRIGPIN, LOW); //kill the pulse
- //Distance Calculation
- duration = pulseIn(ECHOPIN, HIGH); //detects when the ECHO pin goes to HIGH and records the time until it goes back to LOW in uS
- distance = duration*spread/(2*var); //calculate the distance between the object and the sensor
- Serial.println(distance); //print the calculated distance
- delay(delaytime); //repeat every *delaytime* milliseconds
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement