In this use case, the RTC is set up in count mode.
The example configures the RTC in 16-bit mode, with continuous updates to the COUNT register, together with a set compare register value. Every 2000ms a LED on the board is toggled.
Prerequisites
The Generic Clock Generator for the RTC should be configured and enabled; if you are using the System Clock driver, this may be done via conf_clocks.h
.
Clocks and Oscillators
The conf_clock.h
file needs to be changed with the different values to configure the clocks and oscillators for the module according to the used device.
For example, the following oscillator settings are needed for SAMD21:
# define CONF_CLOCK_OSC32K_ENABLE true
# define CONF_CLOCK_OSC32K_STARTUP_TIME SYSTEM_OSC32K_STARTUP_130
# define CONF_CLOCK_OSC32K_ENABLE_1KHZ_OUTPUT true
# define CONF_CLOCK_OSC32K_ENABLE_32KHZ_OUTPUT true
# define CONF_CLOCK_OSC32K_ON_DEMAND true
# define CONF_CLOCK_OSC32K_RUN_IN_STANDBY false
The following generic clock settings are needed for SAMD21:
# define CONF_CLOCK_GCLK_2_ENABLE true
# define CONF_CLOCK_GCLK_2_RUN_IN_STANDBY false
# define CONF_CLOCK_GCLK_2_CLOCK_SOURCE SYSTEM_CLOCK_SOURCE_OSC32K
# define CONF_CLOCK_GCLK_2_PRESCALER 32
# define CONF_CLOCK_GCLK_2_OUTPUT_ENABLE false
Setup
Initialization Code
Create an rtc_module struct and add to the main application source file, outside of any functions:
Copy-paste the following setup code to your applications main()
:
{
#ifdef FEATURE_RTC_CONTINUOUSLY_UPDATED
config_rtc_count.continuously_update = true;
#endif
config_rtc_count.compare_values[0] = 1000;
}
Add to Main
Add the following to your main()
.
Workflow
- Create an RTC configuration structure to hold the desired RTC driver settings.
- Fill the configuration structure with the default driver configuration.
- Note
- This should always be performed before using the configuration struct to ensure that all values are initialized to known default settings.
- Alter the RTC driver configuration to run in 16-bit counting mode, with continuous counter register updates.
#ifdef FEATURE_RTC_CONTINUOUSLY_UPDATED
config_rtc_count.continuously_update = true;
#endif
config_rtc_count.compare_values[0] = 1000;
- Initialize the RTC module.
- Enable the RTC module, so that it may begin counting.
Implementation
Code used to implement the initialized module.
Code
Add after initialization in main().
Workflow
- Set RTC period to 2000ms (two seconds) so that it will overflow and reset back to zero every two seconds.
- Enter an infinite loop to poll the RTC driver to check when a comparison match occurs.
- Check if the RTC driver has found a match on compare channel 0 against the current RTC count value.
- Once a compare match occurs, perform the desired user action.
- Clear the compare match, so that future matches may occur.