51单片机lcd显示时间闹钟蜂鸣器
时间: 2023-07-30 22:10:37 浏览: 170
以下是51单片机lcd显示时间闹钟蜂鸣器的代码示例:
```c
#include <reg51.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit beep = P1^5;
sbit dula = P2^6;
sbit wela = P2^7;
uchar code table[] = {
0x3f, // 0
0x06, // 1
0x5b, // 2
0x4f, // 3
0x66, // 4
0x6d, // 5
0x7d, // 6
0x07, // 7
0x7f, // 8
0x6f // 9
};
uchar hour = 10; // 初始时间为10:00
uchar minute = 0;
uchar second = 0;
uchar alarm_hour = 12; // 初始闹钟时间为12:00
uchar alarm_minute = 0;
bit alarm_flag = 0; // 闹钟标志位
void delayms(uint x) { // 毫秒级延时函数
uint i, j;
for (i = x; i > 0; i--) {
for (j = 110; j > 0; j--);
}
}
void display(uchar hour, uchar minute) { // 在LCD上显示时间
uchar shiwei = hour / 10;
uchar gewei = hour % 10;
P0 = 0xff;
wela = 1;
wela = 0;
P0 = ~(0x01 << 1);
dula = 1;
dula = 0;
P0 = table[shiwei];
wela = 1;
wela = 0;
P0 = ~(0x01 << 0);
dula = 1;
dula = 0;
P0 = table[gewei];
wela = 1;
wela = 0;
P0 = ~(0x01 << 3);
dula = 1;
dula = 0;
shiwei = minute / 10;
gewei = minute % 10;
P0 = 0xff;
wela = 1;
wela = 0;
P0 = ~(0x01 << 5);
dula = 1;
dula = 0;
P0 = table[shiwei];
wela = 1;
wela = 0;
P0 = ~(0x01 << 4);
dula = 1;
dula = 0;
P0 = table[gewei];
wela = 1;
wela = 0;
P0 = ~(0x01 << 7);
dula = 1;
dula = 0;
}
void main() {
TMOD = 0x01; // 设置定时器0为16位定时器
TH0 = 0x3c; // 给定时器0赋初值,定时1ms
TL0 = 0xb0;
TR0 = 1; // 启动定时器0
ET0 = 1; // 打开定时器0中断
EA = 1; // 打开总中断开关
while (1) {
display(hour, minute);
if (alarm_flag) { // 闹钟响起
for (int i = 0; i < 1000; i++) {
beep = ~beep;
delayms(1);
}
alarm_flag = 0;
}
}
}
void timer0() interrupt 1 { // 定时器0中断服务程序
TH0 = 0x3c;
TL0 = 0xb0;
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;
}
}
```
该代码中使用了定时器0进行时间计数,并通过LCD显示时间。同时设定了闹钟时间,当时间到达设定的闹钟时间时,蜂鸣器会响起。
阅读全文