Sub topic 2
Controlling a Pin: `pinMode()` and `digitalWrite()`
This chapter assumes you can open, verify, and upload an Arduino sketch in the Arduino IDE. You should also know what a digital pin, voltage, LED, and resistor are. The examples use an Arduino Uno or a compatible board.
A digital pin has a small set of possible states. As an output, it can drive a voltage level that represents HIGH or LOW. Use pinMode() to configure the pin before using digitalWrite() to set its state.
Configure the pin with `pinMode()`
The basic form is:
pinMode(pin, mode);The pin argument identifies the pin number. The mode argument tells the Arduino how the pin will be used.
| Mode | Meaning |
|---|---|
| `OUTPUT` | The Arduino drives the pin HIGH or LOW. |
| `INPUT` | The pin reads an external signal. |
| `INPUT_PULLUP` | The pin reads an input and enables an internal pull-up resistor. |
For an LED that the Arduino controls, use OUTPUT. Put this configuration in setup(), because setup() runs once after reset or power-up.
Set the output with `digitalWrite()`
The basic form is:
digitalWrite(pin, value);For an output pin, HIGH turns the output voltage on and LOW turns it off. On a typical Uno, HIGH is about 5 volts and LOW is about 0 volts. The exact voltage depends on the board.
This sketch blinks the board's built-in LED:
const byte ledPin = LED_BUILTIN;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
}LED_BUILTIN is a board-specific constant supplied by the Arduino environment. It avoids hard-coding a board's built-in LED pin. const means the pin value should not change while the program runs.
The loop() function runs repeatedly. Each pass turns the LED on, waits 500 milliseconds, turns it off, and waits again. The delay() call pauses the whole program. Later, you can replace it with millis() timing when the sketch must perform other work during the pause.
Connect an external LED safely
For an external LED, connect the pin through a current-limiting resistor. A common arrangement is:
- Arduino digital pin 3 → resistor → LED anode, the longer leg
- LED cathode, the shorter leg → Arduino
GND
Then change the constant:
const byte ledPin = 3;The resistor limits current. Do not connect an LED directly between an output pin and ground. Excessive current can damage the LED, the board, or both.
The LED circuit is active-high: HIGH supplies voltage to the anode, so the LED lights. Some modules are active-low. For those, LOW may turn the device on and HIGH may turn it off. Check the module's wiring and documentation instead of assuming that HIGH always means “on.”
Exercise
What are the two required changes when moving the blinking example from the built-in LED to an external LED connected to pin 3?
Show answer
Set ledPin to 3 and connect the external LED through a current-limiting resistor, with its cathode connected to GND.