Showing posts with label Interrupt. Show all posts
Showing posts with label Interrupt. Show all posts

Monday, February 3, 2014

Example of Timer Interrupt on Arduino

It's example to use Timer Interrupt of Arduino Esplora, to toggle RGB LED when timer interrupt reached.



testTimer.ino
#include <Esplora.h>

volatile boolean ledon;
volatile unsigned long lasttime;
volatile unsigned long now;
 
void setup() {
    ledon = true;
    Esplora.writeRGB(100, 100, 100);

    lasttime = millis();
    
    // initialize Timer1
    noInterrupts(); // disable all interrupts
    TCCR1A = 0;
    TCCR1B = 0;

    TCNT1 = 34286; // preload timer 65536-16MHz/256/2Hz
    TCCR1B |= (1 << CS12); // 256 prescaler
    TIMSK1 |= (1 << TOIE1); // enable timer overflow interrupt
    interrupts(); // enable all interrupts
    
}
 
void loop() {
 
}

ISR(TIMER1_OVF_vect)
{
    TCNT1 = 34286; // preload timer
    
    ledon = !ledon;
    if(ledon){
        Esplora.writeRGB(0, 0, 1);
    }else{
        Esplora.writeRGB(0, 0, 0);
    }
    
    now = millis();
    Serial.println(now - lasttime);
    lasttime = now;
}

reference: http://blog.oscarliang.net/arduino-timer-and-interrupt-tutorial/