目录
一、IIC轮询模式
1.1 配置
1.2 编写AHT20驱动
1.2.1 aht20.h
1.2.2 aht20.c
二、I2C中断
2.1 打开中断
2.2 分离读取流程
2.3 在主函数中重新编写读取流程
2.4 在i2c.c中重新定义stm32f1xx_hal_i2c.h中的两个函数
三、I2CDMA
3.1 配置DMA通道
3.2 代码的修改
一、IIC轮询模式
1.1 配置
1.2 编写AHT20驱动
根据AHT20手册编写初始化与读数据函数
1.2.1 aht20.h
#ifndef INC_AHT20_H_
#define INC_AHT20_H_
#include "i2c.h"
void AHT20_Init();
void AHT20_Read(float* Temperature,float* Humidity);
#endif /* INC_AHT20_H_ */
1.2.2 aht20.c
#include "aht20.h"
#define AHT20_ADDRESS 0x70
void AHT20_Init()
{
uint8_t readBuffer;
HAL_Delay(40);
HAL_I2C_Master_Receive(&hi2c1,AHT20_ADDRESS,&readBuffer,1,HAL_MAX_DELAY);
if((readBuffer& 0x80)==0x00)
{
uint8_t sendBuffer[3]={0xBE,0x80,0x00};
HAL_I2C_Master_Transmit(&hi2c1, AHT20_ADDRESS, sendBuffer, 3, HAL_MAX_DELAY);
}
}
void AHT20_Read(float* Temperature,float* Humidity)
{
uint8_t sendBuffer[3] = {0xAC,0x33,0x00};
uint8_t readBuffer[6];
HAL_I2C_Master_Transmit(&hi2c1, AHT20_ADDRESS, sendBuffer, 3, HAL_MAX_DELAY);
HAL_Delay(75);
HAL_I2C_Master_Receive(&hi2c1,AHT20_ADDRESS,readBuffer,6,HAL_MAX_DELAY);
if((readBuffer[0] & 0x80)== 0x00)
{
uint32_t date = 0;
date=(((uint32_t)readBuffer[3]>>4) + ((uint32_t)readBuffer[2]<<4) + ((uint32_t)readBuffer[1]<<12));
*Humidity = date * 100.0f/(1<<20);
date=(((uint32_t)readBuffer[3]&0x0F)<<16) + ((uint32_t)readBuffer[4]<<8) + (uint32_t)readBuffer[5];
*Temperature = date * 200.0f/(1<<20)-50;
}
}
二、I2C中断
2.1 打开中断
2.2 分离读取流程
分为测量指令 读取指令 解析 三部分
void AHT20_Measure()
{
static uint8_t sendBuffer[3] = {0xAC,0x33,0x00};
HAL_I2C_Master_Transmit_IT(&hi2c1, AHT20_ADDRESS, sendBuffer, 3);
}
void AHT20_Get()
{
HAL_I2C_Master_Receive_IT(&hi2c1,AHT20_ADDRESS,readBuffer,6);
}
void AHT20_Analysis(float* Temperature,float* Humidity)
{
if((readBuffer[0] & 0x80)== 0x00)
{
uint32_t date = 0;
date=(((uint32_t)readBuffer[3]>>4) + ((uint32_t)readBuffer[2]<<4) + ((uint32_t)readBuffer[1]<<12));
*Humidity = date * 100.0f/(1<<20);
date=(((uint32_t)readBuffer[3]&0x0F)<<16) + ((uint32_t)readBuffer[4]<<8) + (uint32_t)readBuffer[5];
*Temperature = date * 200.0f/(1<<20)-50;
}
}
2.3 在主函数中重新编写读取流程
if(aht20State==0)
{
AHT20_Measure();
aht20State=1;
}else if(aht20State==2)
{
HAL_Delay(75);
AHT20_Get();
aht20State=3;
}else if(aht20State==4)
{
AHT20_Analysis(&temperature, &humidity);
sprintf(message,"温度�? %.1f �?, 湿度�?%.1f %%\r\n",temperature,humidity);
HAL_UART_Transmit(&huart1, (uint8_t*)message, strlen(message), HAL_MAX_DELAY);
HAL_Delay(1000);
aht20State=0;
}
2.4 在i2c.c中重新定义stm32f1xx_hal_i2c.h中的两个函数
// 发送完成时回调
void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
if(hi2c==&hi2c1)
{
aht20State=2;
}
}
void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
if(hi2c==&hi2c1)
{
aht20State=4;
}
}
三、I2CDMA
3.1 配置DMA通道
3.2 代码的修改
HAL_I2C_Master_Transmit_IT(&hi2c1, AHT20_ADDRESS, sendBuffer, 3);
//修改为
HAL_I2C_Master_Transmit_DMA(&hi2c1, AHT20_ADDRESS, sendBuffer, 3);
HAL_I2C_Master_Receive_IT(&hi2c1,AHT20_ADDRESS,readBuffer,6);
//修改为
HAL_I2C_Master_Receive_DMA(&hi2c1,AHT20_ADDRESS,readBuffer,6);