stm32 2个按键控制灯熄灭点亮代码
时间: 2023-06-01 18:06:45 浏览: 114
以下是一个简单的基于STM32的代码示例,通过按键控制LED灯的开关,当按键按下时LED灯点亮,当按键松开时LED灯熄灭。
首先,需要定义引脚和按键状态:
```
#define LED_PIN GPIO_PIN_5
#define LED_GPIO_PORT GPIOA
#define BUTTON_PIN GPIO_PIN_6
#define BUTTON_GPIO_PORT GPIOC
GPIO_InitTypeDef GPIO_InitStruct;
```
接下来,需要配置GPIO引脚的模式和中断:
```
HAL_GPIO_WritePin(LED_GPIO_PORT, LED_PIN, GPIO_PIN_RESET);
GPIO_InitStruct.Pin = LED_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
HAL_GPIO_Init(LED_GPIO_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = BUTTON_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
HAL_GPIO_Init(BUTTON_GPIO_PORT, &GPIO_InitStruct);
HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
```
然后,在中断函数中检查按键状态,并根据其状态控制LED灯的开关:
```
void EXTI9_5_IRQHandler(void)
{
HAL_GPIO_EXTI_IRQHandler(BUTTON_PIN);
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if (GPIO_Pin == BUTTON_PIN)
{
if (HAL_GPIO_ReadPin(BUTTON_GPIO_PORT, BUTTON_PIN) == GPIO_PIN_SET)
{
HAL_GPIO_WritePin(LED_GPIO_PORT, LED_PIN, GPIO_PIN_SET); // 按键按下开灯
}
else
{
HAL_GPIO_WritePin(LED_GPIO_PORT, LED_PIN, GPIO_PIN_RESET); // 按键松开关灯
}
}
}
```
最后,在主函数中启动系统时钟和中断:
```
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
while (1)
{
}
```
注意:这个代码示例没有包含所有必要的设备初始化代码,仅供参考。实际使用时,需要根据具体设备和需求进行适当修改和完善。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)