const int ledPin = 7; // Pin for the LED
const int buttonPin = 8; // Pin for the button
unsigned long previousMillis = 0; // Stores the last time the LED was updated
const long interval = 3000; // Interval at which to blink (milliseconds)
bool timerEnabled = false; // Boolean to control timer on/off state
int buttonState = 0; // Current state of the button
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Button with internal pull-up resistor
Serial.begin(9600); // Initialize serial communication for debugging (optional)
}
void loop() {
// Read the button state (LOW when pressed due to pull-up)
buttonState = digitalRead(buttonPin);
// Toggle the timer state if the button is pressed
if (buttonState == LOW) {
timerEnabled = !timerEnabled; // Toggle the timer state
delay(200); // Simple debounce mechanism
Serial.print("Timer state: ");
Serial.println(timerEnabled ? "Enabled" : "Disabled");
}
// Only run the timer if it's enabled
if (timerEnabled) {
unsigned long currentMillis = millis();
// Compare the current time to the previous time the LED was updated
if (currentMillis - previousMillis >= interval) {
// Save the last time the LED was toggled
previousMillis = currentMillis;
// Toggle the LED state
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
}
Restart