/* * Lab 1 - Task 2: Multitasking with Millis() and Pull-Down Switch
* Objective: Blink Green LED continuously without blocking the Red LED button control.
*/
// Define Pins
const int buttonPin = 18; // Push button connected to GPIO 18
const int ledBlinkPin = 5; // Green LED for blinking
const int ledButtonPin = 2; // Red LED for button status
// Variables for millis() timing
unsigned long previousMillis = 0; // Stores last time LED was updated
const long interval = 500; // Interval at which to blink (milliseconds)
int ledState = LOW; // Current state of the blinking LED
void setup() {
pinMode(ledBlinkPin, OUTPUT);
pinMode(ledButtonPin, OUTPUT);
// Initialize the pushbutton pin as an input
// Note: We are using an external pull-down resistor in the circuit
pinMode(buttonPin, INPUT);
Serial.begin(115200);
Serial.println("Task 2 Ready: Multitasking with millis().");
}
void loop() {
// ---------------------------------------------------------
// TASK A: Blink the Green LED using millis() (Non-Blocking)
// ---------------------------------------------------------
unsigned long currentMillis = millis(); // Get the current time
if (currentMillis - previousMillis >= interval) {
// Save the last time you blinked the LED
previousMillis = currentMillis;
// Toggle the LED state
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledBlinkPin, ledState);
}
// ---------------------------------------------------------
// TASK B: Read the Push Button instantly
// ---------------------------------------------------------
int buttonState = digitalRead(buttonPin);
// Check if button is pressed.
// With Pull-Down resistor, Pressed = HIGH, Unpressed = LOW
if (buttonState == HIGH) {
digitalWrite(ledButtonPin, HIGH); // Turn Red LED ON
} else {
digitalWrite(ledButtonPin, LOW); // Turn Red LED OFF
}
}