1 PWM — faking analog with fast switching
PWM (Pulse-Width Modulation) is how a digital pin pretends to be analog. The pin switches HIGH and LOW very fast — the fraction of time it stays HIGH is the duty cycle. A 50 % duty cycle makes an LED glow at half brightness; 100 % is fully on.
On the Uno R3, only the pins marked ~ can do PWM: 3, 5, 6, 9, 10, 11. The call analogWrite(pin, value) sets the duty cycle — value runs from 0 (always LOW) to 255 (always HIGH). You do not need to call pinMode first, though it doesn't hurt.
Path for this lesson: pin 9 → 220 Ω → LED anode → LED cathode → GND. Pin 9 is a PWM pin (~9), so we can dim the LED with analogWrite(9, 128) for roughly half brightness.
void setup() {
pinMode(9, OUTPUT); // pin 9 is a PWM (~) pin
}
void loop() {
analogWrite(9, 0); // off
delay(500);
analogWrite(9, 64); // ~25 % brightness
delay(500);
analogWrite(9, 128); // ~50 % brightness
delay(500);
analogWrite(9, 255); // fully on
delay(500);
}