關(guān)于STM32串口首字符出現(xiàn)亂碼的問題
出現(xiàn)的問題:在使用sscom32串口調(diào)試助手,首字符出現(xiàn)亂碼“?tart?tart?tart?tart?tart?tart”
原因:波特率過高
解決辦法:將波特率設(shè)置的低一點(diǎn),通常9600即可
現(xiàn)象:亂碼為波特率較高; 正常顯示波特率較低
函數(shù)代碼如下:
int main(void)
{
USART1_Init();
printf("Start");
}
#include "usart1.h"
void USART1_Init(void)
{
USART1_GPIO_Config();
USART1_Structure_Config();
USART_Cmd(USART1, ENABLE);
}
static void USART1_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
// GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
static void USART1_Structure_Config(void)
{
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitStructure.USART_BaudRate = 1200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No ;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_Init(USART1, &USART_InitStructure);
}
int fputc(int ch, FILE *f)
{
USART_ClearFlag(USART1,USART_FLAG_TC);//清除串口1發(fā)送中斷--否則第一個(gè)數(shù)不會(huì)發(fā)送
USART_SendData(USART1, (uint16_t) ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TC)!= SET);
return ch;
}