基于C51单片机实现在LCD 1602上显示时间,可以通过串口修改LCD1602显示的时间并且可以设置闹钟的代码
时间: 2024-02-16 21:59:53 浏览: 86
基于51单片机的电子钟设计。这个可以对于普通的51单片机,可以实现时间的计时,还可以设置闹钟,还有秒表功能,整点报时.zip
很高兴为您解答问题。基于C51单片机实现在LCD 1602上显示时间,可以通过串口修改LCD1602显示的时间并且可以设置闹钟的代码如下:
```c
#include <reg51.h>
#include <stdio.h>
#include <string.h>
#define LCD_RS P1_0
#define LCD_RW P1_1
#define LCD_EN P1_2
#define LCD_DATA P2
void delay(unsigned int i)
{
while (i--);
}
void LCD_WriteCommand(unsigned char cmd)
{
LCD_RS = 0;
LCD_RW = 0;
LCD_DATA = cmd;
LCD_EN = 1;
delay(100);
LCD_EN = 0;
}
void LCD_WriteData(unsigned char dat)
{
LCD_RS = 1;
LCD_RW = 0;
LCD_DATA = dat;
LCD_EN = 1;
delay(100);
LCD_EN = 0;
}
void LCD_Clear()
{
LCD_WriteCommand(0x01);
delay(500);
}
void LCD_Init()
{
LCD_WriteCommand(0x38);
delay(500);
LCD_WriteCommand(0x0C);
delay(500);
LCD_WriteCommand(0x06);
delay(500);
LCD_WriteCommand(0x01);
delay(500);
}
void LCD_SetCursor(unsigned char x, unsigned char y)
{
unsigned char addr;
if (y == 0)
{
addr = 0x80 + x;
}
else
{
addr = 0xC0 + x;
}
LCD_WriteCommand(addr);
}
void UART_Init()
{
TMOD = 0x20;
SCON = 0x50;
TH1 = 0xFD;
TR1 = 1;
}
unsigned char UART_Receive()
{
while (!RI);
RI = 0;
return SBUF;
}
void UART_Send(unsigned char dat)
{
SBUF = dat;
while (!TI);
TI = 0;
}
void main()
{
unsigned char hour = 0, minute = 0, second = 0;
unsigned char buf[16] = {0};
unsigned char ch;
unsigned char alarm_hour = 0, alarm_minute = 0;
LCD_Init();
UART_Init();
while (1)
{
LCD_SetCursor(0, 0);
sprintf(buf, "%02d:%02d:%02d", hour, minute, second);
LCD_WriteData(buf[0]);
LCD_WriteData(buf[1]);
LCD_WriteData(':');
LCD_WriteData(buf[3]);
LCD_WriteData(buf[4]);
LCD_WriteData(':');
LCD_WriteData(buf[6]);
LCD_WriteData(buf[7]);
ch = UART_Receive();
if (ch == 'h')
{
UART_Send(hour);
}
else if (ch == 'm')
{
UART_Send(minute);
}
else if (ch == 's')
{
UART_Send(second);
}
else if (ch == 'a')
{
UART_Send(alarm_hour);
UART_Send(alarm_minute);
}
else if (ch == 'H')
{
hour = UART_Receive();
}
else if (ch == 'M')
{
minute = UART_Receive();
}
else if (ch == 'S')
{
second = UART_Receive();
}
else if (ch == 'A')
{
alarm_hour = UART_Receive();
alarm_minute = UART_Receive();
}
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 && second == 0)
{
LCD_SetCursor(0, 1);
LCD_WriteData('A');
LCD_WriteData('L');
LCD_WriteData('A');
LCD_WriteData('R');
LCD_WriteData('M');
}
delay(1000);
}
}
```
这段代码实现了基于C51单片机控制LCD 1602显示时间,并且可以通过串口修改时间和设置闹钟。在代码中,使用了定时器和串口通信,定时器用于控制时间的显示和闹钟的触发,串口用于接收修改时间和设置闹钟的指令,并返回当前时间和闹钟设置的值。具体实现过程可以参考注释。
阅读全文