树莓派之I2C编程

来源:互联网 发布:零起点学算法 编辑:程序博客网 时间:2024/05/18 05:50

树莓派之I2C编程

一、启动I2C

  • 使用: ls /dev/命令可以查看I2C设备是启动。
  • 如果没有启动执行 sudo raspi-config选择 interfacing Options->I2C->yes启动i2c内核驱动。
  • 使用 lsmod 命令可以看到i2c_bcm2708,并且/dev目录下可以看到i2c设备。

二、I2C编程

(1)、包含头文件

#include < linux/i2c-dev.h>
#include

(2)、ioctl函数

查看include/linux/i2c-dev.h,里面包含了i2c-dev支持的所有命令。 (注;版本比较高的linux内核,命令放在include/uapi/Linux/i2c-dev.h内)


#define I2C_RETRIES 0x0701 /* number of times a device address should be polled when not acknowledging */

#define I2C_TIMEOUT 0x0702  /* set timeout in units of 10 ms *//* NOTE: Slave address is 7 or 10 bits, but 10-bit addresses   * are NOT supported! (due to code brokenness)   */  #define I2C_SLAVE   0x0703  /* Use this slave address */  #define I2C_SLAVE_FORCE 0x0706  /* Use this slave address, even if it                   is already in use by a driver! */  #define I2C_TENBIT  0x0704  /* 0 for 7 bit addrs, != 0 for 10 bit */#define I2C_FUNCS   0x0705  /* Get the adapter functionality mask */#define I2C_RDWR    0x0707  /* Combined R/W transfer (one STOP only) */#define I2C_PEC     0x0708  /* != 0 to use PEC with SMBus */#define I2C_SMBUS   0x0720  /* SMBus transfer */

例如:

1. 打开一个i2c从机 ioctl(fd, I2C_SLAVE, addr);
fd是i2c设备的文件标志符
I2_SLAVE是命令
addr是我们要访问的i2c设备的地址

(3)、两种通信方式

  1. 一种是使用操作普通文件的接口read()和write(),这两个函数间接调用了i2c_master_recv和i2c_master_send

2.一种是使用Ioctl的命令I2C_RDWR来实现。

原创粉丝点击