Sunday, August 24, 2014

Arduino Basic Tutorial (timer interrupt) #3

Atmega328p's got three timers two 8 bit and one 16 bit . This means the timer value can get upto 255 and 65535 for 8 bit and 16 bit timer respectively. We can use this for the generation of the interrupt or many other time related jobs. ..
Here we are using this to toggle the led of arduino.
Since this is basic tutorial we are only using the library file for the timer interrupt which is available at http://playground.arduino.cc/code/timer1


#include <TimerOne.h>//this includes the timer libaray

void setup()
{
  // Initialize the digital pin as an output.
  // Pin 13 has an LED connected on most Arduino boards
  pinMode(13, OUTPUT);  

  Timer1.initialize(100000); // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
}

void loop()
{
  // Main code loop
  // TODO: Put your regular (non-ISR) logic here
}

/// --------------------------
/// Custom ISR Timer Routine
/// --------------------------
void timerIsr()
{
    // Toggle LED
    digitalWrite( 13, digitalRead( 13 ) ^ 1 );
}

No comments:

Post a Comment