Last active
February 20, 2020 05:45
-
-
Save Levi-Lesches/12823a33429999cad9e4c08d89836f21 to your computer and use it in GitHub Desktop.
Arduino Ultrasonic sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define echo 2 | |
#define trigger A0 | |
#define threshold 6 | |
long getDistance() { | |
// This function returns the distance of an object from the sensor in cm | |
// | |
// An ultrasonic sensor sends a sound wave pulse outwards, and then waits for it to hit an | |
// object and bounce back to the sensor. | |
// | |
// It uses D = RT -- we have R (the speed of sound), and we will | |
// measure T (the time it takes for the pulse to come back), so we can find D (distance to sensor). | |
// | |
// Thing is, the sound wave has to go hit the object AND THEN come back, so it's really 2 * D: | |
// 2D = RT --> D = RT/2 | |
// Clear the sensor | |
digitalWrite(trigger, LOW); // close the sensor | |
delayMicroseconds(2); // wait for the sensor to close (takes some time) | |
// Trigger a 10 micro-second sound wave pulse | |
digitalWrite(trigger, HIGH); // activate the pulse | |
delayMicroseconds(10); // wait for the hardware to actually work | |
digitalWrite(trigger, LOW); // stop the pulse | |
// Calculate the distance based on the incoming sound wave | |
// Uses the time it took times the speed of sound in cm | |
return pulseIn(echo, HIGH) * 0.034 / 2; | |
} | |
void setup() { | |
pinMode (trigger, OUTPUT); // pin to send the sound wave from | |
pinMode (echo, INPUT); // pin to listen for the sound wave | |
pinMode (13, OUTPUT); // light up the LED for alerts | |
} | |
void loop() { | |
long distance = getDistance(); // get distance in cm | |
digitalWrite(13, distance > threshold ? HIGH : LOW); // send alert | |
delay (200); // Give the sensor a break | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment