【stm32f407】轮序方式的按键应用

接上篇:http://blog.csdn.net/xiaoxiaopengbo/article/details/72829154

1.    硬件原理图:

可以看到user buttonPA0

2.    程序步骤

1)    使能按键对应IO口时钟。

PA0AHB1总线上

调用函数:RCC_AHB1PeriphClockCmd ();

2)    初始化IO模式:上拉/下拉输入。

3)    扫描IO口电平

3.    程序原码

key.h

#ifndef _KEY_H_H_H
#define _KEY_H_H_H

#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"

#define KEY_ON  0
#define KEY_OFF 1
void KEY_Init(void);
uint8_t KEY_Scan(void);
#endif

key.c

#include "key.h"

void delay_ms(u16 time)   
{  
  u16 i=0;  
  while(time--)   
  {  
    i=12000;  
    while(i--);  
  }  
} 

void KEY_Init(void)
{ 
  GPIO_InitTypeDef GPIO_InitStruct;
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
  GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
  GPIO_InitStruct.GPIO_PuPd=GPIO_PuPd_DOWN;  
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOD,&GPIO_InitStruct);
}
uint8_t KEY_Scan(void)
{
  if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == KEY_ON)
  {
    delay_ms(5);
    if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == KEY_ON)
    {
      while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0) == KEY_ON);
      return KEY_ON;
    }
    else
    {
      return KEY_OFF;
    }
  }
  return KEY_OFF;
}

main.c

#include "led.h"
#include "key.h"

void User_Delay(__IO uint32_t nCount)
{
  while(nCount--)
  {
  }
}
static int count = 0;
int main(void)
{
   LED_Init();
   KEY_Init();
   while(1)
   {
    if(KEY_Scan() == KEY_ON)
    {
      if((count++)%2 == 0)
      {
        LED_Operate(LED_RED,LED_ON);
      }
      else
      {
        LED_Operate(LED_RED,LED_OFF);
      }
    }
   }
   
}
发布了200 篇原创文章 · 获赞 548 · 访问量 76万+

猜你喜欢

转载自blog.csdn.net/XiaoXiaoPengBo/article/details/72831503