/* p5_5.c Toggle LED0 on SAMD21 Xplained Pro using TC5 * * This program uses TC5 to create a delay function that delays * the multiple of milliseconds. * * TC5 is configured to run continuously in 8-bit mode. TC5 counter * clock is derived from 1 MHz main clock. The prescaler divides the * GCLK_TC5 by 4. The TOP count is set to 250-1. The counter * overflows at 1 MHz / 4 / 250 = 1 kHz. * The main function calls the delay for 1000 loops between each * toggle of the LED0. 1000 delay loops of 1 ms gives 1 second delay. * * Tested with Atmel Studio 7 v7.0.1006 and Keil MDK-ARM v5.21a. */ #include "samd21.h" void delayMs(int n); int main (void) { REG_GCLK_CLKCTRL = 0x401C; /* GCLK0 -> TC4/TC5 */ REG_PM_APBCMASK |= 0x00002000; /* enable TC5 Clock in PM */ REG_TC5_CTRLA = 1; /* reset TC5 before configuration */ while (REG_TC5_CTRLA & 1) {} /* wait till out of reset */ REG_TC5_CTRLA = 0x0204; /* prescaler /4, 8-bit mode, NFRQ */ REG_TC5_COUNT8_PER = 250 - 1; /* TOP count value in 8-bit mode */ REG_PORT_DIR1 |= 0x40000000; /* make PB30 output */ while(1) { REG_PORT_OUT1 ^= 0x40000000; /* toggle LED0 */ delayMs(1000); /* make a 1 second delay */ } } /* delay number of milliseconds */ void delayMs(int n) { REG_TC5_COUNT8_COUNT = 0; /* start the first count from 0 */ REG_TC5_INTFLAG = 1; /* clear OVF flag */ REG_TC5_CTRLA |= 2; /* enable TC5 */ for (; n > 0; n--) { while ((REG_TC5_INTFLAG & 1) == 0) {} /* wait until OVF is set */ REG_TC5_INTFLAG = 1; /* clear OVF flag */ } REG_TC5_CTRLA &= ~2; /* disable TC5 */ }