Menu
CoddyTech

Parking Sensor: Lights

Part of the Projects section of Coddy's Arduino journey. Lesson 10 of 24.

Nobody reads numbers while parking. The three LEDs turn the distance into a colour: green on pin 6 when the way is clear, yellow on pin 7 when you are getting close, red on pin 13 when you must stop.

Three ranges, and exactly one LED each. An if / else if / else chain fits, because only one of its branches runs:

if (cm >= 100) {
  // green
} else if (cm >= 30) {
  // yellow: 30 to 99
} else {
  // red: under 30
}

The second test does not need to say cm < 100: the else means the first test was false, so the distance is already under 100.

Turn all three LEDs off before turning one on, as with the traffic light. Otherwise the yellow stays lit when the red comes on.

challenge icon

Challenge

Easy

Show the distance as a colour:

  • make pins 6, 7 and 13 outputs
  • 100 cm or more: green only
  • 30 to 99 cm: yellow only
  • under 30 cm: red only

Keep printing the distance. Press Run, drag the sensor's distance, then Check.

Try it yourself

// The distance sensor
const int trigPin = 9;
const int echoPin = 10;

// Send a ping and return the distance in cm.
long readDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  long duration = pulseIn(echoPin, HIGH);
  return duration / 58;
}

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

void loop() {
  long cm = readDistance();
  Serial.println(cm);
  delay(100);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Arduino playground