关于模拟iic的代码参考:https://blog.csdn.net/qq_45467083/article/details/109433847
下面给出AHT10的代码:
#ifndef _AHT10_H__
#define _AHT10_H__
//转自:https://blog.csdn.net/Dinvent/article/details/105953462
#include "main.h"
typedef uint8_t u8;
typedef uint32_t u32;
#define AHT10_ADDRESS 0x70
#define AHT10_WRITE 0x70
#define AHT10_READ 0x71
/*****************函数声明******************/
extern void AHT10Init(void);
extern u8 AHT10Check(void);
extern void AHT10Reset(void);
extern u8 AHT10ReadData(float *temperature,u8 *humidity);
#endif
#include "aht10.h"
#include "IOI2C.h"
void delay_ms(u32 ms){
u32 i = 0;
for(i=0;i<ms;i++){
u32 a = 3500;
while(a--);
}
}
/**
brief AHT10初始化函数
param NONE
return NONE
*/
void AHT10Init()
{
IIC_Init();
IIC_Start();
IIC_Send_Byte(AHT10_ADDRESS);
IIC_Send_Byte(0xe1);
IIC_Send_Byte(0x08);
IIC_Send_Byte(0x00);
IIC_Stop();
delay_ms(40);//延时20ms让传感器稳定
}
/**
brief 检查AHT10是否存在
param NONE
return 0存在 1不存在
*/
u8 AHT10Check(void)
{
u8 ack=0;
IIC_Start();
IIC_Send_Byte(AHT10_ADDRESS);
ack=IIC_Wait_Ack();
IIC_Stop();
return ack;
}
/**
brief AHT10软复位
param NONE
return NONE
*/
void AHT10Reset(void)
{
IIC_Start();
IIC_Send_Byte(AHT10_WRITE);
IIC_Wait_Ack();
IIC_Send_Byte(0xba);
IIC_Wait_Ack();
IIC_Stop();
}
/**
brief 检查AHT10读温湿度数据
param *temperature:需要读出的温度数据,float指针类型,精度范围+-0.3C
param *humidity:需要读出的湿度数据,u8指针类型,精度范围+-2RH
return 0 读数据正常 1读数据失败
*/
u8 AHT10ReadData(float *temperature,u8 *humidity)
{
u8 ack;
u32 SRH=0,ST=0;
u8 databuff[6];
IIC_Start();
IIC_Send_Byte(AHT10_WRITE);
IIC_Wait_Ack();
IIC_Send_Byte(0xac);
IIC_Wait_Ack();
IIC_Send_Byte(0x33);
IIC_Wait_Ack();
IIC_Send_Byte(0x00);
IIC_Wait_Ack();
IIC_Stop();
delay_ms(80);//延时一会等待数据读出
IIC_Start();
IIC_Send_Byte(AHT10_READ);
IIC_Wait_Ack();
ack=IIC_Read_Byte(1);
if((ack&0x40)==0)
{
databuff[0]=IIC_Read_Byte(1);
databuff[1]=IIC_Read_Byte(1);
databuff[2]=IIC_Read_Byte(1);
databuff[3]=IIC_Read_Byte(1);
databuff[4]=IIC_Read_Byte(0);
IIC_Stop();
SRH=(databuff[0]<<12)+(databuff[1]<<4)+(databuff[2]>>4);
ST=((databuff[2]&0X0f)<<16)+(databuff[3]<<8)+(databuff[4]);
*humidity=(int)(SRH*100.0/1024/1024+0.5);
*temperature=((int)(ST*2000.0/1024/1024+0.5))/10.0-50;
return 0;
}
IIC_Stop();
return 1;
}
测试程序:
测试结果: