Last active
September 1, 2015 20:26
-
-
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/
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
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