實現秒表計數功能,使用定時器和外部中斷實現。8號按鍵代表計時開始/結束,C號按鍵代表重置為0,為了演示方便,這裡上限定為15秒。
代碼中有詳細的注釋:
#includesbit WEI=P2^7; sbit DUAN=P2^6; sbit L1=P3^4; unsigned char code dofly_DuanMa[11]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x40};// 顯示段碼值0~9 unsigned char code dofly_WeiMa[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};//分別對應相應的數碼管點亮,即位碼 void delay(int t) { while(t--); } //第一個參數i代表控制第幾個數碼管,n代表要顯示的數字 void Screen(int i,int n) { P0=0; DUAN=1; DUAN=0; P0=dofly_WeiMa[i]; WEI=1; WEI=0; P0=dofly_DuanMa[n]; DUAN=1; DUAN=0; } int sec; int num; int i; int flag; int main() { flag=1; i=0; num=0; sec=0; WEI=0; DUAN=0; //開中斷 EX0=1; IT0=1; EX1=1; IT1=1; //定時器初始化 TMOD |= 0x01; EA=1; ET0=1; TR0=1; L1=0; while(1) { if(num>=10) Screen(3,num/10); Screen(4,num%10); delay(10); Screen(5,10); Screen(6,sec/10); Screen(7,sec%10); } return 0; } void Timer_0() interrupt 1 using 1 { TH0=(65536-10000)/256; TL0=(65535-10000)%256; if(flag==1) { i++; sec++; if(sec==100) //0.1ms sec=0; if(i==101)//1s { i=0; num++; if(num==15) num=0; } } } void ACTION1() interrupt 0 { flag=!flag; } void ACTION2() interrupt 2 { if(flag==0) { Screen(7,0); num=0; sec=0; } }