主页 > 互联网 > 内容页

世界看热讯:【CW32饭盒派开发板试用体验】串口实验

2023-05-29 09:01:47 来源:华仔的编程随笔


(资料图片)

串口选择

示例给出的是串口的,因为今天回老家,带的杜绑线是公对母的,不能接串口1,所以选择串口2,即PA2--TX,PA3--RX。

初始化串口

初始化UART2的时钟:__RCC_UART2_CLK_ENABLE();初始化GPIOA外设时钟:RCC_AHBPeriphClk_Enable( RCC_AHB_PERIPH_GPIOA, ENABLE);复用PA2为UART2TX: PA02_AFx_UART2TXD();复用PA3为UART2RX:PA03_AFx_UART2RXD();初始化PA2为高速输出模式:
GPIO_InitStructure.Pins = GPIO_PIN_2; //PA2  GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;  GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;  GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
初始化PA3为上拉输入:
GPIO_InitStructure.Pins = GPIO_PIN_3; //PA3  GPIO_InitStructure.Mode = GPIO_MODE_INPUT_PULLUP;  GPIO_Init(CW_GPIOA, &GPIO_InitStructure);
初始化UART2配置为9600波特率:
USART_InitStructure.USART_BaudRate= 9600;  USART_InitStructure.USART_Over = USART_Over_16;  USART_InitStructure.USART_Source = USART_Source_PCLK;  USART_InitStructure.USART_UclkFreq = 64000000;  USART_InitStructure.USART_StartBit = USART_StartBit_FE;  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(CW_UART2, &USART_InitStructure);
使能中断输入
//使能UARTx RC中断  USART_ITConfig(CW_UART2, USART_IT_RC, ENABLE);  //优先级,无优先级分组  NVIC_SetPriority(UART2_IRQn, 0);  //UARTx中断使能  NVIC_EnableIRQ(UART2_IRQn);
中断接收函数,主要功能为判断接收到的第一位是否为0,第二位是否为1,如果总接收长度为4位,测翻转LED4,具体代码如下:
void UART2_IRQHandler(void){  /* USER CODE BEGIN */  unsigned char TxRxBuffer;  if(USART_GetITStatus(CW_UART2, USART_IT_RC) != RESET)  { USART_ClearITPendingBit(CW_UART2, USART_IT_RC);     TxRxBuffer = USART_ReceiveData_8bit(CW_UART2);rec[re_count]=TxRxBuffer; if (re_count == 0&&rec[0]==0x00){          rev_start=1;re_count++;}else if(rev_start==1){if(re_count==1&&rec[1]!=0x01){re_count=0;rev_start=0;}else if(re_count==4)           //计算总个数,0-4       {check_flag=1;re_count=0;rev_start=0;}  //如果对,那么将标志位置1,并清除里面的值从新接收else   re_count++;}  }  /* USER CODE END */}

实现效果,下载后,串口接收到0x00 0x01 0x02 0x03 ,HEX发送00 01 02 03 可以实现LED4的翻转:

审核编辑:汤梓红

标签:

上一篇:【一季度江苏经济复苏趋势· 城市观】② 常州与盐城工业经济表现何以如此亮眼-实时
下一篇:最后一页