STM32F4 按键控制小灯亮灭例程 通过一个外接按键,来控制 LED 灯的亮灭。程序需要创建 led.h、led.c、key.h、key.c 文件。需要修改 main.c 文件。外接按键模块的 out 端口接单片机的 F0 端口。 LED 小灯程序 led.h - # ifndef __LED_H
- # define __LED_H
- void LED_Init(void);
- # endif<span style="background-color: rgb(255, 255, 255);"> </span>
复制代码
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);
- }
复制代码
KEY 按键程序 按键程序采用上拉输入 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
复制代码
key.c 复制代码
主程序 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 小灯亮;松开按键,小灯灭。 文章出处: ZZZX 是你鸭鸭
|