Skip to content

Instantly share code, notes, and snippets.

Created March 13, 2013 18:57
Show Gist options
  • Save anonymous/5155023 to your computer and use it in GitHub Desktop.
Save anonymous/5155023 to your computer and use it in GitHub Desktop.
ME007
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
const int pingPin = 9;
const int ledPin=13;
void setup() {
// initialize serial communication:
Serial.begin(9600);
lcd.begin(16, 2);
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
delay(500);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
if(inches<=20)
{
digitalWrite(ledPin, HIGH);
lcd.clear();
lcd.print("Distance:");
lcd.print(inches);
lcd.setCursor(0,1);
lcd.print("Sensor Activated");
Serial.print("Sensor activated");
Serial.print(inches);
delay(500);
}
else
{
lcd.clear();
lcd.setCursor(0,1);
lcd.print("Sensor OFF");
Serial.println("Sensor OFF");
}
delay(100);
}
long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment