Index
In Arduino, digital I/O (Input/Output) lets you control and read binary states on the pins, meaning they can either be on (HIGH) or off (LOW). We’ll explore digital write and read functions through an example where a switch controls an LED.
Objective:
Use a pushbutton switch to turn an LED on and off.
Required Components:
- Arduino Uno
- LED
- 220-ohm resistor (for LED)
- Pushbutton switch
- 10k-ohm resistor (for pull-down configuration)
- Breadboard and jumper wires
Circuit Setup:
- LED Circuit:
- Connect the longer leg (anode) of the LED to digital pin 9 on the Arduino through a 220-ohm resistor.
- Connect the shorter leg (cathode) of the LED to GND on the Arduino.
- Button Circuit:
- Connect one side of the pushbutton to 5V on the Arduino.
- Connect the other side of the button to digital pin 7 on the Arduino.
- Place a 10k-ohm resistor between the button’s other side and GND (for a pull-down resistor).
Code Explanation:
In this example, we’ll write code that reads the state of the button using digitalRead()
, and if the button is pressed, it will turn on the LED by writing HIGH to the LED pin using digitalWrite()
.
Code:
// Define pins
const int ledPin = 9; // LED connected to digital pin 9
const int buttonPin = 7; // Pushbutton connected to digital pin 7
void setup() {
// Set pin modes
pinMode(ledPin, OUTPUT); // Set LED pin as output
pinMode(buttonPin, INPUT); // Set button pin as input
}
void loop() {
// Read the state of the button
int buttonState = digitalRead(buttonPin);
// Check if the button is pressed
if (buttonState == HIGH) {
// Turn on the LED
digitalWrite(ledPin, HIGH);
} else {
// Turn off the LED
digitalWrite(ledPin, LOW);
}
}
Code Breakdown:
- Setup Function:
pinMode(ledPin, OUTPUT);
sets the LED pin as an output.pinMode(buttonPin, INPUT);
sets the button pin as an input.
- Loop Function:
digitalRead(buttonPin);
reads the state of the button pin and stores it inbuttonState
.- If
buttonState
is HIGH (indicating the button is pressed),digitalWrite(ledPin, HIGH);
turns the LED on. - If
buttonState
is LOW (button not pressed),digitalWrite(ledPin, LOW);
turns the LED off.
How It Works:
- When the button is pressed, it connects to 5V, making the buttonPin HIGH. This triggers the
if
statement, and the LED turns on. - When the button is not pressed, the pull-down resistor keeps the buttonPin at LOW, turning the LED off.
This simple example demonstrates how to read digital input from a switch and control digital output to an LED.