Created
February 19, 2021 01:52
-
-
Save brysonian/e8cc379b1fb695fa986135457eed2a9b to your computer and use it in GitHub Desktop.
dist.ino
This file contains hidden or 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
const int ECHO_PIN = 6; | |
const int TRIG_PIN = 5; | |
long duration; | |
int distance; | |
void setup() { | |
pinMode(TRIG_PIN, OUTPUT); | |
pinMode(ECHO_PIN, INPUT); | |
Serial.begin(115200); | |
while (!Serial) { | |
delay(10); | |
} | |
} | |
void loop() { | |
// Clears the trigPin condition | |
digitalWrite(TRIG_PIN, LOW); | |
delayMicroseconds(2); | |
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds | |
digitalWrite(TRIG_PIN, HIGH); | |
delayMicroseconds(10); | |
digitalWrite(TRIG_PIN, LOW); | |
// Reads the echoPin, returns the sound wave travel time in microseconds | |
duration = pulseIn(ECHO_PIN, HIGH); | |
// Calculating the distance | |
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back) | |
// Displays the distance on the Serial Monitor | |
Serial.print("Distance: "); | |
Serial.print(distance); | |
Serial.println(" cm"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment