本帖最后由 huaimengzi 于 2024-12-26 18:43 编辑
想写一个串口通信,利用串口收发中断来写,非DMA,发现上电按复位键调试,串口立马进入中断发送,是什么原因呢?求大家帮助指点一下
实验现象,上电即发送7,代码如下:
1. 串口GPIO初始化
static void Com0_Gpio_Init(void)
{
/* enable COM GPIO clock */
rcu_periph_clock_enable(BSP_USART0_PORT_RCU);
/* connect port to USARTx_Tx */
gpio_af_set(BSP_USART0_PORT, BSP_USART0_AF, BSP_USART0_TX_PIN);
/* connect port to USARTx_Rx */
gpio_af_set(BSP_USART0_PORT, BSP_USART0_AF, BSP_USART0_RX_PIN);
/* configure USART Tx as alternate function push-pull */
gpio_mode_set(BSP_USART0_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, BSP_USART0_TX_PIN);
gpio_output_options_set(BSP_USART0_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, BSP_USART0_TX_PIN);
/* configure USART Rx as alternate function push-pull */
gpio_mode_set(BSP_USART0_PORT, GPIO_MODE_AF, GPIO_PUPD_PULLUP, BSP_USART0_RX_PIN);
gpio_output_options_set(BSP_USART0_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, BSP_USART0_RX_PIN);
/*5.配置RS485的Enable引脚*/
rcu_periph_clock_enable(BSP_RS485EN0_RCU); //开启时钟
gpio_mode_set(BSP_RS485EN0_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP, BSP_RS485EN0_PIN); //输出,上拉
gpio_output_options_set(BSP_RS485EN0_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_10MHZ, BSP_RS485EN0_PIN);//配置为推挽输出
}
2. USART0 配置初始化
static void Com0_Usart0_Init(uint32_t BaudRate)
{
/* enable USART clock */
rcu_periph_clock_enable(BSP_USART0_RCU);
/* USART configure */
usart_deinit(BSP_USART0); //复位串口
usart_baudrate_set(BSP_USART0, BaudRate); //设置波特率
usart_parity_config(BSP_USART0,USART_PM_NONE); //设置无校验
usart_word_length_set(BSP_USART0,USART_WL_8BIT); //配置数据位的长度8
usart_stop_bit_set(BSP_USART0, USART_STB_1BIT); //停止位1位
usart_hardware_flow_rts_config(BSP_USART0, USART_RTS_DISABLE);//RTS流控关闭
usart_hardware_flow_cts_config(BSP_USART0, USART_CTS_DISABLE);//CTS流控关闭
/*打开RX,TX及串口的开关*/
usart_transmit_config(BSP_USART0,USART_TRANSMIT_ENABLE); //使能发送
usart_receive_config(BSP_USART0, USART_RECEIVE_ENABLE); //使能接收
DIR_RX0; //5.2 作为从机,初始状态设置为等待接收状态
usart_enable(BSP_USART0); //使能串口
/* USART interrupt configuration */
nvic_irq_enable(BSP_USART0_IRQn,0U); //在内核中打开串口及配置中断优先级
usart_interrupt_enable(BSP_USART0, USART_INT_RBNE); //读数据缓冲区非空中断和过载错误中断
usart_interrupt_enable(BSP_USART0, USART_INT_TBE); //发送缓冲区空中断
/*6.把结构体进行初始化*/
UART0.m_ReceiveBytes = 0;
UART0.m_SendBytes = 0;
UART0.ComInterruptFlag = 0;
UART0.g_NoticeTimeOutCounterStartFlag = 0;
UART0.g_TimeOutCounter = 0;
UART0.g_RecTimeOverFlag = 0;
UART0.p_RecBuff = (uint8_t *)UART0.RecBuff; //将发送数据指针指向发送缓冲区头
UART0.p_SendBuff = (uint8_t *)UART0.SendBuff; //将接收数据指针指向接收缓存区头
}
3. USART0中断服务函数 接收中断,发送中断
void USART0_IRQHandler(void)
{
if(usart_interrupt_flag_get(BSP_USART0, USART_INT_FLAG_RBNE) != RESET) //接收缓冲区非空中断,表示里面有数据了
{
led_setup(LED2,ON);
data = usart_data_receive(BSP_USART0); //将接收到的字节存储到缓冲区
}
if(usart_interrupt_flag_get(BSP_USART0, USART_INT_FLAG_TBE)!= RESET) //发送缓冲区空中断
{
usart_interrupt_flag_clear(BSP_USART0, USART_INT_FLAG_TBE); //清除发送中断标志
led_setup(LED3,ON);
usart_data_transmit(BSP_USART0, 7); //将数据写入USART_DR进行发送
}
}
4. 调试上电复位后,立马收到数字7
|
很常见,一般都是通过协议处理