《基于51单片机的秒表程序.pdf》由会员分享,可在线阅读,更多相关《基于51单片机的秒表程序.pdf(5页珍藏版)》请在三一文库上搜索。
1、基于基于 51 单片机的秒表程序单片机的秒表程序 #include sbitADDR3=P13;/单片机 I/O 口 sbit ENLED=P14; sbit KEY1 = P24; sbit KEY2 = P25; sbit KEY3 = P26; sbit KEY4 = P27; unsigned char code LedChar = /数码管显示字符转换表 0 xC0, 0 xF9, 0 xA4, 0 xB0, 0 x99, 0 x92, 0 x82, 0 xF8, 0 x80, 0 x90, 0 x88, 0 x83, 0 xC6, 0 xA1, 0 x86, 0 x8E ; uns
2、igned char LedBuff6 = /数码管显示缓冲区 0 xFF, 0 xFF, 0 xFF, 0 xFF, 0 xFF, 0 xFF ; unsigned char KeySta4 = 1,1,1,1; bit StopwatchRefresh=1; bit StopwatchRunning=0; unsigned char DecimalPart=0; unsigned int IntegerPart=0; unsigned char T0RH=0; unsigned char T0RL=0; void ConfigTimer0(unsigned int ms); void St
3、opwatchDisplay(); void KeyDriver(); void main() EA= 1;/使能总中断 ENLED=0; ADDR3=1; P2=0XFE; ConfigTimer0(2); while (1) if (StopwatchRefresh) StopwatchRefresh=0; StopwatchDisplay(); KeyDriver(); void ConfigTimer0(unsigned int ms) unsigned long tmp; tmp=11059200/12; tmp=(tmp*ms)/1000; tmp=65536-tmp; tmp=t
4、mp+18; T0RH=(unsigned char)(tmp8); T0RL=(unsigned char)tmp; TMOD TMOD|=0X01; TH0=T0RH; TL0=T0RL; ET0=1; TR0=1; void StopwatchDisplay() signed char i; unsigned char buf4; LedBuff0=LedCharDecimalPart%10; LedBuff1=LedChar(DecimalPart/10)%10; buf0=IntegerPart%10; buf1=(IntegerPart/10)%10; buf2=(IntegerP
5、art/100)%10; buf3=(IntegerPart/1000)%10; for(i=3;i=1;i-) if(bufi=0) LedBuffi+2=0XFF;/高位消零 else break; for(;i=0;i-) LedBuffi+2=LedCharbufi; LedBuff2/第三个数码管显示小数点 /秒表开始函数 void StopwatchAction() if(StopwatchRunning) StopwatchRunning=0; else StopwatchRunning=1; /秒表复位函数 void StopwatchReset() StopwatchRunn
6、ing=0; DecimalPart=0; IntegerPart=0; StopwatchRefresh=1; /检测按键是否有动作,主函数中调用此函数 voidKeyDriver() unsigned char i; staticunsigned char backup 4= 1,1,1,1; for(i=0; i4; i+) if(backupi != KeyStai) if(backupi != 0) if(i=1) StopwatchReset(); else if(i=2) StopwatchAction(); backupi = KeyStai; /按键扫描函数,需在定时中断中调
7、用,推荐调用间隔 1ms void KeyScan() unsigned char i; static unsigned char keybuf4 = 0 xFF, 0 xFF, 0 xFF, 0 xFF; /将一行的 4 个按键值移入缓冲区 keybuf0 = (keybuf0 1) | KEY1; keybuf1 = (keybuf1 1) | KEY2; keybuf2 = (keybuf2 1) | KEY3; keybuf3 = (keybuf3 1) | KEY4; /消抖后更新按键状态 for (i=0; i4; i+)/每行 4 个按键,所以循环 4 次 if (keybufi
8、= 0 x00) /连续 4 次扫描值为 0,即 4*4ms 内都是按下状态时,可认为按键已稳定的按 下 KeyStai = 0; else if (keybufi=0 xFF) /连续 4 次扫描值为 1,即 4*4ms 内都是弹起状态时,可认为按键已稳定的弹 起 KeyStai = 1; /数码管显示函数,中断函数中调用 void LedScan() static unsigned char i=0; P0=0XFF; P1=(P1 P0=LedBuffi; if(i=10) DecimalPart=0; IntegerPart+; if(IntegerPart=10000) IntegerPart=0; StopwatchRefresh=1; /* T0 中断服务函数,用于数码管显示扫描与按键扫描 */ void InterruptTimer0() interrupt 1 static unsigned char tmr10ms=0; TH0=T0RH; TL0=T0RL; LedScan(); KeyScan(); tmr10ms+; if(tmr10ms=5) tmr10ms=0; StopwatchCount();