Appearance
I2C
一般情况下 MCU 的 I2C 器件都是作为主机和从机通讯,在 RT-Thread 中将 I2C 主机虚拟为 I2C总线设备,I2C 从机通过 I2C 设备接口和 I2C 总线通讯,相关接口如下所示:
函数 | 描述 |
---|---|
rt_device_find() | 根据 I2C 总线设备名称查找设备获取设备句柄 |
rt_i2c_transfer() | 传输数据 |
使用
获取
c
rt_device_t rt_device_find(const char* name);
参数 描述 name I2C 总线设备名称 返回 —— 设备句柄 查找到对应设备将返回相应的设备句柄 RT_NULL 没有找到相应的设备对象
一般情况下,注册到系统的 I2C 设备名称为 i2c0 ,i2c1
数据传输
c
rt_size_t rt_i2c_transfer(struct rt_i2c_bus_device *bus,
struct rt_i2c_msg msgs[],
rt_uint32_t num);
参数 描述 bus I2C 总线设备句柄 msgs[] 待传输的消息数组指针 num 消息数组的元素个数 返回 —— 消息数组的元素个数 成功 错误码 失败 cstruct rt_i2c_msg { rt_uint16_t addr; /* 从机地址 */ rt_uint16_t flags; /* 读1、写0标志等 */ rt_uint16_t len; /* 读写数据字节数 */ rt_uint8_t *buf; /* 读写数据缓冲区指针 */ }
从机地址 addr:支持 7 位和 10 位二进制地址
c#define RT_I2C_WR 0x0000 /* 写标志,不可以和读标志进行“|”操作 */ #define RT_I2C_RD (1u << 0) /* 读标志,不可以和写标志进行“|”操作 */ #define RT_I2C_ADDR_10BIT (1u << 2) /* 10 位地址模式 */ #define RT_I2C_NO_START (1u << 4) /* 无开始条件 */ #define RT_I2C_IGNORE_NACK (1u << 5) /* 忽视 NACK */ #define RT_I2C_NO_READ_ACK (1u << 6) /* 读的时候不发送 ACK */ #define RT_I2C_NO_STOP (1u << 7) /* 不发送结束位 */
这是flag可以使用的标志
封装使用
c
rt_size_t rt_i2c_master_send(struct rt_i2c_bus_device *bus,
rt_uint16_t addr,
rt_uint16_t flags,
const rt_uint8_t *buf,
rt_uint32_t count);
bus I2C 总线设备句柄 addr I2C 从设备地址 flags 标志位,可为上文提到的除 RT_I2C_WR
RT_I2C_RD
之外的其他标志位,可以进行 “|” 操作buf 待数据数据缓冲区 count 待发送数据大小(单位:字节) 返回 —— 消息数组的元素个数 成功 错误码 失败
c
rt_size_t rt_i2c_master_recv(struct rt_i2c_bus_device *bus,
rt_uint16_t addr,
rt_uint16_t flags,
rt_uint8_t *buf,
rt_uint32_t count);
参数 描述 bus I2C 总线设备句柄 addr I2C 从设备地址 flags 标志位,可为上文提到的除 RT_I2C_WR
RT_I2C_RD
之外的其他标志位,可以进行 “|” 操作buf 数据缓冲区 count 缓冲区大小(单位:字节,要大于等于最大接收到的数据长度) 返回 —— 消息数组的元素个数 成功 错误码 失败
实际实现
c
/** if you want to use i2c bus(soft simulate) you can use the following instructions.
*
* STEP 1, open i2c driver framework(soft simulate) support in the RT-Thread Settings file
*
* STEP 2, define macro related to the i2c bus
* such as #define BSP_USING_I2C1
*
* STEP 3, according to the corresponding pin of i2c port, modify the related i2c port and pin information
* such as #define BSP_I2C1_SCL_PIN GET_PIN(port, pin) -> GET_PIN(C, 11)
* #define BSP_I2C1_SDA_PIN GET_PIN(port, pin) -> GET_PIN(C, 12)
*/