FluxBench.AIShared project · read-only

Ultrasonic Parking Sensor

ESP32 DevKit (WROOM-32)·Arduino C++·Updated Jul 27, 2026·by FluxBench TeamIncludes Lab + Schematic + PCB

An HC-SR04 ultrasonic ranger (TRIG GPIO5, ECHO GPIO18) measures the distance to the "car" while a 3-LED bar (green GPIO25, yellow GPIO26, red GPIO27) and a piezo buzzer on GPIO4 mimic a garage parking assistant: green means clear, yellow joins in as you approach, the buzzer beeps faster the closer you get, and under 15 cm the red LED and a solid 880 Hz tone say STOP. Drag the distance slider on the HC-SR04 in the Lab to drive the whole thing live. Bundled Lab bench, schematic and routed PCB included.

sketch.ino
// Ultrasonic Parking Sensor — HC-SR04 + 3-LED distance bar + piezo buzzer
#define TRIG_PIN   5
#define ECHO_PIN   18
#define LED_GREEN  25
#define LED_YELLOW 26
#define LED_RED    27
#define BUZZER_PIN 4

unsigned long lastBeep = 0;
bool beepOn = false;

float readDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, 30000);
  if (us == 0) return 400.0;   // timeout = nothing in range
  return us / 58.0;
}

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_YELLOW, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  Serial.println("Parking sensor ready - drag the distance slider on the HC-SR04");
}

void loop() {
  float cm = readDistanceCm();

  String zone;
  unsigned long beepInterval = 0;   // 0 = silent, 1 = solid tone

  if (cm > 100.0) {
    zone = "CLEAR";
  } else if (cm > 40.0) {
    zone = "APPROACHING";
    beepInterval = 400;
  } else if (cm > 15.0) {
    zone = "CLOSE";
    beepInterval = 120;
  } else {
    zone = "STOP";
    beepInterval = 1;
  }

  digitalWrite(LED_GREEN, cm > 15.0 ? HIGH : LOW);
  digitalWrite(LED_YELLOW, (cm <= 100.0 && cm > 15.0) ? HIGH : LOW);
  digitalWrite(LED_RED, cm <= 40.0 ? HIGH : LOW);

  if (beepInterval == 0) {
    noTone(BUZZER_PIN);
    beepOn = false;
  } else if (beepInterval == 1) {
    tone(BUZZER_PIN, 880);          // solid tone: STOP!
    beepOn = true;
  } else if (millis() - lastBeep >= beepInterval) {
    lastBeep = millis();
    beepOn = !beepOn;
    if (beepOn) tone(BUZZER_PIN, 880); else noTone(BUZZER_PIN);
  }

  Serial.print("Distance: ");
  Serial.print(cm, 1);
  Serial.print(" cm  zone=");
  Serial.println(zone);

  delay(150);
}

Built with FluxBench.AI — the AI workbench for embedded projects.