51单片机写74hc595 32×16点阵共阴led 分别定义p00,p01为ds,p02,p10,p11为ds,p12接口
时间: 2023-06-25 08:02:35 浏览: 50
以下是51单片机控制74hc595驱动32×16点阵共阴LED的代码,其中P00作为DS接口,P01作为ST_CP接口,P02、P10、P11、P12作为SH_CP接口:
```c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DS = P0^0;
sbit ST_CP = P0^1;
sbit SH_CP1 = P0^2;
sbit SH_CP2 = P1^0;
sbit SH_CP3 = P1^1;
sbit SH_CP4 = P1^2;
uchar code num[10][16] = { // 数码管 0~9 的位图
{ // 0
0x3E,0x7F,0x41,0x41,0x41,0x7F,0x3E,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 1
0x00,0x42,0x7F,0x7F,0x40,0x00,0x00,0x00,
0x00,0x00,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 2
0x46,0x67,0x71,0x59,0x4D,0x67,0x63,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 3
0x30,0x79,0x49,0x49,0x49,0x7F,0x36,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 4
0x0F,0x0E,0x08,0x08,0x08,0x7F,0x7F,0x00,
0x00,0x00,0x00,0x00,0x00,0x02,0x02,0x00
},
{ // 5
0x33,0x7B,0x49,0x49,0x49,0x7B,0x32,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 6
0x3E,0x7F,0x49,0x49,0x49,0x7B,0x32,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 7
0x01,0x01,0x01,0x71,0x7D,0x0F,0x07,0x00,
0x00,0x00,0x00,0x02,0x02,0x02,0x02,0x00
},
{ // 8
0x36,0x7F,0x49,0x49,0x49,0x7F,0x36,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
},
{ // 9
0x06,0x4F,0x49,0x49,0x49,0x7F,0x3E,0x00,
0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x00
}
};
void delay(uint t) {
uint i, j;
for(i = 0; i < t; i++) {
for(j = 0; j < 120; j++);
}
}
void sendByte(uchar byte) { // 发送一个字节到74hc595
uchar i;
for(i = 0; i < 8; i++) {
if(byte & 0x80) {
DS = 1;
} else {
DS = 0;
}
byte <<= 1;
SH_CP1 = 0;
SH_CP2 = 0;
SH_CP3 = 0;
SH_CP4 = 0;
SH_CP1 = 1;
SH_CP2 = 1;
SH_CP3 = 1;
SH_CP4 = 1;
}
}
void displayNum(uchar n) { // 显示数码管数字
uchar i;
for(i = 0; i < 16; i++) {
sendByte(num[n][i]);
}
}
void main() {
uchar i, j, k;
while(1) {
for(i = 0; i < 4; i++) { // 每次显示4个数码管
ST_CP = 0;
for(j = 0; j < 4; j++) { // 依次输出4个字节
if(j == i) { // 当前位为高电平
sendByte(0xFF);
} else { // 其他位为低电平
sendByte(0x00);
}
}
ST_CP = 1;
for(k = 0; k < 10; k++) { // 显示数字0~9
displayNum(k);
delay(1000);
}
}
}
}
```
注意,在这个例子中,我们使用了四个 SH_CP 接口,分别连接到 P0.2、P1.0、P1.1、P1.2 上,因为 74hc595 的移位寄存器有 8 位,而这个点阵有 32×16=512 个 LED 灯,所以需要 512/8=64 个 74hc595 芯片,每个芯片控制 8 个 LED 灯。为了控制这么多的芯片,我们需要使用多个 SH_CP 接口,使得每个 SH_CP 可以控制一部分芯片的移位寄存器。