const int resetButtonPin = 4; // Pin for the reset button
const int potentiometerPin = A0; // Pin for the potentiometer
const int relayPin = 3; // Pin for the relay
unsigned long adjVal = 0; // Adjusted value from the potentiometer
unsigned long currentMillis = 0; // Current time
unsigned long previousMillis = 0;
unsigned long targetMillis = 0; // Target time in milliseconds
bool relayOn = false; // Relay state
bool resetButtonPressed = false; // State of the reset button
void setup() {
pinMode(resetButtonPin, INPUT_PULLUP); // Set the reset button pin as an input with pull-up resistor
pinMode(potentiometerPin, INPUT); // Set the potentiometer pin as an input
pinMode(relayPin, OUTPUT); // Set the relay pin as an output
digitalWrite(relayPin, LOW); // Initialize the relay as OFF
Serial.begin(9600); // Initialize serial communication (for debugging)
// Initialize previousMillis once at the start
previousMillis = millis();
}
void loop() {
// Read the adjusted value from the potentiometer
adjVal = map(analogRead(potentiometerPin), 0, 1023, 1000, 10000); // Adjusted time between 1s and 10s
// Read the reset button state
resetButtonPressed = !digitalRead(resetButtonPin);
// Check if the reset button is pressed, then reset the timer
if (resetButtonPressed) {
// Flag for indicating that the relay is turned on
relayOn = false;
// Turn off the relay
digitalWrite(relayPin, LOW);
// Update previousMillis only when the reset button is pressed
previousMillis = millis();
}
// If the relay is OFF and the reset button is not pressed, run the timer
if (!relayOn && !resetButtonPressed) {
// makes the pot value as the target time to reach
targetMillis = adjVal;
// starts the time using millis function
currentMillis = millis();
//for displaying the timer value
Serial.print("Current Timer:");
Serial.println(float(currentMillis - previousMillis) / 1000);
Serial.print("Set Time: ");
Serial.println(float(targetMillis)/1000);
// condition to turn on the relay
if (currentMillis - previousMillis >= targetMillis) {
// raises the flag relayON as true to stop the counting and holds the last state of relay
relayOn = true;
// triggers the relay ON; this will hold until the reset button is pressed
digitalWrite(relayPin, HIGH); // Turn on the relay
}
}
}