开发板引出了2路串口,默认接的是串口1
查看使用的引脚
配置串口,并开启中断
void uart_init()
{
USART_Config_T usartConfigStruct;
GPIO_Config_T GPIO_configStruct;
GPIO_ConfigStructInit(&GPIO_configStruct);
RCM_EnableAHB1PeriphClock(RCM_AHB1_PERIPH_GPIOA);
RCM_EnableAPB2PeriphClock(RCM_APB2_PERIPH_USART1);
GPIO_ConfigPinAF(GPIOA, GPIO_PIN_SOURCE_9, GPIO_AF_USART1);
GPIO_ConfigPinAF(GPIOA, GPIO_PIN_SOURCE_10, GPIO_AF_USART1);
GPIO_configStruct.mode = GPIO_MODE_AF;
GPIO_configStruct.pin = GPIO_PIN_9 | GPIO_PIN_10;;
GPIO_configStruct.speed = GPIO_SPEED_50MHz;
GPIO_Config(GPIOA, &GPIO_configStruct);
usartConfigStruct.baudRate = 115200;
usartConfigStruct.hardwareFlow = USART_HARDWARE_FLOW_NONE;
usartConfigStruct.mode = USART_MODE_TX_RX;
usartConfigStruct.parity = USART_PARITY_NONE;
usartConfigStruct.stopBits = USART_STOP_BIT_1;
usartConfigStruct.wordLength = USART_WORD_LEN_8B;
USART_Config(USART1, &usartConfigStruct);
USART_Enable(USART1);
USART_EnableInterrupt(USART1, USART_INT_RXBNE);
USART_EnableInterrupt(USART1, USART_INT_IDLE);
USART_ClearStatusFlag(USART1, USART_FLAG_RXBNE);
NVIC_EnableIRQRequest(USART1_IRQn,0,0);
}
在中断中处理串口数据的收发
#define UART_BUFFER_LEN 30
uint8_t uart_buffer[UART_BUFFER_LEN] = {0};
uint8_t uart_rxindex = 0;
uint8_t uart_rxlen = 0;
uint8_t uart_txindex = 0;
uint8_t uart_txlen = 0;
void readrxtotxbuffer()
{
uart_txlen += uart_rxlen;
uart_rxlen = 0;
USART_EnableInterrupt(USART1, USART_INT_TXBE);
}
void USART1_IRQHandler(void)
{
if(USART_ReadStatusFlag(USART1, USART_FLAG_RXBNE) == SET){
uart_buffer[uart_rxindex++] = (uint8_t)USART_RxData(USART1);
if(uart_rxindex == UART_BUFFER_LEN)
uart_rxindex = 0;
uart_rxlen++;
}
if(USART_ReadStatusFlag(USART1, USART_FLAG_IDLE) == SET|| uart_rxlen == 10) {
USART_ClearStatusFlag(USART1, USART_FLAG_IDLE);
readrxtotxbuffer();
}
if(USART_ReadStatusFlag(USART1, USART_FLAG_TXBE) == SET){
if(uart_txlen > 0)
{
USART_TxData(USART1,uart_buffer[uart_txindex++]);
if(uart_txindex == UART_BUFFER_LEN)
uart_txindex = 0;
uart_txlen--;
}
else
{
USART_DisableInterrupt(USART1, USART_INT_TXBE);
}
}
}
运行效果
接下来实现printf重定向到串口,方便打印调试信息
在工程设置中勾选这个
代码中添加
int fputc(int ch, FILE *f)
{
USART_TxData(USART1, ch);
while (USART_ReadStatusFlag(USART1, USART_FLAG_TXBE) == RESET);
return ch;
}
测试
int main(void)
{
uint8_t i = 0;
ConfigSysClock();
uart_init();
while (1)
{
i += 1;
printf("极海APM32F411串口Printf测试 by yuyy1989 当前数字是:%d\n",i);
}
}
运行结果
最后用CoreMark测试下性能,仅供参考
|