STM32 例程-6 STM32CubeMx 读取SHT20 温湿度

1、使用STMF32F407ZGTx MCU
RCC
image
SYS
image
2、生成项目,并打开
3、在主代码里添加如下代码

#define SHT20_WriteAddr 0x80
#define SHT20_ReadAddr  0x81

#define SHT20_Trig_T 0xE3
#define SHT20_Trig_RH 0xE5
float TemValue,RhValue;

void SHT20_ReadValues(void)
{
 uint8_t tem[3],rh[3];
 uint16_t Tdata=0,RHdata=0;
 
 //第一种方法:分步操作
// uint8_t cmd;
// 
// cmd=SHT20_Trig_T;
// HAL_I2C_Master_Transmit(&hi2c1,SHT20_WriteAddr,&cmd,1,0xffff);
// HAL_Delay(100);
// HAL_I2C_Master_Receive(&hi2c1,SHT20_ReadAddr,tem,3,0x3ffff);
// 
// cmd=SHT20_Trig_RH;
// HAL_I2C_Master_Transmit(&hi2c1,SHT20_WriteAddr,&cmd,1,0xffff);
// HAL_Delay(100);
// HAL_I2C_Master_Receive(&hi2c1,SHT20_ReadAddr,rh,3,0x3ffff);
 
 //第二种方法:复合操作
 HAL_I2C_Mem_Read(&hi2c2,SHT20_ReadAddr,SHT20_Trig_T,I2C_MEMADD_SIZE_8BIT,tem,3,0xffff);
 HAL_I2C_Mem_Read(&hi2c2,SHT20_ReadAddr,SHT20_Trig_RH,I2C_MEMADD_SIZE_8BIT,rh,3,0xffff);
 
 Tdata = tem[0];
 Tdata <<= 8;
 Tdata += tem[1] & 0xfe;
 
 RHdata = rh[0];
 RHdata <<= 8;
 RHdata += rh[1] & 0xfe;
 
 TemValue = Tdata * 175.72f / 65536 - 46.85f;
 RhValue = RHdata * 125.0f / 65536 - 6.0f;
}

void SHT20_SoftReset(void)
{
 uint8_t cmd=0xfe;
 
 HAL_I2C_Master_Transmit(&hi2c2,SHT20_WriteAddr,&cmd,1,0xffff);
 
 HAL_Delay(100);
}
 while (1)
  {
    /* USER CODE END WHILE */
		SHT20_SoftReset();
		SHT20_ReadValues();
    /* USER CODE BEGIN 3 */
  }

4、下载代码执行
image

posted @ 2022-04-01 21:35  zhaogaojian  阅读(824)  评论(1编辑  收藏  举报