linux I2C 读写 tlv320dac3100
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #define DAC3100_DEV "/dev/i2c-2" #define DAC3100_ADDR 0x18 static unsigned char g_page = 0xFF; void dac3100_change_page(int fd, unsigned char page) { int err; struct i2c_rdwr_ioctl_data data; struct i2c_msg msg; if (g_page == page) { return; } data.nmsgs = 1; data.msgs = &msg; msg.addr = DAC3100_ADDR; msg.flags = 0; msg.len = 2; msg.buf = (unsigned char*)malloc(2); msg.buf[0] = 0; msg.buf[1] = page; err = ioctl (fd, I2C_RDWR, (unsigned long)&data); if (err < 0) { printf("ERR: I2C_RDWR => %d\n", err); } g_page = page; free(msg.buf); } unsigned char dac3100_read(int fd, unsigned char page, unsigned char reg) { int err; struct i2c_rdwr_ioctl_data data; struct i2c_msg msg[2]; unsigned char rst; dac3100_change_page(fd, page); data.nmsgs = 2; data.msgs = msg; msg[0].addr = DAC3100_ADDR; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = ® msg[1].addr = DAC3100_ADDR; msg[1].flags = I2C_M_RD; msg[1].len = 1; msg[1].buf = &rst; err = ioctl(fd, I2C_RDWR, (unsigned long)&data); if (err < 0) { printf("ERR: DAC3100 READ => %d\n", err); } return rst; } int main(int argc, char** argv) { int fd, err; int page, reg, pcnt = 3; unsigned char pages[] = {0, 1, 3}; fd = open(DAC3100_DEV, 0, O_RDWR); if (fd < 0) { printf("ERR: device open failed!"); return -1; } err = ioctl(fd, I2C_TENBIT, 0); if (err < 0) { printf("ERR: IOCTL I2C_TENBIT => %d\n", err); } for (page = 0; page < pcnt; page++) { printf("------- PAGE %d -------\n", pages[page]); for (reg = 0; reg < 128; reg++) { printf("%02X ", dac3100_read(fd, pages[page], reg)); if ((reg % 8) == 7) { printf("\n"); } } } close(fd); return 0; }