1. 程式人生 > >用51單片機實現的簡易秒表

用51單片機實現的簡易秒表

oid err 出發 控制 void main函數 i++ log 51單片機

設計思路:在main函數中不停的控制數碼管顯示時、分、秒,同時用定時器0控制時間的遞增

代碼如下:

  1 #include "reg52.h"
  2 #define led P0
  3 typedef unsigned char u8;
  4 typedef unsigned int u16;
  5 
  6 sbit LSA = P2^2;
  7 sbit LSB = P2^3;
  8 sbit LSC = P2^4;
  9 sbit k3 = P3^2;
 10 sbit k4 = P3^3;
 11 static u8 hour = 0;
 12 static u8 min = 0
; 13 static u8 sec = 0; 14 15 u8 code smgz[] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07, 16 0x7f,0x6f,0x40}; 17 18 u8 code location[8][3] = {1, 1, 1, 19 0, 1, 1, 20 1, 0, 1, 21 0, 0, 1, 22 1
, 1, 0, 23 0, 1, 0, 24 1, 0, 0, 25 0, 0, 0}; 26 //位置表 從左到右 27 28 void delay(u16 j){ 29 while(j--); 30 } 31 32 char nol(char loc){ 33 switch(loc){ 34 case 7: 35 return sec % 10 ; 36 case
6: 37 return sec / 10; 38 case 5: 39 return 10; 40 case 4: 41 return min % 10; 42 case 3: 43 return min / 10; 44 case 2: 45 return 10; 46 case 1: 47 return hour % 10; 48 case 0: 49 return hour / 10; 50 } 51 } 52 53 void Timer0Init() 54 { 55 TMOD |= 0X01; 56 TH0 = 0XFC; 57 TL0 = 0X18; 58 ET0 = 1; 59 IT0=1;//跳變沿出發方式(下降沿) 60 EX0=1;//打開INT0的中斷允許。 61 IT1=1; 62 EX1=1; 63 EA = 1; 64 TR0 = 1; 65 } 66 void main(){ 67 68 Timer0Init(); 69 while(1) 70 { 71 u8 i; 72 for(i = 0; i <= 7; i++){ 73 74 LSA = location[i][0]; 75 LSB = location[i][1]; 76 LSC = location[i][2]; 77 led = smgz[nol(i)]; 78 delay(50); 79 led = 0;//消隱 80 } 81 } 82 } 83 void Timer0() interrupt 1 84 { 85 static int Timer0_times = 0; 86 TH0 = 0XFC; 87 TL0 = 0X18; 88 Timer0_times++; 89 if(Timer0_times == 987) 90 { 91 if(sec < 59) 92 sec++; 93 else if(min < 59) 94 { 95 min++; 96 sec = 0; 97 } 98 else 99 { 100 hour++; 101 min = sec = 0; 102 } 103 Timer0_times = 0; 104 } 105 } 106 107 void Int0() interrupt 0 //外部中斷0的中斷函數 108 { 109 delay(1000); //延時消抖 110 if(k3==0) 111 { 112 TR0 = ~TR0; 113 } 114 } 115 116 void Int1() interrupt 2 //外部中斷1的中斷函數 117 { 118 delay(1000); //延時消抖 119 if(k4==0) 120 { 121 TR0 = 0; 122 hour = min = sec = 0; 123 124 } 125 }

用51單片機實現的簡易秒表