1、说明
(1)MCU为STM32F103C8,温湿度芯片为SHT30; (2)硬件连接:SHT30连接STM32的IIC1; (3)SHT30的ADDR脚连接地,因此其设备地址为:(0x44<<1),即0x88; (4)程序中使用HAL库,代码有CubeMX生成;
2、程序
驱动头文件:sht30.h
1 2 3 4 5 6 7 8 9 10 11 12 13
| #ifndef __SHT30_H_ #define __SHT30_H_
#include "stdbool.h"
#define SHT_ADDR (0x44<<1)
uint8_t sht30_init();
uint8_t sht30_sample(float *t, float *h);
#endif
|
驱动主文件:sht30.c
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| #include "sht30.h" #include "i2c.h"
uint8_t i2c_write_cmd(uint16_t cmd) { uint8_t cmd_buff[2]; cmd_buff[0] = cmd>>8; cmd_buff[1] = cmd;
return HAL_I2C_Master_Transmit(&hi2c1,SHT_ADDR,cmd_buff,2,0xffff); }
#define CRC8_POLYNOMIAL 0x31 uint8_t CheckCrc8(uint8_t* message, uint8_t initial_value) { uint8_t remainder; uint8_t i = 0, j = 0;
remainder = initial_value;
for(j = 0; j < 2;j++) { remainder ^= message[j];
for (i = 0; i < 8; i++) { if (remainder & 0x80) { remainder = (remainder << 1)^CRC8_POLYNOMIAL; } else { remainder = (remainder << 1); } } } return remainder; }
uint8_t sht30_init() { i2c_write_cmd(0x30a2); HAL_Delay(25);
return i2c_write_cmd(0x2220); }
uint8_t sht30_sample(float *t, float *h) { uint8_t read_buff[6] = {0};
uint16_t temp_value; uint16_t humi_value;
i2c_write_cmd(0xe000);
if(HAL_I2C_Master_Receive(&hi2c1,SHT_ADDR0x01,read_buff,6,0xffff) != HAL_OK) { return HAL_ERROR; }
if(CheckCrc8(read_buff, 0xFF) != read_buff[2] CheckCrc8(&read_buff[3], 0xFF) != read_buff[5]) { return HAL_ERROR; }
temp_value = ((uint16_t)read_buff[0]<<8)read_buff[1]; *t = -45 + 175*((float)temp_value/65535);
humi_value = ((uint16_t)read_buff[3]<<8)read_buff[4]; *h = 100 * ((float)humi_value / 65535);
return HAL_OK; }
|
主文件进行调用:
1 2 3 4 5 6 7
| sht30_sample(&temp, &humi);
char tempstr[6] = {0}; char humistr[6] = {0}; sprintf(tempstr, "%.2f", temp); sprintf(humistr, "%.2f", humi); SEGGER_RTT_printf(0, "temp:%s, humi:%s\r\n", tempstr, humistr);
|
注:这里SEGGER_RTT_printf 不支持float打印,因此用sprintf将float转换为char数组即可显示。
显示结果
获取数据如下(用手接触SHT30后温读明显升高):