(1)利用40MHz系统时钟,进行时钟分频,产生1Hz时钟信号clk1;(2)8个LED灯每隔1S依次点亮,数码管从1开始计数,直到8结束,依次循环;(3)8个LED灯每隔0.5S隔位点亮(比如1,3,5,7,2,4,6,8),数码管显示具体数字,依次循环;
时间: 2023-08-16 20:08:34 浏览: 98
以下是基于STC89C52单片机的代码实现:
```c
#include <reg52.h>
typedef unsigned char uchar;
typedef unsigned int uint;
// 数码管位选段选控制
sbit LSA = P2^2;
sbit LSB = P2^3;
sbit LSC = P2^4;
sbit DU = P2^6;
sbit WE = P2^7;
// LED灯控制
sbit LED1 = P1^0;
sbit LED2 = P1^1;
sbit LED3 = P1^2;
sbit LED4 = P1^3;
sbit LED5 = P1^4;
sbit LED6 = P1^5;
sbit LED7 = P1^6;
sbit LED8 = P1^7;
uchar code table[] = { // 数码管显示表
0x3f, // 0
0x06, // 1
0x5b, // 2
0x4f, // 3
0x66, // 4
0x6d, // 5
0x7d, // 6
0x07, // 7
0x7f, // 8
0x6f // 9
};
void delayms(uint ms) { // 延时函数,单位毫秒
uint i, j;
for (i = 0; i < ms; ++i) {
for (j = 0; j < 110; ++j); // 大约延时1ms
}
}
void display(uchar num) { // 数码管显示函数
uchar temp;
LSA = 0;
LSB = 0;
LSC = 0;
temp = table[num];
DU = 1;
P0 = temp;
DU = 0;
delayms(5);
}
void main() {
uint i, j;
uchar num;
TMOD = 0x01; // 定时器0,工作方式1(16位自动重装载)
TH0 = 0x3c; // 定时器初值,计数1ms
TL0 = 0xb0;
TR0 = 1; // 启动定时器
ET0 = 1; // 开启定时器0中断
EA = 1; // 全局中断开启
while (1) {
// 第一种模式:8个LED灯每隔1S依次点亮,数码管从1开始计数,直到8结束,依次循环
for (i = 0; i < 8; ++i) {
switch (i) {
case 0: LED1 = 1; break;
case 1: LED2 = 1; break;
case 2: LED3 = 1; break;
case 3: LED4 = 1; break;
case 4: LED5 = 1; break;
case 5: LED6 = 1; break;
case 6: LED7 = 1; break;
case 7: LED8 = 1; break;
}
for (j = 0; j < 1000; ++j) {
num = i + 1;
display(num);
}
switch (i) {
case 0: LED1 = 0; break;
case 1: LED2 = 0; break;
case 2: LED3 = 0; break;
case 3: LED4 = 0; break;
case 4: LED5 = 0; break;
case 5: LED6 = 0; break;
case 6: LED7 = 0; break;
case 7: LED8 = 0; break;
}
}
// 第二种模式:8个LED灯每隔0.5S隔位点亮(比如1,3,5,7,2,4,6,8),数码管显示具体数字,依次循环
for (i = 0; i < 8; ++i) {
if (i % 2 == 0) {
switch (i) {
case 0: LED1 = 1; break;
case 2: LED3 = 1; break;
case 4: LED5 = 1; break;
case 6: LED7 = 1; break;
}
num = i + 1;
display(num);
delayms(500);
switch (i) {
case 0: LED1 = 0; break;
case 2: LED3 = 0; break;
case 4: LED5 = 0; break;
case 6: LED7 = 0; break;
}
} else {
switch (i) {
case 1: LED2 = 1; break;
case 3: LED4 = 1; break;
case 5: LED6 = 1; break;
case 7: LED8 = 1; break;
}
num = i + 1;
display(num);
delayms(500);
switch (i) {
case 1: LED2 = 0; break;
case 3: LED4 = 0; break;
case 5: LED6 = 0; break;
case 7: LED8 = 0; break;
}
}
}
}
}
void timer0() interrupt 1 { // 定时器0中断服务函数
TH0 = 0x3c;
TL0 = 0xb0;
}
```
其中,定时器0的计数频率为1ms,定时器中断服务函数每隔1ms被调用一次。第一种模式中,每个LED灯点亮1s,期间数码管显示当前值;第二种模式中,每个LED灯隔0.5s点亮,期间数码管显示当前值。
阅读全文