发送数据后无法接收到数据
如图所示
下面是代码(非原创)
main.c
[mw_shl_code=c,true]#include <stm32f10x.h>
#include <USART_ConfigForCom_TX.h>
#include <stdio.h>
uint8_t TxBuffer[] = {0x41, 0x54, 0x2B, 0x42, 0x41, 0x55, 0x44, 0x3F, 0x0D, 0x0A};
//uint8_t TxBuffer[] = {"AT+BAUD?
"};
int flag;
unsigned char RxBuffer[];
int main(void)
{
int i=0;
USART_ConfigForCom_TX();
printf("send:
");
while(TxBuffer
!=' ')
{
USART_SendData(USART1,TxBuffer[i++]);
printf("%c",TxBuffer[i-1]);
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);//每发送一次都要检查发送完成否
//printf("%c",TxBuffer[i-1]);
}
printf("
receive:
");
while(1)
{
while(RxBuffer[flag]!=' ')
printf("%c",RxBuffer[flag++]);
}
}[/mw_shl_code]
串口配置
[mw_shl_code=c,true]void USART_ConfigForCom_TX(void)
{
//定义GPIO,,NVIC,USART结构体
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
//开PA口复用时钟,初始化系统时钟
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_USART1,ENABLE);
//配置PA9即USART1_TX_
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);
//配置PA10即USART1_RX
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//进行USART1的中断配置
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //优先级为第0级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
//配置USART1
USART_InitStructure.USART_BaudRate=9600;
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);
//开USART1中断触发方式为接收中断
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//不能开IT-TXE中断使能,因为初始化时也会有TXE置位,因为此时发送数据寄存器为空
USART_Cmd(USART1,ENABLE);
USART_ClearFlag(USART1,USART_FLAG_TC);
printf("串口初始化完成
");
}
[/mw_shl_code]
接收中断:
[mw_shl_code=c,true]void USART1_IRQHandler(void)
{
int i=0; //中断内读取字符串组用
flag=0; //主函数中打印字符串组用,每进一次中断就清零
if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET) //确保是接收中断发生
{
while(USART_GetFlagStatus(USART1,USART_FLAG_RXNE)==SET) //当接收数据寄存器不为空时就不停地接收
{
RxBuffer[i++]=USART_ReceiveData(USART1); // 将接收到的数据放入缓冲数组里
}
USART_ClearITPendingBit(USART1,USART_IT_RXNE); //清接收中断标志位,不然退不出中断
}
}[/mw_shl_code]
一周热门 更多>