51单片机电子闹钟代码
时间: 2023-11-11 10:03:56 浏览: 204
以下是51单片机电子闹钟的代码:
```c
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
uchar code table[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
uchar hour = 0, minute = 0, second = 0;uchar alarm_hour = 0, alarm_minute = 0;
bit alarm_flag = 0;
void delay(uint xms)
{
uint i, j;
for (i = xms; i > 0; i--)
for (j = 110; j > 0; j--);
}
void display(uchar num)
{
P2 = table[num];
}
void display_time()
{
display(hour / 10);
P1 = 0xfe;
delay(5);
display(hour % 10);
P1 = 0xfd;
delay(5);
display(minute / 10);
P1 = 0xfb;
delay(5);
display(minute % 10);
P1 = 0xf7;
delay(5);
}
void display_alarm()
{
display(alarm_hour / 10);
P1 = 0xfe;
delay(5);
display(alarm_hour % 10);
P1 = 0xfd;
delay(5);
display(alarm_minute / 10);
P1 = 0xfb;
delay(5);
display(alarm_minute % 10);
P1 = 0xf7;
delay(5);
}
void init()
{
TMOD = 0x01;
TH0 = 0x4c;
TL0 = 0x00;
TR0 = 1;
ET0 = 1;
EA = 1;
}
void main()
{
init();
while (1)
{
if (alarm_flag)
{
display_alarm();
}
else
{
display_time();
}
}
}
void time() interrupt 1
{
TH0 = 0x4c;
TL0 = 0x00;
second++;
if (second == 60)
{
second = 0;
minute++;
if (minute == 60)
{
minute = 0;
hour++;
if (hour == 24)
{
hour = 0;
}
}
}
if (hour == alarm_hour && minute == alarm_minute)
{
alarm_flag = 1;
}
}
```
阅读全文