Last active
December 19, 2015 18:49
-
-
Save gskielian/6001894 to your computer and use it in GitHub Desktop.
this reads out the distance from an ultrasonic sensor
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
| int trigPin = 3; | |
| int echoPin = 5; | |
| long duration; | |
| long distance; | |
| long cm; | |
| void setup() | |
| { | |
| Serial.begin(9600); //this starts the talking | |
| pinMode(trigPin, OUTPUT); //we will tell the | |
| //ultrasonic to take a measurement by triggering | |
| //this pin | |
| pinMode(echoPin, INPUT); //get a message via | |
| //this pin | |
| } | |
| void loop() | |
| { | |
| delay(50); | |
| distance = getDistance(); | |
| Serial.println(distance); | |
| } | |
| long getDistance() | |
| { | |
| //give the module nudge | |
| //a pulse. __--__ | |
| digitalWrite(trigPin, LOW); | |
| delayMicroseconds(2); | |
| digitalWrite(trigPin, HIGH); | |
| delayMicroseconds(10); | |
| digitalWrite(trigPin, LOW); | |
| duration = pulseIn(echoPin, HIGH); | |
| cm = microsecondsToCentimeters(duration); | |
| return cm; | |
| } | |
| long microsecondsToCentimeters(long microseconds) { | |
| return microseconds / 29 / 2; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment