Linux下的RTC应用

RTC


RTC基础知识

1. RTC简介

RTC 全称是 Real-Time clock,翻译过来是实时时钟。实时时钟在日常生活中的应用也比较泛,比如电子时钟。实时时钟可以为系统提供精确的实时时间,通常带有电池,可以保证系统断电时还可以正常工作,保证时间不丢失。

2. RTC方案

  1. 方案一:内部RTC。功耗高,成本低
    1725782446132

  2. 方案二:外部RTC。功耗低,成本高
    1725782474127

3. RTC原理

rtc的原理为:通过外部晶振和电容,产生一个稳定的时钟信号,通过计数器来计算时间。

4. RTC子系统框架

1725783126977

5. data 和 hwclock 命令

Linux下有两个时间,一个是系统时间,一个是RTC时间

  • 系统时间:是Linux系统启动后,通过系统时钟来计算的时间,系统时钟是CPU内部的时钟,系统启动后,系统时间会从RTC时间中获取,然后通过系统时钟来计算系统时间。

  • RTC时间:是RTC模块的时间,RTC模块是独立于CPU的时钟模块,RTC模块的时间是独立的,不受系统启动的影响。

  • data命令:用于查看系统时间

  • hwclock命令:用于查看RTC时间

6. RTC时间同步

系统时间与RTC时间同步,可以保证系统断电后,系统时间不丢失。

7. 在应用程序中操作RTC

在应用程序中操作RTC,需要使用Linux系统提供的接口,如rtc_set_time和rtc_get_time等。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>
int main(int argc,char** argv){
    int fd;
    fd = open("/dev/rtc",O_RDONLY);
    if(fd < 0){
        printf("Error opening rtc\n");
        exit(1);
    }
    struct rtc_time rtc;
    //读时间
    int ret = ioctl(fd,RTC_RD_TIME,&rtc);
    if(ret < 0){
        printf("Error reading rtc\n");
        exit(1);
    }
    printf("RTC time: %d-%d-%d %d:%d:%d\n",rtc.tm_year+1900,rtc.tm_mon+1,rtc.tm_mday,rtc.tm_hour,rtc.tm_min,rtc.tm_sec);
    //设置时间
    rtc.tm_year = 2024-1900;
    rtc.tm_mon = 9-1;
    rtc.tm_mday = 8;
    rtc.tm_hour = 16;
    rtc.tm_min = 30;
    rtc.tm_sec = 0;
    ret = ioctl(fd,RTC_SET_TIME,&rtc);
    if(ret < 0){
        printf("Error setting rtc\n");
        exit(1);
    }

    close(fd);
    return 0;
}
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想和我重名?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值