使用RTC实时时钟

8 篇文章 0 订阅
8 篇文章 1 订阅

向rtc设备设置一个周期时间,在循环中每次时间到达时调用。需要管理员权限运行。

#include <stdio.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    unsigned long i = 0;
    unsigned long data = 0;
    //int retval = 0;
    int fd = open("/dev/rtc", O_RDONLY);	//打开RTC

    if (fd < 0)
    {
        perror("open");
        exit(errno);
    }

    //set the freq
    if (ioctl(fd, RTC_IRQP_SET, 1) < 0)	//RTC_IRQP_SET 设定当前周期性中断的频率
    {
        perror("ioctl(RTC_IRQP_SET)");
        close(fd);
        exit(errno);
    }

    //enable periodic interrupts
    if (ioctl(fd, RTC_PIE_ON, 0) < 0)       //打开周期性中断
    {
        perror("ioctl(RTC_PIE_ON)");
        close(fd);
        exit(errno);
    }
    struct timeval tvstart, tvend;

    for (i=0; i<50; i++)
    {
        gettimeofday(&tvstart, 0);
        int res = read(fd, &data, sizeof(unsigned long));   //读取rtc设备

        if (res < 0)
        {
            perror("read");
            close(fd);
            exit(errno);
        }

        gettimeofday(&tvend, 0);
        printf("timer %lld\n", (tvend.tv_sec - tvstart.tv_sec)*1000000LL+(tvend.tv_usec - tvstart.tv_usec));
    }
    //disable periodic interrupts
    ioctl(fd, RTC_PIE_OFF, 0);              //关闭周期性中断
    close(fd);
    return 0;
}

int FREQ = 2048;
ioctl(g_fd, RTC_IRQP_SET, FREQ) ;
频率是2048,网上说频率可用范围是2~8192,一定要是2的n次方, 但是在试验时,1,3,5等值也可以。经测试,1-8192之间的值都可以.频率代表一秒中可以执行多少次,如2048表示1秒钟执行2048次

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值