说明:此篇文章基于上一篇文章点亮LED灯,实现按键控制LED灯的状态翻转
传送门:STM32F429–标准库点亮LED灯
文件说明
bsp_led.c负责LED的初始化配置
- bsp_led.h负责外设LED函数的声明,以及宏定义
- bsp_key.c负责按键初始化
- bsp_key.h负责按键函数的声明,以及宏定义
- main.c实现功能:按键控制LED亮灭
程序
1.bsp_led.c
#include "led.h"
void LED_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
//0-打开系统时钟
RCC_AHB1PeriphClockLPModeCmd(LED_GPIO_CLK,ENABLE);
//1-设置引脚
GPIO_InitStruct.GPIO_Pin = LED_GPIO_PIN;
//2-设置为输出模式
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
//3-设置为推挽输出类型
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
//4-设置为上拉
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
//5-设置速度50MHZ
GPIO_InitStruct.GPIO_Speed = GPIO_Fast_Speed;
//把引脚写进寄存器的函数
GPIO_Init(LED_GPIO_PORT,&GPIO_InitStruct);
}
2.bsp_led.h
#ifndef __LED_H
#define __LED_H
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
void LED_GPIO_Config(void);
#define LED_GPIO_PIN GPIO_Pin_10
#define LED_GPIO_PORT GPIOH
#define LED_GPIO_CLK RCC_AHB1Periph_GPIOH
#define LED_R_TOGGLE {LED_GPIO_PORT->ODR ^= LED_GPIO_PIN ;}
/*异或说明:
*假如原来的状态是0,位异或之后: 0+1 =1
再次异或: 1+1 =0
实现了状态的翻转
*/
#endif /*__LED_H*/
3.bsp_key.c
#include "key.h"
void KEY_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
//0-打开时钟
RCC_AHB1PeriphClockLPModeCmd(KEY1_GPIO_CLK,ENABLE);
//1-设置引脚
GPIO_InitStruct.GPIO_Pin = KEY1_GPIO_PIN;
//2-设置为输入模式
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
//3-输入模式,不需要配置推挽
//GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
//4-设置为下拉,保持初始为低电平,按键按下变为高电平
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_DOWN;
//5-设置速度50MHZ
GPIO_InitStruct.GPIO_Speed = GPIO_Fast_Speed;
//把引脚写进寄存器的函数,第二个参数是结构体指针
GPIO_Init(KEY1_GPIO_PORT,&GPIO_InitStruct);
}
/*
*函数功能:读取到GPIO口的电平
*参数说明: 参数一:端口号 参数二:引脚号
*/
uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin)
{
if (GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON)
{
//如果按下了,KEY_ON 1
while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON);
//做相应的动作
return KEY_ON;
}
else return KEY_OFF;
}
4.bsp_key.h
#ifndef __KEY_H
#define __KEY_H
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#define KEY1_GPIO_PIN GPIO_Pin_0
#define KEY1_GPIO_PORT GPIOA
#define KEY1_GPIO_CLK RCC_AHB1Periph_GPIOA
#define KEY_ON 1
#define KEY_OFF 0
void KEY_GPIO_Config(void);
uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin);
#endif /*__KEY_H*/
5.main.c
#include "stm32f4xx.h"
#include "led.h"
#include "key.h"
typedef unsigned int uint32_t;
typedef unsigned short int uint16_t;
typedef unsigned char uint8_t;
int main(void)
{
LED_GPIO_Config();
KEY_GPIO_Config();
while(1)
{
if (Key_Scan(KEY1_GPIO_PORT,KEY1_GPIO_PIN) == KEY_ON)
{
LED_R_TOGGLE;
}
}
}