作者:mobiledu2502852753 | 来源:互联网 | 2024-11-29 15:38
本项目旨在利用AT89X51单片机实现一个简单的时间和日期显示系统,用户可以通过按键在时间显示和日期显示之间进行切换。以下是具体的实现代码:
#include
// 数码管显示编码表
char display[] = {0X3F, 0X06, 0X5B, 0X4F, 0X66, 0X6D, 0X7D, 0X07, 0X7F, 0X6F, 0XF7, 0X7C, 0X39, 0X5E, 0X79, 0X71};
char hour = 0, minute = 0, secOnd= 0; // 初始化时间为00:00:00
char year = 21, mOnth= 1, day = 1; // 初始化日期为2021年1月1日
// 延时函数
void delay(unsigned int xms) {
unsigned int i, j;
for (i = xms; i > 0; i--) {
for (j = 240; j > 0; j--);
}
}
// 显示数字
void displayNumber(char value) {
P0 = display[value];
}
// 显示时间
void showTime() {
P2 = 0xFE;
displayNumber(hour / 10);
delay(1);
P2 = 0xFD;
P0 = display[hour % 10] | 0x80;
delay(1);
P2 = 0xFB;
displayNumber(minute / 10);
delay(1);
P2 = 0xF7;
P0 = display[minute % 10] | 0x80;
delay(1);
P2 = 0xEF;
displayNumber(second / 10);
delay(1);
P2 = 0xDF;
P0 = display[second % 10];
delay(1);
}
// 显示日期
void showDate() {
P2 = 0xFE;
displayNumber(year / 10);
delay(1);
P2 = 0xFD;
P0 = display[year % 10] | 0x80;
delay(1);
P2 = 0xFB;
displayNumber(month / 10);
delay(1);
P2 = 0xF7;
P0 = display[month % 10] | 0x80;
delay(1);
P2 = 0xEF;
displayNumber(day / 10);
delay(1);
P2 = 0xDF;
P0 = display[day % 10];
delay(1);
}
// 按键扫描
unsigned char scanKey() {
unsigned char keyValue;
P1 = 0x0F;
if (P1 != 0x0F) {
switch (P1) {
case 0x0E: // 第一列
P1 = 0xF0;
switch (P1) {
case 0x70: keyValue = 12; break;
case 0xB0: keyValue = 8; break;
case 0xD0: keyValue = 4; break;
case 0xE0: keyValue = 0; break;
}
break;
case 0x0D: // 第二列
P1 = 0xF0;
switch (P1) {
case 0x70: keyValue = 13; break;
case 0xB0: keyValue = 9; break;
case 0xD0: keyValue = 5; break;
case 0xE0: keyValue = 1; break;
}
break;
case 0x0B: // 第三列
P1 = 0xF0;
switch (P1) {
case 0x70: keyValue = 14; break;
case 0xB0: keyValue = 10; break;
case 0xD0: keyValue = 6; break;
case 0xE0: keyValue = 2; break;
}
break;
case 0x07: // 第四列
P1 = 0xF0;
switch (P1) {
case 0x70: keyValue = 15; break;
case 0xB0: keyValue = 11; break;
case 0xD0: keyValue = 7; break;
case 0xE0: keyValue = 3; break;
}
break;
}
}
return keyValue;
}
// 判断闰年
char isLeapYear(int year) {
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
return 29;
else
return 28;
}
// 获取月份天数
char getMonthDays(int year, char month) {
switch (month) {
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return isLeapYear(year);
default:
return 31;
}
}
char tick = 1;
// 定时器0中断服务程序
void timer0ISR() interrupt 1 {
if (++tick == 20) {
tick = 0;
if (++secOnd== 60) {
secOnd= 0;
if (++minute == 60) {
minute = 0;
if (++hour == 24) {
hour = 0;
if (++day == getMonthDays(2000 + year, month) + 1) {
day = 1;
if (++mOnth== 13) {
mOnth= 1;
year++;
}
}
}
}
}
}
}
void main() {
char key = 0x55;
TMOD = 0x01; // T0模式1,16位定时器
TH0 = -50000 / 256;
TL0 = -50000 % 256;
ET0 = 1; // 允许T0中断
EA = 1; // 允许全局中断
TR0 = 1; // 启动T0
while (1) {
key = scanKey();
if (key == 1)
showTime();
else if (key == 2)
showDate();
}
}
以上代码实现了基本的时钟和日期显示功能,并通过按键进行界面切换。定时器0用于产生每秒一次的中断,以更新时间。按键扫描部分负责检测用户的输入并根据输入切换显示内容。