用串口1进行
通信,上位机用串口调试助手发送数据并进行接收,结果发现上位机接收到的数据少于上位机发送的数据,也就是
STM32接收数据有丢失现象,请帮忙看一下代码哪里出了问题。
#include <stdio.h>
#include "main.h"
void delay_ms(u16
time)
{
u16 i=0;
while(time--)
{
i=12000;
while(i--);
}
}
//配置UART1接收中断
void NVIC_Configuration(void)
{
NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0);
// USART_ITConfig(USART1,USART_IT_TXE,ENABLE); //允许串口1发送中断。
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE); //允许串口1接收中断。
NVIC_InitTypeDef NVIC_InitStructure;
/* Configure the NVIC Preemption Priority Bits */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
/* Enable the USARTy Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART1_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
//PB6->TX PB7->Rx
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_USART1);
}
void USART1_Config(void)
{
USART1_GPIO_Config();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
USART_InitTypeDef USART_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_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStructure);
USART_Cmd(USART1,ENABLE); //启动串口
USART_ClearFlag(USART1,USART_FLAG_TC); //发送完成标志位
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); // 打开中断
USART_ITConfig(USART1, USART_IT_ORE, ENABLE);
}
void USART1_IRQHandler(void)
{
uint8_t ch;
if (USART_GetITStatus(USART1, USART_IT_ORE) == SET)
{
USART_ClearITPendingBit(USART1,USART_IT_ORE);
USART_ReceiveData( USART1 );
}
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
USART_ClearFlag(USART1,USART_FLAG_RXNE);
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
ch = USART1->DR;
ch = USART_ReceiveData(USART1); //接受数据
USART_SendData(USART1,ch);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);
}
}
int fputc(int ch,FILE *f)
{
// USART1->SR;
USART_GetFlagStatus(USART1, USART_FLAG_TC);// 解决第一个字符发送失败的问题
//一个一个发送字符
USART_SendData(USART1, (unsigned char) ch);
//等待发送完成
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)!=SET);
return(ch);
}
int fgetc(FILE *f)
{
/* 等待串口1输入数据 */
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET);
return (int)USART_ReceiveData(USART1);
}
int main(void)
{
NVIC_Configuration();
// USART1 config 9600 8-N-1
USART1_Config();
for(;;)
{
}
}
一周热门 更多>