#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
#define KEY_IO P3
#define LCD_IO P0
sbit LCD_RS = P2^0;
sbit LCD_RW = P2^1;
sbit LCD_EN = P2^2;
sbit SPK = P1^2;//定義蜂鳴器
sbit LED = P2^4;//定義LED
bit new_s, modify = 0;
char t0, sec = 50, min = 59, hour = 23;
char code LCD_line1[] = "THE CLOCK";
char code LCD_line2[] = "Timer: 00:00:00 ";
char Timer_buf[] = "23:59:50";
void delay(uint z)//延時函數
{
uint x, y;
for(x = z; x > 0; x--) for(y = 100; y > 0; y--);
}
void W_LCD_Com(uchar com)//寫指令
{
LCD_RS = 0;
LCD_IO = com;//RS和RW都為低電平,寫入指令
LCD_EN = 1;
delay(5); LCD_EN = 0;
}
void W_LCD_Dat(uchar dat)
{
LCD_RS = 1; LCD_IO = dat;
LCD_EN = 1; delay(5); LCD_EN = 0;
}
void W_LCD_STR(uchar *s)
{
while(*s) W_LCD_Dat(*s++);
}
void W_BUFF(void)
{
Timer_buf[7] = sec % 10 + 48; Timer_buf[6] = sec / 10 + 48;
Timer_buf[4] = min % 10 + 48; Timer_buf[3] = min / 10 + 48;
Timer_buf[1] = hour % 10 + 48;Timer_buf[0] = hour / 10 + 48;
W_LCD_Com(0xc0 + 7); W_LCD_STR(Timer_buf);
}
uchar read_key(void)
{
uchar x1, x2;
KEY_IO = 255;
x1 = KEY_IO;
if (x1 != 255) {
delay(100);
x2 = KEY_IO;
if (x1 != x2) return 255;
while(x2 != 255) x2 = KEY_IO;
if (x1 == 0x7f) return 0;
else if (x1 == 0xbf) return 1;
else if (x1 == 0xdf) return 2;
else if (x1 == 0xef) return 3;
else if (x1 == 0xf7) return 4;
}
return 255;
}
void Init()
{
LCD_RW = 0;
W_LCD_Com(0x38); delay(50);
W_LCD_Com(0x0c);
W_LCD_Com(0x06);
W_LCD_Com(0x01);
W_LCD_Com(0x80); W_LCD_STR(LCD_line1);
W_LCD_Com(0xC0); W_LCD_STR(LCD_line2);
TMOD = 0x01;
TH0 = 0x4c;
TR0 = 1;
PT0 = 1;
ET0 = 1;
EA = 1;
}
void main()
{
uint i, j;
uchar Key;
Init();
while(1) {
if (new_s) {
new_s = 0; sec++; sec %= 60;
if(!sec) { min++; min %= 60;
if(!min) { hour++; hour %= 24;}
}
W_BUFF();
if (!sec && !min) {
for (i = 0; i < 200; i++) {
SPK = 0; for (j = 0; j < 100; j++);
SPK = 1; for (j = 0; j < 100; j++);
} }
}
Key = read_key();
switch(Key) {
case 0: modify = 1; break;
case 1: if(modify) {min++; min %= 60; W_BUFF(); break;}
case 2: if(modify) {hour++; hour %= 24; W_BUFF(); break;}
case 3: modify = 0; break;
} }
}
void timer0(void) interrupt 1
{
TH0 = 0x4c;
t0++; t0 %= 20;
if(t0 == 0) {new_s = 1; LED = ~LED;}
if(modify) LED = 0;
}
|