i2c注册设备知识点:
kernel/msm-4.9/drivers/i2c/i2c-dev.c为每个i2c设备创建设节点,所以我们不用创建。
/dev/i2c-0是在注册i2c-dev.c后产生的,代表一个可操作的适配器。
如果不使用i2c-dev.c的方式,就没有,也不需要这个节点。
需要找到你要操作的i2c设备在哪一根i2c总线上,如/dev/i2c-2上挂着,找到i2c设备地址,
就可以操作这个i2c设备,对其寄存器通过ioctl()控制读写了.
1.i2c_test.c
#include #include
#include
#include
#include
#include
#include
#define DEVICE_NAME "/dev/i2c-2"
#define I2C_ADDR 0x22
#define REG_ADDR 0x05
int main(){
int fd = -1;
struct i2c_rdwr_ioctl_data data;
data.msgs = (struct i2c_msg *)malloc(2 * sizeof(struct i2c_msg));
unsigned char sendbuf[sizeof(unsigned char) + 1] = {0};
unsigned char recvbuf[sizeof(unsigned char) + 1] = {0};
//0.open
fd = open(DEVICE_NAME, O_RDWR);
if(fd < 0) {
printf("Failed to open device %s.\n", DEVICE_NAME);
return -1;
}
printf("open device %s Success.\n", DEVICE_NAME);
//1.write reg to value
data.nmsgs = 1; //消息的数目
data.msgs[0].len = 2;//1个写入目标的reg地址和1个数据
data.msgs[0].addr = I2C_ADDR;//i2c设备地址
data.msgs[0].flags = 0;//flags为0:表示写;为1:表示读.
data.msgs[0].buf = sendbuf;//申请内存为2个Byte
data.msgs[0].buf[0] = REG_ADDR;//i2c设备要操作的reg地址
data.msgs[0].buf[1] = 0x40;//向reg写入的值
ioctl(fd,I2C_RDWR,(unsigned long)&data);
//2.read reg value
data.nmsgs = 2;
data.msgs[0].len = 1;//目标reg的地址的长度
data.msgs[0].addr = I2C_ADDR; //i2c设备地址
data.msgs[0].flags = 0; //write flag
data.msgs[0].buf[0] = REG_ADDR;//目标reg地址
data.msgs[1].len = 1;//目标reg的地址的长度
data.msgs[1].addr = I2C_ADDR; //i2c设备地址
data.msgs[1].flags = 1; //read flag
data.msgs[1].buf = recvbuf;//分配内存
ioctl(fd,I2C_RDWR,(unsigned long)&data);
printf("buf[0] = %x\n",data.msgs[1].buf[0]);
close(fd);
return 0;
}
2.Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := optional
LOCAL_MODULE := i2c_test
LOCAL_SRC_FILES := $(call all-subdir-c-files)
include $(BUILD_EXECUTABLE)