STM32F407 GPIO port input configuration configuration steps

Introduce the STM32F407 new register project process, introduce the configuration method of the input mode, and use the button as an example to complete the button input detection.

【1】F407 Dependent files required for construction projects

img

img

img

img

img

img

【2】New construction

img

img

img

img

img

img

img

img

img

img

img

【3】Analysis of KEY button hardware schematic diagram

img

img

img

【4】Write KEY button driver code

Check out the data sheet:

img

img

The key.c file code is as follows:

#include "key.h"
/*
函数功能:按键初始化配置
硬件连接:
KEY0 --->PE4  按下为低电平
KEY1 --->PE3  按下为低电平
KEY2 --->PE2  按下为低电平
KEY_UP-->PA0  按下为高电平
*/
void KEY_Init(void)
{
    
    
		/*1. 开时钟*/
	  RCC->AHB1ENR|=1<<0;//使能PORTA时钟
		RCC->AHB1ENR|=1<<4;//使能PORTE时钟
	
	  /*2. 配置GPIO口模式*/
	  GPIOE->MODER&=~(0x3<<2*2); //清除模式
		GPIOE->MODER|=0x0<<2*2;    //配置输入模式
	
		GPIOE->MODER&=~(0x3<<3*2); //清除模式
		GPIOE->MODER|=0x0<<3*2;    //配置输入模式
	
		GPIOE->MODER&=~(0x3<<4*2); //清除模式
		GPIOE->MODER|=0x0<<4*2;    //配置输入模式
		
		GPIOA->MODER&=~(0x3<<0*2); //清除模式
		GPIOA->MODER|=0x0<<0*2;    //配置输入模式
			
		/*3. 配置GPIO口上下拉模式*/
		GPIOE->PUPDR&=~(0x3<<2*2); //清除之前配置
		GPIOE->PUPDR|=0x1<<2*2;    //配置上拉
		
		GPIOE->PUPDR&=~(0x3<<3*2); //清除之前配置
		GPIOE->PUPDR|=0x1<<3*2;    //配置上拉
		
		GPIOE->PUPDR&=~(0x3<<4*2); //清除之前配置
		GPIOE->PUPDR|=0x1<<4*2;    //配置上拉
		
		GPIOA->PUPDR&=~(0x3<<0*2); //清除之前配置
		GPIOA->PUPDR|=0x2<<0*2;    //配置下拉
}


/*
函数功能:扫描按键
函数参数:扫描的模式。1表示连续检测、0只能检测单个按键
返 回 值:按下的按键值1、2、3、4
          返回0表示按键没有按下
*/
u8 ScanKeyVal(u8 mode)
{
    
    
		static u8 stat=0; //保存按键按下的状态
		if(mode)stat=0;   //手动清除按键按下标志
		if((KEY_UP||KEY0==0||KEY1==0||KEY2==0)&&stat==0)
		{
    
    
				stat=1;      //标记按键已经按下了
				DelayMs(20); //延时消抖
				if(KEY_UP) return 4;
				if(KEY0==0)return 1;
				if(KEY1==0)return 2;
				if(KEY2==0)return 3;
		}
		else
		{
    
    
			  if(KEY_UP==0&&KEY0&&KEY1&&KEY2)stat=0; //清除按键按下标志
		}
		return 0;
}

key.h code is as follows

#ifndef _KEY_H
#define _KEY_H
#include "stm32f4xx.h"
#include "delay.h"
void KEY_Init(void);
u8 ScanKeyVal(u8 mode);
#define KEY0  (!!(GPIOE->IDR&1<<4))
#define KEY1  (!!(GPIOE->IDR&1<<3))
#define KEY2  (!!(GPIOE->IDR&1<<2))
#define KEY_UP (!!(GPIOA->IDR&1<<0))
#endif

Main.c code is as follows

#include "stm32f4xx.h" // Device header
#include "led.h"
#include "delay.h"
#include "key.h"

int main(void)
{
    
    
		u8 key,i;
		LED_Init();
		KEY_Init();
		while(1)
		{
    
    
			 key=ScanKeyVal(0);
			 if(key)
			 {
    
    
				  i=!i;
					LED0(i);
				  LED1(i);
					BEEP(i);
			 }
		}
}

【5】Compile code configuration download

img

img

img

Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/131457596