#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/types.h>
int main() {
int file;
char *filename = "/dev/i2c-1"; // I2C bus device file
__u8 address = 0x68; // I2C slave address
// Open the I2C bus
if ((file = open(filename, O_RDWR)) < 0) {
perror("Failed to open the i2c bus");
return 1;
}
// Specify the address of the I2C slave
if (ioctl(file, I2C_SLAVE, address) < 0) {
perror("Failed to acquire bus access and/or talk to slave");
return 1;
}
// Example: Write a byte to the I2C slave
__u8 reg = 0x00; // Register to write to
__u8 value = 0xFF; // Value to write
__u8 buffer[2] = { reg, value };
if (write(file, buffer, 2) != 2) {
perror("Failed to write to the i2c bus");
return 1;
}
// Example: Read a byte from the I2C slave
__u8 read_reg = 0x00; // Register to read from
if (write(file, &read_reg, 1) != 1) {
perror("Failed to write to the i2c bus");
return 1;
}
__u8 read_value;
if (read(file, &read_value, 1) != 1) {
perror("Failed to read from the i2c bus");
return 1;
}
printf("Read value: 0x%02X\n", read_value);
close(file);
return 0;
}
open
函数打开指定的I2C总线设备文件(如/dev/i2c-1
),并获取文件描述符。ioctl
系统调用,将文件描述符关联到特定的I2C从设备地址(如0x68
)。write
函数向I2C从设备发送数据。这里我们发送一个寄存器地址和一个值。write
函数发送要读取的寄存器地址,然后使用read
函数从I2C从设备读取数据。这段代码展示了如何在Linux用户空间中通过I2C总线与从设备进行通信的基本步骤。
上一篇:linux创建多级目录
下一篇:linux下载文件夹到本地
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站