Help with trouble shooting

When you have more than 2 or 3 names that are the same except for a trailing number, it's time to consider arrays and loops:

const byte  triggerPin = 13;
const byte  echoPin = 12;
const unsigned long t = 10;
const unsigned long sec = 2000;
const byte ledPins[10] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2};

void setup()
{
  pinMode (triggerPin, OUTPUT);
  pinMode (echoPin, INPUT);
  Serial.begin (9600);

/*
[quote="TheMemberFormerlyKnownAsAWOL, post:7, topic:898057"]
make the LED pins outputs
[/quote]
*/
    for (int i = 0; i < 10; i++)
    {
      pinMode (ledPins[i], OUTPUT);
    }
}

void loop()
{
  //the code below this line sends a ping through the ultrasonic sensor
  digitalWrite (triggerPin, LOW);
  delayMicroseconds(t);
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(t);
  digitalWrite (triggerPin, LOW);
  // the code below this line calculates the distance
  unsigned long pingtime = pulseIn(echoPin, HIGH, 30000UL);
  int distanceCM = pingtime / 58;  // Round-trip time for sound is 58.2 microseconds per cm
  Serial.println(distanceCM);
  Serial.print(" cm");

  // A distanceCM of zero means no echo was seen
  if (distanceCM != 0 && distanceCM <= 5)
  {
    for (int i = 0; i < 10; i++)
    {
      digitalWrite (ledPins[i], HIGH);
      delay (sec);
    }
    for (int i = 0; i < 10; i++)
    {
      digitalWrite (ledPins[i], LOW);
    }
  }
}
1 Like