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; } |
'embeded > i2c' 카테고리의 다른 글
i2c 자료 (0) | 2018.04.26 |
---|---|
i2c mode - tm4c (0) | 2018.04.26 |
i2c BUS에 pull-up, pull-down (0) | 2018.04.26 |
i2c bank switching (0) | 2015.09.02 |
i2c 정리 (4) | 2012.01.10 |