Digital I/O on Arduino
Digital I/O on Arduino
Control LEDs, read buttons, and understand HIGH vs LOW.
Digital Signals
Digital pins have only two states: HIGH (5 V on Uno) and LOW (0 V). This maps directly to 1 and 0 in your code.
You use digital I/O to:
- Output: control LEDs, buzzers, relays, motors via a driver
- Input: read buttons, switches, IR receivers, limit sensors
Configuring a Pin ߀” pinMode()
Before using a pin you must declare its direction:
pinMode(pin, mode);
| Mode | Constant | When to use |
|---|---|---|
| Output | OUTPUT |
Driving components (LED, buzzer) |
| Input | INPUT |
Reading a switch (floating when open) |
| Input with pull-up | INPUT_PULLUP |
Reading a switch with no external resistor |
Always call pinMode() inside setup().
Writing a Pin ߀” digitalWrite()
digitalWrite(pin, value);
digitalWrite(9, HIGH); // Set pin 9 to 5 V
digitalWrite(9, LOW); // Set pin 9 to 0 V
Reading a Pin ߀” digitalRead()
int state = digitalRead(pin); // Returns HIGH or LOW
Wiring an LED
Always add a current-limiting resistor (220 ?©ß€“470 ?©) in series with an LED ߀” without one the LED draws too much current and burns out, or damages the pin.
Arduino pin 9 ß”€ß”€ß”€ß”€ 220 ?© ß”€ß”€ß”€ß”€ LED (+) ß”€ß”€ß”€ß”€ LED (ß?’) ß”€ß”€ß”€ß”€ GND
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
digitalWrite(9, HIGH);
delay(500);
digitalWrite(9, LOW);
delay(500);
}
Wiring a Button
A button connects a pin to either HIGH or LOW when pressed. Using INPUT_PULLUP is the easiest approach ߀” the pin reads HIGH when the button is open, LOW when pressed.
Arduino pin 2 ß”€ß”€ß”€ß”€ Button ß”€ß”€ß”€ß”€ GND
void setup() {
pinMode(2, INPUT_PULLUP); // Internal pull-up resistor active
pinMode(9, OUTPUT);
}
void loop() {
int btn = digitalRead(2);
if (btn == LOW) { // Button is pressed (pulled to GND)
digitalWrite(9, HIGH); // LED on
} else {
digitalWrite(9, LOW); // LED off
}
}
Debouncing
Mechanical buttons produce brief electrical noise when pressed ("bounce"). A simple software debounce:
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
int lastButtonState = HIGH;
void loop() {
int reading = digitalRead(2);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// reading is stable ߀” use it here
}
lastButtonState = reading;
}