用51单片机编程实现8个7段数码管左移轮流显示数字0-9,A-F。
时间: 2024-02-12 18:03:34 浏览: 84
以下是使用51单片机编写的示例代码,实现8个7段数码管左移轮流显示数字0-9和A-F。
```C
#include<reg52.h>
// 数码管的位选引脚
sbit DIGIT1 = P2^0;
sbit DIGIT2 = P2^1;
sbit DIGIT3 = P2^2;
sbit DIGIT4 = P2^3;
sbit DIGIT5 = P2^4;
sbit DIGIT6 = P2^5;
sbit DIGIT7 = P2^6;
sbit DIGIT8 = P2^7;
// 数码管的段选引脚
sbit SEG_A = P1^7;
sbit SEG_B = P1^6;
sbit SEG_C = P1^5;
sbit SEG_D = P1^4;
sbit SEG_E = P1^3;
sbit SEG_F = P1^2;
sbit SEG_G = P1^1;
sbit SEG_DP = P1^0;
// 显示的数字个数
#define NUM_CHARS 16
// 数码管的数量
#define NUM_DIGITS 8
// 数字和字母对应的段选状态表
const unsigned char charTable[NUM_CHARS][NUM_DIGITS] = {
{0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07}, // 0
{0x06, 0x6C, 0x7E, 0x30, 0x30, 0x30, 0x30, 0x30}, // 1
{0x5B, 0x4F, 0x66, 0x6D, 0x79, 0x73, 0x3D, 0x06}, // 2
{0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x77, 0x06}, // 3
{0x30, 0x30, 0x7E, 0x76, 0x30, 0x30, 0x30, 0x30}, // 4
{0x7F, 0x49, 0x49, 0x49, 0x79, 0x6D, 0x6D, 0x06}, // 5
{0x3F, 0x49, 0x49, 0x49, 0x7B, 0x6F, 0x6D, 0x06}, // 6
{0x40, 0x40, 0x7D, 0x06, 0x06, 0x06, 0x06, 0x06}, // 7
{0x7F, 0x6D, 0x6D, 0x6D, 0x7F, 0x6D, 0x6D, 0x06}, // 8
{0x7F, 0x6D, 0x6D, 0x6D, 0x7F, 0x30, 0x30, 0x30}, // 9
{0x7F, 0x6D, 0x6D, 0x6D, 0x7B, 0x6D, 0x6D, 0x06}, // A
{0x7F, 0x49, 0x49, 0x49, 0x3E, 0x6D, 0x6D, 0x06}, // B
{0x3F, 0x41, 0x41, 0x41, 0x41, 0x63, 0x63, 0x06}, // C
{0x7F, 0x41, 0x41, 0x41, 0x3E, 0x63, 0x63, 0x06}, // D
{0x7F, 0x49, 0x49, 0x49, 0x49, 0x63, 0x63, 0x06}, // E
{0x7F, 0x48, 0x48, 0x48, 0x48, 0x60, 0x60, 0x06} // F
};
void delay(unsigned int xms) {
unsigned int i, j;
for(i = xms; i > 0; i--)
for(j = 110; j > 0; j--);
}
void main() {
unsigned char i, j, k;
while (1) {
for (i = 0; i < NUM_CHARS; i++) { // 依次显示每个数字或字母
for (j = 0; j < NUM_DIGITS; j++) { // 依次点亮每个数码管
switch (j) {
case 0:
DIGIT1 = 0;
break;
case 1:
DIGIT2 = 0;
break;
case 2:
DIGIT3 = 0;
break;
case 3:
DIGIT4 = 0;
break;
case 4:
DIGIT5 = 0;
break;
case 5:
DIGIT6 = 0;
break;
case 6:
DIGIT7 = 0;
break;
case 7:
DIGIT8 = 0;
break;
}
for (k = 0; k < 8; k++) {
switch (k) {
case 0:
SEG_A = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 1:
SEG_B = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 2:
SEG_C = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 3:
SEG_D = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 4:
SEG_E = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 5:
SEG_F = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 6:
SEG_G = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
case 7:
SEG_DP = (charTable[i][(j + k) % NUM_DIGITS] & 0x01);
break;
}
}
delay(5); // 等待5毫秒
switch (j) {
case 0:
DIGIT1 = 1;
break;
case 1:
DIGIT2 = 1;
break;
case 2:
DIGIT3 = 1;
break;
case 3:
DIGIT4 = 1;
break;
case 4:
DIGIT5 = 1;
break;
case 5:
DIGIT6 = 1;
break;
case 6:
DIGIT7 = 1;
break;
case 7:
DIGIT8 = 1;
break;
}
}
}
}
}
```
该代码使用了`delay()`函数实现延时。在`main()`函数中,依次显示每个数字或字母,依次点亮每个数码管,设置段选引脚的状态,点亮当前数码管,等待5毫秒后再进行下一个数码管的显示。最终实现了左移轮流显示数字0-9和A-F的功能。
阅读全文