RTC
在本章中,我们将学习 Luckfox Aura RTC 的时间读写。
1. RTC
RTC(Real‑Time Clock,实时时钟)是嵌入式系统、微控制器中专用的硬件计时模块。该模块一般搭载独立后备电源(常见为纽扣电池),当设备主电源掉电断开后,依然可以独立持续运行、维持日期与时间计数。 凭借掉电保时的特性,RTC 可为设备提供稳定可靠的时间基准,广泛应用于日志数据打时间戳、定时唤醒、系统时钟同步、定时任务调度等对实时性有要求的业务场景。
2. RTC 测试(Shell)
2.1 查看 RTC 设备
查看 RTC 设备节点和驱动信息:
ls -l /dev/rtc*
cat /proc/driver/rtc
dmesg | grep -i rtc
2.2 读写 RTC
Linux 系统中内置了 hwclock 工具,用于便捷地读取 RTC 硬件时钟提供的当前时间和日期。只需执行如下命令,即可展示 RTC 上的精确时间。
-
读取 RTC 时间:
hwclock --show指定 RTC 设备:
hwclock -f /dev/rtc0 --show -
设置 RTC 时间:
date -s "2026-09-02 12:00:00" #设置系统时间hwclock -f /dev/rtc0 --systohc #将系统时间写入 RTC -
从 RTC 恢复系统时间:
hwclock -f /dev/rtc0 --hctosys
3. 读写 RTC(Python 程序)
-
完整代码:
#!/usr/bin/env python3import subprocessdef get_rtc_time():try:result = subprocess.run(["hwclock", "-r"],capture_output=True,text=True,check=True)return result.stdout.strip()except subprocess.CalledProcessError as e:print(f"Error in get_rtc_time: {e.stderr}")return Nonedef set_rtc_from_system():try:subprocess.run(["hwclock", "-w"],check=True)print("RTC time set successfully.")except subprocess.CalledProcessError as e:print(f"Error in set_rtc_time: {e.stderr}")if __name__ == "__main__":rtc_time = get_rtc_time()if rtc_time:print(f"RTC time: {rtc_time}")set_rtc_from_system() -
读取 RTC 时间:
get_rtc_time()使用hwclock -r读取 RTC 时间。def get_rtc_time():try:result = subprocess.run(["hwclock", "-r"],capture_output=True,text=True,check=True)return result.stdout.strip()except subprocess.CalledProcessError as e:print(f"Error in get_rtc_time: {e.stderr}")return None读取成功时返回RTC时间;命令执行失败时输出错误信息并返回
None。 -
将系统时间写入 RTC:
set_rtc_from_system()使用hwclock -w将当前系统时间写入RTC。def set_rtc_from_system():try:subprocess.run(["hwclock", "-w"],check=True)print("RTC time set successfully.")except subprocess.CalledProcessError as e:print(f"Error in set_rtc_time: {e.stderr}") -
主程序:读取并显示RTC时间,然后把当前系统时间写入RTC。
if __name__ == "__main__":rtc_time = get_rtc_time()if rtc_time:print(f"RTC time: {rtc_time}")set_rtc_from_system() -
运行程序:
python3 RTC.py执行结果:
4. 读写 RTC(C 程序)
-
完整代码:
#include <stdio.h>#include <stdlib.h>#include <sys/wait.h>static int command_succeeded(int status){return status != -1 &&WIFEXITED(status) &&WEXITSTATUS(status) == 0;}int get_rtc_time(void){char rtc_time[256];FILE *pipe = popen("hwclock -r", "r");if (pipe == NULL) {perror("Error in get_rtc_time");return -1;}if (fgets(rtc_time, sizeof(rtc_time), pipe) == NULL) {fprintf(stderr, "Error in get_rtc_time: no output\n");pclose(pipe);return -1;}int status = pclose(pipe);if (!command_succeeded(status)) {fprintf(stderr, "Error in get_rtc_time\n");return -1;}printf("RTC time: %s", rtc_time);return 0;}int set_rtc_from_system(void){int status = system("hwclock -w");if (!command_succeeded(status)) {fprintf(stderr, "Error in set_rtc_time\n");return -1;}printf("RTC time set successfully.\n");return 0;}int main(void){if (get_rtc_time() < 0)return EXIT_FAILURE;if (set_rtc_from_system() < 0)return EXIT_FAILURE;return EXIT_SUCCESS;} -
读取 RTC 时间:
get_rtc_time()通过popen()执行hwclock -r,读取并输出RTC时间。FILE *pipe = popen("hwclock -r", "r");fgets(rtc_time, sizeof(rtc_time), pipe);printf("RTC time: %s", rtc_time); -
将系统时间写入 RTC:
set_rtc_from_system()通过system()执行hwclock -w。int status = system("hwclock -w"); -
主程序:先读取并显示RTC时间,再把当前系统时间写入RTC。
if (get_rtc_time() < 0)return EXIT_FAILURE;if (set_rtc_from_system() < 0)return EXIT_FAILURE; -
交叉编译:
export PATH=<Luckfox_Aura_SDK>/tools/linux/toolchain/aarch64-rockchip1240-linux-gnu/bin:$PATHaarch64-rockchip1240-linux-gnu-gcc RTC.c -o RTC -
运行程序:
chmod +x RTC./RTC执行结果:
5. 系统校时
网络校时先通过 NTP 服务器校准 Linux 系统时间,再将准确的系统时间写入 RTC,以便在连接后备电池后实现掉电保时。
-
安装网络校时工具:
apt updateapt install ntpsec -
修改时区:
- 打开文件:
vi /etc/profile
- 添加内容:
export TZ=CST-8
- 重新加载配置文件:
source /etc/profile
- 查看当前时区:
date -R
- 打开文件:
-
启动服务并设置开机自启:
systemctl enable --now ntpsecsystemctl status ntpsec -l --no-pagerenable:设置开机自动启动;--now:立即启动服务;-l --no-pager:完整显示状态和日志,避免长行被省略。
-
网络校时:
ntpd -p cn.ntp.org.cn -qn -
将系统时间同步到hwclock:
hwclock --systohc -
查看hwclock:
hwclock -
开机启动时,从hwclock同步到系统时间:
hwclock -u -s