AVR-GCC programming – Simple Interrupt for blinking LED on Arduino Uno using pure C

Interrupt is powerfull tool because you can harnest the hardware power of Arduino, for instance to blink multiple LEDs simultaneously.

Supposed you want to blink a LED using interrupt and not a timer, the following example will toggle PIN13 (PB5) which is liknked to the in-built LED using Timer.

 

#include <avr/io.h>

#include <avr/interrupt.h> // notice that we have swapped libraries, from delay to interrupt

 

int main (void) {

DDRB |= (1 << PB5); // set LED pin as output

TCCR1B |= (1 << WGM12); // configure timer1 for CTC mode

TIMSK1 |= (1 << OCIE1A); // enable the CTC interrupt

sei(); // enable global interrupts

OCR1A = 19531; // set the CTC compare value, which will give you a delay for 1 second.

TCCR1B |= ((1 << CS10) | (1 << CS12)); // start the timer at 20MHz/1024

while(1) { // main loop

//This won’t effect Pin 13, so you can blink other LED, toggle other pins, or do other activities.

}

}

 

ISR(TIM1_COMPA_vect) { // this function is called every time the timer reaches the threshold we set

PORTB ^= (1 << PB5); // toggle the LED

}

Compile and flash the above codes. If you do not know how to flash an Arduino. Please follow the previous tutorial.

If you like theories, further reading:

http://exploreembedded.com/wiki/AVR_Timer_programming

http://fabacademy.org/archives/content/tutorials/09_Embedded_Programming/1sec/index.htm

http://www.avr-tutorials.com/interrupts/avr-external-interrupt-c-programming

https://sites.google.com/site/qeewiki/books/avr-guide/timers-on-the-atmega328

(Visited 45 times, 1 visits today)