首页 > 技术文章 > 利用中断制作一个秒钟

yongy1030 2017-08-17 11:27 原文

 

我是每个函数都单独写了一个文件

 

  • 头文件里东西
1 #include <reg52.h>
2 
3 #define uint unsigned int
4 #define uchar unsigned char

 

  • 主函数
 1 #include "head.h"
 2 
 3 void init();
 4 void display(uint num);
 5 
 6 uint num = 0;
 7 void main()
 8 {
 9     init();
10     while(1){
11         display(num);
12     }
13 }

init() 是初始化函数

display() 是动态扫描显示函数

 

  • init函数
 1 #include "head.h"
 2 
 3 void init()
 4 {
 5     TMOD = 0x01;
 6     TH0 = (65536-45872)/256;
 7     TL0 = (65536-45872)%256;
 8     EA = 1;
 9     ET0 = 1;
10     TR0 = 1;
11     P0 = 0xff;
12     P1 = 0x00;
13 }

 

 

 初始化步骤:

  1,中断工作方式寄存器TMOD初始化。(定时器0设置成16位的)

  2,给定时器装初值。(递增计时, 一次时间50ms)

  3,中断允许寄存器IE初始化,使用位寻址。(EA 全局中断允许,ET0 定时器0允许)

  4,定时器控制寄存器TCON初始化,位寻址。(TR0启动定时器0)

  5,两个8字显示管初始化(位选共阴极),使全部熄灭。

 

  • 中断服务函数
 1 #include "head.h"
 2 
 3 extern uint num;
 4 uint temp = 0;
 5 void T0_timer() interrupt 1
 6 {
 7     TH0 = (65536-45872)/256;
 8     TL0 = (65536-45872)%256;
 9     temp++;
10     if(temp == 20){
11         temp = 0;
12         num++;
13         if(num == 60)
14             num = 0;
15     }
16 }

 

每次要重装初值。每1s,num++。

 

  • display函数
 1 #include "head.h"
 2 
 3 void delayms(uint xms);
 4 
 5 uchar table[]={
 6     0x3f, 0x06, 0x5b, 0x4f,
 7     0x66, 0x6d, 0x7d, 0x07,
 8     0x7f, 0x6f, 0x77, 0x7c,
 9     0x39, 0x5e, 0x79, 0x71
10 };
11 void display(uint num)
12 {
13     uint shi = num/10;
14     uint ge = num%10;
15     P1 = table[shi];
16     P0 = 0xfe;
17     delayms(1);
18     P1 = table[ge];
19     P0 = 0xfd;
20     delayms(1);
21 }

 

table[]数组是共阴极的七段译码管的显示数组。

 

  • delayms的ms延时函数
1 #include "head.h"
2 
3 void delayms(uint xms)
4 {
5     uint i, j;
6     for(i = 0; i < xms; i++)
7         for(j = 0; j < 110; j++);
8 }

 

延时xms个ms时间。

晶振为11.0592MHz。110是调试出来的。

 

推荐阅读