跳到主要内容

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 上的精确时间。

  1. 读取 RTC 时间:

    hwclock --show

    指定 RTC 设备:

    hwclock -f /dev/rtc0 --show
  2. 设置 RTC 时间:

    date -s "2026-09-02 12:00:00" #设置系统时间
    hwclock -f /dev/rtc0 --systohc #将系统时间写入 RTC
  3. 从 RTC 恢复系统时间:

    hwclock -f /dev/rtc0 --hctosys

3. 读写 RTC(Python 程序)​

  1. 完整代码:


    #!/usr/bin/env python3
    import subprocess

    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

    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}")

    if __name__ == "__main__":
    rtc_time = get_rtc_time()
    if rtc_time:
    print(f"RTC time: {rtc_time}")
    set_rtc_from_system()

  2. 读取 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。

  3. 将系统时间写入 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}")
  4. 主程序:读取并显示RTC时间,然后把当前系统时间写入RTC。

    if __name__ == "__main__":
    rtc_time = get_rtc_time()
    if rtc_time:
    print(f"RTC time: {rtc_time}")
    set_rtc_from_system()
  5. 运行程序:

    python3 RTC.py

    执行结果:

4. 读写 RTC(C 程序)​

  1. 完整代码:

    #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;
    }
  2. 读取 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);
  3. 将系统时间写入 RTC:set_rtc_from_system() 通过 system() 执行 hwclock -w。

    int status = system("hwclock -w");
  4. 主程序:先读取并显示RTC时间,再把当前系统时间写入RTC。

    if (get_rtc_time() < 0)
    return EXIT_FAILURE;

    if (set_rtc_from_system() < 0)
    return EXIT_FAILURE;
  5. 交叉编译:

    export PATH=<Luckfox_Aura_SDK>/tools/linux/toolchain/aarch64-rockchip1240-linux-gnu/bin:$PATH
    aarch64-rockchip1240-linux-gnu-gcc RTC.c -o RTC
  6. 运行程序:

    chmod +x RTC
    ./RTC

    执行结果:

5. 系统校时​

网络校时先通过 NTP 服务器校准 Linux 系统时间,再将准确的系统时间写入 RTC,以便在连接后备电池后实现掉电保时。

  1. 安装网络校时工具:

    apt update
    apt install ntpsec
  2. 修改时区:

    1. 打开文件:
      vi /etc/profile
    2. 添加内容:
      export TZ=CST-8
    3. 重新加载配置文件:
      source /etc/profile
    4. 查看当前时区:
      date -R
  3. 启动服务并设置开机自启:

    systemctl enable --now ntpsec
    systemctl status ntpsec -l --no-pager
    • enable:设置开机自动启动;
    • --now:立即启动服务;
    • -l --no-pager:完整显示状态和日志,避免长行被省略。
  4. 网络校时:

    ntpd -p cn.ntp.org.cn -qn
  5. 将系统时间同步到hwclock:

    hwclock --systohc
  6. 查看hwclock:

    hwclock
  7. 开机启动时,从hwclock同步到系统时间:

    hwclock -u -s