配置完成后,对I2C2的具体初始化代码如下:
static void MX_I2C2_Init(void) {
hi2c2.Instance = I2C2;
hi2c2.Init.ClockSpeed = 100000;
hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c2.Init.OwnAddress1 = 0;
hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c2.Init.OwnAddress2 = 0;
hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c2)!= HAL_OK)
{
Error_Handler();
}
}
对GPIO的初始化配置:
void HAL_I2C_MspInit(I2C_HandleTypeDef* hi2c)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(hi2c->Instance==I2C2)
{
/**I2C2GPIO 配置
PB10 ------> I2C2_SCL
PB11 ------> I2C2_SDA */
GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
__HAL_RCC_I2C2_CLK_ENABLE();
}
}
完成以上配置后,接下来我们编写SHT20的驱动程序,由于SHT20采用的是标准的I2C协议,所以我们可以方便的使用ST提供的相关库函数。
//读取测量数据
uint8_t SHT2x_MeasureHM(etSHT2xMeasureTypeeSHT2xMeasureType, nt16 *pMeasurand)
{
uint8_tchecksum;
uint8_tdata[2];
uint8_terror=0;
uint16_ti;
I2c_StartCondition();
error |=I2c_WriteByte (I2C_ADR_W);
switch(eSHT2xMeasureType)
{
caseHUMIDITY:
{
error|= I2c_WriteByte (TRIG_RH_MEASUREMENT_HM);
break;
}
case TEMP:
{
error|= I2c_WriteByte (TRIG_T_MEASUREMENT_HM);
break;
}
default:assert(0);
}
I2c_StartCondition();
error |=I2c_WriteByte (I2C_ADR_R);
SCL=HIGH;
for(i=0;i<1000; i++)
{DelayMicroSeconds(1000);
if(SCL_CONF==1) break;
}
if(SCL_CONF==0) error |= TIME_OUT_ERROR;
pMeasurand->s16.u8H = data[0] =I2c_ReadByte(ACK);
pMeasurand->s16.u8L = data[1] =I2c_ReadByte(ACK);
checksum=I2c_ReadByte(NO_ACK);
error |=SHT2x_CheckCrc (data,2,checksum);
I2c_StopCondition();
returnerror;
}
//软件复位
uint8_t SHT2x_SoftReset()
{
uint8_terror=0;
I2c_StartCondition();
error |=I2c_WriteByte (I2C_ADR_W);
error |=I2c_WriteByte (SOFT_RESET);
I2c_StopCondition();
DelayMicroSeconds(15000);
returnerror;
}
//计算相对湿度
float SHT2x_CalcRH(uint16_t u16sRH)
{
fthumidityRH;
u16sRH&= ~0x0003;
humidityRH= -6.0 + 125.0/65536 * (ft)u16sRH;
returnhumidityRH;
}
//计算温度
float SHT2x_CalcTemperatureC(uint16_t u16sT)
{
fttemperatureC;
u16sT&= ~0x0003;
temperatureC= -46.85 + 175.72/65536*(ft)u16sT;
returntemperatureC;
}
编写完成编译没问题,运行看一看结果。显示当前的室温为23.3摄氏度,相对湿度为17.5%。
接下来我们试验一下,对传感器吹一口气。由于人呼出的气体含有大量水蒸气,所以湿度时都会明显上升。但是温度的变化不会太明显。
由于空气的流动,湿度会在停止吹气后开始下降,如下图所示: