// Define the LED and pushbutton pins
const int LED_PIN = 9;
const int BUTTON_PIN = 2;
// Define the state variables
bool ledOn = false;
bool buttonPressed = false;
unsigned long buttonPressTime = 0;
// Define the timing variables for blinking the LED
const unsigned long BLINK_PERIOD = 500; // Blink period in milliseconds
unsigned long lastBlinkTime = 0; // Time of the last blink
void setup() {
// Set the LED pin as an output
pinMode(LED_PIN, OUTPUT);
// Set the button pin as an input with internal pull-up resistor enabled
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
// Read the button state and update the buttonPressTime variable if the button was just pressed
bool buttonState = digitalRead(BUTTON_PIN);
if (buttonState == LOW && buttonPressed == false) {
buttonPressed = true;
buttonPressTime = millis();
} else if (buttonState == HIGH) {
buttonPressed = false;
}
// Determine the desired LED state based on the button press time
bool newLedOn = ledOn;
if (buttonPressed == true) {
if (millis() - buttonPressTime < 2000) {
newLedOn = !ledOn;
} else {
newLedOn = false;
if (millis() - lastBlinkTime >= BLINK_PERIOD) {
analogWrite(LED_PIN, 255);
delay(100);
analogWrite(LED_PIN, 0);
lastBlinkTime = millis();
}
}
}
// Update the LED state if it has changed
if (newLedOn != ledOn) {
ledOn = newLedOn;
if (ledOn) {
digitalWrite(LED_PIN, HIGH);
} else {
digitalWrite(LED_PIN, LOW);
}
}
}