一文了解串口打印,你知道嗎?
串口在嵌入式領(lǐng)域不僅是一個(gè)通訊接口,還是一種調(diào)試工具,其好用程度不亞于硬件仿真。有些環(huán)境不方便連接Jlink進(jìn)行硬件仿真,或者并不是必現(xiàn)的問題,我們需要定位出現(xiàn)問題的地方,可以選擇保存log的方式,但是需要后續(xù)讀取,且受到Flash大小的限制,如果可以放置一臺計(jì)算機(jī)到現(xiàn)場,使用串口打印無疑是最好的辦法,在C語言中 printf函數(shù)輸出各種類型的數(shù)據(jù),使用格式控制輸出各種長度的字符,甚至輸出各種各樣的圖案,需要將串口重定向到printf函數(shù)。
01硬件打印
在STM32的應(yīng)用中,我們常常對printf進(jìn)行重定向的方式來把打印信息printf到我們的串口助手。在MDK環(huán)境中,我們常常使用MicroLIB+fputc的方式實(shí)現(xiàn)串口打印功能,即:串口重映射
代碼中記得添加一下頭文件
#include < stdio.h >
兼容不同IDE的putchar重映射。
- #ifdef __GNUC__
- /* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
- set to 'Yes') calls __io_putchar() */
- #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
- #else
- #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
- #endif /* __GNUC__ */
當(dāng)然也需要配置下串口,不需要配置中斷。
- void UART_Init(void)
- {
- USART_InitTypeDef USART_InitStructure;
- GPIO_InitTypeDef GPIO_InitStructure;
- /* Enable GPIO clock */
- RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
- /* Enable UART1 clock */
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
- /* Connect PXx to USARTx_Tx*/
- GPIO_PinAFConfig(GPIOA, 9, GPIO_AF_USART1);
- /* Connect PXx to USARTx_Rx*/
- GPIO_PinAFConfig(GPIOA, 10, GPIO_AF_USART1);
- /* Configure USART Tx as alternate function */
- GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
- GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
- GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
- GPIO_Init(GPIOA, &GPIO_InitStructure);
- /* Configure USART Rx as alternate function */
- GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
- GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
- GPIO_Init(GPIOA, &GPIO_InitStructure);
- USART_InitStructure.USART_BaudRate = 115200;
- USART_InitStructure.USART_WordLength = USART_WordLength_8b;
- 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 configuration */
- USART_Init(USART1, &USART_InitStructure);
- /* Enable USART */
- USART_Cmd(USART1, ENABLE);
- }
打印函數(shù)
- PUTCHAR_PROTOTYPE
- {
- /* Place your implementation of fputc here */
- /* e.g. write a character to the USART */
- USART_SendData(USART1, (uint8_t) ch);
- /* Loop until the end of transmission */
- while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET)
- {}
- return ch;
- }
不同的IDE也要對應(yīng)的的配置。
Keil配置,需要勾選MicroLIB選項(xiàng)。
IAR配置
打印效果
本文轉(zhuǎn)載自微信公眾號「知曉編程」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系知曉編程公眾號。