SHT20 Command
Hold/No Hold Master Mode
Hold Master Mode : SHT20在测量完之前会拉低SCL,暂停通信。
NoHold Master mode :测量未完成,SHT20 只回应 NACK
*数据最后两位是状态位,计算时置0
#include "S_SHT20.h"
#include "S_IIC.h"
#include "stdio.h"
/*
* SHT20 地址:1000 000
* hold master 模式
* 温度:1110 0011
湿度:1110 0101
no hold master 模式
* 温度:1111 0011
湿度:1111 0101
写寄存器:1110 0110
读寄存器:1110 0111
软重置:1111 1110
*/
#define SHT20_address 0x80
/*SHT20 command*/
#define CMD_T_Measure_Hold 0xe3
#define CMD_RH_Measure_Hold 0xe5
#define CMD_T_Measure_noHold 0xf3
#define CMD_RH_Measure_noHold 0xf5
#define CMD_Write_userRegister 0xe6
#define CMD_Read_userRegister 0xe7
#define CMD_SoftReset 0xfe
/*温度测量函数,返回温度值*/
float SHT20_Get_Temperature(void)
{
uint8_t cmd = CMD_T_Measure_noHold;
uint8_t DataBuff[3] = {0};
uint16_t DataBuff_Link = 0;
float SHT20_Temperature = 0;
HAL_I2C_Master_Transmit(&h_I2C_1,SHT20_address,&cmd,1,100);
HAL_Delay(100);
HAL_I2C_Master_Receive(&h_I2C_1,SHT20_address,DataBuff,3,100);
DataBuff_Link =(uint16_t)DataBuff[0];
DataBuff_Link=DataBuff_Link<<8;
DataBuff_Link=DataBuff_Link + (DataBuff[1] & 0xfc);
//printf("DataBuff_Link = %d\n",DataBuff_Link);
SHT20_Temperature = -46.85+175.72*((float)DataBuff_Link/65536);
return SHT20_Temperature;
}
/*湿度测量函数,返回湿度值*/
float SHT20_Get_RelativeHumidity(void)
{
uint8_t cmd = CMD_RH_Measure_noHold;
uint8_t DataBuff[3] = {0};
uint16_t DataBuff_Link = 0;
float SHT20_Humidity = 0;
HAL_I2C_Master_Transmit(&h_I2C_1,SHT20_address,&cmd,1,100);
HAL_Delay(100);
HAL_I2C_Master_Receive(&h_I2C_1,SHT20_address,DataBuff,3,100);
DataBuff_Link =(uint16_t)DataBuff[0];
DataBuff_Link=DataBuff_Link<<8;
DataBuff_Link= DataBuff_Link + (DataBuff[1] & 0xfc);
//printf("DataBuff_Link = %d\n",DataBuff_Link);
SHT20_Humidity = -6+125*((float)DataBuff_Link/65536);
return SHT20_Humidity;
}
/*使用串口打印温度和湿度值*/
void SHT20_test(void )
{
printf("Temperature = %f\n",SHT20_Get_Temperature());
HAL_Delay(20);
printf("Humidity = %f\n",SHT20_Get_RelativeHumidity());
}
打印读取结果到串口
数据参考
标签:SHT20,I2C,HAL,温湿度,CMD,DataBuff,define From: https://www.cnblogs.com/Yannnnnn/p/17663453.html