该工具可用于读取i2c 设备上寄存器地址中的值,且寄存器的地址可设定

//可用于读取IC2 设备寄存器中的值
#include <stdio.h>
#include <linux/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>

int main(int argc, char **argv)
{
    struct i2c_rdwr_ioctl_data work_queue;
    unsigned int idx;
    unsigned int fd;
    unsigned int slave_address, reg_address;
    unsigned char val;
    int i;
    int ret;

    if (argc < 4) {
        printf("Usage:\n%s /dev/i2c-x start_addr reg_addr\n", argv[0]);
        return 0;
    }

    fd = open(argv[1], O_RDWR);

    if (!fd) {
        printf("Error on opening the device file\n");
        return 0;
    }
    sscanf(argv[2], "%x", &slave_address);
    sscanf(argv[3], "%x", &reg_address);

    work_queue.nmsgs = 2;
    /* 消息数量 */
    work_queue.msgs = (struct i2c_msg*)malloc(work_queue.nmsgs *sizeof(struct i2c_msg));
    if (NULL == work_queue.msgs) {
        printf("Memory alloc error\n");
        close(fd);
        return 0;
    }

    ioctl(fd, I2C_TIMEOUT, 2);
    /* 设置超时 */
    ioctl(fd, I2C_RETRIES, 1);
    /* 设置重试次数 */

    for (i = reg_address; i < reg_address + 16; i++) {
        val = i;
        (work_queue.msgs[0]).len = 1;
        (work_queue.msgs[0]).addr = slave_address;
        (work_queue.msgs[0]).buf = &val;
        (work_queue.msgs[1]).len = 1;
        (work_queue.msgs[1]).flags = I2C_M_RD;
        (work_queue.msgs[1]).addr = slave_address;
        (work_queue.msgs[1]).buf = &val;
        ret = ioctl(fd, I2C_RDWR, (unsigned long) &work_queue);
        if (ret < 0)
            printf("Error during I2C_RDWR ioctl with error code: %d\n", ret);
        else
            printf("reg:%02x val:%02x\n", i, val);
    }
    close(fd);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值