embeded/i2c
linux i2c 예제
구차니
2022. 12. 27. 11:02
i2c read 예제
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <errno.h> #include <linux/i2c-dev.h> #include <linux/i2c.h> const int bus = 0; const unsigned long slave_addr = 0xA0; const unsigned short sub_addr = 0x10; int main() { int fd; int rval; char path[20]; unsigned char buf[2]; unsigned char rxd[1]; sprintf(path, "/dev/i2c/%d", bus); fd = open(path, O_RDWR); if ((fd < 0) && (errno == ENOENT)) { sprintf(path, "/dev/i2c-%d", bus); fd = open(path, O_RDWR); } if (fd < 0) { fprintf(stderr, "Can't open file '/dev/i2c-%d' or '/dev/i2c/%d': %s\r\n", bus, bus, strerror(errno)); exit(EXIT_FAILURE); } // Read 1byte ioctl(fd, I2C_SLAVE, slave_addr); buf[0] = (sub_addr & 0xFF00) >> 8; buf[1] = sub_addr & 0xFF; if ((rval = write(fd, buf, 2)) < 0) { fprintf(stderr, "Writing error! (%lX): %s\r\n", slave_addr, strerror(errno)); exit(EXIT_FAILURE); } if ((rval = read(fd, rxd, sizeof(unsigned char))) < 0) { fprintf(stderr, "Reading error! (%lX): %s\r\n", slave_addr, strerror(errno)); exit(EXIT_FAILURE); } fprintf(stdout, "Read 1byte = 0x%02X\r\n", rxd[0]); close(fd); return 0; } |