在 Linux 中向 I2C 接口发送数据的例子可以通过使用 i2c-dev
接口实现。以下是一个简单的 C 语言示例,展示了如何打开 I2C 设备并向其发送数据。
首先,确保你的系统已经安装了 i2c-dev 模块,并且你有权限访问 /dev/i2c-X
设备文件(X 是 I2C 总线的编号)。
示例代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
int main() {
int file;
const char *filename = "/dev/i2c-1"; // 使用适当的 I2C 总线
int addr = 0x50; // 从设备地址 (替换为你的设备地址)
// 打开 I2C 设备
if ((file = open(filename, O_RDWR)) < 0) {
perror("Failed to open the i2c bus");
exit(1);
}
// 指定从设备地址
if (ioctl(file, I2C_SLAVE, addr) < 0) {
perror("Failed to connect to the device");
close(file);
exit(1);
}
// 要发送的数据
char data[3] = {0x00, 0x01, 0x02}; // 替换为要发送的数据
// 向从设备发送数据
if (write(file, data, sizeof(data)) != sizeof(data)) {
perror("Failed to write to the i2c bus");
close(file);
exit(1);
}
printf("Data sent successfully\n");
close(file);
return 0;
}
编译和运行
将上面的代码保存为
i2c_write.c
。使用以下命令编译:
gcc -o i2c_write i2c_write.c
确保以 root 用户或具有相应权限的用户运行该程序,因为访问
/dev/i2c-X
通常需要特权:sudo ./i2c_write
注意事项
- 替换
filename
为你的实际 I²C 总线文件,例如/dev/i2c-1
。 - 替换
addr
为你的实际从设备地址,注意地址应该是七位制格式。 - 根据你的具体应用情况,修改要发送的数据内容。
内容由零声教学AI助手提供,问题来源于学员提问