/*
Button controlled LED flasher
Arduino | coding-help
Darn millis()
TheStudier August 2, 2025 — 2:12 AM
So I'm trying to make a code using millis().
*/
// constants
const int BTN_PIN = 8;
const int LED_PIN = 7;
const unsigned long BLINK_INT = 500;
// global variables
bool ledState = false;
bool doBlink = false;
int oldBtnVal = HIGH; // INPUT_PULLUP idles HIGH
unsigned long prevLedTime = 0;
bool checkButton() {
bool isPressed = false;
int buttonValue = digitalRead(BTN_PIN);
if (buttonValue != oldBtnVal) { // button changed
oldBtnVal = buttonValue; // remember state
if (buttonValue == LOW) { // was just pressed
Serial.println("Button pressed");
isPressed = true;
} else {
Serial.println("Button released"); // was just released
isPressed = false;
}
delay(20); // short delay to debounce button
}
return isPressed;
}
void blinkLed() {
if (millis() - prevLedTime >= BLINK_INT) {
prevLedTime = millis();
ledState = !ledState;
}
}
void setup() {
Serial.begin(9600);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
Serial.println("Push the button!\n");
}
void loop() {
if (checkButton()) {
doBlink = !doBlink;
}
if (doBlink) {
blinkLed();
} else {
ledState = false;
}
digitalWrite(LED_PIN, ledState);
}