RTC是常用外设之一。下面分享如何在rtthread下配置RTC并定时打印时间。
配置
打开env图形配置工具:
保存后在工程上添加一个rtc_demo.c,内容如下。
#include "ch32v20x.h"
#include <rtthread.h>
#include <rtdevice.h>
#define RTC_NAME "rtc"
#define THREAD_PRIORITY 25
#define THREAD_STACK_SIZE 512
#define THREAD_TIMESLICE 5
static rt_thread_t tid1 = RT_NULL;
static void RTC_entry(void *parameter)
{
rt_err_t ret = RT_EOK;
time_t now;
rt_device_t device = RT_NULL;
device = rt_device_find(RTC_NAME);
if (!device)
{
rt_kprintf("find %s failed!", RTC_NAME);
return ;
}
if(rt_device_open(device, 0) != RT_EOK)
{
rt_kprintf("open %s failed!", RTC_NAME);
return ;
}
while (1)
{
now = time(RT_NULL);
rt_kprintf("%s\n", ctime(&now));
rt_thread_mdelay(5000);
}
}
static int rtc_sample(int argc, char *argv[])
{
rt_err_t ret = RT_EOK;
time_t now;
rt_device_t device = RT_NULL;
device = rt_device_find(RTC_NAME);
if (!device)
{
rt_kprintf("find %s failed!", RTC_NAME);
return RT_ERROR;
}
if(rt_device_open(device, 0) != RT_EOK)
{
rt_kprintf("open %s failed!", RTC_NAME);
return RT_ERROR;
}
ret = set_date(2023, 4, 15);
if (ret != RT_EOK)
{
rt_kprintf("set RTC date failed\n");
return ret;
}
ret = set_time(16, 48, 50);
if (ret != RT_EOK)
{
rt_kprintf("set RTC time failed\n");
return ret;
}
tid1 = rt_thread_create("rtc_demo",
RTC_entry, RT_NULL,
THREAD_STACK_SIZE,
THREAD_PRIORITY, THREAD_TIMESLICE);
if (tid1 != RT_NULL)
rt_thread_startup(tid1);
else
rt_kprintf("set RTC time failed\n");
return ret;
}
MSH_CMD_EXPORT(rtc_sample, rtc sample);
编译后,打开串口终端,执行rtc_demo,获取时间,并打印:
0
|
|
|
|