Loading

STM32F4 按键控制小灯亮灭例程

我的公众号目前已搁置(临近注销),所以我将以前所写的文章转移到博客园。

此篇公众号文章创建于 2020-12-30 18:05,内容后期无修改。

通过一个外接按键,来控制 LED 灯的亮灭。程序需要创建 led.hled.ckey.hkey.c 文件。需要修改 main.c 文件。外接按键模块的 out 端口接单片机的 F0 端口。

LED 小灯程序

led.c

# include <led.h>
# include <stm32f4xx.h>
void LED_Init(void) {
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); 
    // F8
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // 上拉
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOF, &GPIO_InitStructure);
    GPIO_SetBits(GPIOF, GPIO_Pin_8);
}

led.h

# ifndef __LED_H
# define __LED_H
void LED_Init(void);
# endif

KEY 按键程序

按键程序采用上拉输入

key.c

# include <key.h>
# include <stm32f4xx.h>
# include <delay.h>

// 按键初始化
void key_Init(void) {
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); // 打开 PA 口时钟
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; // 上拉
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOF, &GPIO_InitStructure);
    GPIO_SetBits(GPIOF, GPIO_Pin_0);
}

// 判断按键是否按下
u8 Key_Scan(GPIO_TypeDef * GPIOx, u16 GPIO_Pin) {
    if(GPIO_ReadInputDataBit(GPIOx, GPIO_Pin) == KEY_ON) {
        delay_ms(50); // 战略性消抖,根据实际情况加减延迟时长
        if(GPIO_ReadInputDataBit(GPIOx, GPIO_Pin) == KEY_ON) {
            return KEY_ON;
        }
        else
            return KEY_OFF;
    }
    else
        return KEY_OFF;
}

key.h

# ifndef KEY_H
# define KEY_H
# include <sys.h>
# include <stm32f4xx.h>

#define KEY_ON 1  // 按键初始化程序设置为上拉,所以要达到按键按下小灯亮
#define KEY_OFF 0 // 的功能需要设置 KEY_ON 为高电平,KEY_OFF 为低电平

void key_Init(void);

u8 Key_Scan(GPIO_TypeDef * GPIOx, u16 GPIO_Pin);

# endif

主程序

main.c

# include <stm32f4xx.h>
# include <led.h>
# include <key.h>
# include <delay.h>

int main() {
    delay_init(168);
    LED_Init(); // LED 初始化
    key_Init(); // 按键初始化

    while(1) {
        if(Key_Scan(GPIOF, GPIO_Pin_0) == KEY_ON) {
            GPIO_SetBits(GPIOF, GPIO_Pin_8);
        }
        if(Key_Scan(GPIOF, GPIO_Pin_0) == KEY_OFF) {
            GPIO_ResetBits(GPIOF, GPIO_Pin_8);
        }
    }
}

效果

按键按下后,LED0 小灯亮;松开按键,小灯灭。

posted @ 2023-03-29 15:49  滑稽果  阅读(113)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end