请书写基于c语言的i2c通信读写代码
时间: 2023-04-04 16:00:33 浏览: 165
以下是基于 C 语言的 I2C 通信读写代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#define I2C_ADDR x68 // I2C 设备地址
#define I2C_BUS "/dev/i2c-1" // I2C 总线设备文件路径
int main(int argc, char **argv)
{
int fd;
char buf[2];
// 打开 I2C 总线设备文件
if ((fd = open(I2C_BUS, O_RDWR)) < ) {
perror("Failed to open I2C bus");
exit(1);
}
// 设置 I2C 设备地址
if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < ) {
perror("Failed to set I2C address");
exit(1);
}
// 读取 I2C 设备寄存器
buf[] = x00; // 寄存器地址
if (write(fd, buf, 1) != 1) {
perror("Failed to write to I2C device");
exit(1);
}
if (read(fd, buf, 1) != 1) {
perror("Failed to read from I2C device");
exit(1);
}
printf("Register value: x%02x\n", buf[]);
// 写入 I2C 设备寄存器
buf[] = x00; // 寄存器地址
buf[1] = x01; // 数据
if (write(fd, buf, 2) != 2) {
perror("Failed to write to I2C device");
exit(1);
}
// 关闭 I2C 总线设备文件
close(fd);
return ;
}