前言
本文基于RTT操作系统使用STM32F401RET6驱动BMP280气压计模块,使用I2C协议通信
一、新建工程

二、添加软件包

三、添加这个包

四、打开CubeMX

五、配置时钟源,使用外部晶振

六、配置串行下载口

七、打开I2C,我这里使用的是I2C2,因为我原理图上连接的是I2C2

八、打开串口一,因为创建工程的时候默认使用串口一,这里顺便也配置一下

九、配置时钟线,直接拉满

十、生成代码

十一、在board.h中配置一下时钟(其实这里改不改关系不大,因为已经在CubeMX中配置了使用外部时钟,感兴趣可以自行查看其调用关系,这里改是为了看得爽些)

十二、打开I2C2的宏(具体用I2C几看自己的原理图),并绑定通讯口

十三、使能I2C模块

十四、打开I2C设备驱动程序

十五、打开传感器设备驱动

十六、编译一下,报如下错误

十七、点击错误进行跳转,将这段代码进行注释

十八、再次编译,报错解决

十九、在main.c文件中写入如下代码
c
/*
* Copyright (c) 2006-2024, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2024-04-13 睡个好觉 first version
*/
#include <rtthread.h>
#include "sensor_bs_bmp280.h"
int bmp280_port(void);//bmp280初始化
rt_size_t Get_Data_Bmp280(void);//获取压力值
struct bmp280_dev bmp;
rt_uint32_t atmos = 0; //大气压值
//初始化空闲时间
#define SYSTEM_INIT_TIME 300
int main(void)
{
rt_thread_mdelay(SYSTEM_INIT_TIME);
bmp280_port(); //bmp280初始化
while(1)
{
Get_Data_Bmp280(); //读取BMP280数据
rt_kprintf("%d \r\n",atmos);
rt_thread_mdelay(20);
}
}
int bmp280_port(void)
{
struct rt_sensor_config cfg;
cfg.intf.dev_name = BMP280_I2CBUS_NAME;
cfg.intf.user_data = (void *)BMP280_ADDR_DEFAULT; //I2C从机地址
rt_hw_bmp280_init("bmp280", &cfg);
return 0;
}
rt_size_t Get_Data_Bmp280(void)
{
struct bmp280_uncomp_data ucomp_data;
uint32_t pres32;
/* Reading the raw data from sensor */
if(bmp280_get_uncomp_data(&ucomp_data, &bmp)!=BMP280_OK)
{
LOG_E("Reading the raw data from sensor error");
return 0;
}
/* Getting the compensated pressure using 32 bit precision */
bmp280_get_comp_pres_32bit(&pres32, ucomp_data.uncomp_press, &bmp);
atmos = pres32;
return 1;
}
二十、编译,有如下报错

二十一、打开ulog日志

二十二、然后在sensor_bs_bmp280.h头文件里面新增下图的两个文件包含

二十三、再次编译,报错解决

二十四、下载程序,打开串口查看,成功输出数据

番外:
如果你打印出这样的,读取数据错误,可以尝试检查两个地方

1、
找到这个从机地址,跳转进去

地址定义为这个,继续跳转进去

BMP280的从机地址有两个选择,0x76和0x77,模块出厂默认是0x76,确保你的地址选择正确

2、
第二个检查点就是这个I2C设备名,确保和你使用的是一致的
