#include <TM1637Display.h>
// Ultrasonic Sensor Pins
const int trigPin = 10; // Trigger pin
const int echoPin = 11; // Echo pin
// LED setup
const int ledPins[] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; // Pins for the 10 LEDs
const int numLeds = sizeof(ledPins) / sizeof(ledPins[0]);
// Buzzer pin
const int buzzerPin = 12;
// 7-Segment Display Pins (TM1637)
#define CLK 2 // Clock pin for TM1637
#define DIO 3 // Data pin for TM1637
TM1637Display display(CLK, DIO);
void setup() {
// Initialize LEDs
for (int i = 0; i < numLeds; i++) {
pinMode(ledPins[i], OUTPUT);
digitalWrite(ledPins[i], LOW); // Turn all LEDs off initially
}
// Initialize Buzzer
pinMode(buzzerPin, OUTPUT);
// Initialize Ultrasonic Sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize 7-Segment Display
display.setBrightness(7); // Set brightness level (0-7)
Serial.begin(9600); // For debugging
}
void loop() {
long duration;
int distance;
// Send a 10-microsecond pulse to the trigger pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate distance
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Convert time to distance (cm)
Serial.println(distance); // Debugging: print the distance
// Map distance to the number of LEDs to turn on
int ledsToTurnOn = map(distance, 0, 100, numLeds, 0); // Map distance to LED count (0-100 cm)
ledsToTurnOn = constrain(ledsToTurnOn, 0, numLeds); // Constrain to valid range
// Update LED states
for (int i = 0; i < numLeds; i++) {
if (i < ledsToTurnOn) {
digitalWrite(ledPins[i], HIGH); // Turn on the LED
} else {
digitalWrite(ledPins[i], LOW); // Turn off the LED
}
}
// Map distance to buzzer tone frequency
int buzzerFrequency = map(distance, 0, 100, 2000, 100); // Closer = higher frequency (2000 Hz max)
buzzerFrequency = constrain(buzzerFrequency, 100, 2000); // Constrain to valid frequency range
// Play tone on buzzer
if (distance <= 100) {
tone(buzzerPin, buzzerFrequency); // Play the tone
} else {
noTone(buzzerPin); // Stop the buzzer if out of range
}
// Update 7-Segment Display
if (distance > 9999) {
display.showNumberDecEx(9999, 0b01000000, true); // Display '----' if distance is too large
} else {
display.showNumberDec(distance, false); // Show distance in cm
}
delay(100); // Small delay for stability
}