Skip to content

Instantly share code, notes, and snippets.

Created November 6, 2011 18:11
Show Gist options
  • Save anonymous/1343261 to your computer and use it in GitHub Desktop.
Save anonymous/1343261 to your computer and use it in GitHub Desktop.
Working code for LEDs graphing distance with a PING))) sensor
const int pingPin = 10;
int ledPins[] = {
2, 3, 4, 5, 6, 7, 8 }; // an array of pin numbers to which LEDs are attached
int pinCount = 7;
long duration, inches, cm;
void setup() {
// initialize serial communication:
Serial.begin(9600);
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop()
{
runPing();
setPair(0, HIGH);
}
void setPair(int thisPin, int state)
{
digitalWrite(ledPins[thisPin], state);
digitalWrite(ledPins[thisPin+1], state);
}
long runPing(){
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(300);
test();
}
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;
}
void test(){
if (cm > 76 && cm < 122){
setPair(2, HIGH);
}
else if(cm > 122){
setPair(2, LOW);
}
if (cm > 46 && cm < 76){
setPair(4, HIGH);
setPair(2, HIGH);
}
else if(cm > 76){
setPair(4, LOW);
}
if (cm < 46){
digitalWrite(ledPins[6], HIGH); //Red LEDs group 3
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(100);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
}
else if (cm > 46){
digitalWrite(ledPins[6], LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment