C51单片机使用定时器T1的方式2制作电子时钟,并在LED数码管上显示“小时.分钟.秒”,如12点整,显示为:12.00.00。代码
时间: 2024-03-03 22:48:02 浏览: 85
好的,以下是C51单片机使用定时器T1的方式2制作电子时钟的代码:
```C
#include <reg52.h>
// 定义数码管端口
sbit LSA = P2^2;
sbit LSB = P2^3;
sbit LSC = P2^4;
sbit D1 = P0^0;
sbit D2 = P0^1;
sbit D3 = P0^2;
sbit D4 = P0^3;
// 定义时钟变量
unsigned char hour = 12;
unsigned char minute = 0;
unsigned char second = 0;
// 定时器T1中断服务程序
void timer1() interrupt 3
{
TH1 = 0x3C;
TL1 = 0xAF;
second++;
if (second == 60) {
second = 0;
minute++;
if (minute == 60) {
minute = 0;
hour++;
if (hour == 24) {
hour = 0;
}
}
}
}
// 显示函数
void display(unsigned char num, unsigned char pos)
{
unsigned char i;
unsigned char code table[] = {
0x3f, 0x06, 0x5b, 0x4f,
0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x00
};
LSA = 1;
LSB = 1;
LSC = 1;
P0 = 0xFF;
switch (pos) {
case 1: D1 = 0; break;
case 2: D2 = 0; break;
case 3: D3 = 0; break;
case 4: D4 = 0; break;
}
P0 = table[num];
for (i = 0; i < 100; i++);
P0 = 0xFF;
D1 = 1;
D2 = 1;
D3 = 1;
D4 = 1;
}
// 主函数
void main()
{
TMOD = 0x10;
TH1 = 0x3C;
TL1 = 0xAF;
TR1 = 1;
ET1 = 1;
EA = 1;
while (1) {
display(hour / 10, 1);
display(hour % 10, 2);
display(minute / 10, 3);
display(minute % 10, 4);
}
}
```
在上面的代码中,我们使用了定时器T1的方式2,每隔1秒钟就会触发一次定时器T1中断,此时我们在中断服务程序中更新时钟变量,然后在主函数中不断调用显示函数来显示时钟。具体实现细节可以看代码注释。
阅读全文