/**
******************************************************************************
* @file AM23xx.c
* @author Kite
* @version NULL
* @date 4-November-2012
* @brief The AM23xx C file.
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "AM23xx.h"
#include "delay.h"
//delay functions
void delay_am23xx_ms(uint16_t xms)
{
delay_ms(xms);
}
/* Exported variables --------------------------------------------------------*/
uint8_t AM_SensorData[5]={0x00, 0x00, 0x00, 0x00, 0x00};
uint16_t RH_value;
uint16_t Temp_value;
/* Private functions declared ------------------------------------------------*/
unsigned char AM23XX_Read_Byte(void); //读取单字节
/* Exported functions ------------------------------------------------------- */
/**
* @brief AM23XX read data.
* @param None
* @retval dat: The data to be read.
*/
unsigned char AM23XX_Read(void) //读取温湿度
{
unsigned char i, AM23XX_answerFlag=0;
unsigned int cnt=0;
AM23XX_OUT_SET; //IO设置为输出
AM23XX_OUT(0); //主机发开始信号, 单总线拉低(至少500us)
delay_ms(1);
AM23XX_OUT(1); //释放总线, 等待从机响应
delay_us(30); //延时(20~40us)
AM23XX_IN_SET; //IO设置为输入
if(AM23XX_IN == 0) //检测从机响应信号
{
cnt = 0;
while(! AM23XX_IN) //等待低电平结束(80us)
{
if(++cnt >= 100000)
return 0;
}
cnt = 0;
while(AM23XX_IN) //等待高电平结束
{
if(++cnt >= 100000)
return 0;
}
for(i=0; i<5; i++)
{
AM_SensorData[i] = AM23XX_Read_Byte();
}
AM23XX_answerFlag = 1; //应答标志变量置位
}
else
{
AM23XX_answerFlag = 0;
}
return AM23XX_answerFlag;
}
/**
* @brief Check the data received.
* @param None
* @retval None
*/
unsigned char AM23XX_DataCheck(void)
{
uint8_t data_check;
data_check = AM_SensorData[0]+AM_SensorData[1]+AM_SensorData[2]+AM_SensorData[3];
if(data_check == AM_SensorData[4])
return 1;
else
return 0;
}
/**
* @brief Convert the data to decimal base.
* @param None
* @retval None
*/
void AM23XX_DataConvert(void)
{
RH_value = AM_SensorData[0]*256 + AM_SensorData[1];
Temp_value = AM_SensorData[2]*256 + AM_SensorData[3];
}
/* Private functions -------------------------------------------------------- */
/**
* @brief AM23XX Read single byte.
* @param None
* @retval None
*/
unsigned char AM23XX_Read_Byte(void)
{
unsigned char i, single_bit, dat;
unsigned int cnt;
AM23XX_IN_SET; //IO设置为输入
for(i=0; i<8; i++)
{
while(! AM23XX_IN) //等待低电平结束
{
if(++cnt >= 100000)
break;
}
delay_us(30); //判断单位数据(26~28us为"0", 70us为"1")
single_bit = 0;
if(AM23XX_IN) //若高电平时间超过30us,则为"1"
{
single_bit = 1;
}
cnt = 0;
while(AM23XX_IN) //等待高电平结束
{
if(++cnt >= 100000)
break;
}
dat <<= 1; //存储数据
dat |= single_bit;
}
return dat;
}