首先需要配置GPIO和NVIC中断控制器,使能对应的中断。

接着,在中断服务函数中判断是哪个按键被按下,根据不同的按键触发不同的操作。

例如,如果是控制流水灯转动方向的按键被按下,则改变流水灯的转动方向;如果是控制所有灯亮灭的按键被按下,则改变所有灯的状态。

代码示例:

#include "stm32f10x.h"

void GPIO_Config(void);
void EXTI_Config(void);
void NVIC_Config(void);
void Delay(uint32_t nCount);

int main(void)
{
    GPIO_Config();
    EXTI_Config();
    NVIC_Config();

    while (1)
    {
    }
}

void GPIO_Config(void)
{
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOC, ENABLE);

    GPIO_InitTypeDef GPIO_InitStructure;

    // 流水灯控制引脚配置
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    // 按键引脚配置
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 | GPIO_Pin_5;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
}

void EXTI_Config(void)
{
    EXTI_InitTypeDef EXTI_InitStructure;

    // 按键4对应的EXTI配置
    EXTI_InitStructure.EXTI_Line = EXTI_Line4;
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    // 按键5对应的EXTI配置
    EXTI_InitStructure.EXTI_Line = EXTI_Line5;
    EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd = ENABLE;
    EXTI_Init(&EXTI_InitStructure);
}

void NVIC_Config(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;

    // 按键4对应的NVIC配置
    NVIC_InitStructure.NVIC_IRQChannel = EXTI4_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    // 按键5对应的NVIC配置
    NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

void EXTI4_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line4) != RESET)
    {
        EXTI_ClearITPendingBit(EXTI_Line4);

        // 按键4被按下
        // 改变流水灯转动方向
        GPIO_Write(GPIOC, ~(GPIO_ReadOutputData(GPIOC) << 1));
    }
}

void EXTI9_5_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_Line5) != RESET)
    {
        EXTI_ClearITPendingBit(EXTI_Line5);

        // 按键5被按下
        // 改变所有灯的状态
        GPIO_Write(GPIOC, ~GPIO_ReadOutputData(GPIOC));
    }
}

void Delay(uint32_t nCount)
{
    for (; nCount != 0; nCount--);
}
``
stm32通过中断方式用两个按键分别控制流水灯的转动方向和所有灯亮灭

原文地址: https://www.cveoy.top/t/topic/eMo1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录