drivers: rtc: api: Add helper for determining calibration

Add helper function which calculates the required calibration to
1 Hertz from the actual frequency of an RTC. This helper is both
functional and adds to the documentation of the RTC calibration
API.

The rtc.h header now includes zephyr/kernel.h instead of
zephyr/types.h as __ASSERT_NO_MSG is now referenced in the header.

The commit additionally extends the rtc_api_helpers test suite
with a test to validate the conversion function itself.

Signed-off-by: Bjarki Arge Andreasen <bjarki@arge-andreasen.me>
This commit is contained in:
Bjarki Arge Andreasen 2024-06-10 20:21:08 +02:00 committed by Anas Nashif
parent 724762facd
commit 1fc26b8974
3 changed files with 68 additions and 3 deletions

View file

@ -22,7 +22,7 @@
* @{
*/
#include <zephyr/types.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <errno.h>
@ -459,6 +459,8 @@ static inline int z_impl_rtc_update_set_callback(const struct device *dev,
* the RTC clock, a negative value will decrease the
* frequency of the RTC clock.
*
* @see rtc_calibration_from_frequency()
*
* @param dev Device instance
* @param calibration Calibration to set in parts per billion
*
@ -527,6 +529,20 @@ static inline struct tm *rtc_time_to_tm(struct rtc_time *timeptr)
return (struct tm *)timeptr;
}
/**
* @brief Determine required calibration to 1 Hertz from frequency.
*
* @param frequency Frequency of the RTC in nano Hertz
*
* @return The required calibration in parts per billion
*/
static inline int32_t rtc_calibration_from_frequency(uint32_t frequency)
{
__ASSERT_NO_MSG(frequency > 0);
return (int32_t)((1000000000000000000LL / frequency) - 1000000000);
}
/**
* @}
*/

View file

@ -10,6 +10,5 @@ project(rtc_api)
target_sources(app PRIVATE
src/main.c
src/test_rtc_time_to_tm.c
src/test_rtc_calibration_from_frequency.c
)
target_include_directories(app PRIVATE inc)

View file

@ -0,0 +1,50 @@
/*
* Copyright 2022 Bjarki Arge Andreasen
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/ztest.h>
#include <zephyr/drivers/rtc.h>
struct test_sample {
uint32_t frequency;
int32_t calibration;
};
static const struct test_sample test_samples[] = {
{
.frequency = 1000000000,
.calibration = 0,
},
{
.frequency = 1000000001,
.calibration = -1,
},
{
.frequency = 999999999,
.calibration = 1,
},
{
.frequency = 2000000000,
.calibration = -500000000,
},
{
.frequency = 500000000,
.calibration = 1000000000,
},
};
ZTEST(rtc_api_helpers, test_validate_calibration_from_frequency)
{
uint32_t frequency;
int32_t calibration;
int32_t result;
ARRAY_FOR_EACH(test_samples, i) {
frequency = test_samples[i].frequency;
calibration = test_samples[i].calibration;
result = rtc_calibration_from_frequency(frequency);
zassert_equal(result, calibration);
}
}