1. #include "reg52.h"
    2. #include "intrins.h"
    3. sbit LED1 = P1^1; // LED灯
    4. sbit SLED1 = P2^4; // 数码管
    5. sbit SLED2 = P2^5;
    6. sbit SLED3 = P2^6;
    7. sbit SLED4 = P2^7;
    8. unsigned char counter;
    9. unsigned char time_counter;
    10. // 数码管显示的数字
    11. typedef unsigned char uchar;
    12. uchar code dataArr[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
    13. // ms级延时函数
    14. void delay(unsigned int xms)
    15. {
    16. unsigned int i,j;
    17. for(i = xms; i > 0; i--)
    18. for(j = 114; j > 0; j--);
    19. }
    20. // 数码管计时
    21. void display(unsigned char time_counter)
    22. {
    23. unsigned char shi, ge;
    24. shi = time_counter / 10;
    25. ge = time_counter % 10;
    26. // 只让数码管1亮
    27. SLED1 = 1;
    28. SLED2 = 0;
    29. SLED3 = 0;
    30. SLED4 = 0;
    31. P0 = dataArr[shi]; // 十位
    32. delay(2);
    33. // 只让数码管2亮
    34. SLED1 = 0;
    35. SLED2 = 1;
    36. SLED3 = 0;
    37. SLED4 = 0;
    38. P0 = dataArr[ge]; // 个位
    39. delay(2);
    40. }
    41. void main()
    42. {
    43. // 定时器
    44. /* 定时50ms
    45. 11.0592晶振的机器周期为 1/11.0592 * 12 = 1.085ns
    46. 50000/1.085 = 46082
    47. 65536-46082 = 19454 = 4bfe
    48. */
    49. TMOD = 0x01; // 选择定时器模式1 定时器0
    50. TH0 = (65536 - 46082)/256; // 定时50ms
    51. TL0 = (65536 - 46082)%256;
    52. TR0 = 1; // 启动定时器0
    53. LED1 = 0;
    54. while(1)
    55. {
    56. if(TF0 == 1)
    57. {
    58. TF0 = 0;
    59. TH0 = 0x4b;
    60. TL0 = 0xfe;
    61. counter++;
    62. }
    63. if(counter == 20)
    64. {
    65. LED1 = ~LED1;
    66. counter = 0;
    67. time_counter++;
    68. }
    69. if(time_counter == 60)
    70. {
    71. time_counter = 0; // 到60s计时器清零
    72. }
    73. display(time_counter);
    74. }
    75. }