Sub topic 2
Setting a Pin as Input and Calling digitalRead
This chapter covers the two calls that every digital input depends on: pinMode to put a pin in input mode, and digitalRead to ask what voltage it sees. The chapter uses a bare jumper wire as the signal source. The push button comes in the next chapters.
Prerequisites. You should already know:
- The
setup()andloop()structure of a sketch. - Ohm's law at a basic level.
- How to place parts and jumper wires on a breadboard.
- How to drive an LED with
digitalWrite.
The examples were written for an Arduino Uno (5 V logic, ATmega328P). Notes mark where other boards differ.
What a digital input actually measures
A digital input pin has no concept of "pressed" or "on". It compares the voltage on the pin with two internal thresholds and reports one of two values:
HIGH(the number 1) means the voltage is near the supply voltage.LOW(the number 0) means the voltage is near ground.
On a 5 V Uno, the ATmega328P datasheet guarantees these ranges:
| Pin voltage | What the pin reports |
|---|---|
| 0 V up to about 1.5 V (0.3 × Vcc) | Reliably `LOW` |
| About 1.5 V to 3.0 V | Undefined. It may read either value, and it can change from reading to reading |
| About 3.0 V (0.6 × Vcc) up to 5 V | Reliably `HIGH` |
The middle band is the main reason later chapters spend time on wiring. A pin that sits in that band gives unreliable answers. Your job as a designer is to make sure the pin is always clearly in the LOW band or the HIGH band.
On 3.3 V boards the thresholds scale with the supply. Vcc is 3.3 V there, so HIGH begins at roughly 2 V. Applying 5 V to the pin of a 3.3 V board can damage it, so check your board's documentation.
Configuring a pin with pinMode
The pinMode(pin, mode) function sets the direction and electrical behavior of a pin. For input work you use two of its three modes:
| Mode | Direction | Behavior |
|---|---|---|
| `INPUT` | Input | The pin is high impedance. It draws almost no current and has no connection to Vcc or ground except through whatever you wire to it |
| `INPUT_PULLUP` | Input | Same as `INPUT`, but an internal resistor (roughly 20 kΩ to 50 kΩ on AVR boards) connects the pin to Vcc |
| `OUTPUT` | Output | The pin actively drives `HIGH` or `LOW` |
"High impedance" is the key idea for INPUT. The pin behaves as if it were connected to a very large resistance, typically in the tens or hundreds of megaohms. The pin therefore does not disturb the circuit it measures. It also means the pin has no firm voltage of its own. If nothing drives it, the pin has no defined value. That condition has a name, a floating input, and the next chapters address it.
INPUT_PULLUP is introduced here only so you can recognize it in the table. Chapter material on pull-up resistors explains when and why to use it.
Where to call pinMode
Call pinMode once in setup(). The mode does not change by itself, so repeating the call on every pass through loop() only wastes time.
const int inputPin = 2;
void setup() {
pinMode(inputPin, INPUT);
}
void loop() {
// read inputPin here
}Pins start as inputs after a reset, so a sketch that never calls pinMode on a pin still reads it. Do not rely on that. An explicit pinMode call documents your intent. It also protects you if the same pin was an output earlier in the sketch.
Naming pins with constants
Use const int for pin numbers, as the examples do. The compiler replaces the name with the number and uses no extra memory. A name such as buttonPin also tells the reader what the number means. If you rewire the board, you change one line instead of hunting through the file.
Reading with digitalRead
digitalRead(pin) samples the pin once and returns an int: HIGH or LOW. The read happens at the moment of the call. The function does not wait, does not filter, and does not remember previous readings. On an Uno one call takes a few microseconds, so a tight loop() can sample the pin many thousands of times per second.
Here is a minimal sketch that prints the level every half second:
const int inputPin = 2;
void setup() {
Serial.begin(9600);
pinMode(inputPin, INPUT);
}
void loop() {
int level = digitalRead(inputPin);
Serial.print("pin 2 = ");
Serial.println(level);
delay(500);
}To try it:
- Upload the sketch and open the Serial Monitor at 9600 baud.
- Power off or unplug the board, then connect a jumper wire from pin 2 to the
GNDpin. Reconnect power. The monitor showspin 2 = 0. - Move the same wire to the
5Vpin. The monitor showspin 2 = 1.
Always attach the wire to one rail or the other before you read the output. Pulling the wire out and leaving its free end dangling gives a floating input, and the readings will not be meaningful. The chapter on floating inputs shows you exactly that effect on purpose.
Comparing the result
HIGH and LOW are constants, so you can compare against them directly:
const int inputPin = 2;
const int ledPin = LED_BUILTIN;
void setup() {
pinMode(inputPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
if (digitalRead(inputPin) == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}With pin 2 wired to 5V the built-in LED lights, and with pin 2 wired to GND it goes dark. A shorter equivalent is digitalWrite(ledPin, digitalRead(inputPin));. The long form is easier to extend when the logic later becomes more than a copy.
Which pins can you read
Every numbered digital pin can be read, including pins that also have other jobs:
- On an Uno, pins 0 and 1 are shared with the USB serial connection. Avoid them for inputs while you use the Serial Monitor.
- The analog pins
A0toA5also work as digital pins. You can calldigitalRead(A0), andA0throughA5are numbered 14 to 19 on the Uno. - Pin 13 has the built-in LED and its series resistor attached. This loads the pin, so an input wired to pin 13 behaves less cleanly than one on pin 2. Prefer other pins for input.
Reading an output pin
digitalRead also works on a pin set to OUTPUT. It returns the level the pin is currently driving. This is handy for toggling:
const int ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, !digitalRead(ledPin));
delay(500);
}The sketch reads the current state, inverts it with !, and writes it back, so the LED blinks without a separate state variable. Keeping the state in a variable, as later chapters do, is usually clearer. This pattern is still worth recognizing in other people's code.
Polling and reporting changes
Calling digitalRead repeatedly from loop() is called polling. A level read tells you the state right now. It does not tell you that something just happened. To report only changes, compare each reading with the previous one:
const int inputPin = 2;
int previousLevel = LOW;
void setup() {
Serial.begin(9600);
pinMode(inputPin, INPUT);
previousLevel = digitalRead(inputPin);
}
void loop() {
int level = digitalRead(inputPin);
if (level != previousLevel) {
Serial.println(level == HIGH ? "went HIGH" : "went LOW");
previousLevel = level;
}
}Two details matter here. The sketch takes a first reading in setup() so that the starting state is not reported as a change. The sketch also has no delay(), so loop() runs very fast and checks the pin thousands of times per second.
Touch the jumper wire from GND to pin 2 and then to 5V, and watch the output. You may see extra lines such as several went HIGH and went LOW messages for one touch of the wire. That is contact bounce, caused by the wire's metal touching and separating in the first few milliseconds. A push button does the same thing, and a later chapter on debouncing treats it properly.
Common errors
- Using
=instead of==.if (digitalRead(pin) = HIGH)assigns rather than compares, and the compiler may only warn. Always write==. - Calling
pinModeinsideloop()and expecting it to matter. It works, but it is wasted effort. Put it insetup(). - Assuming
HIGHmeans "pressed" or "on". The meaning depends on the wiring. Later chapters show a wiring in which a pressed button readsLOW. - Reading an unwired pin. A pin with nothing attached floats, and the result changes with your hand's position, nearby wires, and noise.
- Storing the result in a
byteorbooland comparing it with other types. This usually works, becauseHIGHis 1 andLOWis 0. Keep anintunless you have a reason to change it, so comparisons stay readable. - Using the pin in a function that changes its mode. Libraries such as
ServoorSPIchange pin modes. If a pin stops reading correctly, check whether a library claimed it.
What comes next
You can now configure a pin and sample it. The next chapter connects a push button to a pin and shows why the button alone does not give a reliable reading.
Exercise
A sketch sets pin 4 with pinMode(4, INPUT) and then wires pin 4 to the 5V pin through a jumper. What does digitalRead(4) return, and why does the sketch not need to call pinMode inside loop()?
Show answer
It returns HIGH (the number 1), because 5 V is above the roughly 3 V threshold a 5 V Uno needs to read HIGH. pinMode sets the pin's mode once, and the mode stays in effect until something changes it, so calling it once in setup() is enough.
Exercise
You print digitalRead(2) with nothing connected to pin 2 and see a mix of 0 and 1 that changes when you move your hand near the board. What is the condition called, and what do you need to do to the circuit to get a stable reading?
Show answer
The pin is a floating input. It has no defined voltage, so it picks up noise and can sit in the undefined band between LOW and HIGH. To fix it, connect the pin to a defined level, either directly to 5V or GND, or, for a button, through a pull-down or pull-up resistor.