Last active
October 21, 2019 09:56
-
-
Save techzeero/d8c12b8b1d52b87fda8eb603798b0160 to your computer and use it in GitHub Desktop.
In this tutorial, we learn how to measure the distance by using the Ultrasonic Sensor with Arduino. https://techzeero.com/arduino-tutorials/ultrasonic-sensor-with-arduino/
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
/* | |
Ultrasonic Sensor with Arduino | |
For more details, visit: https://techzeero.com/arduino-tutorials/ultrasonic-sensor-with-arduino/ | |
*/ | |
int trigPin = 9; // Trigger Pin of Ultrasonic Sensor | |
int echoPin = 8; // Echo Pin of Ultrasonic Sensor | |
void setup() | |
{ | |
Serial.begin(9600); | |
pinMode(trigPin, OUTPUT); | |
pinMode(echoPin, INPUT); | |
} | |
void loop(){ | |
long duration, inches, cm; | |
digitalWrite(trigPin, LOW); | |
delayMicroseconds(2); | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(10); | |
digitalWrite(trigPin, LOW); | |
duration = pulseIn(echoPin, HIGH); | |
inches = duration/74 /2; //convert microseconds into inches | |
cm = duration/29 /2; //convert microseconds into cm | |
Serial.print(inches); | |
Serial.print(" inches "); | |
Serial.print(cm); | |
Serial.print(" cm"); | |
Serial.println(); | |
delay(200); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment