Sub topic 2
Controlling a pin: pinMode() and digitalWrite()
This chapter covers how a sketch drives a digital output pin. It assumes you can open, verify, and upload a sketch in the Arduino IDE. It also assumes you have a board such as an Arduino Uno connected over USB, and that you know what a pin, a voltage, and an LED are. You should already know that setup() runs once and loop() runs repeatedly. The previous chapter covered that.
What a digital pin does
A digital pin is a connection on the board that your sketch can set to one of two voltage levels. On an Uno the two levels are:
HIGH: about 5 V.LOW: about 0 V (ground).
On boards that run at 3.3 V, such as many ARM-based boards, HIGH is about 3.3 V. Check the board's documentation before wiring parts that expect a specific voltage.
A pin does not decide on its own whether it sends or receives a signal. Your sketch tells it. This is called the pin's mode. The two modes this chapter uses are:
OUTPUT: the pin drives a voltage. Your sketch controls it.INPUT: the pin reads a voltage that something else supplies.
Later chapters read inputs. Here we focus on OUTPUT.
The two functions
Two functions do most of the work.
| Function | Purpose | Typical place to call it |
|---|---|---|
| `pinMode(pin, mode)` | Sets whether a pin is an output or an input | `setup()` |
| `digitalWrite(pin, value)` | Sets an output pin to `HIGH` or `LOW` | `loop()` |
pinMode() takes a pin number and a mode. digitalWrite() takes a pin number and a level. Neither returns a value you need to use.
The usual pattern is to configure each pin once in setup(), then change its level as often as needed in loop(). Configuring a pin repeatedly in loop() is not an error, but it wastes time and hides the structure of the program.
A first complete sketch
The following sketch blinks the LED built into the board. It stores the pin number in a constant, configures it once, and then alternates between HIGH and LOW.
const int ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}Here is what happens, step by step:
- After reset or upload,
setup()runs once.pinMode(ledPin, OUTPUT)makes the pin an output. loop()starts.digitalWrite(ledPin, HIGH)raises the pin to the high level, and the LED turns on.delay(500)pauses the sketch for 500 milliseconds. The pin keeps its level during the pause.digitalWrite(ledPin, LOW)drops the pin to the low level, and the LED turns off.- A second
delay(500)pauses again, thenloop()starts over.
LED_BUILTIN is a name the board definition provides. It maps to the pin of the on-board LED, which is pin 13 on an Uno. Using the name instead of the number keeps the sketch portable across boards whose on-board LED sits on a different pin.
Wiring an external LED
The on-board LED is convenient, but you will usually drive parts on a breadboard. A basic LED circuit has three pieces in series:
- A digital pin (for example pin 3).
- A resistor, commonly 220 Ω to 1 kΩ for a standard LED on 5 V.
- The LED, with its longer leg (the anode) toward the resistor and pin, and its shorter leg (the cathode) toward ground.
The resistor limits current. Without it, the LED can draw more current than it or the pin can handle. Do not skip it.
Swapping the LED's orientation does not damage it in this circuit, but it will not light. If your LED stays dark, flip it before assuming the code is wrong.
To use pin 3 instead of the on-board LED, change one line:
const int ledPin = 3;Everything else in the first sketch stays the same. This is the main reason to name the pin once at the top.
Current limits
A pin is a signal source, not a power supply. On an Uno, a single pin should supply no more than about 20 mA in normal use. The absolute maximum is 40 mA, and the chip as a whole has a total limit as well. A standard LED with a suitable resistor draws roughly 5 to 15 mA, which is fine.
Do not connect motors, relays, or long LED strips directly to a pin. They need more current than a pin can give. Drive them through a transistor or a driver board, and power them from a separate supply that shares a ground with the Arduino.
Several LEDs with a loop
Once you have more than one output, repeating pinMode() and digitalWrite() for each pin gets long and easy to get wrong. An array of pin numbers and a for loop handle this cleanly. The next chapters cover arrays and loops in detail, so treat this as a preview of why the pieces matter.
const byte ledPins[] = {3, 4, 5, 6};
const byte ledCount = sizeof(ledPins) / sizeof(ledPins[0]);
void setup() {
for (byte i = 0; i < ledCount; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
for (byte i = 0; i < ledCount; i++) {
digitalWrite(ledPins[i], HIGH);
delay(200);
digitalWrite(ledPins[i], LOW);
}
}Reading it:
ledPinslists the four pins.sizeof(ledPins) / sizeof(ledPins[0])computes how many entries the array has, soledCountupdates itself when you edit the list.- The first
forloop insetup()sets every listed pin toOUTPUT. - The
forloop inloop()lights each LED for 200 ms in turn, then turns it off. The effect is a light that chases from pin 3 to pin 6 and repeats.
To add a fifth LED, wire it and add its pin number to the array. No other line changes.
What a pin does before pinMode()
A pin starts as an input after a reset. If you call digitalWrite() on a pin you never set to OUTPUT, the call does not drive the pin as you expect. On AVR boards such as the Uno, writing HIGH to an input pin enables its internal pull-up resistor. This produces a very dim glow on an LED rather than full brightness, and it confuses many beginners.
So the symptom "my LED is on but very faint" usually means a missing or misplaced pinMode(pin, OUTPUT).
What a pin remembers
An output pin holds its last level until your sketch changes it. After digitalWrite(ledPin, HIGH), the pin stays high even while the sketch is busy elsewhere or inside delay(). Nothing needs to refresh it.
This has two consequences:
- You do not need to repeat
digitalWrite(ledPin, HIGH)in every pass ofloop()to keep the LED on. Writing the same level again is harmless but unnecessary. - If the sketch stops or resets, the pin returns to its power-on state, which is an input. The LED will go dark.
You can also read back what you last wrote with digitalRead() on an output pin, but it is cleaner to keep the state in a variable. You will do that when you replace delay() with millis() timing in the last chapter.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| LED never lights | LED reversed, wrong pin number, or no ground connection | Flip the LED, check the pin in the sketch against the wiring, and confirm the ground path |
| LED lights faintly | `pinMode()` missing, so the pin is still an input | Add `pinMode(pin, OUTPUT)` in `setup()` |
| LED stays on and never blinks | `LOW` write is missing, or `delay()` is absent so the blink is too fast to see | Check both writes exist and that each is followed by a delay |
| Compile error: `'ledpin' was not declared` | Capitalization mismatch. C++ is case sensitive | Match `ledPin` exactly everywhere |
| Compile error about `HIGH` or `OUTPUT` | Wrong case, such as `high` or `Output` | Use uppercase `HIGH`, `LOW`, `OUTPUT`, `INPUT` |
| Upload fails | Wrong board or port selected in the IDE | Choose the correct board and serial port from the Tools menu |
| Pin 0 or 1 behaves oddly | These are used by the USB serial connection on an Uno | Use pins 2 and above for LEDs |
Using the value names
HIGH and LOW are constants defined by the Arduino core. They stand for the numbers 1 and 0. The following two lines do the same thing on an Uno:
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin, 1);Prefer the names. They tell the reader what you mean, and they are the form every Arduino example uses.
A related point: a bool variable converts to a level neatly. This sketch flips the LED each pass using a variable that holds the current state:
const byte ledPin = LED_BUILTIN;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
delay(500);
}The ! operator flips true to false and back. The expression ledOn ? HIGH : LOW picks HIGH when ledOn is true and LOW otherwise. Operators and conditionals get their own chapters, so for now read it as "set the pin to match the variable."
Design habits worth forming
- Name your pins. A constant like
ledPinmakes the sketch readable and lets you move a part by editing one line. - Configure in
setup(). One place to find every pin's mode. - Keep wiring and code in step. When you move a wire, change the constant in the same sitting.
- Mind the current. If the load is more than a small LED, add a transistor or driver.
- Avoid long
delay()calls when the sketch must do other things. Duringdelay(), the board cannot react to anything else. The final chapter shows themillis()alternative.
Exercises
Exercise
A sketch calls digitalWrite(8, HIGH) in loop() but never calls pinMode(8, OUTPUT). An LED with a resistor is wired from pin 8 to ground, and on an Uno it glows very faintly. Why, and what is the fix?
Show answer
Pin 8 is still in its default INPUT mode. On AVR boards, writing HIGH to an input pin turns on the internal pull-up resistor, which supplies only a tiny current. That is enough for a faint glow but not full brightness. Add pinMode(8, OUTPUT) in setup() so the pin drives a full HIGH level.
Exercise
You have the four-LED chase sketch on pins 3, 4, 5, and 6 and you add a fifth LED on pin 7. Which lines of the sketch must change, and why do the loops need no edits?
Show answer
Only the array initializer changes, to {3, 4, 5, 6, 7}. ledCount is calculated from sizeof(ledPins) / sizeof(ledPins[0]), so it becomes 5 automatically, and both for loops run from 0 to ledCount - 1.
Exercise
A pin drives an LED through a 220 ohm resistor from a 5 V pin. Roughly how much current flows if the LED drops about 2 V? Is it within a safe per-pin limit of about 20 mA?
Show answer
The resistor sees about 5 V - 2 V = 3 V. By Ohm's law, I = 3 V / 220 ohm, which is about 13.6 mA. That is below the 20 mA recommended limit, so it is safe.