Sub topic 3
PWM pins and analogWrite
This chapter assumes you know voltage, current, and resistance, can read a setup() and loop() sketch, and can follow a breadboard diagram. It covers PWM, logic levels, current limits, safe wiring, shared pin functions, and other boards.
PWM pins and analogWrite
Pulse width modulation (PWM) switches a digital pin fully HIGH and LOW many times per second. The fraction of each cycle spent HIGH is the duty cycle. On the Uno, analogWrite() takes a value from 0 to 255, so 128 gives roughly 50 percent duty and about half brightness on an LED.
Only pins marked with ~ support PWM on the Uno: 3, 5, 6, 9, 10, and 11. Pin 13 does not.
const int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
analogWrite(ledPin, 128); // roughly half brightness
}Logic levels: why 5V and 3.3V matter
The Uno runs at 5V logic, so HIGH means about 5V. A 3.3V board treats HIGH as about 3.3V. Applying 5V to a 3.3V input can damage it. A 3.3V output may also fail to register as HIGH on some 5V inputs. Use a level shifter when you connect the two.
How much current a pin and the board can supply
Each I/O pin is rated for 20 mA recommended and 40 mA absolute maximum. The ATmega328P chip has a total limit of about 200 mA across all pins. Drive LEDs through a resistor, and drive motors or relays through a transistor, not directly from a pin.
Wiring habits that protect the board
- Place a resistor in series with every LED.
- Wire buttons with
INPUT_PULLUPso no floating input is left. - Disconnect power before changing wires.
- Connect the grounds of the Uno and any external sensor together.
Pins with a second job: UART, I2C, and SPI
Several pins serve more than one function.
| Function | Uno pins |
|---|---|
| Serial (UART) | 0 (RX), 1 (TX) |
| I2C | A4 (SDA), A5 (SCL) |
| SPI | 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK) |
Pins 0 and 1 also carry USB serial, so avoid them during an upload. Pin 11 is both PWM and SPI MOSI, so analogWrite() on that pin conflicts with SPI use.
Beyond the Uno
| Board | Logic level | Notes |
|---|---|---|
| Nano | 5V | Same ATmega328P chip, smaller form factor |
| Mega 2560 | 5V | More pins, more PWM and serial ports |
| Leonardo | 5V | ATmega32U4 with native USB, so serial behaves differently |
| Due | 3.3V | Not 5V tolerant |
Check each board's pinout and voltage before reusing Uno wiring.
Exercise
Exercise
Which of pins 2, 7, 9, and 13 on an Uno can output PWM with analogWrite()?
Show answer
Pin 9. It is marked with ~ on the Uno. Pins 2 and 7 have no PWM, and pin 13 is not a PWM pin.