Skip to content

Instantly share code, notes, and snippets.

@gskielian
Last active December 19, 2015 18:49
Show Gist options
  • Select an option

  • Save gskielian/6001894 to your computer and use it in GitHub Desktop.

Select an option

Save gskielian/6001894 to your computer and use it in GitHub Desktop.
this reads out the distance from an ultrasonic sensor
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