RT-Thread 的 I2C 设备驱动框架即支持硬件 I2C 也支持软件模拟 I2C。
由于软件用起来比较方便,随便设置引脚,这里尝试开启一下软件I2C。
一、步骤
1.打开RT-Thread Setting中软件模拟I2C

2.开启board.h中关于I2C的宏定义

3.直接仿照官方例程初始化读写所需的I2C设备
例子:
/*
* Copyright (c) 2006-2020, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2020-04-18 CRJ the first version
*/
#include "stm32f1xx_hal.h"
#include <board.h>
#include <rtthread.h>
#include <rtdevice.h>
#include "app_i2c.h"
#define AHT10_I2C_BUS_NAME "i2c1" /* 传感器连接的I2C总线设备名称 */
#define AHT10_ADDR 0x38 /* 从机地址 */
#define AHT10_CALIBRATION_CMD 0xE1 /* 校准命令 */
#define AHT10_NORMAL_CMD 0xA8 /* 一般命令 */
#define AHT10_GET_DATA 0xAC /* 获取数据命令 */
static struct rt_i2c_bus_device *i2c_bus = RT_NULL; /* I2C总线设备句柄 */
static rt_bool_t initialized = RT_FALSE; /* 传感器初始化状态 */
/* 写传感器寄存器 */
static rt_err_t write_reg(struct rt_i2c_bus_device *bus, rt_uint8_t reg, rt_uint8_t *data)
{
rt_uint8_t buf[3];
struct rt_i2c_msg msgs;
buf[0] = reg; //cmd
buf[1] = data[0];
buf

本文详细介绍了在RT-Thread操作系统中使用软件I2C驱动进行设备通信的过程,包括配置步骤、宏定义启用及通过实例演示如何初始化和读写AHT10温湿度传感器。
最低0.47元/天 解锁文章
663





