Linux下I2C应用程序

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/ioctl.h>
#include<linux/types.h>


#define I2C_RDWR 0x0707

struct i2c_rdwr_ioctl_data {
struct i2c_msg  *msgs; /* pointers to i2c_msgs */
unsigned int nmsgs; /* number of i2c_msgs */
};
struct i2c_msg {
unsigned short addr; /* slave address */
unsigned short flags;
unsigned short len; /* msg length */
unsigned char *buf; /* pointer to msg data */
};
int main()
{
int fd;
//1.打开通用设备文件
fd = open("/dev/hi_i2c",O_RDWR);
struct i2c_rdwr_ioctl_data data;
data.msgs = (struct i2c_msg *)malloc(2*sizeof(struct i2c_msg));
//2.构造写入到从设备的消息
data.nmsgs = 1;   //消息的数目
data.msgs[0].len = 2;
data.msgs[0].addr = 0x20;
data.msgs[0].flags = 0;  //flags说明读还是写
data.msgs[0].buf = (unsigned char *)malloc(2);
data.msgs[0].buf[0] = 0x01;     //填入从设备寄存器地址
data.msgs[0].buf[1] = 0x20;     //向寄存器写入的值
//3.使用ioctl写入数据
ioctl(fd,I2C_RDWR,(unsigned long)&data);
//4.构造读出从设备数据的消息
data.nmsgs = 2;
data.msgs[0].len = 1;
data.msgs[0].addr = 0x20; //从设备地址
data.msgs[0].flags = 0;  //flags说明读还是写
//data.msgs[0].buf = (unsigned char *)malloc(2);
data.msgs[0].buf[0] = 0x01;     //填入从设备寄存器地址 
data.msgs[1].len = 1;
data.msgs[1].addr = 0x20; //从设备地址
data.msgs[1].flags = 1;  //flags说明读还是写
data.msgs[1].buf = (unsigned char *)malloc(2);
data.msgs[1].buf[0] = 0;     //填入从设备寄存器地址 
//5.使用ioctl读数据
ioctl(fd,I2C_RDWR,(unsigned long)&data);
printf("buf[0]=%x\n",data.msgs[1].buf[0]);
//6.关闭设备
close(fd);
}
  • 1
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Linux 4.9下,可以使用i2c-dev驱动程序来控制I2C总线。以下是一些基本步骤: 1. 安装i2c-tools: `sudo apt-get install i2c-tools` 2. 确认I2C总线是否已启用:`sudo i2cdetect -l` 3. 打开I2C总线设备文件:`sudo modprobe i2c-dev`,这会在/dev目录下创建i2c-N文件,其中N是总线号。 4. 用open()函数打开设备文件,使用ioctl()函数发送I2C信号。 以下是一些示例代码,用于向I2C设备写入和读取数据: ```c #include <stdio.h> #include <fcntl.h> #include <linux/i2c-dev.h> #include <unistd.h> int main() { int file; char *filename = "/dev/i2c-1"; // I2C总线1 int addr = 0x68; // I2C从设备地址 char buf[2]; if ((file = open(filename, O_RDWR)) < 0) { printf("Failed to open I2C device.\n"); return 1; } if (ioctl(file, I2C_SLAVE, addr) < 0) { printf("Failed to select I2C device.\n"); return 1; } // 写入数据 buf[0] = 0x00; // 寄存器地址 buf[1] = 0x12; // 数据 if (write(file, buf, 2) != 2) { printf("Failed to write to I2C device.\n"); return 1; } // 读取数据 buf[0] = 0x00; // 寄存器地址 if (write(file, buf, 1) != 1) { printf("Failed to write to I2C device.\n"); return 1; } if (read(file, buf, 1) != 1) { printf("Failed to read from I2C device.\n"); return 1; } printf("Data read: 0x%x\n", buf[0]); close(file); return 0; } ``` 在以上示例代码中,我们使用了/dev/i2c-1作为I2C总线设备文件,选择了从设备地址0x68,写入了0x12到寄存器地址0x00,并读取了该地址的数据。如果一切正常,将会输出读取的数据。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值