Sub topic 2
Finding the PWM pins on your board
This chapter assumes you know the structure of setup() and loop(), how to call pinMode() and digitalWrite(), how to wire a breadboard, and Ohm's law at an introductory level.
Finding the PWM pins on your board
Only some digital pins can produce PWM (pulse-width modulation). On an Arduino Uno, these pins are 3, 5, 6, 9, 10, and 11. The board marks each one with a tilde (~) next to its number. Use one of these pins for any output that needs variable brightness.
Check the pinout for your specific board before wiring. An Arduino Mega or Nano may have a different set of PWM pins.
Setting brightness with analogWrite()
analogWrite(pin, value) sets the duty cycle on a PWM pin. The value ranges from 0 to 255. A value of 0 keeps the pin off, 255 keeps it fully on, and values in between set the average output in proportion.
Wire an LED in series with a 220 ohm resistor from pin 9 to GND, then run this sketch:
const uint8_t LED_PIN = 9;
void setup() {
pinMode(LED_PIN, OUTPUT);
analogWrite(LED_PIN, 128); // about half brightness
}
void loop() {
}callout note Call pinMode(LED_PIN, OUTPUT) in setup() so the code states its intent and the pin is configured before use. Ensure the pin number in your code matches a PWM pin on your board.
Fading an LED up and down
Changing the value passed to analogWrite() over time fades the LED. This sketch moves brightness by 5 on each step, reverses direction at 0 and 255, and waits 20 ms between steps.
const uint8_t LED_PIN = 9;
int brightness = 0;
int step = 5;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
analogWrite(LED_PIN, brightness);
if (brightness + step < 0 || brightness + step > 255) {
step = -step;
}
brightness += step;
delay(20);
}diagram mermaid caption: Each pass through loop() writes the current brightness, then picks the next step. alt: Flowchart showing that the loop writes brightness, checks whether the next step would leave the 0 to 255 range, reverses the step if so, adds the step to brightness, waits 20 ms, and repeats. flowchart TD A[Write brightness to pin] --> B{Next step would leave 0 to 255?} B -- Yes --> C[Reverse step direction] B -- No --> D[Keep step] C --> E[Add step to brightness] D --> E E --> F[Wait 20 ms] F --> A
exercise Q: What value should you pass to analogWrite() for 25 percent brightness? A: About 64, because 0.25 × 255 = 63.75, which rounds to 64.
estimate minutes: 20