#include <LiquidCrystal.h>
const int buttonPin = 2; // the pin that the button is connected to
const int relayPin = 3; // the pin that the relay is connected to
const int rs = 7, en = 8, d4 = 9, d5 = 10, d6 = 11, d7 = 12; // the pins that the LCD is connected to
LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // initialize the LCD
int buttonState = HIGH; // the current state of the button
int lastButtonState = HIGH; // the previous state of the button
unsigned long lastDebounceTime = 0; // the last time the button was pressed
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
bool relayState = false; // the current state of the relay
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW); // turn the relay off initially
lcd.begin(16, 2); // initialize the LCD with 16 columns and 2 rows
lcd.print("Relay state:"); // display the initial message
lcd.setCursor(0, 1); // move the cursor to the second row
lcd.print("OFF");
}
void loop() {
// read the state of the button
int reading = digitalRead(buttonPin);
// debounce the button
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if (millis() - lastDebounceTime > debounceDelay) {
// update the button state only if debounceDelay has passed
if (reading != buttonState) {
buttonState = reading;
// toggle the relay if the button is pressed
if (buttonState == LOW) {
relayState = !relayState; // toggle the relay state
digitalWrite(relayPin, relayState ? HIGH : LOW); // set the relay pin accordingly
}
}
}
// update the LCD display with the current relay state
lcd.setCursor(12, 1); // move the cursor to the second row, 13th column
lcd.print(relayState ? "ON " : "OFF"); // display the relay state as "ON" or "OFF"
// save the button state for the next iteration
lastButtonState = reading;
}