// HC-SR04, buzzer and LED pins const int TRIG_PIN = 7; const int ECHO_PIN = 8; const int BUZZER_PIN = 9; const int GREEN_PIN = 10; const int YELLOW_PIN = 11; const int RED_PIN = 12; // Zones (cm): beeping starts at 100, // red at 30, a steady tone at 10 const int FAR_CM = 100; const int NEAR_CM = 30; const int STOP_CM = 10; // The beep's pitch (Hz) and length (ms) const int BEEP_HZ = 2000; const int BEEP_MS = 50; // Time between readings: 60 ms at least const unsigned long MEASURE_EVERY = 100; unsigned long lastMeasure = 0; unsigned long lastBeep = 0; // -1: nothing in front to measure int distance = -1; void setup() { pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); pinMode(BUZZER_PIN, OUTPUT); pinMode(GREEN_PIN, OUTPUT); pinMode(YELLOW_PIN, OUTPUT); pinMode(RED_PIN, OUTPUT); Serial.begin(9600); } // Distance in cm; -1 when no echo comes int measureCm() { digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); // A 10 µs pulse starts one reading digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); // No echo in 30 ms (~5 m): give up unsigned long echo = pulseIn(ECHO_PIN, HIGH, 30000); if (echo == 0) { return -1; } // There and back: µs / 58 = cm return echo / 58; } // Sets all three LEDs: HIGH is on void lights(int green, int yellow, int red) { digitalWrite(GREEN_PIN, green); digitalWrite(YELLOW_PIN, yellow); digitalWrite(RED_PIN, red); } void loop() { unsigned long now = millis(); // No delay: measure when it is time if (now - lastMeasure >= MEASURE_EVERY) { lastMeasure = now; distance = measureCm(); if (distance < 0) { Serial.println("Distance: nothing there"); } else { Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); } } if (distance < 0 || distance > FAR_CM) { // Far away: green on, no sound lights(HIGH, LOW, LOW); noTone(BUZZER_PIN); } else if (distance <= STOP_CM) { // Very close: red and a steady tone lights(LOW, LOW, HIGH); tone(BUZZER_PIN, BEEP_HZ); } else { if (distance <= NEAR_CM) { lights(LOW, LOW, HIGH); } else { lights(LOW, HIGH, LOW); } // The beep is over: stop the sound if (now - lastBeep >= BEEP_MS) { noTone(BUZZER_PIN); } // Closer means shorter gaps unsigned long gap = map(distance, STOP_CM, FAR_CM, 80, 800); if (now - lastBeep >= gap) { lastBeep = now; tone(BUZZER_PIN, BEEP_HZ, BEEP_MS); } } }