用C语言实现iic通讯
时间: 2023-05-17 13:07:24 浏览: 101
IIC协议用C语言实现
5星 · 资源好评率100%
可以使用以下代码实现iic通讯:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
int main(int argc, char **argv)
{
int file;
char *filename = "/dev/i2c-1";
int addr = 0x68; // I2C address of the device
char buf[2] = {0};
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 acquire bus access and/or talk to slave");
exit(1);
}
// Write to the device
buf[0] = 0x00; // Register address
buf[1] = 0x01; // Value to write
if (write(file, buf, 2) != 2) {
perror("Failed to write to the i2c device");
exit(1);
}
// Read from the device
buf[0] = 0x00; // Register address
if (write(file, buf, 1) != 1) {
perror("Failed to write to the i2c device");
exit(1);
}
if (read(file, buf, 1) != 1) {
perror("Failed to read from the i2c device");
exit(1);
}
printf("Data read from the device: %d\n", buf[0]);
close(file);
return 0;
}
阅读全文