STM32F103C8T6按键控制LED灯代码
时间: 2023-11-19 12:11:39 浏览: 104
stm32f103c8t6hal库的按键控制led(中断/非中断两种)
以下是一个简单的按键控制LED灯的示例代码,使用STM32F103C8T6的GPIO和中断功能:
```c
#include "stm32f10x.h"
#define LED_PIN GPIO_Pin_13
#define LED_GPIO_PORT GPIOC
#define BUTTON_PIN GPIO_Pin_0
#define BUTTON_GPIO_PORT GPIOA
void GPIO_Configuration(void);
void NVIC_Configuration(void);
void EXTI_Configuration(void);
int main(void) {
GPIO_Configuration();
NVIC_Configuration();
EXTI_Configuration();
while (1) {
// 循环等待中断事件
}
}
void GPIO_Configuration(void) {
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_GPIO_PORT, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = BUTTON_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(BUTTON_GPIO_PORT, &GPIO_InitStructure);
}
void NVIC_Configuration(void) {
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void EXTI_Configuration(void) {
EXTI_InitTypeDef EXTI_InitStructure;
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource0);
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);
}
void EXTI0_IRQHandler(void) {
if (EXTI_GetITStatus(EXTI_Line0) != RESET) {
// 检测到按键事件
if (GPIO_ReadInputDataBit(BUTTON_GPIO_PORT, BUTTON_PIN) == RESET) {
// 按键被按下
GPIO_WriteBit(LED_GPIO_PORT, LED_PIN, Bit_SET);
} else {
// 按键被释放
GPIO_WriteBit(LED_GPIO_PORT, LED_PIN, Bit_RESET);
}
EXTI_ClearITPendingBit(EXTI_Line0);
}
}
```
该代码将PA0引脚配置为输入模式,使用内部上拉电阻,控制一个外部按键。同时,PC13引脚被配置为输出模式,控制一个LED灯。当按键被按下时,LED灯会亮起;当按键被释放时,LED灯会熄灭。中断功能允许程序在按键事件发生时立即响应,而不需要不断地轮询输入引脚状态。
阅读全文