51單片機(jī)矩陣鍵盤(pán)與左右流水燈控制C程序
hex文件及其工程文件下載:http://www.51hei.com/f/jzzyou.rar 以下是測(cè)試ok的源代碼:
本文引用地址:http://butianyuan.cn/article/201612/324623.htm/*
*功能:使用矩陣按鍵使得按鍵按下時(shí)數(shù)碼管上顯示各自對(duì)應(yīng)的數(shù)字的平方數(shù);
* 且使用定時(shí)器0中斷使得彩色流水燈先以20毫秒的速度左移流動(dòng)4秒后,
* 然后使得彩色流水燈以20毫秒的速度右移流動(dòng);
*日期:2013-05-02-16:46
*作者:徐冉
*特別說(shuō)明:本程序代碼已經(jīng)通過(guò)調(diào)試,僅供學(xué)習(xí)使用;
*
*/
/***********AT89C52-RC單片機(jī)- 51hei-5 實(shí)驗(yàn)板***********/
/*****************51hei開(kāi)發(fā)板*********************/
#include
typedef unsigned int uint;
typedef unsigned char uchar;
sbit wela = P2^7;
sbit dula = P2^6;
sbit FM = P2^3;
uchar code table[] = {
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F //"9"
};
uint key1 = 0;
uchar counter = 0, x = 0, flag = 0;
void display(uint num);
void delay(uint xms);
void Marix_keyscan();
void init();
//主程序
void main()
{
init();//定時(shí)器0初始化
while(1)
{
if(counter == 200)//定時(shí)器定時(shí)左移流動(dòng)4秒
{
counter = 0;
flag= 1;
TR0 = 0;
TH0 = 0xB8;
TL0 = 0X00;
TR0 = 1;
x = 0;
}
Marix_keyscan();
display(key1);
}
}
//定時(shí)器0初始化子程序
void init()
{
TMOD = 0x01;
TH0 = 0xB8;
TL0 = 0X00;
EA = 1;
ET0 = 1;
TR0 = 1;
}
//數(shù)碼管優(yōu)化顯示子程序
void display(uint num)
{
uchar bai, shi, ge;
bai = num / 100 % 10;
shi = num / 10 % 10;
ge = num % 10;
if(num < 10)
{
dula = 1;
P0 = table[ge];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfe;
wela = 0;
P0 = 0x00;
delay(1);
}
else if(num < 100)
{
dula = 1;
P0 = table[shi];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfe;
wela = 0;
P0 = 0x00;
delay(1);
dula = 1;
P0 = table[ge];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfd;
wela = 0;
P0 = 0x00;
delay(1);
}
else
{
dula = 1;
P0 = table[bai];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfe;
wela = 0;
P0 = 0x00;
delay(1);
dula = 1;
P0 = table[shi];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfd;
wela = 0;
P0 = 0x00;
delay(1);
dula = 1;
P0 = table[ge];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfb;
wela = 0;
P0 = 0x00;
delay(1);
}
}
//延時(shí)子程序
void delay(uint xms)
{
uint i, j;
for(i = xms; i > 0; i--)
for(j = 125; j > 0; j--);
}
//矩陣按鍵檢測(cè)子程序
void Marix_keyscan()
{
uchar temp; //定義一個(gè)變量存放P3口的值
//第一次矩陣按鍵檢測(cè)
P3 = 0xfe; //給P3口賦一個(gè)值,使得矩陣按鍵的第一行置為低電平,其余口置為高電平;
temp = P3; //將P3口的值賦給temp
temp &= 0xf0; //通過(guò)與0xf0&來(lái)檢測(cè)矩陣按鍵的各列通過(guò)行列檢測(cè)與檢測(cè)矩陣按鍵
if(temp != 0xf0)
{
//檢測(cè)有矩陣按鍵按下
delay(5);//消抖
temp = P3;//再次將P3口的值賦給temp,即再次賦初值檢測(cè)矩陣按鍵;
temp &= 0xf0; //再次按位與檢測(cè)矩陣按鍵行列
if(temp != 0xf0)
{ //確認(rèn)有鍵按下
FM = 0;//蜂鳴器發(fā)聲
temp = P3; //將此時(shí)的P3口的值賦給temp
switch(temp)
{
case 0xee: key1 = 1 * 1;
break; //檢測(cè)到key1按下
case 0xde: key1 = 2 * 2;
break; //檢測(cè)到key2按下
case 0xbe: key1 = 3 * 3;
break; //檢測(cè)到key3按下
case 0x7e: key1 = 4 * 4;
break; //檢測(cè)到key4按下
default:
break;
}
//按鍵釋放
while(temp != 0xf0)
{
//重新賦初值檢測(cè)矩陣按鍵
temp = P3;
temp &= 0xf0;
}
delay(5);//釋放去抖
//按鍵釋放
while(temp != 0xf0)
{
//重新賦初值檢測(cè)矩陣按鍵
temp = P3;
temp &= 0xf0;
}
//按鍵釋放關(guān)閉蜂鳴器
FM = 1;
}
}
評(píng)論