Home / Learn Chip Programming / Project 1: Blink Pro (Registers and Timers)
Project 1: Blink Pro (Registers and Timers)
Blink LEDs without delay(): direct port registers, a hardware timer in CTC mode, an interrupt and a button.
Theory in plain words
What it is
You build a blinker that never stops the CPU. Timer1 counts clock ticks in hardware and fires an interrupt every half period. The main loop stays free to read a button that changes the speed.
Why we use it
delay() wastes the CPU. Real products use timers and interrupts. This is the first step from Arduino user to chip programmer.
How it works
Set the prescaler and compare value (OCR1A) so that f = F_CPU / (2 x prescaler x (1 + OCR1A)). The ISR toggles the LED pin through the PINB register.
Where it is used
- Status LEDs in every product
- Precise timing without blocking
- Base of PWM, scheduling and RTOS ticks
Equipment
The multimeter checks the LED current and the 5 V rail before you trust the circuit.
Wiring
| From | To | Note |
|---|---|---|
| Uno pin 13 (PB5) | 330 ohm resistor then LED anode | LED long leg is the anode |
| LED cathode | GND | common ground |
| Uno pin 2 | button, other side to GND | use internal pull-up |
| Uno pin 8 (PB0) | 330 ohm then second LED to GND | shows button state |
Live timer calculator and LED
The formula is the same for every AVR timer; only register names change.
Code (AVR C, no Arduino library)
#include <avr/io.h>
#include <avr/interrupt.h>
volatile uint8_t fast = 0;
ISR(TIMER1_COMPA_vect) { PINB = (1 << PB5); } // writing 1 to PINx toggles the pin
static void timer_set(uint16_t ocr) { OCR1A = ocr; TCNT1 = 0; }
int main(void) {
DDRB |= (1 << PB5) | (1 << PB0); // outputs
PORTD |= (1 << PD2); // pull-up on button pin
TCCR1B = (1 << WGM12) | (1 << CS12); // CTC mode, prescaler 256
timer_set(31249); // 1 Hz toggle = 0.5 Hz blink
TIMSK1 = (1 << OCIE1A);
sei();
uint8_t last = 1;
for (;;) {
uint8_t now = (PIND >> PD2) & 1;
if (last && !now) { fast ^= 1; timer_set(fast ? 7811 : 31249); } // falling edge
if (now) PORTB &= ~(1 << PB0); else PORTB |= (1 << PB0);
last = now;
}
}Build steps
- Collect the parts from the list above and check each LED with the multimeter diode test.
- Wire as in the table. Always keep a resistor in series with every LED.
- Install avr-gcc and avrdude (or PlatformIO). Build:
avr-gcc -mmcu=atmega328p -Os main.c -o main.elf. - Flash:
avr-objcopy -O ihex main.elf main.hexthenavrdude -p m328p -c arduino -P /dev/ttyUSB0 -b 115200 -U flash:w:main.hex. - Press the button: the blink speed changes while the main loop keeps running.
Challenges
- Add a second LED on Timer2 blinking at a different rate.
- Make the button cycle through three speeds.
- Replace the LED toggle with PWM on OC1A (pin 9) to fade the LED.
- Measure the real blink period with a logic analyzer.
Quick quiz
1. Why use a timer instead of delay()?
Hardware counts while the CPU does other work.
2. In CTC mode the timer...
Then fires the compare interrupt.