#include <TM1637Display.h>
// Pin definitions
const int trigPin = 9;
const int echoPin = 10;
const int relayPin = 8;
const int buttonPin = 7;
const int buzzerPin = 6;
// 4-Digit Display (TM1637)
#define CLK 2
#define DIO 3
TM1637Display display(CLK, DIO);
// Variables for ultrasonic sensor
long duration;
int distance;
// State variables
bool relayState = false;
bool buttonPressed = false;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
pinMode(buzzerPin, OUTPUT);
// Turn off relay and buzzer at the start
digitalWrite(relayPin, LOW);
digitalWrite(buzzerPin, LOW);
// Initialize display
display.setBrightness(0x0f); // Set brightness
display.showNumberDec(0); // Initialize display with 0
}
void loop() {
// Measure distance using HC-SR04
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2; // Calculate distance in cm
// Show the distance on the 4-digit display
display.showNumberDec(distance);
// Check if push button is pressed
if (digitalRead(buttonPin) == LOW && !buttonPressed) {
buttonPressed = true; // Set flag
relayState = !relayState; // Toggle relay state
delay(200); // Debounce delay
}
// Reset button flag after release
if (digitalRead(buttonPin) == HIGH && buttonPressed) {
buttonPressed = false;
}
// Control the relay
if (relayState) {
digitalWrite(relayPin, HIGH); // Turn relay on
digitalWrite(buzzerPin, HIGH); // Turn buzzer on
} else {
digitalWrite(relayPin, LOW); // Turn relay off
digitalWrite(buzzerPin, LOW); // Turn buzzer off
}
// Small delay before repeating loop
delay(100);
}