keaibukelian 发表于 2024-12-3 13:13

单片机倒计时

#include <reg51.h>

// 数码管段码表
unsigned char code segCode[] = {
0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F
};

// 倒计时秒数
int countdownSeconds = 60;
int tensDigit, unitsDigit;
// 标志位,用于记录倒计时状态,0为停止,1为运行,2为暂停
bit countdownStatus = 0;

// 延时函数
void delay(unsigned int i) {
while (i--);
}

// 定时器0初始化
void Timer0_Init() {
TMOD &= 0xF0;
TMOD |= 0x01;
TH0 = (65536 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
ET0 = 1;
EA = 1;
}

// 数码管显示函数
void Display(int tens, int units) {
P0 = segCode;
P2 = P2 & 0xF8;
P2 = P2 | 0x04;
delay(100);
P0 = segCode;
P2 = P2 & 0xF8;
P2 = P2 | 0x02;
delay(100);
}

// 检测按键状态函数
void CheckKeys() {
if (P1_0 == 0) { // 启动键按下
delay(1000); // 去抖延时
if (P1_0 == 0 && countdownStatus == 0) {
countdownStatus = 1;
TR0 = 1; // 启动定时器0
}
}
if (P1_1 == 0) { // 暂停键按下
delay(1000);
if (P1_1 == 0 && countdownStatus == 1) {
countdownStatus = 2;
TR0 = 0; // 停止定时器0
}
}
if (P1_2 == 0) { // 复位键按下
delay(1000);
if (P1_2 == 0) {
countdownSeconds = 60;
tensDigit = 6;
unitsDigit = 0;
countdownStatus = 0;
TR0 = 0;
}
}
}

// 定时器0中断服务函数
void Timer0_ISR() interrupt 1 {
static unsigned int count = 0;
TH0 = (65536 - 50000) / 256;
TL0 = (65536 - 50000) % 256;
count++;
if (count >= 20 && countdownStatus == 1) {
count = 0;
if (countdownSeconds > 0) {
countdownSeconds--;
tensDigit = countdownSeconds / 10;
unitsDigit = countdownSeconds % 10;
}
}
}

void main() {
Timer0_Init();
while (1) {
Display(tensDigit, unitsDigit);
CheckKeys();
}
}
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/2301_81350563/article/details/144097166

laocuo1142 发表于 2024-12-13 12:10

非常实用的功能

Bowclad 发表于 2024-12-13 14:26

这个精度是不是不高啊

flycamelaaa 发表于 2024-12-13 15:00

单片机倒计时和普通计时器有什么区别

powerantone 发表于 2024-12-13 16:20

用于各种需要精确时间控制的场合

小夏天的大西瓜 发表于 2024-12-15 22:38

精度应该还算是不错的

OKAKAKO 发表于 2024-12-22 21:24

非常不错的程序案例

jf101 发表于 2024-12-25 12:47

倒计时稳定性怎样?

怎么总是重复啊 发表于 2025-2-28 15:29

定时器的中断使得每次定时器溢出时,可以进行相应的操作,如更新倒计时。

自动化陈稳 发表于 2025-5-25 18:21

你在代码中定义了变量,但没在main()或者全局初始化时给tensDigit和unitsDigit赋初值,导致刚上电时显示不确定。

自动化陈稳 发表于 2025-5-25 18:21

建议在main()开始时初始化:

c
复制
编辑
tensDigit = countdownSeconds / 10;// 6
unitsDigit = countdownSeconds % 10; // 0
页: [1]
查看完整版本: 单片机倒计时