STM32按键控制LED灯
时间: 2023-09-01 11:10:41 浏览: 89
5、POLLING-按键.zip_stm32 按键_按键灯
这是一个非常简单的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 i;
/* Enable GPIOC clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
/* Configure PC13 in input pushpull mode */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* Enable AFIO clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
/* Connect EXTI13 Line to PC13 pin */
GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource13);
/* Configure EXTI13 line */
EXTI_InitStructure.EXTI_Line = EXTI_Line13;
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 EXTI15_10 Interrupt to the lowest priority */
NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* Enable GPIOB clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
/* Configure PB0 in output pushpull mode */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
while (1)
{
/* Toggle LED on PB0 every second */
GPIO_WriteBit(GPIOB, GPIO_Pin_0, (BitAction)(1 - GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_0)));
Delay(0xFFFFF);
}
}
void Delay(__IO uint32_t nCount)
{
for (; nCount != 0; nCount--);
}
```
这个代码实现了以下功能:
1. 配置PC13引脚为上拉输入模式,用于连接按键。
2. 配置PB0引脚为输出模式,用于连接LED灯。
3. 配置EXTI13中断线,用于接收PC13引脚的中断信号。
4. 在中断处理函数中,检测PC13引脚的状态,如果是按下,则控制PB0引脚输出高电平,点亮LED灯;如果是松开,则控制PB0引脚输出低电平,熄灭LED灯。
当然,你也可以根据自己的需求进行修改和扩展。
阅读全文