【问题标题】:Can i2cdump/i2cget be used in a C executable?i2cdump/i2cget 可以在 C 可执行文件中使用吗?
【发布时间】:2020-12-31 15:16:51
【问题描述】:

我有一个脚本可以创建一个文件,并根据系统时间生成一个时间戳,并通过该时间戳命名文件。

// Creating file name. Time stamp included. File will be sent to USB.
    
    FILE * fp;
    
    time_t rawtime;             // Generating time stamp
    char buffer[255];
    time(&rawtime);
    sprintf(buffer, "/mnt/usb/DAT_%s.txt", ctime(&rawtime));

但是,我想通过 I2C 从 RTC 生成时间戳。从终端,我可以轻松地从 RTC 读取时间:

$ i2cdump -y -r 0-0xF 1 0x68 b
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f    0123456789abcdef
00: 51 51 21 01 14 01 17 00 00 00 00 00 00 00 1c 88    QQ!????.......??

每个寄存器对应的地方

  • 00h-06h:秒、分、小时、星期几、日期、月份、年份(全部为 BCD)

所以上面的内容是 2017 年 1 月 14 日星期六 21:51:55(我希望如此)。

出于时间戳目的,打印注册表值(未格式化)就足够了。那么我可以在这个脚本中使用 i2cdump 吗?如果是,应该如何实施?我是 C 的新手,所以任何针对新手的建议都值得赞赏!

【问题讨论】:

  • 您可以简单地运行i2cdump 并通过管道man popen 读取其输出。

标签: c linux ubuntu system i2c


【解决方案1】:

您可以使用管道读取像i2cdump 这样的实用程序的输出。例如:

FILE *f = popen ("i2cdump", "r");
// read from f until end of file
pclose (f);

但是,使用内核的内置驱动程序直接从 I2C 总线读取数据并不难。概述:

#include <fcntl.h>   
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <sys/ioctl.h>

int f = open ("/dev/i2c-0", O_RDONLY); // Or whatever your device is
ioctl (f, I2C_SLAVE, address);
read (....);
close (f);

当然,还有更多内容,但这就是要点。在代码中实现 I2C 操作并不是那么困难,消除了对外部实用程序的依赖,并且操作会稍微快一些。

【讨论】:

  • 为什么?!有libi2c。 -1.
  • 为什么要在您的应用程序中引入另一个依赖项,您可能必须从源代码为嵌入式平台构建它,并且您必须学习如何使用它来完成一项几乎非常简单的工作在代码中做?
  • 如果可以在裸机上运行任何东西,为什么还要拥有操作系统?
猜你喜欢
  • 2014-02-17
  • 2011-04-23
  • 1970-01-01
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2018-06-15
  • 1970-01-01
相关资源
最近更新 更多