獨立鍵盤工作原理
編程思路:
將獨立按鍵連接的IO口設(shè)為高電平鲫惶,持續(xù)檢查該IO口電平蜈首。若按鍵按下,IO口電平會被拉低剑按。檢查到IO口低電平即可判斷按鍵被按下疾就。
以下是沒有按鍵消抖的程序
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit DU = P2^6; //數(shù)碼管段選
sbit WE = P2^7; //數(shù)碼管位選
sbit key_s2 = P3^0; //獨立按鍵s2
uchar num = 0; //數(shù)碼管顯示的值
uchar code table[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f} ;
void main()
{
WE = 1; //打開位選鎖存器
P0 = 0xfe; //1111 1110
WE = 0; //鎖存位選數(shù)據(jù)
while(1)
{
if(key_s2 == 0)
{
num++; //當(dāng)按鍵按下,數(shù)字+1
if(num == 10)
num = 0; //數(shù)字超過10則歸0
}
DU = 1; //打開段選鎖存器
P0 = table[num]; //顯示對應(yīng)數(shù)字
DU = 0; //鎖存段選數(shù)據(jù)
}
}
以上程序中艺蝴,當(dāng)按下按鍵時猬腰,可能會改變好幾次數(shù)字,松開按鍵的時候也可能改變幾次數(shù)字猜敢。
這是因為按鍵在按下和松開的過程中存在機械抖動姑荷,按鍵在抖動過程中會反復(fù)多次地“閉合”盒延、“斷開”、“閉合”鼠冕、“斷開”......單片機抓取了這些抖動信號添寺,以為按鍵快速地被“按下”、“松開”懈费、“按下”计露、“松開”......
加入軟件消抖。當(dāng)按鍵按下后憎乙,數(shù)字持續(xù)增加
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit DU = P2^6; //數(shù)碼管段選
sbit WE = P2^7; //數(shù)碼管位選
sbit key_s2 = P3^0; //獨立按鍵s2
uchar num = 0; //數(shù)碼管顯示的值
uchar code table[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f} ;
void delay(unsigned int z)
{
unsigned int x, y;
for(x = z; x > 0; x--)
for(y = 114; y >0; y--);
}
void main()
{
WE = 1; //打開位選鎖存器
P0 = 0xfe; //1111 1110
WE = 0; //鎖存位選數(shù)據(jù)
while(1)
{
if(key_s2 == 0)
{
delay(20); //延時20ms票罐,在延時期間按鍵在抖動,延時結(jié)束后按鍵狀態(tài)已經(jīng)平穩(wěn)
if(key_s2 == 0) //確認按鍵確實是被按下的
{
num++; //當(dāng)按鍵按下泞边,數(shù)字+1
if(num == 10)
num = 0; //數(shù)字超過10則歸0
}
}
DU = 1; //打開段選鎖存器
P0 = table[num]; //顯示對應(yīng)數(shù)字
DU = 0; //鎖存段選數(shù)據(jù)
}
}
加入松手檢測该押。按鍵按下并松手后才顯示加一
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit DU = P2^6; //數(shù)碼管段選
sbit WE = P2^7; //數(shù)碼管位選
sbit key_s2 = P3^0; //獨立按鍵s2
uchar num = 0; //數(shù)碼管顯示的值
uchar code table[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f} ;
void delay(unsigned int z)
{
unsigned int x, y;
for(x = z; x > 0; x--)
for(y = 114; y >0; y--);
}
void main()
{
WE = 1; //打開位選鎖存器
P0 = 0xfe; //1111 1110
WE = 0; //鎖存位選數(shù)據(jù)
while(1)
{
if(key_s2 == 0)
{
delay(20); //延時20ms,在延時期間按鍵在抖動阵谚,延時結(jié)束后按鍵狀態(tài)已經(jīng)平穩(wěn)
if(key_s2 == 0) //確認按鍵確實是被按下的
{
num++; //當(dāng)按鍵按下蚕礼,數(shù)字+1
if(num == 10)
num = 0; //數(shù)字超過10則歸0
while(!key_s2); //如果按鍵還沒松開,key_s2==0梢什,!key_s2就是非零奠蹬,程序停留在while循環(huán)內(nèi),不往下進行
}
}
DU = 1; //打開段選鎖存器
P0 = table[num]; //顯示對應(yīng)數(shù)字
DU = 0; //鎖存段選數(shù)據(jù)
}
}