生成一个i2c读写接口的c代码
时间: 2024-02-17 13:00:00 浏览: 17
好的,下面是一个简单的 i2c 读写接口的 C 代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#define I2C_BUS "/dev/i2c-1" // I2C 总线设备节点
// 初始化 i2c 总线
int i2c_init(int addr)
{
int fd = open(I2C_BUS, O_RDWR);
if (fd < 0) {
perror("open");
return -1;
}
if (ioctl(fd, I2C_SLAVE, addr) < 0) {
perror("ioctl");
close(fd);
return -1;
}
return fd;
}
// 读取一段数据
int i2c_read(int fd, char *buf, int len)
{
return read(fd, buf, len);
}
// 写入一段数据
int i2c_write(int fd, char *buf, int len)
{
return write(fd, buf, len);
}
// 关闭 i2c 总线
void i2c_close(int fd)
{
close(fd);
}
// 主函数
int main()
{
int fd = i2c_init(0x68); // 初始化 i2c 总线,设备地址为 0x68
if (fd < 0) {
printf("i2c_init failed!\n");
return -1;
}
char buf[2] = {0x00, 0x00}; // 读取 MPU6050 的设备 ID
i2c_write(fd, buf, 1);
i2c_read(fd, buf, 1);
printf("Device ID: 0x%02x\n", buf[0]);
i2c_close(fd); // 关闭 i2c 总线
return 0;
}
```
注意:以上代码仅供参考,使用前请根据实际情况进行修改和测试。