实验内容:
利用所学的单片机知识及电路知识编程实现显示时钟,选中 8 位数码管,编程实现 8 位数码管示时钟,显示格式为 XX(小时) —XX(分钟)—XX(秒)。
实验步骤:根据实验室二数码管的电路原理图编写 C 程序,调试并烧写入单片机;
数码管电路如下:
效果如下:
代码如下:
#include <REGX52.H> #include <intrins.h> typedef unsigned char uchar; //共阴段码(0-9) uchar code leddata[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D, 0x7D,0x07,0x7F,0x6F}; uchar hour=0,minute=0,second=0;//全局变量时分秒 uchar count=0; //定时器初始化 void Timer0Init() //50毫秒@12.000MHz { TMOD &= 0xF0; //设置定时器模式 TMOD |= 0x01; //设置定时器模式 TL0 = 0xB0; //设置定时初值 TH0 = 0x3C; //设置定时初值 TF0 = 0; //清除TF0标志 TR0 = 1; //定时器0开始计时 ET0=1; //打开小开关 EA=1; //打开总开关 } //延时函数 void delay(unsigned int ms){ while(ms--){ unsigned char i, j; _nop_(); i = 2; j = 199; do { while (--j); } while (--i); } } /* 显示时钟函数 参数1:时 参数2:分 参数3:秒 返回值:无 */ void display(uchar hour,uchar minute,uchar second){ int i; for(i=1;i<=8;i++){ switch(i){ case 1: P2_4=0;P2_3=0;P2_2=0;P0=leddata[second%10];break; case 2: P2_4=0;P2_3=0;P2_2=1;P0=leddata[second/10];break; case 3: P2_4=0;P2_3=1;P2_2=0;P0=0x40;break;//显示 — case 4: P2_4=0;P2_3=1;P2_2=1;P0=leddata[minute%10];break; case 5: P2_4=1;P2_3=0;P2_2=0;P0=leddata[minute/10];break; case 6: P2_4=1;P2_3=0;P2_2=1;P0=0x40;break;//显示 — case 7: P2_4=1;P2_3=1;P2_2=0;P0=leddata[hour%10];break; case 8: P2_4=1;P2_3=1;P2_2=1;P0=leddata[hour/10];break; } delay(1); P0=0; //消影 } } //定时器中断函数 void interrupt_T0()interrupt 1 { TL0 = 0xB0; //重新设置定时初值 TH0 = 0x3C; //重新设置定时初值 count++; if(count==20){//一秒时间到了~ count=0; second++; if(second==60){ second=0; minute++; if(minute==60){ minute=0; hour++; if(hour==24) hour=0; } } } } void main(){ Timer0Init();//定时器T0初始化 while(1){ display(hour,minute,second); //显示时间 } }
电路的晶振是12Mhz 就能让时间没有误差,假如电路用的晶振是11.0592的话 得改定时器的装入初值为,TL0 = 0x00; TH0 = 0x4C; ,中断那里也是同样,这样就能保证计时的精度了