linux设备驱动开发详解 通过O_RDWR IOCTL 读写i2c设备

#include #include #include #include #include #include #include #include #include #include #include #include int main(int argc, char **argv){ struct i2c_rdwr_ioctl_data work_queue; unsi
摘要由CSDN通过智能技术生成
#include <stdio.h>
#include <linux/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.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;
	unsigned int num;

	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);
	if(argc == 4)
	{
		num = 1;
	}
	else
	{
		sscanf(argv[4], "%d", &num);
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在这个示例中,`ioctl` 函数用于对 I2C 设备进行读写操作。 `i2c_fd` 是打开 I2C 设备的文件描述符,可以通过 `open` 函数获得。 `I2C_RDWR` 是一个特定的 ioctl 命令,用于指定对 I2C 设备进行读写操作。 `&data` 是一个指向 `struct i2c_rdwr_ioctl_data` 结构体的指针,用于传递读写数据的相关信息。 `struct i2c_rdwr_ioctl_data` 结构体定义如下: ```c struct i2c_rdwr_ioctl_data { struct i2c_msg *msgs; // 指向一个或多个 i2c_msg 结构体的指针 int nmsgs; // msgs 数组中的元素个数 }; ``` `struct i2c_msg` 结构体定义了一个 I2C 传输的消息: ```c struct i2c_msg { __u16 addr; // 从设备地址 __u16 flags; // 标志位,用于指定读写操作 __u16 len; // 数据长度 __u8 *buf; // 数据缓冲区 }; ``` 通过配置 `struct i2c_rdwr_ioctl_data` 结构体中的 `msgs` 数组,可以同时进行多个 I2C 操作。 以下是一个简单的例子,展示如何使用 `ioctl` 函数进行 I2C 读写操作: ```c #include <linux/i2c-dev.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> int main() { int i2c_fd; struct i2c_rdwr_ioctl_data data; struct i2c_msg msgs[2]; unsigned char buf[2]; // 打开 I2C 设备文件 i2c_fd = open("/dev/i2c-1", O_RDWR); if (i2c_fd < 0) { perror("open"); return -1; } // 设置要写入的数据 buf[0] = 0x12; buf[1] = 0xAB; // 配置 I2C 读写数据信息 msgs[0].addr = 0x50; msgs[0].flags = 0; msgs[0].len = 1; msgs[0].buf = &buf[0]; msgs[1].addr = 0x50; msgs[1].flags = I2C_M_RD; msgs[1].len = 1; msgs[1].buf = &buf[1]; data.msgs = msgs; data.nmsgs = 2; // 发送 I2C 读写命令 if (ioctl(i2c_fd, I2C_RDWR, &data) < 0) { perror("ioctl"); close(i2c_fd); return -1; } // 关闭 I2C 设备文件 close(i2c_fd); return 0; } ``` 以上示例中,通过打开 `/dev/i2c-1` 文件获取 I2C 设备的文件描述符,然后配置 `struct i2c_rdwr_ioctl_data` 结构体中的 `msgs` 数组,分别进行写入和读取操作。最后使用 `ioctl` 函数发送 I2C 读写命令,完成对 I2C 设备的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值