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


4 comments:

  1. amazing thank you i was looking for this for some time
    it helped me a lot

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Hi Andr.oid Eric ;

    thanks a lot for this pack of code for timer..i really needed this badly...and it run perfectly.
    But it would be nice if you can just clear my thooughts on how u have set the value of RA and RC and why u have choosen two sets of registers for this(RC and RA, why nnot RB).I mean what compare match is going on here for 1 sec timer. I have understood the handler,but i have got struct with calculation for this.

    Thanks in advance...

    ReplyDelete
  4. This code is not accurate past about 2 hz. As an example, disabling all the serial I/O and routing the led toggle to pin 53 with FREQ_1Hz set to 100 gives a measured frequency of about 49.9 Hz. This is no replacement for the PWM function for the 8 bit Arduinos using the TimerOne library.

    ReplyDelete