独立按键
说明:本文承接上一篇蓝桥杯模块化整理——LED,用到了上一篇中的led.c和led.h。在下面展示代码中不会放入这两个文件,有需要的请自行点击超链接翻看上一篇。
在蓝桥杯开发板中,独立按键是经常考到的内容,而要想使用独立按键,首先先要将跳帽连接到BTN上,否则开发板将使用的是4x4的键盘,不是独立按键。
不多说直接上代码:(有不懂的地方在下方请留言)
key.h
#ifndef __KEY_H_
#define __KEY_H_
unsigned int readkey();
#endif
key.c
#include <stc15.h>
#include <key.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit s7=P3^0;
sbit s6=P3^1;
sbit s5=P3^2;
sbit s4=P3^3;
uint no;
void delayms(int ms)//延时程序,消抖时使用
{
int i,j;
for(i=ms;i>0;i--)
for(j=845;j>0;j--);
}
unsigned int readkey()
{
if(s7==0)
{
delayms(5);//延时消抖
if(s7==0) { no=1; }//s7按下,返回值赋值
while(!s7);//等待按键抬起
}
else if(s6==0)
{
delayms(5);//延时消抖
if(s6==0) { no=2; }//s6按下,返回值赋值
while(!s6);//等待按键抬起
}
else if(s5==0)
{
delayms(5);//延时消抖
if(s5==0) { no=3; }//s5按下,返回值赋值
while(!s6);//等待按键抬起
}
else if(s4==0)
{
delayms(5);//延时消抖
if(s4==0) { no=4; }//s4按下,返回值赋值
while(!s4);//等待按键抬起
}
return no;//返回值
}
当然,我们需要测试一下这个模块是否能用。所以我写了一个测试程序,可实现用独立按键(S4-S7)分别控制四个LED灯的亮与灭
test_key_dulianjian
#include <stc15.h>
#include <led.h>//调用LED方法
#include<intrins.h>
#include <key.h>//调用key方法
sbit buzzer=P0^6;
void Delay100us() //@11.0592MHz
{
unsigned char i;
i = 100;
while (--i);
}
void main()
{
unsigned int i=0;
P2=0xa0;buzzer=0;P2=0x00;//关闭蜂鸣器
while (1)
{
i=readkey();//读取键值
ledlight(i);//根据返回值,点亮LED灯
Delay100us();//延时
}
}
——效果:按下哪个独立按键,哪个灯就亮,原先的灯同时随之熄灭。
这也可以使用,可替换使用
key.c
#include <stc15.h>
#define uchar unsigned char
#define uint unsigned int
#define key_input P3
#define key_state_0 0
#define key_state_1 1
#define key_state_2 2
unsigned int readkey()
{
static uchar key_state=0;
uchar key_press,key_return=0;
key_press=key_input&0x0f;
switch(key_state)
{
case key_state_0:
if(key_press!=0x0f) key_state=key_state_1;
break;
case key_state_1:
if(key_press==(key_input&0x0f))
{
if(key_press==0x0e) key_return=4;//S7
if(key_press==0x0d) key_return=3;//S6
if(key_press==0x0b) key_return=2;//S5
if(key_press==0x07) key_return=1;//S4
key_state=key_state_2;
}
else key_state=key_state_0;
break;
case key_state_2:
if(key_press==0x0f) key_state=key_state_0;
break;
}
return key_return;
}