stm32按键中断控制led灯代码
时间: 2023-09-18 19:09:43 浏览: 128
下面是一个简单的示例代码,用于在STM32上使用按键中断控制LED灯:
```c
#include "stm32f10x.h"
void Delay(__IO uint32_t nCount);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
uint32_t ButtonPressed = 0x00;
/* Enable the GPIO_LED Clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
/* Configure the GPIO_LED pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* Enable the GPIO_BUTTON Clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
/* Configure the GPIO_BUTTON pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
/* Enable AFIO clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
/* Connect EXTI Line0 to PA0 pin */
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource0);
/* Configure EXTI Line0 */
EXTI_InitStructure.EXTI_Line = EXTI_Line0;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
/* Enable and set EXTI Line0 Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
while (1)
{
if (ButtonPressed == 0x01)
{
/* Turn on LED */
GPIO_SetBits(GPIOC, GPIO_Pin_13);
/* Delay */
Delay(0xFFFFF);
/* Turn off LED */
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
/* Reset ButtonPressed flag */
ButtonPressed = 0x00;
}
}
}
void EXTI0_IRQHandler(void)
{
/* Make sure that interrupt flag is set for EXTI Line0 */
if (EXTI_GetITStatus(EXTI_Line0) != RESET)
{
/* Set ButtonPressed flag */
ButtonPressed = 0x01;
/* Clear interrupt flag */
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void Delay(__IO uint32_t nCount)
{
for (; nCount != 0; nCount--);
}
```
在此示例中,我们使用PA0上的按键来控制PC13上的LED灯。当按下按钮时,会触发EXTI0_IRQHandler中断处理程序,在其中设置ButtonPressed标志,表示需要切换LED灯的状态。在主循环中,我们检查ButtonPressed标志,并相应地切换LED灯的状态。
阅读全文