stm32f405按键控制led灯亮灭
时间: 2023-09-17 18:10:16 浏览: 164
以下是一个使用STM32F405按键控制LED灯亮灭的示例代码:
```
#include "stm32f4xx.h"
void GPIO_Configuration(void);
void EXTI_Configuration(void);
void delay(uint32_t nCount);
int main(void)
{
GPIO_Configuration();
EXTI_Configuration();
while (1)
{
}
}
void GPIO_Configuration(void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
// Configure PA0 as input with pull-up resistor
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Configure PC13 as output
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void EXTI_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
// Configure EXTI Line0
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0);
EXTI_InitTypeDef EXTI_InitStructure;
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);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void EXTI0_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line0) != RESET)
{
// Toggle PC13
GPIO_ToggleBits(GPIOC, GPIO_Pin_13);
// Clear the EXTI line pending bit
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
void delay(uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
```
此代码将PA0配置为输入,PC13配置为输出。当按下PA0时,将触发外部中断,并切换PC13的状态。您可以通过修改EXTI_InitStructure.EXTI_Trigger变量的值来更改触发条件,例如EXTI_Trigger_Rising将在上升沿触发外部中断。
阅读全文