How to Blink LED in Arduino: Simple Guide with Code
To blink an LED in Arduino, connect the LED to a digital pin and use
pinMode() to set it as output. Then, use digitalWrite() to turn the LED on and off with delay() in the loop() function to create the blinking effect.Syntax
The basic syntax to blink an LED involves three main parts:
pinMode(pin, OUTPUT);sets the LED pin as an output.digitalWrite(pin, HIGH);turns the LED on.digitalWrite(pin, LOW);turns the LED off.delay(milliseconds);pauses the program to keep the LED on or off for a set time.
arduino
void setup() { pinMode(LED_BUILTIN, OUTPUT); // Set LED pin as output } void loop() { digitalWrite(LED_BUILTIN, HIGH); // Turn LED on delay(1000); // Wait 1 second digitalWrite(LED_BUILTIN, LOW); // Turn LED off delay(1000); // Wait 1 second }
Example
This example blinks the built-in LED on most Arduino boards on and off every second. It shows how to set the pin mode and use the loop to repeat the blinking.
arduino
void setup() { pinMode(LED_BUILTIN, OUTPUT); // Initialize the LED pin as output } void loop() { digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on delay(1000); // Wait for 1000 milliseconds (1 second) digitalWrite(LED_BUILTIN, LOW); // Turn the LED off delay(1000); // Wait for 1000 milliseconds (1 second) }
Output
The built-in LED on the Arduino board blinks on for 1 second, then off for 1 second, repeatedly.
Common Pitfalls
Common mistakes when blinking an LED include:
- Not setting the pin mode to
OUTPUT, so the LED won't turn on. - Using the wrong pin number or forgetting to connect the LED properly.
- Not using
delay(), which causes the LED to blink too fast to see. - Forgetting to connect a resistor in series with the LED, which can damage the LED or board.
arduino
/* Wrong way: Missing pinMode setup */ void setup() { // pinMode(LED_BUILTIN, OUTPUT); // This line is missing } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); } /* Right way: Include pinMode */ void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { digitalWrite(LED_BUILTIN, HIGH); delay(1000); digitalWrite(LED_BUILTIN, LOW); delay(1000); }
Quick Reference
Here is a quick cheat sheet for blinking an LED on Arduino:
| Command | Purpose |
|---|---|
| pinMode(pin, OUTPUT); | Set the pin as output to control LED |
| digitalWrite(pin, HIGH); | Turn the LED on |
| digitalWrite(pin, LOW); | Turn the LED off |
| delay(milliseconds); | Pause the program for visible blinking |
Key Takeaways
Always set the LED pin as OUTPUT using pinMode before controlling it.
Use digitalWrite with HIGH and LOW to turn the LED on and off.
Use delay to create visible on/off blinking intervals.
Connect a resistor in series with the LED to protect it and the board.
Check your wiring and pin numbers carefully to avoid mistakes.