STM32 HAL库 读取SHT30
CubeMX
CubuMx就配置完成了
接下来进入代码
从机地址
模块的命令
发送命令
复位
/**
* @brief 复位SHT30
* @param none
* @retval none
*/
void SHT30_reset(void)
{
SHT30_Send_Cmd(SOFT_RESET_CMD);
HAL_Delay(20);
}
``初始化
/**
* @brief 初始化SHT30
* @param none
* @retval 成功返回HAL_OK
* @note 周期测量模式
*/
uint8_t SHT30_Init(void)
{
return SHT30_Send_Cmd(MEDIUM_2_CMD);
}
uint8_t SHT30_Read_Dat(uint8_t* dat)
{
SHT30_Send_Cmd(READOUT_FOR_PERIODIC_MODE);
return HAL_I2C_Master_Receive(&hi2c1, SHT30_ADDR_READ, dat, 6, 0xFFFF);
}
### 校验CRC
```c
#define CRC8_POLYNOMIAL 0x31
uint8_t CheckCrc8(uint8_t* const 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);
}
}
}
/* 返回计算的CRC码 */
return remainder;
}
转换为温湿度值
/**
* @brief 将SHT30接收的6个字节数据进行CRC校验,并转换为温度值和湿度值
* @param dat —— 存储接收数据的地址(6个字节数组)
* @retval 校验成功 —— 返回0
* 校验失败 —— 返回1,并设置温度值和湿度值为0
*/
uint8_t SHT30_Dat_To_Float(uint8_t* const dat, float* temperature, float* humidity)
{
uint16_t recv_temperature = 0;
uint16_t recv_humidity = 0;
/* 校验温度数据和湿度数据是否接收正确 */
if(CheckCrc8(dat, 0xFF) != dat[2] || CheckCrc8(&dat[3], 0xFF) != dat[5])
return 1;
/* 转换温度数据 */
recv_temperature = ((uint16_t)dat[0]<<8)|dat[1];
*temperature = -45 + 175*((float)recv_temperature/65535);
/* 转换湿度数据 */
recv_humidity = ((uint16_t)dat[3]<<8)|dat[4];
*humidity = 100 * ((float)recv_humidity / 65535);
printf("%f",*humidity);
return 0;
}
CHT30.H
#ifndef __SHT30_H_
#define __SHT30_H_
#include "stm32f4xx.h" // Device header
#include "i2c.h"
void SHT30_reset(void);
extern uint8_t SHT30_Init(void);
extern uint8_t SHT30_Read_Dat(uint8_t* dat);
extern uint8_t CheckCrc8(uint8_t* const message, uint8_t initial_value);
extern uint8_t SHT30_Dat_To_Float(uint8_t* const dat, float* temperature, float* humidity);
#endif
测试
SHT30_reset();
if(SHT30_Init() == HAL_OK)
printf("sht30 init ok.\n");
else
printf("sht30 init fail.\n");
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(1000);
if(SHT30_Read_Dat(recv_dat) == HAL_OK)
{
if(SHT30_Dat_To_Float(recv_dat, &temperature, &humidity)==0)
{
printf("temperature = %d, humidity = %d\n", (uint8_t)temperature, (uint8_t)humidity);
}
else
{
printf("crc check fail.\n");
}
}
else
{
printf("read data from sht30 fail.\n");
}
HAL_GPIO_TogglePin(LED_GPIO_Port,LED_Pin);
}
printf("Strat!!\n");
HAL_Delay(200);
/* USER CODE END 3 */
}