51單片機秒表C程序
本程序的keil工程下載:http://www.51hei.com/f/miaobiao.rar 以下是通過測試的源代碼:
本文引用地址:http://m.butianyuan.cn/article/201612/324640.htm/*
*功能:用定時器0實現(xiàn)秒表,實現(xiàn)60秒定時,精確度為1毫秒
* 利用key1獨立按鍵實現(xiàn)定時器的啟動和停止,
* 利用key2獨立按鍵實現(xiàn)秒表的清零;
*日期:2013-03-24
*作者:徐冉
*注意事項:若打開兩個定時器時,必須使用兩個定時器,
* 否則兩個定時器都不工作?。?!
**/
/**********stc89C52-RC 51hei單片機實驗板**********/
/**********51hei-5開發(fā)板**********/
#include
typedef unsigned int uint;
typedef unsigned char uchar;
sbit wela = P2^7;
sbit dula = P2^6;
sbit key1 = P3^4;
sbit key2 = P3^5;
sbit FM = P2^3;//蜂鳴器
uchar code table[] = {
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F, //"9"
0x77, //"A"
0x7C, //"B"
0x39, //"C"
0x5E, //"D"
0x79, //"E"
0x71, //"F"
0x76, //"H"
0x38, //"L"
0x37, //"n"
0x3E, //"u"
0x73, //"P"
0x5C, //"o"
0x40, //"-"
0x00, //熄滅
0x40 //自定義
};
uint counter, num_h, num_m;
void delay(uint xms);
void display_h(uint num_h);
void init();
void display_m(uint num_m);
void keyscan_D();
void keyscan_Q();
//主函數(shù)
void main()
{
init();
while(1)
{
dula = 1;
P0 = table[22];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfb;
wela = 0;
keyscan_D();
keyscan_Q();
display_h(num_h);
display_m(num_m);
}
}
//定時器0初始化函數(shù)
void init()
{
TMOD = 0x01;
TH0 = 0xFC;
TL0 = 0x67;
TR0 = 1;
EA = 1;
ET0 = 1;
}
//毫秒位顯示子函數(shù)
void display_h(uint num_h)
{
uchar bai,shi,ge;
bai = num_h / 100 % 10;
shi = num_h / 10 % 10;
ge = num_h % 10;
dula = 1;
P0 = table[bai];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xf7;
wela = 0;
P0 = 0x00;
delay(1);
dula = 1;
P0 = table[shi];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xef;
wela = 0;
P0 = 0x00;
delay(1);
dula = 1;
P0 = table[ge];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xdf;
wela = 0;
P0 = 0x00;
delay(1);
}
//秒位顯示子函數(shù)
void display_m(uint num_m)
{
uchar shi_, ge_;
shi_ = num_m / 10 % 10;
ge_ = num_m % 10;
dula = 1;
P0 = table[shi_];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfe;
wela = 0;
P0 = 0x00;
delay(1);
dula = 1;
P0 = table[ge_];
dula = 0;
P0 = 0xff;
wela = 1;
P0 = 0xfd;
wela = 0;
P0 = 0x00;
delay(1);
}
//延時子函數(shù)
void delay(uint xms)
{
uint i, j;
for(i = xms; i > 0; i--)
for(j = 125; j > 0; j--);
}
//獨立按鍵1檢測子函數(shù) ,開啟和關(guān)閉
void keyscan_D()
{
if(key1 == 0)
{
delay(10);
if(key1 == 0)
{
TR0 = ~TR0;
FM = 0;
while(!key1);
FM = 1;
}
}
}
//獨立按鍵2檢測子函數(shù),清零
void keyscan_Q()
{
if(key2 == 0)
{
delay(10);
if(key2 == 0)
{
counter = 0;
num_h = 0;
num_m = 0;
FM = 0;
while(!key2);
FM = 1;
}
}
}
//定時器0中斷子程序
void int_time0() interrupt 1
{
TH0 = 0xFC;
TL0 = 0x67;
counter++;
if(counter == 1)
{
counter = 0;
num_h++; //毫秒自增
if(num_h == 1000)
{
num_h = 0;
num_m++; //秒自增
if(num_m == 60)
{
num_m = 0;
}
}
}
}
評論