使用VSCode+CubeMx开发STM32,这里使用模拟软件I2C接口来连接SHT30温湿度传感器;

1.建立工程

1.1 创建项目文件

从已有的仓库中创建一个工程:

1
git clone https://github.com/makerinchina-iot/vscode_stm32cubemx_hello.git sht30

使用VSCode打开工程后,需要更改如下名字:

  • 文件夹根目录下CMakeLists.txt 文件中修改工程名字为sht30:
1
set(CMAKE_PROJECT_NAME sht30)
  • stm32cubemx配置文件更改为 sht30.ioc ,并更改以下文件名:
1
2
3
4
...
ProjectManager.ProjectFileName=sht30.ioc
ProjectManager.ProjectName=sht30
...
1.2 引脚配置

使用STM32CubeMx打开ioc配置文件,然后配置对应的引脚,这里配置SCL引脚为GPIOB0,SDA引脚为GPIOB1,两个引脚都配置为输出模式:

2 编写代码

2.1 模拟软件I2C接口
2.1.1 soft_i2c 文件夹结构
  • 在工程文件夹的libs目录下新建soft_i2c文件夹作为软件i2c代码库,文件源码结构如下:
  • CMakeList.txt 文件内容如下,如下内容可以使这个文件夹作为一个库方便其他地方使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
cmake_minimum_required(VERSION 3.22)

add_library(soft_i2c STATIC)

target_sources(soft_i2c
PRIVATE
src/soft_i2c.c
port/soft_i2c_port.c
src/i2c_scanner.c
)

target_include_directories(soft_i2c PUBLIC include port)
target_link_libraries(soft_i2c PUBLIC stm32cubemx)

2.1.2 模拟软件i2c

软件i2c模拟代码主要按照标准的i2c时序实现start、stop、send、ack等信号,然后实现i2c读写接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @brief init the soft i2c
*/
void soft_i2c_init();

/**
* @brief i2c write and read function
* @param dev_addr
* @param tx_buffer
* @param tx_size
* @param rx_buffer
* @param rx_size
* @return
*/
bool soft_i2c_transfer(uint8_t dev_addr, uint8_t *tx_buffer, uint16_t tx_size, uint8_t *rx_buffer, uint16_t rx_size);

/**
* @brief scan i2c device
* @param from_addr
* @param to_addr
* @param callback
* @param delay_cb
*/
void scan_i2c_bus(uint8_t from_addr, uint8_t to_addr,
void (*callback)(uint8_t address, bool result));

  • 其中 scan_i2c_bus 主要方便调试,查找是否有连接i2c设备;
2.1.3 i2c接口硬件相关接口

与硬件相关的接口单独在port文件夹中实现,需要根据具体硬件和框架来实现,主要是引脚初始化设置、输入获取及输出高低电平的实现代码;

2.2 sht30读写

SHT30读写温湿度的命令和转换关系需要根据规格书进行编写:

在main函数中添加如下代码,即可读取sht30温湿度数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void sht30_sample(float *temp, float *humi)
{
uint8_t rd_buff[6] = {0};
uint8_t cmd[2] = {0x20, 0x32};

uint8_t dev_addr = 0x44;

// send read cmd
soft_i2c_transfer(dev_addr, cmd, 2, 0, 0);

// some sensor need more waite time
HAL_Delay(20);

// receive data
soft_i2c_transfer(dev_addr, 0, 0, rd_buff, 6);

uint16_t temp_int = (uint16_t)((rd_buff[0] << 8) | (rd_buff[1]));
uint16_t humi_int = (uint16_t)((rd_buff[3] << 8) | (rd_buff[4]));

*temp = -45 + (float)(175 * temp_int / 65535.0000);
*humi = 100 * (float)(humi_int / 65535.0000);
}

3 编译并烧录代码

3.1 编译和烧录
  • 点击生成按键即可编译工程;

  • 在VSCode中执行task:openocd-flash烧录;

3.2 硬件连接与结果
  • 按照如下方式连接硬件:
STM32 SHT30
3.3V 3V3
PB6 SCL
PB7 SDA
GND GND
  • 结果如下: