SHT30温湿度传感器应用笔记

  • Post author:
  • Post category:其他


芯片介绍

SHT30是一款温湿度传感器,使用IIC通信接口。可根据命令设置其测量频率、测量时间;测量持续时间有三种可选(见芯片手册2.2):

HIGH:12.5ms;

medium:4.5ms;

low:2.5ms;

测量频率有五种可选:0.5次/秒、1次/秒、2次/秒、4次/秒、10次/秒。

如采样时间12.5ms,10次/秒的指令为:0x2737.例程如下:

static void start_measure(void)
{
    const uint8_t iic_addr = 0x44 << 1;
    const uint16_t cmd_meas_freq = 0x2737;
    uint8_t cmd[2];
    
    cmd[0] = cmd_meas_freq >> 8;
    cmd[1] = cmd_meas_freq;
    
    HAL_I2C_Master_Transmit(&hi2c1, iic_addr, cmd, 2, 100);
}

温湿度读取

在芯片手册4.6节有讲解如何读取芯片测量数据:

在芯片手册4.11节有讲解读出数据CRC校验方法:

例程如下:

uint8_t CRC8(uint8_t * p_buf, UINT16 num)
{
    uint8_t result = 0xff;
    uint8_t const ploynomial = 0x31;
    
    for(uint8_t i = 0; i < num; i++)
    {
        result ^= p_buf[i];
        
        for(uint8_t j = 0; j < 8; j++)
        {
            if(result&0x80)
            {
                result <<= 1;
                result ^= ploynomial;
            }
            else
            {
                result <<= 1;
            }
        }
    }
    
    return result;
}

在芯片手册4.12节有讲解如何将芯片测量数据转换成我们想要的温湿度数据:


例程如下:

typedef struct
{
    float temperature;
    float humidity;
}Param;

uint8_t read_param(Param *param)
{
    uint8_t data[6];
    const uint8_t iic_addr = 0x44 << 1;
    const uint16_t cmd_fetch_data = 0xE000;
    
    uint8_t cmd[2];
    cmd[0] = cmd_fetch_data >> 8;
    cmd[1] = (uint8_t)cmd_fetch_data;
    
    HAL_I2C_Master_Transmit(&hi2c1, iic_addr, cmd, 2, 100);
    
    HAL_I2C_Master_Receive(&hi2c1, iic_addr, data, sizeof(data), 100);
    
    if((CRC8(&data[0], 2) != data[2]) || (CRC8(&data[3], 2) != data[5]))
    {
        return FALSE;
    }
    
    uint8_t tmp = (data[0] << 8) + data[1];
    param->temperature = ((float)(175*tmp)/65535) - 45;
    
    tmp = (data[3] << 8) + data[4];
    param->humidity = (float)(100*tmp)/65535;
    
    return TRUE;
}



版权声明:本文为liuwuyi1987原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。