STM32串列埠接收字串並控制LED
阿新 • • 發佈:2018-12-18
串列埠相關配置
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|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);
//USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //接收中斷
//USART_ITConfig(USART1, USART_IT_TXE, ENABLE); //傳送中斷
USART_Cmd(USART1, ENABLE);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //接收中斷使能
串列埠中斷配置
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
重定向fputc,並勾選Options - Target 中的Use Micro LIB
USART_SendData(USART1, (uint8_t) ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
{}
return ch;
串列埠中斷服務函式,接收字串的關鍵
u8 i=0;
if(USART_GetFlagStatus(USART1,USART_IT_RXNE)==SET)
{
if(USART_ReceiveData(USART1)=='\n') //串列埠除錯助手必須是點上換行符
{
sp=0;
USART_REC_Finish_FLAG = 1;
for(i=0;i<20;i++) //i 字串長度
Rec_Buffer[i]='\0';
}
else
{
if(sp==0)
{
for(i=0;i<20;i++)
SendData[i]='\0';
}
Rec_Buffer[sp] = USART_ReceiveData(USART1);
SendData[sp]= Rec_Buffer[sp];
sp=sp+1;
}
}
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
USART_ClearITPendingBit(USART1, USART_IT_RXNE); //清除接收中斷標誌
}
主函式
while(USART_REC_Finish_FLAG == 1) //等待串列埠接收完成標誌位置1
{
delay(1000); //延時1ms
USART_REC_Finish_FLAG = 0; //使用完成後將串列埠標誌位置〇
if(strcmp(SendData, LED1ON)==0) //比較字串
ch = '1';
else if(strcmp(SendData, LED1OFF)==0)
ch = '2';
else
ch = '3';
printf("%c \r\n",ch);
switch(ch)
{
case '1':
LED1_ON;
printf("LED1 ON\r\n");
break;
case '2':
LED1_OFF;
printf("LED1 OFF\r\n");
break;
case '3':
LED2_TOGGLE;
printf("LED2 TOGGLE\r\n");
break;
default:
printf("Error!\r\n");
break;
}
}
效果如圖