在学习了独立按键后,就产生了这个想法。所以今天就把他实现了出来:
#include<reg52.h> sbit KEY_s2 = P3^0; //定义按键s2 sbit WE = P2^7; //定义位选 sbit DU = P2^6; //定义段选 unsigned int code table[10] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F}; unsigned int code duan[10] = {0,0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F}; void delay() //20ms延时函数 (用于键盘消抖) { unsigned char a,b,c; for(c=1;c>0;c--) for(b=222;b>0;b--) for(a=40;a>0;a--); } void softwaredelay() //用于动态显示数码管 { unsigned char a,b; for(b=102;b>0;b--) for(a=3;a>0;a--); } void digitaltube(unsigned int du,unsigned int num) { if(num == 0) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[0]; DU = 0; } if(num == 1) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[1]; DU = 0; } if(num == 2) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[2]; DU = 0; } if(num == 3) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[3]; DU = 0; } if(num == 4) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[4]; DU = 0; } if(num == 5) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[5]; DU = 0; } if(num ==6) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[6]; DU = 0; } if(num == 7) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[7]; DU = 0; } if(num == 8) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[8]; DU = 0; } if(num == 9) { P0 = 0xFF; WE = 1; P0 = duan[du]; WE = 0; DU = 1; P0 = table[9]; DU = 0; } } void main() { unsigned int sec = 0; unsigned int dt4; unsigned int dt3; unsigned int dt2; unsigned int dt1; while(1) { if(KEY_s2 == 0) { delay(); //键盘消抖 if(KEY_s2 == 0) { sec ++; while(!KEY_s2); } } //松键盘后数码管显示加1 dt4 = sec % 10; dt3 = (sec / 10) % 10; dt2 = (sec / 100) % 10; dt1 = (sec/ 1000) % 10; digitaltube(1 , dt1); softwaredelay(); digitaltube(2 , dt2); softwaredelay(); digitaltube(3 , dt3); softwaredelay(); digitaltube(4 , dt4); softwaredelay(); } }
但是在烧录到单片机里执行的时候会发现在按键按下时,数码管是熄灭的......这就涉及到了中断的问题。我们下一个笔记会探讨一下这个程序的中断版本。