AVR Tutorial – Experiment 5

Experiment 5

LED toggle with Timer

Objective – Toggle the LED every second using Timer interrupt.

Pre-Requisites – AVR Motherboard, Mini USB cable, 12V DC Adapter, Software Setup (as described in introduction)

Theory – Generating precise delay or time duration using a microcontroller can be one of the most critical application. A special hardware module, timer is used for this purpose. Timer module count on each tick of microcontroller clock or the source clock. Timer module have various registers assigned to it, which can be used to set the mode of counting, the value up to which the module will count. By setting a particular count value precise delay can be generated, this method will be used to generate delay if 1second as per the requirement. Required timer module registers can be obtained from AVR datasheet.

The hardware connections are discussed in connection/schematic part.


Connections :-
Nano <–> MV1

D4(PD4) <–> LED


#include <avr/io.h>
#include <avr/interrupt.h>

#define LED PD4

ISR (TIMER1_OVF_vect)    // Timer1 ISR
    PORTD ^= (1 << LED);
    TCNT1 = 49916;   // for 1 sec at 16 MHz

int main()
    DDRD = (0x01 << LED);     //Configure the PORTD4 as output

    TCNT1 = 49916;   // for 1 sec at 16 MHz

    TCCR1A = 0x00;
    TCCR1B = (1<<CS10) | (1<<CS12);;  // Timer mode with 1024 prescler
    TIMSK1 = (1 << TOIE1) ;   // Enable timer1 overflow interrupt(TOIE1)
    sei();        // Enable global interrupts by setting global interrupt enable bit in SREG