Unable to get the timer working

439 views Asked by At

I have written simple timer program for Atmega328 in normal mode. But I am unable to flash the LED if I compile the code in Atmel Studio 6.2. But same code works perfect if I compile in arduino IDE. I have given the code for Arduino as well as Atmel Studio below. There seems to be small issue somewhere. Is there any issue with F_CPU value?

    // Code compiled using Atmel Studio:
    #include <avr/io.h>
    #include <avr/interrupt.h>
    #define F_CPU 16000000
    unsigned char x=0;

    ISR(TIMER1_OVF_vect) {
        x=!x;
    }

    void setup() {
        DDRB=0x01;
        TIMSK1=0x01; // enabled global and timer overflow interrupt;
        TCCR1A = 0x00; // normal operation page 148 (mode0);
        TCNT1=0x0000; // 16bit counter register
        TCCR1B = 0x04; // start timer/ set clock
    };


    int main (void) 
    {
        setup();
        while(1)
        {
            PORTB= x;
        }
        return(0);
    }

Code written with Arduino IDE:

#define LED 8
boolean x=false;

ISR(TIMER1_OVF_vect) {
x=!x;
}

void setup() {
pinMode(LED, OUTPUT);
TIMSK1=0x01; // enabled global and timer overflow interrupt;
TCCR1A = 0x00; // normal operation page 148 (mode0);
TCNT1=0x0000; // 16bit counter register
TCCR1B = 0x04; // start timer/ set clock
};

void loop() {
PORTB= x;
}
1

There are 1 answers

0
Kevin Brown-Silva On BEST ANSWER

When working with interrupts, you need to enable both the global interrupts (in the timer register) and the local interrupts (in the status registers) in order for interrupt vectors to trigger.

This can be done by calling sei() (set enable interrupts) when you are ready to receive local interrupts. Typically you want to do this after you set up the global interrupts, near the end of you setup method.

I suspect that the interrupts are automatically enabled when working with the Arduino IDE.