小学生
最后登录1970-1-1
在线时间 小时
注册时间2021-4-21
|
我用中断接收字符串并发送回来遇到点问题求助各位大佬。就是为什么我要在主函数中调用中断函数他才会返回我发送的字符串并产生相应的效果,但是我把他注释掉就不行了。下面是程序,求大佬看看,就是下面红色的那一行。void USART1_GPIO_Config()
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
//GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_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_Rx | USART_Mode_Tx;
USART_Init(USART1,&USART_InitStructure);
NVIC_USART1_Config();//中断优先级配置
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能接收中断
USART_Cmd(USART1,ENABLE);//使能串口
}
char USART_ReceiveString[256]; //接收PC端发送过来的字符
int Receive_Flag = 0; //接收消息标志位
int Receive_sum = 0; //数组下标
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1,USART_IT_RXNE) == 1) //USART_FLAG_RXNE判断数据,== 1则有数据
{
if(Receive_sum > 255) //数组能存放50个字节的数据
{
USART_ReceiveString[255] = '\0'; //数据字节超过50位时,将最后一位设置为\0
Receive_Flag = 1; //接收标志位置1,停止接收数据
Receive_sum = 0; //数组下标置0
}
if(Receive_Flag == 0) //接收标志位等于0,开始接收数据
{
USART_ReceiveString[Receive_sum] = USART_ReceiveData(USART1); //通过USART1串口接收字符
Receive_sum++; //数组下标++
}
if(Receive_sum >= 2) //数组下标大于2
{
if(USART_ReceiveString[Receive_sum-2] == '\r' && USART_ReceiveString[Receive_sum-1] == '\n' )
{
USART_ReceiveString[Receive_sum-1] = '\0';
USART_ReceiveString[Receive_sum-2] = '\0';
Receive_Flag = 1; //接收标志位置1,停止接收数据
Receive_sum = 0;
printf("%s\r\n",USART_ReceiveString);
if(strcmp(USART_ReceiveString,"hello") == 0)
{
LED1_ON;
}
if(strcmp(USART_ReceiveString,"world") == 0)
{
LED2_ON;
}
if(strcmp(USART_ReceiveString,"jiajia") == 0)
{
LED1_OFF;
}
if(strcmp(USART_ReceiveString,"haha") == 0)
{
LED2_OFF;
}
}
USART_ClearITPendingBit(USART1,USART_IT_RXNE); //接收后先清空标志位
}
}
}
int main()
{
led_GPIO_Config();
USART1_GPIO_Config();
USART_SendString(USART1, "Hello world!\r\n");
while(1)
{
USART1_IRQHandler();
while(Receive_Flag == 1)
{
Receive_Flag = 0;
}
//接收数据标志位置0(可以开始接收)
}
}
|
|