TA的每日心情 | 奋斗 半小时前 |
---|
签到天数: 1970 天 连续签到: 26 天 [LV.Master]伴坛终老
|
本帖最后由 流水源 于 2023-7-24 13:50 编辑
本次实验测试一下串口的发送接收。方便后面输出调试信息。
首先找到串口端口,PA11和PA12。
找到PA11和PA12的复用功能表,可以看到是AF5组复用功能对应USART1.
下面初始化串口端口:
- void PLATFORM_InitConsole(uint32_t Baudrate)
- {
- GPIO_InitTypeDef GPIO_InitStruct;
- USART_InitTypeDef USART_InitStruct;
- RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
- GPIO_PinAFConfig(GPIOA, GPIO_PinSource11, GPIO_AF_5);
- GPIO_PinAFConfig(GPIOA, GPIO_PinSource12, GPIO_AF_5);
- GPIO_StructInit(&GPIO_InitStruct);
- GPIO_InitStruct.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
- GPIO_InitStruct.GPIO_Speed = GPIO_Speed_High;
- GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
- GPIO_Init(GPIOA, &GPIO_InitStruct);
-
-
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART1, ENABLE);
- USART_StructInit(&USART_InitStruct);
- USART_InitStruct.USART_BaudRate = Baudrate;
- USART_InitStruct.USART_WordLength = USART_WordLength_8b;
- USART_InitStruct.USART_StopBits = USART_StopBits_1;
- USART_InitStruct.USART_Parity = USART_Parity_No;
- USART_InitStruct.USART_Mode = USART_Mode_Tx|USART_Mode_Rx;
- USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
- USART_Init(USART1, &USART_InitStruct);
- USART_Cmd(USART1, ENABLE);
-
- //使能UARTx RC中断
- USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
- //优先级,无优先级分组
- NVIC_SetPriority(USART1_IRQn, 0);
- //UARTx中断使能
- NVIC_EnableIRQ(USART1_IRQn);
- }
复制代码 映射到printf输出:
- int stdout_putchar (int ch)
- {
- USART_SendData(USART1, (uint8_t)ch);
- while (RESET == USART_GetFlagStatus(USART1, USART_FLAG_TC)){;}
- return (ch);
- }
- int fputc(int ch,FILE *f)
- {
- return stdout_putchar(ch);
- }
复制代码 中断接收数据,通过FIFO缓存:
- typedef struct fifo_buffer
- {
- volatile uint32_t read_i;
- volatile uint32_t write_i;
- uint8_t buff[128];
- }fifo_buffer;
- extern fifo_buffer shell_uart_rx;
- fifo_buffer shell_uart_rx=
- {
- .read_i = 0,
- .write_i = 0,
- };
- void USART1_IRQHandler(void)
- {
- uint32_t statusFlag;
- uint32_t ch;
-
- statusFlag = USART1->SR;
- if((statusFlag & USART_IT_RXNE) != 0)
- {
- ch = USART_ReceiveData(USART1);
- if(((shell_uart_rx.write_i+1)&0x7f) != shell_uart_rx.read_i)
- {
- shell_uart_rx.buff[shell_uart_rx.write_i++] = ch & 0xff;
- shell_uart_rx.write_i &= 0x7f;
- }
- }
- USART1->SR &= ~statusFlag;
- }
复制代码 测试接收数据,将接收的数据重复发送出来。
- void shell_usart_loop(void)
- {
- if(shell_uart_rx.read_i != shell_uart_rx.write_i)
- {
- stdout_putchar(shell_uart_rx.buff[shell_uart_rx.read_i++]);
- shell_uart_rx.read_i &= 0x7f;
- }
- }
复制代码
- void GPIO_LED_Toggle_Sample(void)
- {
- printf("\r\nTest %s", __FUNCTION__);
- GPIO_Configure();
- while (1)
- {
- GPIO_IO_Toggle(GPIOB, GPIO_Pin_9);
- shell_usart_loop(); //串口接收并发送
- PLATFORM_DelayMS(100);
- }
- }
复制代码
|
|