请教大虾,不知是什么原因,代码中明明写的是9600的波特率,用串口助手接收的却是乱码,改成4800就正常了,写4800波特率的时候,用2400接收就正常了
部分代码如下:
void USART_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
USART_ClockInitTypeDef USART_ClockInitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //选择GPIO的引脚 TX
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //GPIO输出模式:推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; //GPIO输出频率:2MHZ
GPIO_Init(GPIOA,&GPIO_InitStructure); //GPIOA初始化
// USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO |RCC_APB2Periph_USART1 , ENABLE);
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
USART_InitStructure.USART_BaudRate = 4800;
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_ClockInitStructure.USART_Clock = USART_Clock_Disable;
USART_ClockInitStructure.USART_CPOL = USART_CPOL_Low;
USART_ClockInitStructure.USART_CPHA = USART_CPHA_2Edge;
USART_ClockInitStructure.USART_LastBit= USART_LastBit_Disable;
USART_ClockInit(USART1,&USART_ClockInitStructure);
USART_Init(USART1,&USART_InitStructure);
USART_Cmd(USART1,ENABLE);
}
上面是串口配置部分
void USART1_Puts(char * str)
{
while(*str)
{
USART_SendData(USART1, *str++);
/* Loop until the end of transmission */
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
}
发送函数
void RCC_Configuration(void)
{
u8 RCC_flag = 0;
while(!RCC_flag)
{
ErrorStatus HSEStartUpStatus;
RCC_HSEConfig(RCC_HSE_ON); //使能HSE
HSEStartUpStatus = RCC_WaitForHSEStartUp(); //等待HSE就绪
if(HSEStartUpStatus == SUCCESS) //如果HSE就绪,跳出while
RCC_flag = 1;
else
RCC_flag = 0;
}
}
时钟配置
int main(void)
{
RCC_Configuration();
GPIO_Configuration();
USART_Configuration();
while(1)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
USART1_Puts("Hellow\n");
// USART1_Puts("神舟1号\n");
Delay(0x5fffff);
GPIO_SetBits(GPIOA,GPIO_Pin_2);
Delay(0x5fffff);
}
}
在主程序中不断地发数据,并且让灯闪烁 |