Skip to content

Instantly share code, notes, and snippets.

@sjsd
Last active September 1, 2015 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjsd/cf9ea98577b9b277143c to your computer and use it in GitHub Desktop.
Save sjsd/cf9ea98577b9b277143c to your computer and use it in GitHub Desktop.
Example of using Ping (ultrasonic sensor) with Arduino and three LEDs. See more at https://helgejohnsen.wordpress.com/2015/09/01/arduino-og-ping-ultrasonisk-sensor/
const int pingPin = 7;
void setup() {
Serial.begin(9600);
pinMode(2, OUTPUT); // Led red
pinMode(3, OUTPUT); // Led orange
pinMode(4, OUTPUT); // Led green
}
void loop()
{
long duration, cm;
// Send pulse to ping
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW); // Low pulse to ensure a clean high pulse
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// Read pulse from ping
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// Convert the time into a distance
cm = microsecondsToCentimeters(duration);
// If very close (red LED)
if (cm < 10) {
digitalWrite(4,HIGH);
digitalWrite(2,LOW);
digitalWrite(3,LOW);
}
// If close (orange LED)
if (cm > 10 && cm =< 25) {
digitalWrite(3,HIGH);
digitalWrite(2,LOW);
digitalWrite(4,LOW);
}
// If far away (green LED)
if (cm > 26) {
digitalWrite(2,HIGH);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
}
// Print distance to serial
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
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