標(biāo)題: 51單片機(jī)通過(guò)按鍵進(jìn)行計(jì)數(shù) [打印本頁(yè)]

作者: Mr_Shier    時(shí)間: 2018-3-22 23:15
標(biāo)題: 51單片機(jī)通過(guò)按鍵進(jìn)行計(jì)數(shù)
51單片機(jī)按鍵和數(shù)碼管的簡(jiǎn)單使用。通過(guò)按鍵P34和P35循環(huán)計(jì)數(shù)0000~9999,并通過(guò)數(shù)碼管顯示。附上一段代碼:
/*********************51單片機(jī)學(xué)習(xí)例程******************
*    功能:通過(guò)按鍵P34、P35循環(huán)計(jì)數(shù)0000~9999
*    編寫:十二
*    晶振:12MHZ
*****************************************************/
#include <reg52.h>
typedef unsigned int uint;
typedef unsigned char uchar;
sbit P2_0=P2^0;
sbit P2_1=P2^1;
sbit P2_2=P2^2;
sbit P2_3=P2^3;
sbit key1=P3^4;
sbit key2=P3^5;
void delay_10ms(uint t)
{
        uint i,j;
        for(i=t;i>0;i--)
                for(j=125;j>0;j--);                  
}
void display_count(uint x,uint y,uint z,uint w)
{
        uint a[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
        uint i;
        for(i=0;i<20;i++)
        {
                P0=a[x];
                P2_0=0;
                delay_10ms(1);
                P2_0=1;
                P0=a[y];
                P2_1=0;
                delay_10ms(1);
                P2_1=1;
                P0=a[z];
                P2_2=0;
                delay_10ms(1);
                P2_2=1;
                P0=a[w];
                P2_3=0;
                delay_10ms(1);
                P2_3=1;
        }       
}

void main()
{
        uint x,y,z,w;
        x=y=z=w=0;
        while(1)
        {
                display_count(x,y,z,w);
                if(key1==0)
                {
                        delay_10ms(1);
                        if(key1==0)
                        {
                                z++;
                                while(key1==0);
                        }
                }
                if(key2==0)
                {
                        delay_10ms(1);
                        if(key2==0)
                        {
                                w++;
                                while(key2==0);
                        }
                }
                if(w>9)
                {
                        z++;
                        w=0;
                }
                if(z>9)
                {
                        y++;
                        z=0;
                }
                if(y>9)
                {
                        x++;
                        y=0;
                }
                if(x>9)
                        x=0;
        }
}










歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1