天天看點

stm32 uart列印

電子調試借助uart列印,輕松實作實時debug。

STM32子產品操作常用的方式,先配置GPIO與相對子產品對接,然後對子產品配置;stm32序列槽列印示例如下,以stm32f030x8為例:

1.配置gpio,配置uart:

增加gpio 和 usart lib檔案,可以到lib查找相關結構體的使用;

GPIO_InitTypeDef // IO相關結構體

USART_InitTypeDef // uart相關結構體

RCC_AHBPeriphClockCmd // 時鐘配置,差點别忘記了

到#include “stm32f0xx_rcc.h”//檢視每個子產品時鐘設定方式,每個晶片基本都有點差別,這個需要留意,確定所選時鐘與配置時鐘函數對應上;

void Uart_config(void)

{

GPIO_InitTypeDef GPIO_InitStructure;

USART_InitTypeDef USART_InitStructure;

/* Enable GPIO clock */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

/* USART1 Pins configuration ************************************************/
/* Connect pin to Periph */
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1); 
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);  

/* Configure pins as AF pushpull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_2;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);  
//USART 
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_Init(USART1, &USART_InitStructure);   
USART_Cmd(USART1, ENABLE);                    
           

}

2. 增加#include “stdio.h”,配置uart列印與系統 io對應,此操作友善用系統printf列印輸出;增加相關函數如下:

int fputc(int ch, FILE *f)

{

USART_SendData(USART1, (u8) ch);

while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)

{}

return ch;

}

3.在target修改設定如下:

stm32 uart列印

4.設定OK後,在main裡初始化完成後便可以用printf列印輸出。

int main(void)

{

Uart_config();

printf(“uart_init is ok”);

}

繼續閱讀