1 仿真现象
2 程序设计
2.1 主程序
#include "DisplaySmg.h"
#include "Timer0.h"
sbit LED = P1^0;
unsigned int SystemTimer=0; //系统时间
unsigned char SystemFlag=1; //初始状态
unsigned int NUM = 1983; //待显示数据
void disp_num();
void main()
{
Timer0Init(); //启动定时器T0
do //开机显示
{
if(SystemTimer%500 == 0) //每间隔50ms
LED = ~LED; //LED灯闪烁
}while(SystemTimer<5000); //开机显示5000ms
SystemFlag = 0; //关闭初始状态,进入工作状态
while(1)
{
disp_num(); //显示四位十进制数
}
}
void disp_num()
{
LedBuf[0]= NUM/1000; //取千位
LedBuf[1]= NUM/100%10; //取百位
LedBuf[2]= NUM/10%10; //取十位
LedBuf[3]= NUM%10; //取个位
}
//定时计数器T0每满1ms,执行该中断函数,
void Timer0_ISR(void) interrupt 1
{
TR0=0;
if(SystemFlag==1) SystemTimer++; //系统时间自加1
DisplaySmg(); //实现数码管的动态显示刷新
TL0 = 0x66; //设置定时初始值
TH0 = 0xFC; //设置定时初始值
TR0=1;
}
2.2 数码管显示函数模块(switch case语言实现)
#ifndef __DisplaySmg_H__
#define __DisplaySmg_H__
#include
#define GPIO_SEG P0 //段选端
#define GPIO_SEL P2 //位选端
#define SMG_NUM 4 //数码管的个数
extern unsigned char LedBuf[]; //外部变量声明
void DisplaySmg();
#endif
#include "DisplaySmg.h"
unsigned char code LedData[]={ //共阴型数码管的段码表,字符,序号
0x3F, //"0",0
0x06, //"1",1
0x5B, //"2",2
0x4F, //"3",3
0x66, //"4",4
0x6D, //"5",5
0x7D, //"6",6
0x07, //"7",7
0x7F, //"8",8
0x6F, //"9",9
0x77, //"A",10
0x7C, //"B",11
0x39, //"C",12
0x5E, //"D",13
0x79, //"E",14
0x71, //"F",15
0x76, //"H",16
0x38, //"L",17
0x37, //"n",18
0x3E, //"u",19
0x73, //"P",20
0x5C, //"o",21
0x40, //"-",22
0x00, //熄灭 23
};
unsigned char code LedAddr[]={0xfe,0xfd,0xfb,0xf7}; //数码管位选
unsigned char LedBuf[]={22,22,22,22}; //显示缓存区
void DisplaySmg()
{
unsigned char i; //等价于 "static unsigned char i = 0;"
switch(i)
{
case 0:
GPIO_SEG = 0x00; //消影
GPIO_SEG = LedData[LedBuf[0]]; //段码
GPIO_SEL = LedAddr[0]; //位选
i++;
break;
case 1:
GPIO_SEG = 0x00;
GPIO_SEG = LedData[LedBuf[1]];
GPIO_SEL = LedAddr[1];
i++;
break;
case 2:
GPIO_SEG = 0x00;
GPIO_SEG = LedData[LedBuf[2]];
GPIO_SEL = LedAddr[2];
i++;
break;
case 3:
GPIO_SEG = 0x00;
GPIO_SEG = LedData[LedBuf[3]];
GPIO_SEL = LedAddr[3];
i=0;
break;
default:break;
}
}
3.3 定时/计数器中模块
#ifndef __Timer0_H__
#define __Timer0_H__
#include
void Timer0Init(void);
#endif
#include "Timer0.h"
void Timer0Init(void) //1毫秒@11.0592MHz
{
TMOD &= 0xF0; //设置定时器模式
TMOD |= 0x01; //设置定时器模式
TL0 = 0x66; //设置定时初始值
TH0 = 0xFC; //设置定时初始值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
ET0 = 1; //定时器0中断开关
EA = 1; //中断总开关
}
//中断服务函数一定是一个没有返回值的函数
//中断服务函数一定是没有参数的函数
//中断服务函数函数名后跟着关键字interrupt
//interrupt n 0~4 5个中断源,8*n+0003H
// 0003H INT0, 00BH T0, 0013H INT1, 001BH T1, 0023H ES
//中断服务函数不能被主程序或者其他程序所调用
//n后面跟着using m(0~3)工作寄存器组
//void Timer0_ISR(void) interrupt 1
//{
// TL0 = 0x66; //设置定时初始值
// TH0 = 0xFC; //设置定时初始值
//}
3 参考来源
(1)单片机应用实践篇之定时计/数器中断方式实现数码管动态显示刷新_哔哩哔哩_bilibili;