Sub topic 8
Digital Pins: Reading and Driving HIGH and LOW
Assume you know basic voltage, current, and resistance, and that you can write a sketch using setup() and loop(). This chapter uses the Arduino Uno R3, whose digital pins are numbered 0 through 13.
A digital pin has two main jobs:
- As an input, it measures whether a signal is LOW or HIGH.
- As an output, it drives a signal LOW or HIGH.
A digital signal has two expected states, rather than a continuous range of values. On a 5 V Uno, LOW is near 0 V and HIGH is near 5 V. The microcontroller interprets voltage ranges using input thresholds, so HIGH does not mean that the voltage must be exactly 5 V.
Configuring a pin
Use pinMode() in setup() to choose a pin's direction. An output pin controls its voltage. An input pin senses voltage without intentionally driving the circuit.
const int ledPin = 13;
const int buttonPin = 2;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}digitalWrite() sets an output HIGH or LOW. digitalRead() returns the state currently sensed on an input. The constants HIGH, LOW, INPUT, and OUTPUT make the code easier to read than numeric values.
With this wiring, the button input needs a defined voltage when the button is not pressed. An unconnected input can float, meaning electrical noise may make it change unpredictably.
The signal path
Choosing a digital pin
Pins 2 through 13 can usually serve as general-purpose digital pins on an Uno. Pins 0 and 1 have a second job as the hardware serial receive and transmit pins. Avoid using them for ordinary circuits while uploading sketches or communicating with the Serial Monitor.
A pin's electrical limits matter. An Arduino pin is for signals and small loads, not for powering motors, relays, or long LED strips. Use a resistor with a bare LED, and use a transistor or driver module for higher-current devices.
| Pin use | Function | Typical code |
|---|---|---|
| Digital input | Sense HIGH or LOW | `digitalRead(pin)` |
| Digital output | Drive HIGH or LOW | `digitalWrite(pin, state)` |
Exercise
Why must an input pin have a defined voltage instead of being left unconnected?
Show answer
An unconnected input can float, allowing noise to produce unpredictable HIGH and LOW readings.