我现在在用一款 Honeywell的温湿度传感器-HIH-6131-021-001,根据他家的datasheet,我写的程序不能正确读出来数据,下面直接说问题,贴代码。
获取该温湿度传感器数据包括两步:(1)主机通过I2C发送写传感器命令,传感器开始测量温湿度。(2)主机通过I2C发送读传感器命令,获取传感器温度。
[mw_shl_code=c,true]/*Read data from senesor*/
void Humi_Temp(void)
{
/*4 Byte to be read */
u16 NumByteToRead=0x04;
u16 Humidity=0;
u16 Temperature=0;
u8 I2C_Buffer[4]={0x00,0x00,0x00,0x00};
I2C_SensorWrite();
/*Delay for measurement.
The measurement cycle duration is typically 36.65 ms for
temperature and humidity readings */
delay_xms(36);
I2C_SensorRead(I2C_Buffer,NumByteToRead);
/*I2C_Buffer[0-1]: Humidity
I2C_Buffer[2-3]: Temperature
Humidity(%)=Humidity_Output_Count/(2^14-2)*100%
Temperature(Celsius)=Temperature_Output_Count/(2^14-2)*165-40 */
Humidity =((I2C_Buffer[0] & 0x3f) << 8 | I2C_Buffer[1])/(2^14-2)*100;
Temperature = (((I2C_Buffer[2]<<8)|(I2C_Buffer[3]&0xfc))>>2)/(2^14-2)*165-40;
delay_xms(20);
USART_SendData(USART2,Humidity);
delay_xms(20);
USART_SendData(USART2,Temperature);
}
/*Send Measurement Request */
void I2C_SensorWrite(void)
{
/*send Measurement Request (MR) command to sensor */
/* While the bus is busy */
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY)){;}
/* Enable the I2C1 Acknowledgement */
// I2C_AcknowledgeConfig(I2C1, ENABLE);
/* Send START condition */
I2C_GenerateSTART(I2C1, ENABLE);
/* Test on EV5 and clear it */
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT)){;}
/* Send Measurement Request */
I2C_Send7bitAddress(I2C1, I2C1_SLAVE_ADDRESS7, I2C_Direction_Transmitter);
/* Test on EV6 and clear it */
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)){;}
/*EV8*/
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED)){;}
/* Send STOP Condition */
I2C_GenerateSTOP(I2C1, ENABLE);
}
/*read humidity and temperature */
void I2C_SensorRead(u8 *pBuffer,u16 NumByteToRead)
{
/*send read command to sensor */
/* While the bus is busy */
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY)){;}
/* Enable the I2C1 Acknowledgement */
I2C_AcknowledgeConfig(I2C1, ENABLE);
/*Send STRAT condition a second time */
I2C_GenerateSTART(I2C1, ENABLE);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT)){;}
/* Read sensor data */
I2C_Send7bitAddress(I2C1, I2C1_SLAVE_ADDRESS7, I2C_Direction_Receiver);
while(!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)){;}
/* While there is data to be read */
while(NumByteToRead)
{
if(NumByteToRead == 1)
{
/* Disable Acknowledgement */
I2C_AcknowledgeConfig(I2C1, DISABLE);
/* Send STOP Condition */
I2C_GenerateSTOP(I2C1, ENABLE);
}
/* Test on EV7 and clear it */
if(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_RECEIVED))
{
/* Read a byte from the EEPROM */
*pBuffer = I2C_ReceiveData(I2C1);
/* Point to the next location where the byte read will be saved */
pBuffer++;
/* Decrement the read bytes counter */
NumByteToRead--;
}
}
/* Enable the I2C1 Acknowledgement */
I2C_AcknowledgeConfig(I2C1, ENABLE);
}[/mw_shl_code]
|