STM32实例源码剖析(SHT30 基于 IIC的温湿度获取程序)

下边是我之前做的时候写的代码,需要的可以参考




/*获取温湿度*/
bool eb_I2C_SHT30_Read(unsigned int tickMs)
{
    uint8_t TempH,TempL,CRCT;   
    uint8_t HumiH,HumiL,CRCH;
    if (!I2C1_Start())  //根据函数返回值判断是否设置成功
    {
        return false;
    }   
    I2C1_SendByte(SHT30_IIC_ADDR1 << 1 | I2C1_Direction_Transmitter);     //设置器件地址,设置为发送   
    if (!I2C1_WaitAck()) //读SDA电平,拉低则接受端成功
    {
        I2C1_Stop();
        return false;
    }
//--------------------------------------------------------/发送FETCH DATA COMMAND/------------------------------------------------// 
    I2C1_SendByte(0xE0);                        //发送读取高8位命令
    if (!I2C1_WaitAck()) //等待从设备回应
    {
         I2C1_Stop();
         return false;
    }       
    I2C1_SendByte(0x00);                        //发送读取低8位命令
    if (!I2C1_WaitAck())
    {
         I2C1_Stop();
         return false;
     }
//--------------------------------------------------------/发送FETCH DATA COMMAND/------------------------------------------------// 
    if (!I2C1_Start())
    {
        return false;
    }   
    I2C1_SendByte(SHT30_IIC_ADDR1 << 1 | I2C1_Direction_Receiver);      //设置器件地址,设置为接受
   
    if (!I2C1_WaitAck())
    {
        I2C1_Stop();
        return false;
    }
    TempH = I2C1_ReceiveByte(); //温度高8位
    I2C1_Ack();//此时发送回应给从设备
    TempL = I2C1_ReceiveByte();
    I2C1_Ack();
    CRCT = I2C1_ReceiveByte(); //校验位
    I2C1_Ack();

    HumiH = I2C1_ReceiveByte(); //湿度高8位
    I2C1_Ack();
    HumiL = I2C1_ReceiveByte();
    I2C1_Ack();
    CRCH = I2C1_ReceiveByte();
    I2C1_NoAck();  //非回应

    I2C1_Stop();  //停止
   
    unsigned char crc_t[2] = {TempH,TempL};
    unsigned char crc_h[2] = {HumiH,HumiL};
   
    if((CRCT == SHT3X_CalcCrc(crc_t,2)) && (CRCH == SHT3X_CalcCrc(crc_h,2)))
    {   
        eb_Info.envTemperature_raw_data = ((uint16_t)TempH << 8) | TempL;
        eb_Info.envHumidity_raw_data = ((uint16_t)HumiH << 8) | HumiL;
        eb_Info.envInHumiture = (float)(eb_Info.envHumidity_raw_data * 100) / 65535;  //转换湿度
        eb_Info.envInTemperature = ((175 * (float)eb_Info.envTemperature_raw_data) / 65535) - 45;  //转换温度
       
        return true;
    }
    return false;
}

 

你可能感兴趣的:(STM32深入剖析实践)