Hello everybody,
I am tinkering with some new board with SAMD21G MCUs on Arduino Zero compatible boards. I am trying to use its internal hardware counter in basic counter mode. I somewhere heard that it could work even in power-save mode but thats not important for now.
I need to count absolutely random logical pulses in speed up to 7000 counts per second (so basic 16bit counter should be fine). I found a lot of resources about Timer/Counter hardware in SAM architecture. I guess that basic mechanics are same in whole SAMxxx family.
Sadly all I found are examples/snippets related to slightly different things:
- generating PWM on LED:
//source: https://www.digikey.com/eewiki/display/microcontroller/Getting+Started+with+the+SAM+D21+Xplained+Pro+without+ASF
#include "sam.h"
#define LED0 PORT_PB30;
void init_TC3();
void enable_interrupts();
// Global error flag for TC3
volatile uint8_t TC3_error = 0;
int main(void)
{
SystemInit(); // Initialize the SAM system
enable_interrupts();
init_TC3();
// Configure LED0 as output
REG_PORT_DIRSET1 = LED0;
while (1)
{
}
}
void init_TC3()
{
/* Configure Timer/Counter 3 as a timer to blink LED0 */
// Configure Clocks
REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID_TCC2_TC3;
REG_PM_APBCMASK |= PM_APBCMASK_TC3; // Enable TC3 bus clock
// Configure TC3 (16 bit counter by default)
REG_TC3_CTRLA |= TC_CTRLA_PRESCALER_DIV8;
// Enable interrupts
REG_TC3_INTENSET = TC_INTENSET_OVF | TC_INTENSET_ERR;
// Enable TC3
REG_TC3_CTRLA |= TC_CTRLA_ENABLE;
while ( TC3->COUNT16.STATUS.bit.SYNCBUSY == 1 ){} // wait for TC3 to be enabled
}
void TC3_Handler()
{
// Overflow interrupt triggered
if ( TC3->COUNT16.INTFLAG.bit.OVF == 1 )
{
REG_PORT_OUTTGL1 = LED0;
REG_TC3_INTFLAG = TC_INTFLAG_OVF;
}
// Error interrupt triggered
else if ( TC3->COUNT16.INTFLAG.bit.ERR == 1 )
{
TC3_error = 1;
REG_TC3_INTFLAG = TC_INTFLAG_ERR;
}
}
void enable_interrupts()
{
NVIC_EnableIRQ( TC3_IRQn );
}
- frequency counter, but this uses capture mode:
GitHub - avandalen/avdweb_FreqPeriodCounter: Smart library with comprehensive functions for counting (multiple) frequencies and period-times. For Arduino Uno and Zero. - this topic on avrfreaks.com is exactly what I need, but snippets are partial and not working:
https://www.avrfreaks.net/forum/samd21-counting-random-pulses
So it seems that I should make the code completely from scratch. Sad is there is no basic draft how to configure everything to work in just simple counting mode.
I also can add some external I2C counter like DS1672, but still it seems to me odd and completely wrong since hardware itself should be able to do it without anything extra.
Can anybody point me to some additional resources or code that could help me? Or at lease some basic outline of sequence of which should be how configured?