STM32F429--按鍵檢測

說明:此篇文章基於上一篇文章點亮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;
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章