STM32按键的使用控制指示灯和蜂鸣器的使用

## 开发手册讲解

 

 

 ## 软件设计

key.h

#ifndef _key_H
#define _key_H
#include "system.h"

#define KEY0_PIN  GPIO_Pin_4
#define KEY1_PIN  GPIO_Pin_3
#define KEY2_PIN  GPIO_Pin_2
#define KEY_UP_PIN  GPIO_Pin_0

#define KEY012_PORT   GPIOE
#define KEY_UP_PORT   GPIOA

#define KEY_UP   PAin(0) //位带引脚
#define KEY0     PEin(4)
#define KEY1     PEin(3)
#define KEY2     PEin(2)

#define KEY012_PORT_RCC RCC_APB2Periph_GPIOE //时钟
#define KEY_UP_PORT_RCC RCC_APB2Periph_GPIOA //时钟

#define KEY_UP_PRESS 1
#define KEY0_PRESS   2
#define KEY1_PRESS   3
#define KEY2_PRESS   4
void KEY_Init();
u8 KEY_Scan(u8 mode);

#endif

key.c

#include "key.h"
#include "SysTick.h"

void KEY_Init()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	
	RCC_APB2PeriphClockCmd(KEY012_PORT_RCC | KEY_UP_PORT_RCC, ENABLE);
	
	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPD;
	GPIO_InitStructure.GPIO_Pin=KEY_UP_PIN;
	GPIO_Init(KEY_UP_PORT,&GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
	GPIO_InitStructure.GPIO_Pin=KEY0_PIN | KEY1_PIN | KEY2_PIN;
	GPIO_Init(KEY012_PORT,&GPIO_InitStructure);
	

}

u8 KEY_Scan(u8 mode)//mode=0,单次检测按键 //mode=1, 连续检测按键
{
	static u8 key=1;
	if(mode ==1 )key=1;
//刚开始key=1,按键启用,key又为0,按键没有启用,key又变为1. 
//若为连续按键,则key经过第二个大if又返回后经过第一个大if变为1,则变为连续按键
	if(key==1&&(KEY_UP==1 || KEY0==0 || KEY1==0 || KEY2==0))
	{
		delay_ms(10);//消抖处理
		key=0;
		if(KEY_UP==1)
		{
			return KEY_UP_PRESS;
		}
		else if(KEY0==0)
		{
		return KEY0_PRESS;
		}
		else if(KEY1==0)
		{
			return KEY1_PRESS;
		}
		else if(KEY2==0)
		{
			return KEY2_PRESS;
		}
	}
	else if(key==0&&(KEY_UP==0 && KEY0==1 && KEY1==1 && KEY2==1))
	{
		key=1;
	}
	return 0;
}

main.c

#include "stm32f10x.h"
#include "led.h"
#include "system.h"
#include "SysTick.h"
#include "beep.h"
#include "key.h"
int main()
{
	u8 key=0;
	u8 i=0;
  SysTick_Init(72);
	BEEP_Init();
	LED_Init();
	KEY_Init();
	while(1)
	{
		key=KEY_Scan(0);//单次按键扫描
		switch(key)
		{
			case KEY_UP_PRESS:LED2=0;break;
			case KEY0_PRESS:BEEP=0;break;
			case KEY1_PRESS:LED2=1;break;
			case KEY2_PRESS:BEEP=1;break;
		}
		i++;
		if(i%20==0)
			LED1=!LED1;//指示灯亮提示机器正在运行
		delay_ms(10);
		
	}
}

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值