#define LED_PIN 23 // Pin connected to the LED
#define BUTTON_PIN 22 // Pin connected to the button
bool ledState = false; // Variable to store the LED state
bool lastButtonState = HIGH; // Track the previous state of the button
void setup() {
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button pin as input with pull-up
Serial.begin(115200); // Initialize serial communication
Serial.println("Enter '1' to turn ON the LED and '0' to turn it OFF.");
}
void loop() {
// Check button input
handleButtonInput();
// Check serial input
handleSerialInput();
}
void handleButtonInput() {
bool currentButtonState = digitalRead(BUTTON_PIN); // Read button state
if (currentButtonState == LOW && lastButtonState == HIGH) { // Button pressed
ledState = !ledState; // Toggle LED state
digitalWrite(LED_PIN, ledState ? HIGH : LOW);
Serial.println(ledState ? "LED is ON (Button)" : "LED is OFF (Button)");
delay(300); // Simple debounce delay
}
lastButtonState = currentButtonState; // Update last button state
}
void handleSerialInput() {
if (Serial.available() > 0) { // Check if data is available on Serial
char input = Serial.read(); // Read the incoming data
if (input == '1') { // If '1' is received
ledState = true; // Set LED state to ON
digitalWrite(LED_PIN, HIGH);
Serial.println("LED is ON (Serial)");
} else if (input == '0') { // If '0' is received
ledState = false; // Set LED state to OFF
digitalWrite(LED_PIN, LOW);
Serial.println("LED is OFF (Serial)");
} else {
Serial.println("Invalid input. Please enter '1' or '0'.");
}
}
}