Sub topic 1
Why a Digital Pin Can't Output a Steady In-Between Voltage
Prerequisites
This chapter assumes you can write a basic Arduino sketch with setup() and loop(), call pinMode() and digitalWrite(), wire a breadboard, and apply Ohm's law (V = I × R) at an introductory level.
Digital Outputs Have Two States
A digital pin is either HIGH or LOW. On a 5 V Arduino Uno, HIGH means about 5 V and LOW means about 0 V. digitalWrite() produces nothing in between. Internally, the pin acts as a switch that connects it to either 5 V or ground.
This matters when you want a dimmer LED. Driving the pin at a steady 2.5 V would give half brightness, but the Uno has no pin that holds 2.5 V. Pulse-width modulation (PWM) solves this. It switches the pin fully on and fully off so quickly that the LED responds to the average.
PWM Basics: Period and Duty Cycle
A PWM signal repeats a cycle called the period. On most Uno pins, analogWrite() produces a period of about 2 ms, or roughly 490 Hz.
The duty cycle is the fraction of each period the signal spends HIGH. A 25% duty cycle is HIGH for a quarter of the period and LOW for the rest.
analogWrite() accepts a value from 0 to 255. A value of 0 gives a 0% duty cycle, 255 gives 100%, and 128 gives about 50%.
From Duty Cycle to Average Voltage and Brightness
The average voltage equals the duty cycle multiplied by the HIGH voltage:
Vavg = duty cycle × 5 V
| analogWrite value | Duty cycle | Average voltage |
|---|---|---|
| 0 | 0% | 0.0 V |
| 64 | 25% | 1.25 V |
| 128 | 50% | 2.5 V |
| 191 | 75% | 3.7 V |
| 255 | 100% | 5.0 V |
The LED cannot follow each switch, and your eye cannot see flicker at 490 Hz, so the LED appears to glow at the average.
Wiring an LED with a Current-Limiting Resistor
A red LED has a forward voltage of about 2 V. Above that voltage, its current rises steeply, so it needs a series resistor to limit current.
Wire the circuit as follows: pin 9, then a 220 Ω resistor, then the LED's long leg (anode), then the short leg (cathode), then GND.
The resistor math is (5 V − 2 V) / 0.02 A = 150 Ω for 20 mA. A 220 Ω resistor gives about 14 mA, which is safe and still bright.
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
analogWrite(9, 128); // about 50% duty cycle, about 2.5 V average
}Exercise
What duty cycle and average voltage does analogWrite(9, 64) produce?
Show answer
64 / 255 is about 25%, so the average voltage is about 0.25 × 5 V = 1.25 V.