|
发表于 2025-6-13 08:47:18
|
显示全部楼层
最近我也迷上数码管,试试用代码描述电路,用C语言指挥电路工作,这是其中一个9999倒计时的完整程序,还不能独立编辑,借助人工智能进度快了不少,有再高的人指点最终还得自己动手
include <reg52.h>
//数码闪烁解决,调整显示函数的延时时间150,有再高的人指点最终还得自己动手
// 共阳数码管段码表 (0-9)
unsigned char code SegCode[] = {
0xC0, //"0"
0xFC, //"1"
0x92, //"2"
0x98, //"3"
0xAC, //"4"
0x89, //"5"
0x81, //"6"
0xDC, //"7"
0x80, //"8"
0x88, //"9"
};
//数码管位选定义
sbit DIG4 = P2^0; // 个位
sbit DIG3 = P2^1; // 十位
sbit DIG2 = P2^2; // 百位
sbit DIG1 = P2^3; // 千位
//全局变量
unsigned int count = 9999; //倒计时计数器(9999秒)
unsigned int tmrCount = 0; // 定时器中断计数器
unsigned char digit = 0; // 当前显示位
unsigned char digits[4]; // 存储各位数字
// 函数声明
void Timer0_Init(void);
void Display(void);
void DelayUs(unsigned int us);
void UpdateDigits(void);
void main() {
// 初始化定时器
Timer0_Init();
// 初始化位选
P2 &= 0xF0; // 关闭所有数码管,
while(1) {
UpdateDigits(); // 更新各位数字
Display(); // 显示数码管
}
}
//定时器0初始化
void Timer0_Init() {
TMOD = 0x01; // 定时器0,模式1有再高的人指点最终还得自己动手
TH0 = (65536 - 46080) / 256;// 50ms定时初值 (11.0592MHz)
TL0 = (65536 - 46080) % 256;
ET0 = 1; // 允许定时器0中断
EA = 1; // 开启总中断
TR0 = 1; // 启动定时器0
}
//定时器0中断服务函数
void Timer0_ISR() interrupt 1 {
TH0 = (65536 - 46080) / 256; // 重装初值
TL0 = (65536 - 46080) % 256;
tmrCount++;
if(tmrCount >= 2) { // 1秒到达 (20× 50ms = 1000ms)
tmrCount = 0;
if(count > 0) {
count--; // 秒计数器减1
} else {
count = 9999; // 重置为9999秒
}
}
}
//更新各位数字
void UpdateDigits() {
digits[0] = count / 1000; // 千位
digits[1] = (count % 1000) / 100; // 百位
digits[2] = (count % 100) / 10; // 十位
digits[3] = count % 10; // 个位
}
//数码管显示函数,有再高的人指点最终还得自己动手
void Display() {
// 关闭所有位选
DIG1 = DIG2 = DIG3 = DIG4 = 1
;
// 根据当前位显示对应数字
switch(digit) {
case 0: // 显示千位,有再高的人指点最终还得自己动手
P0 = SegCode[digits[0]];
DIG4 = 0;
break;
case 1: // 显示百位
P0 = SegCode[digits[1]];
DIG3 = 0;
break;
case 2: // 显示十位
P0 = SegCode[digits[2]];
DIG2 = 0;
break;
case 3: // 显示个位
P0 = SegCode[digits[3]];
DIG1 = 0;
break;
}
// 延时保持显示
DelayUs(150);
// 移动到下一位
digit = (digit + 1) % 4;
}
// 简单微秒延时函数
void DelayUs(unsigned int us) {
while(us--) {
unsigned char i = 2;
while(i--);
}
}
|
打赏
-
查看全部打赏
|