对于单片机来说信息交互显示才是有利于问题排查的一个友好界面。一般情况下,大多数单片机都有串口通讯,
下面咱们就以芯源的CW32F003ExPx StartKit开发板给大家展示串口通讯的一个过程。
首先咱们查阅文档发现CW32F003ExPx StartKit开发板PA00与PB02分别为串口接收与发送口,
而且这2个引脚挨在一起方便引线。
下面就是对这个2个引脚的复用配置,以及串口波特率等参数配置
//UARTx
#define DEBUG_USARTx CW_UART1
#define DEBUG_USART_CLK RCC_APB2_PERIPH_UART1
#define DEBUG_USART_APBClkENx RCC_APBPeriphClk_Enable2
#define DEBUG_USART_BaudRate 9600
#define DEBUG_USART_UclkFreq 8000000
//UARTx GPIO
#define DEBUG_USART_TX_GPIO_CLK RCC_AHB_PERIPH_GPIOB
#define DEBUG_USART_RX_GPIO_CLK RCC_AHB_PERIPH_GPIOA
#define DEBUG_USART_TX_GPIO_PORT CW_GPIOB
#define DEBUG_USART_TX_GPIO_PIN GPIO_PIN_2
#define DEBUG_USART_RX_GPIO_PORT CW_GPIOA
#define DEBUG_USART_RX_GPIO_PIN GPIO_PIN_0
//GPIO AF
#define DEBUG_USART_AFTX PB02_AFx_UART1TXD()
#define DEBUG_USART_AFRX PA00_AFx_UART1RXD()
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
//UART TX RX 复用
DEBUG_USART_AFTX;
DEBUG_USART_AFRX;
GPIO_InitStructure.Pins = DEBUG_USART_TX_GPIO_PIN;
GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_Init(DEBUG_USART_TX_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.Pins = DEBUG_USART_RX_GPIO_PIN;
GPIO_InitStructure.Mode = GPIO_MODE_INPUT_PULLUP;
GPIO_Init(DEBUG_USART_RX_GPIO_PORT, &GPIO_InitStructure);
}
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] 配置UART
*
*/
void UART_Configuration(void)
{
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = DEBUG_USART_BaudRate;
USART_InitStructure.USART_Over = USART_Over_16;
USART_InitStructure.USART_Source = USART_Source_PCLK;
USART_InitStructure.USART_UclkFreq = DEBUG_USART_UclkFreq;
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(DEBUG_USARTx, &USART_InitStructure);
}
然后就是prinft重定向
PUTCHAR_PROTOTYPE
{
USART_SendData_8bit(DEBUG_USARTx, (uint8_t)ch);
while (USART_GetFlagStatus(DEBUG_USARTx, USART_FLAG_TXE) == RESET);
return ch;
}
编写主函数main
int32_t main(void)
{
//配置RCC
RCC_Configuration();
//配置GPIO
GPIO_Configuration();
//配置UART
UART_Configuration();
uint8_t i=1;
printf("\r\n %d CW32F003 UART Printf Example\r\n",i);
while(1)
{
i++;
Delay(0x7ffff);
printf("\r\nWelcome to CW32F003 UART Example %d \r\n", i);
Delay(0x7ffff);
}
}
这样就能够正常显示打印了,用串口调试助手进行通讯测试:
需要注意的是串口通讯的TTL电平,串口接收也需要是TTL电平的才可以,否则会无法通讯或乱码
|