1.要求使用中断完成,板子复位后,三个LED灯是跑马灯的效果,按下某个按键后,在中断函数中实现三个灯常亮的效果。用Keil写stm32的代码
时间: 2024-12-17 08:43:36 浏览: 17
为了实现这个功能,你需要在STM32中设置跑马灯效果作为中断服务,并添加按键中断用于切换到常亮模式。这里是一个基本的示例,使用Keil MDK编写STM32CubeMX生成的工程。假设我们有GPIOA、GPIOB和GPIOC分别控制三个LED,按键连接到PA0:
```c
#include "stm32f10x.h"
#include "delay.h"
// LED GPIOs
GPIO_TypeDef* led_pins[] = {GPIOA, GPIOB, GPIOC};
uint8_t led_mask[] = {0b00001111, // mask for all bits on a pin
0b11110000, // same for the other pins
0b00001111};
// Key press GPIO and interrupt
GPIO_TypeDef* key_pin = GPIOA;
uint16_t key_mask = 0b00000001;
// Global variables
bool is_led_on = false; // flag to switch between flashing and on
void LedInit(void) {
GPIO_InitTypeDef GPIO_InitStructure;
for (int i = 0; i < 3; i++) {
GPIO_InitStructure.GPIO_Pin = led_pins[i]->IDR & led_mask[i]; // Set initial LEDs off
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // Push-Pull Output
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
HAL_GPIO_Init(led_pins[i], &GPIO_InitStructure);
}
}
void KeyInit(void) {
GPIO_InitStructure.GPIO_Pin = key_pin->IDR & key_mask;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_In_FLOATING; // Input with no pull-up or pull-down
HAL_GPIO_Init(key_pin, &GPIO_InitStructure);
EXTI_InitStructure.EXTI_Line = key_pin->IDR & key_mask;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; // Interrupt on rising edge
EXTI_InitStructure.EXTI_LINE_ID = EXTI_Line_GPIOx; // Replace x with your key Pin number
HAL_NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn; // EXTI9_5_IRQn corresponds to GPIO interrupts
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
HAL_NVIC_Config(&NVIC_InitStructure);
}
void EXTI9_5_IRQHandler(void) {
if (HAL_GPIO_ReadPin(key_pin, key_mask)) { // Check if key is pressed
is_led_on = !is_led_on;
ToggleLeds(is_led_on); // Switch LED state
} else {
HAL_GPIO_EXTI_IRQHandler(KEY_PIN); // Clear interrupt if key was released
}
}
void ToggleLeds(bool state) {
for (int i = 0; i < 3; i++) {
uint16_t pin_mask = led_pins[i]->IDR & led_mask[i];
if (state)
HAL_GPIO_WritePin(led_pins[i], pin_mask, GPIO_PIN_SET);
else
HAL_GPIO_WritePin(led_pins[i], pin_mask, GPIO_PIN_RESET);
}
if (!state)
__disable_irq(); // Disable interrupts while keeping LED state to avoid flickering
Delay_ms(100); // Short delay before re-enabling interrupts
__enable_irq();
}
int main(void) {
LedInit();
KeyInit();
while (1) {
// Your main loop here - not needed for this example
}
}
阅读全文