用51单片机制作数码管时钟程序
时间: 2023-08-11 18:04:44 浏览: 50
以下是51单片机制作数码管时钟程序的示例代码:
```c
#include <reg52.h> // 51单片机头文件
// 数码管共阴极连接方式
unsigned char code tab[] = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
void delay(unsigned int t) // 延时函数
{
unsigned int i, j;
for (i = 0; i < t; i++)
{
for (j = 0; j < 125; j++);
}
}
void main()
{
unsigned int cnt = 0; // 计数器
unsigned char hour = 12, minute = 0, second = 0; // 时间变量
while (1)
{
// 显示小时
P0 = tab[hour / 10];
P2 = 0xfe;
delay(5);
P0 = tab[hour % 10];
P2 = 0xfd;
delay(5);
// 显示分钟
P0 = tab[minute / 10];
P2 = 0xfb;
delay(5);
P0 = tab[minute % 10];
P2 = 0xf7;
delay(5);
// 显示秒钟
P0 = tab[second / 10];
P2 = 0xef;
delay(5);
P0 = tab[second % 10];
P2 = 0xdf;
delay(5);
// 更新时间
cnt++;
if (cnt == 200) // 1秒钟
{
cnt = 0;
second++;
if (second == 60)
{
second = 0;
minute++;
if (minute == 60)
{
minute = 0;
hour++;
if (hour == 24)
{
hour = 0;
}
}
}
}
}
}
```
该程序使用了数码管共阴极连接方式,需要将数码管的公共端连接到P2口,并将数码管的段选线连接到P0口。程序中使用了一个计数器,每隔5毫秒更新一次数码管的显示,同时更新时间变量hour、minute和second,实现时钟的功能。该程序可以根据需要进行修改,实现不同的功能。