Arduino Due counter

Sorry for the long delay, but I used your code and wrote a working example for time measurement between two input signals for the DUO. It includes a mostly copied version from your comment and has some comments and parts added:

https://github.com/petl/ArduinoDueCounter

jpedrego:
Hi all.

I have modified the code from Magician. If my understanding of what is going on is correct, the code below should put into the variable “CaptureCountA”, the value of the clock (MCK/2 = 42MHz?) on the “rising edge of the trigger input”, to quote the documentation.

Using a wavefunction generator, I am generating a square waveform of 0V-3V, with a 100us period. Such signal is send to the AnalogIn7 of the Arduino Due

When using the code below, I would have expected to get values spaced of 4200 (100us * 42MHz), however, I get non-sense (see the attached file, copied from the serial monitor).

Therefore, I am missing something… Any idea?

volatile uint32_t CaptureCountA, TimerCount;

volatile boolean CaptureFlag;
const int max_i = 64;
int i;

void setup() {
 Serial.begin(115200);

PMC->PMC_PCER0 |= PMC_PCER0_PID28;                      // Timer Counter 0 channel 1 IS TC1
 TC0->TC_CHANNEL[1].TC_CCR = TC_CCR_CLKDIS ;             // disable internal clocking while setup regs
 TC0->TC_CHANNEL[1].TC_CMR = TC_CMR_TCCLKS_TIMER_CLOCK1   // capture mode, MCK/2, clk on rising edge                          
                             | TC_CMR_ABETRG              // TIOA is used as the external trigger
                             | TC_CMR_LDRA_RISING ;       // load RA on rising edge of trigger input

TC0->TC_CHANNEL[1].TC_IER |= TC_IER_LDRAS;               // Trigger interruption on Load RA and load RB
 TC0->TC_CHANNEL[1].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN ;// Reset TC counter and enable

NVIC_EnableIRQ(TC1_IRQn);                             // Enable TC1 interrupts
}

void loop() {
   if (i < max_i){
       i+=1;  
       if (CaptureFlag) {
       CaptureFlag = 0;
       printf("\r %d , %d , %d \n", CaptureCountA);
       }
       else {
       Serial.println(TC0->TC_CHANNEL[1].TC_CV);
       }
   }
}
void TC1_Handler() {
 uint32_t status = TC0->TC_CHANNEL[1].TC_SR;       // Read & Save satus register -->Clear status register
 if ((status & TC_SR_LOVRS) == TC_SR_LOVRS) abort();
 if ((status & TC_SR_LDRAS) == TC_SR_LDRAS) {  // If ISR is fired by LDRAS then …
   CaptureCountA = TC0->TC_CHANNEL[1].TC_RA;        // get data from capture register A for TC0 channel 1
 }
 CaptureFlag = 1;                      // set flag indicating a new capture value is present
}