Hey guys,
I know there've been hundreads of topics regarding this but I've spent a lot of time already and have no idea what's wrong. My goal is to run timer2 on my arduino uno (without using arduino ide) every second and use interrupt to do something. I went through so many articles, copied the code from different sources, I keep looking at the documentation but it still doesn't work. The problem is that the program stops working and when I check the serial port for messages, the only one I get is the first one - "cli". If I remove line
TIMSK2 = (1 << OCIE2A);
the program runs successfuly and the built in diode changes its state every second (see while loop). The timer is not running then, obviously. Here's the code, maybe you'll spot something...
#define UART_BAUD_RATE 9600 #define F_CPU 16000000UL #include <util/delay.h> #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "uart.h" ISR(TIMER2_COMPA_vect) { uart_puts("Hello, World!\n"); } void initTimer2() { cli(); uart_puts("cli\n"); TCNT2 = 0; // set counter to 0 uart_puts("counter = 0\n"); TCCR2A |= (1 << WGM21); // ctcmode uart_puts("ctcmode\n"); TIMSK2 = (1 << OCIE2A); // enable interrupt on match uart_puts("interrupt on match\n"); OCR2A = 15624; // set ocr2a to match value 15625 uart_puts("max value\n"); TCCR2B |= ((1 << CS20) | (1 << CS21) | (1 << CS22)); // set prescaler to 1024 uart_puts("prescaler\n"); sei(); uart_puts("sei\n"); } int main(void) { DDRB = 0xFF; uart_init(UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU)); initTimer2(); while (1) { PORTB = (1 << PORTB5); _delay_ms(1000); PORTB = (0 << PORTB5); _delay_ms(1000); } }