I2C-Tools的交叉编译
tar xvf i2c-tools-4.2.tar.xz 首先解压下压缩包
cd i2c-tools-4.2 进入 i2c-tools-4.2目录
make USE_STATIC_LIB=1 执行 make
将i2cset ,i2cget ,i2cdump,i2cdetect,i2ctransfer放到板子上
命令直接操作IIC设备
命令行直接操作iic向AP3216C传感器获取数据
基于 SMBus:
i2cset -f -y 0 0x1e 0 0x4 向0号总线的0x1e芯片地址的0号地址寄存器写入0x4
i2cset -f -y 0 0x1e 0 0x3 向0号总线的0x1e芯片地址的0号地址寄存器写入0x3
i2cget -f -y 0 0x1e 0xc 从0号总线的0x1e芯片地址的0xc号地址寄存器读一个字节
i2cget -f -y -w 0 0x1e 0xc 从0号总线的0x1e芯片地址的0xc号地址寄存器读两个字节
基于 I2C:
i2ctransfer -f -y 0 w2@0x1e 0 0x4 向0号总线的0x1e芯片地址的0号地址寄存器写入0x4 w2表示向0x1e芯片地址写入两个字节(0,0x4)
i2ctransfer -f -y 0 w2@0x1e 0 0x3 向0号总线的0x1e芯片地址的0号地址寄存器写入0x3
i2ctransfer -f -y 0 w1@0x1e 0xc r2 从0号总线的0x1e芯片地址的0xc号地址寄存器读两个字节 r2表示从 0x1e芯片地址0xc地址读寄存器读取两个字节
i2ctransfer -f -y 0 w1@0x1e 0xe r2 从0号总线的0x1e芯片地址的0xe号地址寄存器读两个字节
编写程序访问AP3216C
AP3216C 是红外、光强、距离三合一的传感器,以读出光强、距离值为例
程序
#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <i2c/smbus.h>
#include "i2cbusses.h"
#include <time.h>/* ./AP3216C <i2c_bus_number> light * ./AP3216C <i2c_bus_number> distance */int main(int argc, char **argv)
{unsigned char dev_addr = 0x1e;unsigned char light_addr[2] = {0x0c,0x0d};unsigned char distance_addr[2] = {0x0e,0x0f};unsigned char buf[32];int file;char filename[20];unsigned char *str;int ret;struct timespec req;if (argc != 3 ){printf("Usage:\n");printf(" read AP3216C: %s <i2c_bus_number> light/distance \n", argv[0]);return -1;}file = open_i2c_dev(argv[1][0]-'0', filename, sizeof(filename), 0);if (file < 0){printf("can't open %s\n", filename);return -1;}if (set_slave_addr(file, dev_addr, 1)){printf("can't set_slave_addr\n");return -1;}ret = i2c_smbus_write_byte_data(file, 0, 0x04);ret = i2c_smbus_write_byte_data(file, 0, 0x03);sleep(0.5);if (!strcmp(argv[2],"light")){//ret = i2c_smbus_read_i2c_block_data(file, light_addr[1], 2, buf);ret = i2c_smbus_read_i2c_block_data(file, light_addr[0], 1, &buf[0]);ret = i2c_smbus_read_i2c_block_data(file, light_addr[1], 1, &buf[1]);if (ret < 0){printf("i2c_smbus_read_i2c_block_data err\n");return -1;}printf("as:%d\r\n",buf[0]);printf("ass:%d\r\n",buf[1]);printf("light: 0x%x%x\n", buf[0],buf[1]);}else if(!strcmp(argv[2],"distance")){// readret = i2c_smbus_read_i2c_block_data(file, distance_addr[0], 1, &buf[0]);ret = i2c_smbus_read_i2c_block_data(file, distance_addr[1], 1, &buf[1]);if (ret < 0){printf("i2c_smbus_read_i2c_block_data err\n");return -1;}printf("distance: 0x%x%x\n", buf[0],buf[1]);}return 0;}