Showing posts with label Timer. Show all posts
Showing posts with label Timer. 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/

Wednesday, April 10, 2013

Implement Timer Interrupt for Arduino Due

The code implement Timer Interrupt for Arduino Due, to toggle LED every second and send the duration in millisecond to PC via Serial port.

int led = 13;

volatile boolean ledon;
volatile unsigned long lasttime;
volatile unsigned long now;

int FREQ_1Hz = 1;

void TC3_Handler(){
    TC_GetStatus(TC1, 0);
    
    now = millis();
    
    digitalWrite(led, ledon = !ledon);
    
    Serial.println(now - lasttime);
    lasttime = now;
    
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t frequency){
  
    //Enable or disable write protect of PMC registers.
    pmc_set_writeprotect(false);
    //Enable the specified peripheral clock.
    pmc_enable_periph_clk((uint32_t)irq);  
    
    TC_Configure(tc, channel, TC_CMR_WAVE|TC_CMR_WAVSEL_UP_RC|TC_CMR_TCCLKS_TIMER_CLOCK4);
    uint32_t rc = VARIANT_MCK/128/frequency;
    
    TC_SetRA(tc, channel, rc/2);
    TC_SetRC(tc, channel, rc);
    TC_Start(tc, channel);
    
    tc->TC_CHANNEL[channel].TC_IER = TC_IER_CPCS;
    tc->TC_CHANNEL[channel].TC_IDR = ~TC_IER_CPCS;
    NVIC_EnableIRQ(irq);
}

void setup() {
    pinMode(led, OUTPUT);
    Serial.begin(9600);
    startTimer(TC1, 0, TC3_IRQn, FREQ_1Hz);
    lasttime = 0;
}

void loop() {

}

Implement Timer Interrupt for Arduino Due
Implement Timer Interrupt for Arduino Due