#ifndef _KEY_H_
#define _KEY_H_
typedef unsigned char uint8;
typedef unsigned int uint16;
typedef char int8;
typedef int int16;
sbit KeyIn4 = P2^7;
sbit keyIn3 = P2^6;
sbit KeyIn2 = P2^5;
sbit keyIn1 = P2^4;
sbit KeyOut1 = P2^3;
sbit keyOut2 = P2^2;
sbit KeyOut3 = P2^1;
sbit keyOut4 = P2^0;
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
#endifkey.h ↑
key.c↓
按一下KeyInt1 数码管加1,按一下KeyInt2 数码管减1。
#include<reg51.h>
#include "key.h"
code uint8 number[] = {0xc0,0xf9,0xa4,0xb0,0x99,
0x92,0x82,0xf8,0x80,0x90,
0xFF};
int8 n = 0;
main()
{
P0 = 0xff;
KeyOut1 = 0;
ENLED = 0;ADDR3=1;
ADDR0 = 0; ADDR1 = 0; ADDR2 = 0;
P0 = number[0];
while(1)
{
if(!KeyIn1){
if(n>=9) n=0;
else n++;
P0 = number[n];
while(!KeyIn1);
}
if(!KeyIn2){
if(n<=0) n=9;
else n--;
P0 = number[n];
while(!KeyIn2);
}
}
}硬件去抖,加电容去高频。
软件去抖,检测出键闭合后执行延时程序,前沿抖动消失后再次检测键的状态。
#include<reg51.h>
#include "key.h"
code uint8 number[] = {0xc0,0xf9,0xa4,0xb0,0x99,
0x92,0x82,0xf8,0x80,0x90,
0xFF};
void delay()
{
uint16 i = 1000;
while(i--);//roughly delay
}
int8 n = 0;
main()
{
P0 = 0xff;
KeyOut1 = 0;
ENLED = 0;ADDR3=1;
ADDR0 = 0; ADDR1 = 0; ADDR2 = 0;
P0 = number[0];
while(1)
{
if(!KeyIn1){
delay();
if(!KeyIn1){
if(n>=9) n=0;
else n++;
P0 = number[n];
while(!KeyIn1);
}
}
if(!KeyIn2){
delay();
if(!KeyIn2){
if(n<=0) n=9;
else n--;
P0 = number[n];
while(!KeyIn2);
}
}
}
}
版权声明:本文为m0_37574068原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。