pinMode, digitalWrite & digitalRead Explained
The three functions behind almost every digital pin interaction — what each one actually does, and the mistake that trips up most beginners.
The last two lessons used three functions together without pausing on each individually — worth doing now, since they cover the large majority of simple digital I/O work:
- pinMode(pin, mode) — configures a pin's role before you use it, either
OUTPUT(the board will drive the pin's voltage) orINPUT(the board will read the pin's voltage, set externally by your circuit). Called once insetup(), for every pin you plan to use. - digitalWrite(pin, value) — on an OUTPUT pin, sets its voltage to
HIGH(5V) orLOW(0V). Calling this on a pin still configured as INPUT does something different and unrelated (toggling that pin's internal pull-up resistor) — an easy, confusing mistake if the pinMode call is missing or wrong. - digitalRead(pin) — on an INPUT pin, checks the pin's current voltage and returns
HIGHorLOWaccordingly.
There's also a third pinMode option, INPUT_PULLUP, which enables the pin's own internal pull-up resistor (mentioned in the last bullet) — this lets you skip wiring an external pull-up resistor for a simple button, at the cost of inverted logic: the pin reads HIGH normally and LOW when the button (wired to GND) is pressed, the opposite of Lesson ard-05's external pull-down.
The single most common beginner bug involving these three: forgetting the pinMode() call entirely, or setting the wrong mode. If a pin behaves strangely with no obvious wiring fault, checking its pinMode() is always worth doing first.