My first Arduino project, I am creating an alarm system for machine processing.
This is my code:
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
// Pin definitions
const int relayRed = 8; // Relay for red light
const int relayYellow = 9; // Relay for yellow light
const int relayGreen = 10; // Relay for green light
const int relaySiren = 11; // Relay for siren
const int buttonPin = 2; // Button to control the system
const unsigned long loadCycleTime = 60000; // Load cycle time in milliseconds (e.g., 60 seconds)
// Adjust the address and dimensions if your LCD is different
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the LCD, adjust the address if needed
unsigned long startTime;
bool cycleRunning = false;
bool buttonPressed = false;
bool lastButtonState = HIGH; // Initial state of the button
void setup() {
pinMode(relayRed, OUTPUT);
pinMode(relayYellow, OUTPUT);
pinMode(relayGreen, OUTPUT);
pinMode(relaySiren, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(relayRed, HIGH); // Red light on initially (relay off)
digitalWrite(relayYellow, LOW); // Yellow light off
digitalWrite(relayGreen, LOW); // Green light off
digitalWrite(relaySiren, LOW); // Siren off
// Initialize the LCD with its dimensions and I2C address
lcd.begin(); // No parameters needed here, defaults to 16x2 and 0x27 address
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Time Left:");
}
void loop() {
bool currentButtonState = digitalRead(buttonPin);
if (currentButtonState == LOW && lastButtonState == HIGH && !buttonPressed) {
delay(50); // Debounce delay
buttonPressed = true;
lastButtonState = LOW;
if (!cycleRunning) {
startTime = millis();
cycleRunning = true;
digitalWrite(relayRed, LOW); // Turn off red light
digitalWrite(relayYellow, HIGH); // Turn on yellow light
} else {
resetSystem(); // Reset system when button is pressed during siren
}
} else if (currentButtonState == HIGH) {
lastButtonState = HIGH;
buttonPressed = false;
}
if (cycleRunning) {
unsigned long elapsedTime = millis() - startTime;
if (elapsedTime < loadCycleTime) {
unsigned long remainingTime = (loadCycleTime - elapsedTime) / 1000;
lcd.setCursor(10, 0);
lcd.print(remainingTime);
lcd.print(" s ");
} else {
digitalWrite(relayYellow, LOW); // Turn off yellow light
digitalWrite(relayGreen, HIGH); // Turn on green light
digitalWrite(relaySiren, HIGH); // Turn on siren
cycleRunning = false; // Stop the cycle
}
}
}
void resetSystem() {
digitalWrite(relayRed, HIGH); // Turn on red light
digitalWrite(relayYellow, LOW); // Turn off yellow light
digitalWrite(relayGreen, LOW); // Turn off green light
digitalWrite(relaySiren, LOW); // Turn off siren
lcd.setCursor(10, 0);
lcd.print(" ");
cycleRunning = false;
}
Any help would be appreciated