STM32_HAL库I2C通信状态机下中断&DMA模式操作指令(基于CubeMX软件)

发布于 2024-03-01  197 次阅读


流程图展示

uint8_t readBuffer[6];
//全局变量

void ****_Measure(){
  static uint8_t sendBuffer[3]={***,***,***};
//定义静态变量防止sendBuffer被修改
  HAL_I2C_Master_Transmit_IT(&hi2c1,****_ADRESS,sendBuffer,3);
//HAL_I2C_Master_Transmit_DMA(&hi2c1,****_ADRESS,sendBuffer,3);
}
//数据发送函数

void ****_Get(){
  HAL_I2C_Master_Receive_IT(&hi2c1,****_ADRESS,&readBuffer,6);
//HAL_I2C_Master_Receive_DMA(&hi2c1,****_ADRESS,&readBuffer,6);
//I2C中断接收
}
//数据接收函数

void ****_Analysis(float*Temperature,float*Humidity){
    if ((readBuffer[0]&0x80)==0x00{
    uint32_t data =0;
    data=((unit32_t)readBuffer[3]>>4+**************;
    *Humidity = data *300*******;
    *Temperature = data**********;}

}
//数据分析函数

void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
{if(hi2c==&hi2c1)
  {
   ****State=2;} 
}
//发送回调函数

void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
{if(hi2c==&hi2c1)
  {
   ****State=4;}
}
//接收回调函数
uint8_t ****State = 0;
//0:初始状态,发松测量指令 1:正在发送测量命令  2:测量命令发送完成,等待75毫秒后读取数据  3:读取中  4:  读取完成,解析并展示数据恢复初始状态
//main.h中声明 extern uint8_t ****State;全局变量

while(1){
  if(****State==0){
    ****_Measure();
    ****State = 1;
  }else if(****State==2){
    HAL_Delay(75);
    ****_Get();
    ****State = 3;
  }else if(****State==4){
    ****_Analysis(&temperature,&humidity);
    sprintf(message,"温度:%.lf℃,湿度%.lf %%\r\n",temperature,humidity);
    HAL_UART_Transmit(&huart2<(unit8_t*)message,strlen(message),HAL_MAS_DELAY);
    
    HAL_Delay(1000);
    ****State=0;
  }


}