Intro
For the SAM15x15 Arduino compatible board, which uses the SAMD21G, I needed a timer library. Unfortunately, such a library didn't exist, so I have time invested in its development myself.
Without having a sophisticated library, using the Timer/Counter is a complicated task and you have to go into many details such as counter modes, compare/capture channels, prescaler values etc. Here, a proper library makes life easier. I'm lazy, the only thing I want to do is specify the period time and the output pin, and the rest should be figured out by the library.
Download
Download the avdweb_SAMDtimer library from GitHub, you will find here program examples too.
The Adafruit_ZeroTimer library should also be installed.
Using a timer with an output pin
The library is easy to use; the following code generates a square wave of 1Hz to pin 5 of the Arduino Zero:
SAMDtimer mytimer1 = SAMDtimer(3, TC_COUNTER_SIZE_16BIT, 5, 1e6);
Notes
- The maximum period time is 1398080us (0.7Hz).
- The minimum period time is = 1us (1MHz).
- For now, the library has three timers available (number 3, 4, 5), only in 16-bit mode.
- There is no check on the proper parameters values.
- Without specifying the pulse width, it is the half of the period time (duty cycle 50%).
Timer interrupts
A timer can also be used for calling interrupts, without using a timer output pin. To periodically execute an ISR, simply use this code:
SAMDtimer mytimer2 = SAMDtimer(4, myISR, 5e5);
Attaching interrupts to a timer with an output pin
A timer can be used for both calling an interrupt and steering its output pin at the same time. This has to be carried out in two steps: first create a timer with an output pin, and than attach an ISR to it.
Mytimer3.attachInterrupt(myISR);