按键控制数字加1减1

前面学习了数码管和按键,将两者结合,完成一个用两个按键控制加减数字的小程序,一个按键控制加1另一个控制减1。

#include <reg52.h>

sbit KeyAdd = P0^0; //加1按键
sbit KeyDec = P0^1; //减1按键
sbit LATCH1 = P2^2; //段锁存
sbit LATCH2 = P2^3; //位锁存
unsigned char code DuanMa[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};// 显示段码值0~9
unsigned char code WeiMa[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};//位码
unsigned char TempData[8]; //存储显示值

void Delay(unsigned int t);
void Display(unsigned char FirstBit,unsigned char Num);

void main(void)
{    unsigned char num = 0;
    while (1)
    {
        if (!KeyAdd)        //加1按键有效
        {
            Delay(1500);    //延时去抖 一般10-20ms
            if (!KeyAdd)
            {
                while (!KeyAdd);
                if (num < 9)
                  num++;
            }    
        }

        if (!KeyDec)        //减1按键有效
        {
            Delay(1500);
            if (!KeyDec)
            {
                while (!KeyDec);
                if (num > 0)
                  num--;
            }
        }

        TempData[0] = DuanMa[num % 10];
        Display(0, 1);
    }
}

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

void Display(unsigned char FirstBit,unsigned char Num)
{
    unsigned char i;
      
    for(i = 0; i < Num; i++)
    {
        P1 = 0;   //清空数据,防止有交替重影
        LATCH1 = 1;     //段锁存
        LATCH1 = 0;

        P1 = WeiMa[i + FirstBit]; //取位码 
        LATCH2=1;     //位锁存
        LATCH2=0;

        P1 = TempData[i]; //取显示数据,段码
        LATCH1=1;     //段锁存
        LATCH1=0;
       
        Delay(2000); // 保持显示一段时间
       }
}

 

posted @ 2014-03-19 21:50  彩蛋  阅读(1407)  评论(0编辑  收藏  举报