原创 STM32学习-USART1中断

2013-4-7 17:31 1186 16 16 分类: MCU/ 嵌入式 文集: STM32F1学习笔记

采用中断方式,由串口调试助手,发送数据,控制开发板上的LED。发送‘1’,LED1亮;发送‘2’,LED2亮。

硬件连接:
USART1_RX——PA9;USART1_TX——PA10
LED1——PB14;LED2——PB15
程序见附件。
 
采用中断方式要注意以下几点:
1:
在USART1初始化时,要注意使能串口的接收中断,因为该实验应用的是接收中断。
/* USART1 mode config */
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_Cmd(USART1, ENABLE);
 
2:
配置NVIC(Nested Vector Interrupt Controller)
static void NVIC_Configuration(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
 
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
 
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
 
3:
中断服务程序编写
u8 ReceiveData;
void USART1_IRQHandler(void)
{
    if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)//中断产生
{
   USART_ClearITPendingBit(USART1, USART_IT_RXNE);//软件清除中断标志
ReceiveData = USART_ReceiveData(USART1);
}
switch(ReceiveData)
{
      case '1':
  {
      ReceiveData = 0;
  GPIO_SetBits(GPIOB, GPIO_Pin_14 | GPIO_Pin_15);
  GPIO_ResetBits(GPIOB, GPIO_Pin_14);
  break;
  }
  case '2':
  {
      ReceiveData = 0;
  GPIO_SetBits(GPIOB, GPIO_Pin_14 | GPIO_Pin_15);
  GPIO_ResetBits(GPIOB, GPIO_Pin_15);
  break;
  }
  default:break;
}
}
 
参考文献:
2:http://wenku.baidu.com/view/e09dbeeb551810a6f5248690.html

文章评论0条评论)

登录后参与讨论
我要评论
0
16
关闭 站长推荐上一条 /2 下一条