- #include<reg52.h>
- bit timeint0,timeint1;
- unsigned char dispbuf[4];
- unsigned int period;
- unsigned int timecount=0;
- unsigned int count_1s;
- unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71}; //7段数码管代码表
- HEX_TO_BCD(unsigned int n)
- {
- unsigned char i; //当显示的频率超出范围,显示EEEE报错
- if (n>9361)
- for(i=0;i<4;i++)
- dispbuf[i]=0x0e;
- else
- {
- dispbuf[3]=n/1000; //取出千位字节
- dispbuf[2]=(n/100)%10; //取出百位字节
- dispbuf[1]=(n/10)%10; //取出十位字节
- dispbuf[0]=n%10; //取出个位字节
- }
- }
- void scandisp(void) //显示子程序,
- //将显示缓存数组中的BCD码扫描并显示在数码管上
- {
- unsigned char posi=0x01;
- unsigned char i,j,temp;
- for(i=0;i<4;i++) //依次选中4个数码管
- {
- temp=dispbuf[i];//查出字码
- temp=table[temp];//第三位显示小数点
- if(i==1)
- {
- for(j=0;j<200;j++)
- {
- P2=posi;
- P0=temp|0x80;
- }
- }
- else
- {
- for(j=0;j<200;j++)
- {
- P2=posi;
- P0 =temp;
- }
- }
- //依次点亮字位
- posi<<=1;
- }
- }
- void INIT_TMR1INT(void) //定时器初始化了程序,定义了两种
- {
- //定时/计数器0工作定时器方式,定时/计数器1工作在计数器方式
- TMOD=0x51;
- ET1=1;//中断0开中断
- ET0=1;//CPU开中断
- EA=1;
- count_1s=0;//启动定时/计数器0开始定时
- TR0=1;
- TR1=1;
- }
- void time0(void) interrupt 1 //定时器0中断服务程序,系统自动调用,
- //每2.5ms执行一次
- {
- TH0=0xf6;
- TH1=0x3c;//每次定时是2.5 ms, 40次即0.1s
- if(++count_1s>40)
- {
- count_1s=0;//每0.1s对计数器1所计数值进行统计
- timecount=TH1*256+TL1;
- TH1=0;
- TL1=0;//精确到小数点后1位,以KHz为单位
- period=timecount/10;//四舍五入显示
- if((timecount%10)>4)
- period++;
- timecount=0;
- HEX_TO_BCD(period);
- }
- }
- void timer1(void) interrupt 3 //定时器1中断服务程序,溢出后中断
- {
- TH1=0x00;
- TL1=0x00;
- }
- void main(void) //主函数
- {
- //初始化
- INIT_TMR1INT();
- while(1)
- {
- //显示子程序
- scandisp();
- }
- }
复制代码 |