电子万年历代码c语言keil
时间: 2023-08-12 09:32:13 浏览: 86
C语言写的电子万年历代码
下面是一个简单的电子万年历的代码示例,使用C语言和Keil开发环境:
```c
#include <reg51.h>
// 定义数码管显示的端口
sbit dula = P2 ^ 6;
sbit wela = P2 ^ 7;
sbit beep = P1 ^ 5;
// 定义按键的端口
sbit key1 = P3 ^ 1;
sbit key2 = P3 ^ 0;
sbit key3 = P3 ^ 2;
// 定义闹铃时间
unsigned char alarm_hour = 0;
unsigned char alarm_minute = 0;
// 定义当前时间
unsigned char hour = 0;
unsigned char minute = 0;
unsigned char second = 0;
// 定义当前日期
unsigned char year = 0;
unsigned char month = 0;
unsigned char day = 0;
unsigned char week = 0;
// 数码管显示表
unsigned char code table[] = {
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71
};
// 延时函数
void delay(unsigned int i) {
while (i--);
}
// 数码管显示函数
void display(unsigned char *p) {
unsigned char i;
for (i = 0; i < 8; i++) {
dula = 1;
P0 = table[p[i]];
dula = 0;
delay(100);
}
for (i = 0; i < 8; i++) {
wela = 1;
P0 = 0xfe << i;
wela = 0;
delay(100);
}
}
// 设置时间函数
void set_time() {
unsigned char i, j, k;
i = j = k = 0;
while (1) {
if (key1 == 0) {
delay(10);
if (key1 == 0) {
i++;
if (i == 24) i = 0;
while (!key1);
}
}
if (key2 == 0) {
delay(10);
if (key2 == 0) {
j++;
if (j == 60) j = 0;
while (!key2);
}
}
if (key3 == 0) {
delay(10);
if (key3 == 0) {
k++;
if (k == 60) k = 0;
while (!key3);
}
}
hour = i;
minute = j;
second = k;
display(&hour);
beep = 0;
delay(500);
beep = 1;
}
}
// 主函数
void main() {
// 初始化定时器
TMOD = 0x01;
TH0 = (65536 - 45872) / 256;
TL0 = (65536 - 45872) % 256;
ET0 = 1;
EA = 1;
TR0 = 1;
// 显示欢迎语
unsigned char welcome[] = {0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f};
display(welcome);
delay(1000);
// 设置时间
set_time();
// 正常运行
while (1) {
// 显示时间和日期
unsigned char time[] = {hour / 10, hour % 10, 10, minute / 10, minute % 10, 10, second / 10, second % 10};
display(time);
unsigned char date[] = {year / 10, year % 10, 11, month / 10, month % 10, 11, day / 10, day % 10};
display(date);
// 检查闹铃时间
if (hour == alarm_hour && minute == alarm_minute) {
beep = 0;
delay(500);
beep = 1;
}
}
}
// 定时器中断函数
void timer0() interrupt 1 {
TH0 = (65536 - 45872) / 256;
TL0 = (65536 - 45872) % 256;
second++;
if (second == 60) {
second = 0;
minute++;
if (minute == 60) {
minute = 0;
hour++;
if (hour == 24) {
hour = 0;
week++;
if (week == 7) {
week = 0;
}
}
}
}
}
```
注意:此代码仅供参考,实际应用中还需要添加更多的功能和错误处理。
阅读全文