NAME:LIEZEL MAE TORRES 02-07-25
BSIT2-Y2-3 ADET|[Link]
// Define LED pin as a constant variable
#define LED_PIN 13
void setup() {
pinMode(LED_PIN, OUTPUT); // Set pin 13 as an output
void loop() {
toggleLED(); // Call function to toggle LED
delay(1000); // Wait for 1 second
// Function to toggle LED state
void toggleLED() {
static bool ledState = false; // Variable to store LED state
ledState = !ledState; // Toggle state (true -> false, false -> true)
digitalWrite(LED_PIN, ledState ? HIGH : LOW); // Update LED
Here’s another version of an Arduino sketch to blink an LED on pin 13, along with an explanation.
Arduino Sketch (Alternative Version):
// Define LED pin as a constant variable
#define LED_PIN 13
void setup() {
pinMode(LED_PIN, OUTPUT); // Set pin 13 as an output
}
void loop() {
toggleLED(); // Call function to toggle LED
delay(1000); // Wait for 1 second
// Function to toggle LED state
void toggleLED() {
static bool ledState = false; // Variable to store LED state
ledState = !ledState; // Toggle state (true -> false, false -> true)
digitalWrite(LED_PIN, ledState ? HIGH : LOW); // Update LED
Structure Explanation:
1. setup() Function:
o Runs once at startup.
o Initializes pin 13 as an output using pinMode().
2. loop() Function:
o Runs repeatedly after setup().
o Calls toggleLED() to change the LED state.
3. toggleLED() Function:
o Uses a static variable to track the LED state.
o Flips the state and updates the LED accordingly.
Programming Constructs:
Variables:
o #define LED_PIN 13 defines a constant for the LED pin.
o static bool ledState = false; stores the LED state.
Data Types:
o bool (Boolean) is used for the LED state (true/false).
Functions:
o setup(), loop(), and the custom toggleLED() function.
Digital I/O Operations:
pinMode(LED_PIN, OUTPUT); sets pin 13 as an output.
digitalWrite(LED_PIN, HIGH); turns the LED on.
digitalWrite(LED_PIN, LOW); turns it off.
Static variable toggles the LED state efficiently.