Sub topic 3
Driving a pin with pinMode() and digitalWrite()
Prerequisites and scope
This chapter assumes you know what a variable and a function are. It also assumes you understand voltage, current and resistance at an introductory level. You should have an Arduino-compatible board, a USB cable and the Arduino IDE installed.
The previous chapters covered what a digital pin is and how setup() and loop() are structured. This chapter covers the two functions that make a pin do something: pinMode() and digitalWrite(). It also covers what happens inside the chip when you call them, and the mistakes that most often go wrong.
The two-step pattern
Every digital output in Arduino follows the same two steps:
- Declare the pin as an output with
pinMode(pin, OUTPUT). Do this once, normally insetup(). - Set its level with
digitalWrite(pin, level). Do this whenever the level needs to change.
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}LED_BUILTIN is a constant that the board definition sets to the pin number of the on-board LED. On an Uno this is pin 13. Other boards use other pins, so use the constant instead of a literal number when you want portable code.
pinMode(): choosing a pin's direction
A general-purpose pin on the microcontroller can act as an input or as an output. pinMode() sets which one.
| Mode | What the pin does | Typical use |
|---|---|---|
| `OUTPUT` | The chip drives the pin to a defined high or low voltage | LEDs, relays through a driver, signals to other chips |
| `INPUT` | The pin senses voltage and draws almost no current | Buttons with an external resistor, sensors |
| `INPUT_PULLUP` | Like `INPUT`, with an internal resistor pulling the pin to the supply voltage | Buttons wired to ground, no external resistor |
The signature is pinMode(pin, mode). Both arguments matter. If you swap them, or pass a mode that does not exist, the code may still compile, because OUTPUT and the pin number are both just integers. The pin then behaves in a way you did not intend.
After a reset, every pin starts as an input. A pin you never configure therefore does not drive anything. This is the most common reason a first blink sketch compiles, uploads and then does nothing.
What pinMode() does internally
On an AVR board such as the Uno, each pin belongs to a port. Each port has a data direction register, abbreviated DDR. Each pin corresponds to one bit in that register. A 1 means output and a 0 means input. pinMode(pin, OUTPUT) looks up which port and bit the pin number maps to, then sets that bit.
You do not need to touch these registers. Knowing they exist explains two facts. First, the setting persists until you change it or reset the board, so you do not need to call pinMode() again in every pass of loop(). Second, the pin number you pass is an Arduino label, not a hardware address. The core library translates it through a lookup table.
digitalWrite(): setting the level
The signature is digitalWrite(pin, value). The value is HIGH or LOW.
HIGHconnects the pin to the board's supply voltage. That is 5 V on an Uno and 3.3 V on many newer boards.LOWconnects the pin to ground, which is 0 V.
On an AVR board, digitalWrite() sets or clears one bit in the port's output register. The pin driver then pushes the pin to the matching voltage. The level stays until you write a different one.
HIGH and LOW are defined as 1 and 0. Because of this, any non-zero value written to a pin is treated as HIGH, and zero is treated as LOW. Prefer the named constants, since they say what you mean.
Sourcing current: why HIGH lights the LED
When a pin is HIGH and an LED with a resistor connects from that pin to ground, current flows out of the pin through the LED and resistor to ground. The pin is the source of the current. If you wire the LED the other way, from the supply voltage to the pin, the LED lights when the pin is LOW, because the pin then sinks current to ground. Both arrangements work. The first is easier to reason about, so this tutorial uses it.
Current limits
A pin can supply only a small current. On an ATmega328P (the Uno's chip), the absolute maximum rating is 40 mA per pin, and the datasheet recommends staying at or below 20 mA in normal use. There is also a limit for the whole chip. Treat these as ceilings, not targets. A typical indicator LED needs about 5 to 15 mA, which is well inside the limit when a resistor is present. A later chapter shows how to size that resistor.
Reading the example line by line
Take the external LED version of the sketch, which uses a named constant for the pin:
const uint8_t LED_PIN = 8;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
}const uint8_t LED_PIN = 8;stores the pin number in a constant. An unsigned 8-bit integer is enough, since pin numbers are small. Changing the pin later means editing one line.pinMode(LED_PIN, OUTPUT);runs once at start-up. It sets pin 8 as an output.digitalWrite(LED_PIN, HIGH);raises pin 8 to the supply voltage, so current flows through the LED.delay(500);holds that state for 500 milliseconds. Without it the LED would switch so fast that you would see a dim glow, not a blink.digitalWrite(LED_PIN, LOW);drops the pin to 0 V, and the LED goes dark.- The second
delay(500);holds the dark state. Becauseloop()runs repeatedly, the cycle starts again.
The pin changes state in microseconds. The visible blink comes entirely from the delays.
The sequence over time
The following diagram shows what the pin does during one pass of the loop.
Common errors
Forgetting pinMode()
On an Uno, if you call digitalWrite(pin, HIGH) on a pin that is still an input, the call does not drive the pin. It enables the internal pull-up resistor on that pin, which is a weak connection to the supply voltage. An LED with a series resistor may then glow faintly. This is a useful clue when diagnosing a dim LED. The fix is to call pinMode(pin, OUTPUT) in setup().
Calling pinMode() in the wrong place
pinMode() inside loop() works, but it repeats work for no benefit. Put it in setup(). A related mistake is calling digitalWrite() in setup() and expecting it to continue. It sets the level once, which is fine for a constant state, but it will never blink.
Using the wrong pin number
Labels printed on the board are the numbers you pass to the functions. Some boards print both a digital label such as D8 and a GPIO number. Use the one the board's Arduino core documents. Analog pins such as A0 can also work as digital pins, since A0 is an alias for a digital pin number, but do not use them accidentally.
Case sensitivity
HIGH, LOW, OUTPUT and INPUT are all upper case. Writing high or Output causes a compile error, because C++ is case sensitive and these are separate names.
Putting pins 0 and 1 to use
On an Uno, pins 0 and 1 are shared with the serial connection to the computer. Driving them as outputs can disturb uploads and serial output. For first projects, use pins 2 to 13.
Reading back a pin
digitalRead(pin) returns the level of a pin. On a pin set to OUTPUT, it returns the level you last wrote. That makes it possible to toggle without keeping a separate variable:
const uint8_t LED_PIN = 8;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(LED_PIN, !digitalRead(LED_PIN));
delay(500);
}The ! operator flips HIGH to LOW and LOW to HIGH. After a reset, the pin starts LOW, so the first write turns the LED on. This form is shorter, but it hides the intent, and it depends on the pin's read-back behavior. Many boards support it, though a few cores do not. The explicit HIGH and LOW version works everywhere, which is why it is the one to learn first.
Design choices
| Choice | Option A | Option B | Guidance |
|---|---|---|---|
| Pin number | Literal, as in `digitalWrite(8, HIGH)` | Named constant, as in `LED_PIN` | Use a constant. The number appears in one place. |
| Level values | `HIGH` and `LOW` | `1` and `0` | Use `HIGH` and `LOW`. They are clearer. |
| Where to call `pinMode()` | `setup()` | `loop()` | Use `setup()`. It needs to run only once. |
| Toggle method | Explicit writes | `!digitalRead()` | Use explicit writes until you are comfortable with the shorter form. |
Speed and cost
digitalWrite() is convenient but not the fastest option. On an AVR board it does a table lookup, checks whether the pin has PWM active, and disables interrupts briefly while it changes the register. A call takes a few microseconds, which is irrelevant for a blink. It matters only when you generate signals in the hundreds of kilohertz. For those cases, boards offer direct port manipulation. That is beyond this chapter, and a blink never needs it.
Exercise
A sketch calls pinMode(8, OUTPUT) in setup(), then loop() calls digitalWrite(8, HIGH), delay(250), digitalWrite(8, LOW) and delay(250). The LED is correctly wired in series with a resistor from pin 8 to ground, yet it stays dark. Name two causes related to the code, and say how a sketch that omitted pinMode() would behave differently from one that wrongly set the mode to INPUT.
Show answer
Two code-related causes are using a different pin number in the code than the one the LED is wired to, and a wrong or missing mode, such as pinMode(8, INPUT) or a mistyped constant. Omitting pinMode() and setting INPUT give the same result, because every pin starts as an input after reset. In both cases digitalWrite(HIGH) only enables the weak internal pull-up, so the LED stays dark or glows faintly. Setting OUTPUT is what makes the pin drive the LED at full strength.
Exercise
Why is it a good idea to write const uint8t LEDPIN = 8; instead of writing 8 in each call to pinMode() and digitalWrite()?
Show answer
The pin number then appears in exactly one place. To move the LED to another pin you change one line, and there is no risk of updating some calls and missing others. The name LED_PIN also tells a reader what the number means.