#include "iic.h"
#include "delay.h"
/* Private define ------------------------------------------------------------*/
#define AHT20_Addr 0x70
/* Public variables ----------------------------------------------------------*/
float gHumi;
float gTemp;
/* Private function ----------------------------------------------------------*/
/* Public function -----------------------------------------------------------*/
void AHT20_Init(void)
{
uint8_t tx_buff[2], rx_buff[3]={0};
//①刚上电,产品芯片内部就绪需要时间,延时100~500ms,建议500ms
//②上电第一次发0x71读取状态字,判断状态字是否为0x18,如果不是0x18,进行寄存器初始化
IIC_WriteRead(AHT20_Addr, 0, 0, 0, 1, rx_buff, 0);
if((rx_buff[0] & 0x18) != 0x18)
{
tx_buff[0] = 0x00;
tx_buff[1] = 0x00;
IIC_WriteRead(AHT20_Addr, 0x1B, 2, tx_buff, 3, rx_buff, 0);
delay_ms(10);//延时10ms左右
IIC_WriteRead(AHT20_Addr, 0xB0|0x1B, 2, rx_buff+1, 0, 0, 0);
tx_buff[0] = 0x00;
tx_buff[1] = 0x00;
IIC_WriteRead(AHT20_Addr, 0x1C, 2, tx_buff, 3, rx_buff, 0);
delay_ms(10);//延时10ms左右
IIC_WriteRead(AHT20_Addr, 0xB0|0x1C, 2, rx_buff+1, 0, 0, 0);
tx_buff[0] = 0x00;
tx_buff[1] = 0x00;
IIC_WriteRead(AHT20_Addr, 0x1E, 2, tx_buff, 3, rx_buff, 0);
delay_ms(10);//延时10ms左右
IIC_WriteRead(AHT20_Addr, 0xB0|0x1E, 2, rx_buff+1, 0, 0, 0);
}
}
//获得正确的值
uint8_t AHT20_Read(void)
{
uint8_t cnt=0, tx_buff[2]={0x33, 0x00}, rx_buff[6]={0};
uint32_t RetuData = 0;
uint8_t failed_code;
failed_code = IIC_WriteRead(AHT20_Addr, 0xAC, 2, tx_buff, 0, 0, 0); //发送触发测量命令
if(!failed_code)
{
delay_ms(80);
while(1)
{
failed_code = IIC_WriteRead(AHT20_Addr, 0, 0, 0, 1, rx_buff, 0);
if(!failed_code && (rx_buff[0] & 0x80) == 0x80)//直到状态bit[7]为0,表示为空闲状态,若为1,表示忙状态
{
delay_ms(10);
cnt++;
if(cnt >= 10)
break;
}
else
break;
}
if(!failed_code && cnt < 10)
{
failed_code = IIC_WriteRead(AHT20_Addr, 0, 0, 0, 6, rx_buff, 0);
if(!failed_code)
{
RetuData = (RetuData|rx_buff[1])<<8;
RetuData = (RetuData|rx_buff[2])<<8;
RetuData = (RetuData|rx_buff[3]);
RetuData = RetuData >> 4;
gHumi = (RetuData*100*10/1024.0/1024.0)/10.0;//湿度
RetuData = 0;
RetuData = (RetuData|rx_buff[3])<<8;
RetuData = (RetuData|rx_buff[4])<<8;
RetuData = (RetuData|rx_buff[5]);
RetuData = RetuData & 0xfffff;
gTemp = (RetuData*200*10/1024.0/1024.0-500)/10.0; //温度
return 0;
}
}
}
return 1;
}
无线温湿度传感器
● 内置电池或外接5V电源供电
● 无线传输方式支持4G、NB、WIFI、LORA等
● 支持所有传感器接口
【单片机-传感器】项目定制开发 |