Menu
CoddyTech

Parking Sensor: Beeps

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

A parking sensor speaks as well as shows: the closer the wall, the faster it beeps, until it holds one steady tone that means stop. The buzzer is on pin 8.

The gap between beeps comes from the distance: the distance times 10, in milliseconds. At 70 cm a beep every 700 ms, at 20 cm every 200 ms. A millis() timer decides when the next beep is due:

if (millis() - lastBeep >= cm * 10) {
  lastBeep = millis();
  tone(buzzerPin, 1000, 50);  // a 50 ms beep
}

There are two more cases. Under 10 cm, play tone(buzzerPin, 1000) with no length: it sounds until something stops it. At 100 cm or more, stay quiet, and call noTone(buzzerPin) so a steady tone left over from before is stopped too.

challenge icon

Challenge

Medium

Add the beeps:

  • 100 cm or more: no sound (call noTone())
  • 10 to 99 cm: a 50 ms beep at 1000 Hz every cm * 10 ms, timed with millis()
  • under 10 cm: a steady 1000 Hz tone

Keep the lights and the printing. Press Run, move the object closer, then Check.

Try it yourself

// The distance sensor
const int trigPin = 9;
const int echoPin = 10;
// The warning lights
const int greenPin = 6;
const int yellowPin = 7;
const int redPin = 13;

// 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;
}

// Green when clear, yellow when close, red when too close.
void showLights(long cm) {
  digitalWrite(greenPin, LOW);
  digitalWrite(yellowPin, LOW);
  digitalWrite(redPin, LOW);
  if (cm >= 100) {
    digitalWrite(greenPin, HIGH);
  } else if (cm >= 30) {
    digitalWrite(yellowPin, HIGH);
  } else {
    digitalWrite(redPin, HIGH);
  }
}

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

void loop() {
  long cm = readDistance();
  Serial.println(cm);
  showLights(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