第一种方式:当主板外接I2C设备时,可直接使用CPU的I2C适配器,在应用层即可直接控制设备。
#include <stdio.h> //printf() #include <stdlib.h> //exit() #include <string.h> //strlen(), bzero(); #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <time.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> int i2c_write(int fd, char dev_addr, char write_addr, char data) { struct i2c_rdwr_ioctl_data i2c_data; struct i2c_msg msg; char buf[2] = {0}; buf[0] = write_addr; buf[1] = data; msg.addr = dev_addr; msg.flags = 0; msg.len = 2; msg.buf = buf; i2c_data.nmsgs = 1; i2c_data.msgs = &msg; int ret = ioctl(fd, I2C_RDWR, &i2c_data); if (ret < 0) { printf("i2c read error %d\n", ret); } return ret; } int i2c_read(int fd, char dev_addr, char read_addr, char *buf, int size) { struct i2c_rdwr_ioctl_data i2c_data; struct i2c_msg msg[2]; msg[0].addr = dev_addr; msg[0].flags = 0; msg[0].len = 1; msg[0].buf = &read_addr; msg[1].addr = dev_addr; msg[1].flags = 1; msg[1].len = size; msg[1].buf = buf; i2c_data.msgs = msg; i2c_data.nmsgs = 2; int ret = ioctl(fd, I2C_RDWR, &i2c_data); if (ret < 0) { printf("i2c read error %d\n", ret); } return ret; } int main(int argc, char *argv[]) { int fd = open("/dev/i2c-4", O_RDONLY); printf("fd = %d\n", fd); char buf[4] = {0}; i2c_read(fd, 0x1a, 0x0, buf, 1); close(fd); return 0; }第二种方式:linux内核源码TS2007触摸驱动,使用I2C控制。
1、在板子适配文件mach-itop4412.c中添加 struct i2c_board_info i2c_devs7[] __initdata = { { I2C_BOARD_INFO("tsc2007", 0x48), .type = "tsc2007", .platform_data = &tsc2007_info, .irq = IRQ_EINT(0), } } //注册到内核 i2c_register_board_info(7, i2c_devs7, ARRAY_SIZE(i2c_devs7)); 2、驱动代码 static struct i2c_driver tsc2007_driver = { .driver = { .owner = THIS_MODULE, .name = "tsc2007" }, //.id_table = tsc2007_idtable, .probe = tsc2007_probe, .remove = __devexit_p(tsc2007_remove), }; static int __init tsc2007_init(void) { return i2c_add_driver(&tsc2007_driver); } static void __exit tsc2007_exit(void) { i2c_del_driver(&tsc2007_driver); } module_init(tsc2007_init); module_exit(tsc2007_exit); MODULE_DESCRIPTION("TSC2007 TouchScreen Driver"); MODULE_LICENSE("GPL");