矩阵键盘扫描

根据矩阵键盘的原理图可知,当没有按键按下时,P1=0xf0;然后依次将P1^0~P1^3单独置低电平,其他置高,再扫描各列的状态,来判断是哪个按键按下,比如,将P1^0输出低电平,其他的引脚都输出高电平,即P1=0xfe,那么当第1行有按键按下时P1的相应值为,

1X1(01111110=0x7e)  1X2(10111110=0xbe)  1x3(11011110=0xde) 1X4(11101110=0xee)

将P1^1输出低电平,其他的引脚都输出高电平,即P1=0xfd,那么当第2行有按键按下时P1的相应值为,

2X1(01111101=0x7d)  2X2(10111101=0xbd)  2x3(11011101=0xdd) 2X4(11101101=0xed)

将P1^2输出低电平,其他的引脚都输出高电平,即P1=0xfd,那么当第2行有按键按下时P1的相应值为,

3X1(01111011=0x7b)  3X2(10111011=0xbb)  3x3(11011011=0xdb) 3X4(11101011=0xeb)

将P1^3输出低电平,其他的引脚都输出高电平,即P1=0xfd,那么当第2行有按键按下时P1的相应值为,

4X1(01110111=0x77)  4X2(10110111=0xb7)  4x3(11010111=0xd7) 4X4(11100111=0xe7)

下面通过一个来测试上面结果,

/*
程序中用到了置位,如果检测第一行时置位为0xfe,是为了初始化一下P1口,初始化后
*/
#include <reg52.h>

unsigned int Val;

void Delay(unsigned int t);

void main(void)
{
    while (1)
    {
        if(P1 != 0xf0)//当没有按键按下时,P0=0xf0;
        {
            Delay(1500);  //去抖
            if(P1 != 0xf0)//表示按键还在按下,判断是哪个按键
            {          
                P1 = 0xfe; //置位为fe,检测第一行    1111 1110
                //根据矩阵键盘原理图,当非第一行有按键按下时P1一直保持为0xfe
                if(P1 != 0xfe)  //将P1置为0xfe后,经过一个指令周期后如果它还是0xfe说明按下的键不在第一行
                {
                    Val = P1;
                    Delay(1500); //去抖
                    while(P1 != 0xfe); //等待按键弹起
                    P0 = Val;
                }
                P1 = 0xfd;       //置位为fd,检测第二行    1111 1101
                if (P1 != 0xfd)
                {
                    Val = P1;
                    Delay(1500);
                    while (P1 != 0xfd)
                    P0 = Val;
                }
                P1 = 0xfb;       //置位为fb,检测第三行    1111 1011
                if (P1 != 0xfb)
                {
                    Val = P1;
                    Delay(1500);
                    while (P1 != 0xfb)
                    P0 = Val;
                }
                P1 = 0xf7;       //置位为f7,检测第四行    1111 0111
                if (P1 != 0xf7)
                {
                    Val = P1;
                    Delay(1500);
                    while (P1 != 0xf7)
                    P0 = Val;
                }
            }
        }
    }
}

void Delay(unsigned int t)
{
    while (--t);
}

 

posted @ 2014-04-16 22:01  彩蛋  阅读(10631)  评论(0编辑  收藏  举报