stm32串口回调函数 2021-09-02

2021-09-02  本文已影响0人  宜居远控

STM32中断数据回调函数接收处理


1.定义一个空的指针函数 指针函数的参数是uint8_t 类型ch

typedef void (* usart_recv_callback)(uint8_t ch);

2.声明这个类型

usart_recv_callback  usart1_recv_cb;

3.串口配置时,一个形参为串口中断接收回调

void Usart_Config(USART_TypeDef* USARTx, uint32_t baudRate, usart_recv_callback cb)

{

GPIO_InitTypeDef GPIO_InitStructure;

USART_InitTypeDef USART_InitStructure;

NVIC_InitTypeDef NVIC_InitStructure;

if(USARTx == USART1)

{

usart1_recv_cb = cb;

RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);

/* Configure USART1 Tx (PA.09) as alternate function push-pull */

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;

GPIO_Init(GPIOA, &GPIO_InitStructure);

/* Configure USART1 Rx (PA.10) as input floating */

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;

GPIO_Init(GPIOA, &GPIO_InitStructure);

USART_InitStructure.USART_BaudRate = baudRate;

USART_InitStructure.USART_WordLength = USART_WordLength_8b;

USART_InitStructure.USART_StopBits = USART_StopBits_1;

USART_InitStructure.USART_Parity = USART_Parity_No;

USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;

USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

USART_Init(USART1, &USART_InitStructure);

if(cb)

{

USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);

/* Enable the USARTy Interrupt */

NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;

NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;

NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

NVIC_Init(&NVIC_InitStructure);

}

USART_Cmd(USART1, ENABLE);

}

}


分析:usart1_recv_cb = cb;这句语句是将形参指针函数 cb 赋值给 usart1_recv_cb

            if(cb):是判断回调函数指针是否为空,如果不为空则中断初始化

4.串口中断函数

void USART1_IRQHandler(void)

{

uint8_t ch;

if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)

{

/* Read one byte from the receive data register */

ch = USART_ReceiveData(USART1);

usart1_recv_cb(ch);

USART_ClearITPendingBit(USART1, USART_IT_RXNE);

}

}

分析:将串口1中断接收到的值赋值给ch,然后ch作为usart1_recv_cb函数的输入参数


5.

void HCHO_Test(uint8_t recv_data)

{

if((sensorstr.hcho_addr == 0) && (recv_data != 0xff))

{

sensorstr.hcho_addr = 0;

return;

}

if((sensorstr.hcho_addr == 1) && (recv_data != 0x17))

{

sensorstr.hcho_addr = 0;

return;

}

if((sensorstr.hcho_addr == 2) && (recv_data != 0x04))

{

sensorstr.hcho_addr = 0;

return;

}

sensorstr.hcho_packet[sensorstr.hcho_addr++] = recv_data;

}

分析:void HCHO_Test(uint8_t recv_data)函数就是我们所说的回调函数,此函数和 1.里所定义的void (* usart_recv_callback)(uint8_t ch)函数指针是对应的。

6.

int main(void)

{

Usart_Config(PM_UART, 9600, PM_Test);

}

PM_Test函数首地址就是usart_recv_callback cb的形参

转自:https://blog.csdn.net/qq_27568125/java/article/details/55253723

上一篇下一篇

猜你喜欢

热点阅读