Look below the sketch
You can skip this page. It shows what analogWrite does inside the chip.
Inside the chip, a counter called Timer1 makes pin 9’s on-off pattern4.
Timer1 counts from 0 up to 255 and back down, over and over2. Pin 9 is on while the count is below OCR1A, and off above it2. So OCR1A sets the share of time the pin is on2.
Set it up with registers
TCCR1A and TCCR1B are registers that pick how Timer1 runs2. In TCCR1A, WGM10 picks the count up to 255 and back. COM1A1 makes the count switch pin 9 that way2. In TCCR1B, CS11 and CS10 set the prescaler to 643. So pin 9 repeats about 16 MHz ÷ (2 × 64 × 255) = 490 times a second2, 5. Arduino’s startup code sets Timer1 up the same way3.
Two ways
l3-fade-arduino.ino// Lesson 3, Arduino version: the knob on A0 sets how
// bright the LED on pin 9 is.
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
int reading = analogRead(A0); // 0 to 1023
analogWrite(9, reading / 4); // 0 to 255
}l3-fade-registers.ino// Lesson 3, register version: Timer1 drives pin 9 (OC1A)
// directly.
void setup() {
DDRB |= (1 << DDB1); // pin 9 (PB1, OC1A) is an output
// Non-inverting PWM on OC1A, 8-bit phase-correct (mode 1)
TCCR1A = (1 << COM1A1) | (1 << WGM10);
// Timer clock = 16 MHz / 64
TCCR1B = (1 << CS11) | (1 << CS10);
}
void loop() {
// Still read with analogRead: this lesson is about PWM
int reading = analogRead(A0);
OCR1A = reading / 4; // duty = OCR1A / 255
}Registers in this lesson (ATmega328P data-space addresses)2
| Register | Address | Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|---|---|
| TCCR1A | 0x80 | COM1A1 | COM1A0 | COM1B1 | COM1B0 | – | – | WGM11 | WGM10 |
| TCCR1B | 0x81 | ICNC1 | ICES1 | – | WGM13 | WGM12 | CS12 | CS11 | CS10 |
| OCR1AL | 0x88 | bit 7 | bit 6 | bit 5 | bit 4 | bit 3 | bit 2 | bit 1 | bit 0 |
Watch it
Switch between the two programs. At 1.25 V, OCR1A is 64, so pin 9 is on about 25% of the time2.
Sources for this page
- Microchip ATmega328P datasheet DS40002061A: Timer1 PWM frequency (p135), extreme values (p136), Tables 16-3 and 16-4 (p141); ADC result (p256)
- ArduinoCore-avr, cores/arduino/wiring.c: Timer1 prescaler 64, 8-bit phase-correct PWM
- ArduinoCore-avr, variants/standard/pins_arduino.h: pin 9 is TIMER1A
- Arduino UNO R3 technical specifications: Clock speed: ATmega328P 16 MHz; DC Current per I/O Pin: 20 mA