2. RTC 操作指南¶
2.1. 模块介绍¶
RTC(real time clock)硬件时钟,为系统提供与记录时间。若RTC 由电池供电,当处理器处于下电关机或休眠状态时,RTC 仍会继续计数并维护时间信息不丢失。
Linux 内核将 RTC 作为时间与日期维护器,当Linux系统启动时,内核读取RTC时间以初始化系统(软件)时钟达成时间同步。内核在需要时,亦可将时间与日期回写到RTC中。
2.2. 计数时钟频率¶
RTC 的计数时钟采用 32.768KHz 时钟,运行基于一个 32-bit 加法计数器提供秒计数,计数最大时间为 :
2^32秒 = 49710 天 = 136 年
2.3. 操作准备¶
RTC的操作准备如下:
使用SDK发布的kernel
插入模块: insmod cv180x_rtc.ko/ cv181x_rtc.ko
2.4. 使用方式¶
2.4.1. Ioctl控制RTC¶
应用层可以通过 ioctl 控制 RTC,设备节点为/dev/rtc0
使用方式如下:
int ioctl(int fd, ind cmd);
ioctl 指令功能描述
指令 |
描述 |
---|---|
RTC_ALM_READ |
读取闹钟时间 |
RTC_ALM_SET |
设置闹钟时间 |
RTC_RD_TIME |
读取时间与日期 |
RTC_SET_TIME |
读取时间与日期 |
RTC_PIE_ON |
开 RTC 全局中断 |
RTC_PIE_OFF |
关 RTC 全局中断 |
RTC_AIE_ON |
使能 RTC 闹钟中断 |
RTC_AIE_OFF |
禁止 RTC 闹钟中断 |
RTC_UIE_ON |
使能 RTC 更新中断 |
RTC_UIE_OFF |
禁止 RTC 更新中断 |
RTC_IRQP_SET |
设置中断频率 |
2.4.2. ioctl使用范例¶
static const char default_rtc[] = "/dev/rtc0";
struct rtc_time rtc_tm;
int fd;
fd = open(rtc, O_RDONLY);
if (fd == -1) {
perror(rtc);
exit(errno);
}
通过如下命令可获取 RTC 时间:
/* Read the RTC time/date */
retval = ioctl(fd, RTC_RD_TIME, &rtc_tm);
if (retval == -1) {
perror("RTC_RD_TIME ioctl");
exit(errno);
}
fprintf(stderr, "\n\nCurrent RTC date/time is %d-%d-%d, %02d:%02d:%02d.\n",
rtc_tm.tm_mday, rtc_tm.tm_mon + 1, rtc_tm.tm_year + 1900,
rtc_tm.tm_hour, rtc_tm.tm_min, rtc_tm.tm_sec);
通过如下命令可设置RTC时间:
retval = ioctl(fd, RTC_SET_TIME, &rtc_tm);
if (retval == -1) {
perror("RTC_RD_TIME ioctl");
exit(errno);
}
2.4.3. 结构体¶
rtc_time
struct rtc_time {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
tm_mday: 一个月中的日期,取值区间为[1,31]
tm_wday:一个星期的第几天,星期日为 0, 星期一为1, 以此类推
tm_yday:一年中的第几天,取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推
tm_isdst:判断是否为夏令时, 1 是夏令时; 0 非夏令时