基于AT89s52单片机的计数器并用数码管显示
时间: 2023-11-26 14:04:30 浏览: 93
以下是基于AT89s52单片机的计数器并用数码管显示的程序:
```c
#include <REG52.h>
#define uchar unsigned char
#define uint unsigned int
sbit D1 = P2^0;
sbit D2 = P2^1;
sbit D3 = P2^2;
sbit D4 = P2^3;
sbit EN = P2^4;
sbit RS = P2^5;
uint count = 0;
void delay(uint xms) {
uint i, j;
for (i = xms; i > 0; i--)
for (j = 110; j > 0; j--);
}
void write_command(uchar command) {
RS = 0;
P0 = command;
EN = 1;
delay(1);
EN = 0;
}
void write_data(uchar data) {
RS = 1;
P0 = data;
EN = 1;
delay(1);
EN = 0;
}
void init_lcd() {
write_command(0x38);
write_command(0x0c);
write_command(0x06);
write_command(0x01);
}
void display_count() {
uint i, j, k, l;
uchar a, b, c, d;
a = count % 10;
b = count / 10 % 10;
c = count / 100 % 10;
d = count / 1000 % 10;
for (i = 0; i < 50; i++) {
for (j = 0; j < 4; j++) {
switch (j) {
case 0: P1 = 0x00; break;
case 1: P1 = 0x10; break;
case 2: P1 = 0x20; break;
case 3: P1 = 0x30; break;
}
switch (j) {
case 0: k = a; break;
case 1: k = b; break;
case 2: k = c; break;
case 3: k = d; break;
}
switch (k) {
case 0: P0 = 0x3f; break;
case 1: P0 = 0x06; break;
case 2: P0 = 0x5b; break;
case 3: P0 = 0x4f; break;
case 4: P0 = 0x66; break;
case 5: P0 = 0x6d; break;
case 6: P0 = 0x7d; break;
case 7: P0 = 0x07; break;
case 8: P0 = 0x7f; break;
case 9: P0 = 0x6f; break;
}
switch (j) {
case 0: D1 = 1; break;
case 1: D2 = 1; break;
case 2: D3 = 1; break;
case 3: D4 = 1; break;
}
delay(1);
switch (j) {
case 0: D1 = 0; break;
case 1: D2 = 0; break;
case 2: D3 = 0; break;
case 3: D4 = 0; break;
}
}
}
}
void main() {
init_lcd();
while (1) {
display_count();
count++;
}
}
```
在程序中定义了四个数码管显示位的引脚,分别是P2.0-P2.3。定义了使能引脚EN和RS引脚,分别用于写入指令和数据。在程序中定义了计数器count,并在display_count()函数中将count拆分为四个数码管位需要显示的数字,然后通过循环一位一位地显示。在循环中,首先通过P1口控制数码管位选,然后根据需要显示的数字选择数码管段选,最后通过D1-D4控制数码管的点亮。程序中使用了延时函数delay()来控制数码管的刷新频率。在主函数中,通过不断调用display_count()函数实现计数器的自增并用数码管显示。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)