51单片机,选择其中两位数码管实现60s倒计时
#include <reg51.h>
#define GPIO_DIG P0
sbit LED = P1^2;
sbit LSA = P2^2;
sbit LSB = P2^3;
sbit LSC = P2^4;
unsigned char num = 0;
unsigned char num2 = 60; // 倒计时从60开始
unsigned char k;
unsigned char i;
unsigned char code DIG_CODE[10] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f}; // 0-9的显示码
unsigned char DisplayData[8] = {0}; // 用来存放要显示的8位数的值,但这里只用两位
void delayms(unsigned char xms) {
unsigned char a, b;
for (a = xms; a > 0; a–) {
for (b = 112; b > 0; b–); // 稍微调整延时以匹配您的硬件
}
}
void saomiao() {
DisplayData[0] = DIG_CODE[num2 / 10];
DisplayData[1] = DIG_CODE[num2 % 10];
for (k = 0; k < 2; k++) {
switch (k) {
case 0:
LSA = 1; LSB = 1; LSC = 1; // 选择第一位数码管(这里可能需要调整以匹配您的硬件)
GPIO_DIG = DisplayData[0];
break;
case 1:
LSA = 0; LSB = 1; LSC = 1; // 选择第二位数码管(这里可能需要调整以匹配您的硬件)
GPIO_DIG = DisplayData[1];
break;
}
delayms(1);
GPIO_DIG = 0x00; // 消隐
}
}
void timer0_isr(void) interrupt 1 { // 定时器0中断服务程序
TH0 = (65535 – 50000) / 256;
TL0 = (65536 – 50000) % 256;
num++;
if (num >= 20) { // 每20个中断周期更新一次num2和LED状态
num = 0;
num2–;
if (num2 == 0) {
num2 = 60;
}
LED = ~LED;
}
}
void main(void) {
TMOD = 0x01; // 设置定时器0为模式1(16位定时器)
TH0 = (65535 – 50000) / 256;
TL0 = (65535 – 50000) % 256;
EA = 1; // 使能全局中断
ET0 = 1; // 使能定时器0中断
TR0 = 1; // 启动定时器0
while (1) {
saomiao();
}
}
// DigDisplay 函数在这里不需要,因为我们已经在saomiao中实现了动态显示逻辑。
pr电路图见上一篇文章
作者:猫咪小虎