[藍橋杯單片機 共陽數碼管]
一、數碼管原理圖
開發板上的八位數碼管爲共陽連接,com1–com8分別控制公共端(公共陽極);a–dp分別控制數碼管每一位的八個段。它們兩又分別被鎖存器U6和U7控制着。
當com端爲高電平,對應的a–dp爲低電平時相應段碼就會亮。如:com1爲高電平,com2–com8爲低電平,此時讓dp爲低電平,a–g爲高電平,則第一個數碼管只有dp亮,也就是亮一個點。
由於段碼有八個,如果一個一個賦值很麻煩,因此一般用十六進制數一次性給段碼進行賦值。十六進制數控制的段碼顯示如下:
二、數碼管顯示代碼
下面舉幾個例子:
1、讓數碼管八個位都顯示6(數碼管靜態顯示)
#include"reg52.h"
sbit HC138_A = P2^5;//定義譯碼器中ABC所在引腳
sbit HC138_B = P2^6;
sbit HC138_C = P2^7;
void Show_SMG()
{
HC138_C = 1; //給CBA賦值,打通U6
HC138_B = 1;
HC138_A = 0;
P0 = 0xff; //com1-8設爲高電平
HC138_C = 1; //給CBA賦值,打通U7
HC138_B = 1;
HC138_A = 1;
P0 = 0x82; //給八個段賦值顯示6
}
void main()
{
while(1)
{
Show_SMG();
}
}
2、讓數碼管八個位從0顯示到9(數碼管靜態顯示)
爲了方便,我們將所有要用的段碼放在一個數組中;將選擇鎖存器的代碼也進行優化,要理解這些的原理都要將十六進制轉化爲二進制來理解。
#include"reg52.h"
unsigned char SMG_Duanma[12] =
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,
0x82,0xf8,0x80,0x90,0xbf,0x7f};//數碼管段碼
void Delay(unsigned int t)
{
while(t--);
}
void SelectHC573(unsigned channel) //選擇鎖存器
{
switch(channel)
{
case 6: //選擇U6鎖存器
P2 = P2 & 0x1f | 0xc0;
break;
case 7: //選擇U7鎖存器
P2 = P2 & 0x1f | 0xe0;
break;
}
}
unsigned char i;
void ShowSMG()
{
SelectHC573(6);
P0 = 0xff; //com1-8設爲高電平
SelectHC573(7);
for(i = 0; i<=9; i++)
{
P0 = SMG_Duanma[i];
Delay(50000);
Delay(50000);
}
}
void main()
{
while(1)
{
ShowSMG();
}
}
3、讓數碼管從0顯示到99(數碼管動態顯示)
動態顯示原理:讓不同位的數碼管只亮一小段極小時間,從而造成視覺暫留效果,人眼無法識別這極小段的熄滅時間,從而覺得這些不同位數碼管是同時亮的。
上代碼:
#include"reg52.h"
unsigned char SMG_Duanma[12]=
{0xc0,0xf9,0xa4,0xb0,0x99,0x92,
0x82,0xf8,0x80,0x90,0xbf,0x7f};//數碼管段碼
void Delay(unsigned int t)
{
while(t--);
}
void SelectHC573(unsigned char channel)
{
switch(channel)
{
case 6: //選擇U6鎖存器
P2 = P2 & 0x1f | 0xc0;
break;
case 7: //選擇U7鎖存器
P2 = P2 & 0x1f | 0xe0;
break;
}
}
void ShowSMG_Bit(unsigned char pos, unsigned char value) //pos位顯示value
{
SelectHC573(6);
P0 = 0x01 << (pos - 1);
SelectHC573(7);
P0 = value;
Delay(200); //消影
P0 = 0xff; //消影
}
unsigned char i, j;
void DelaySMG(unsigned int t)
{
while(t--)
{
ShowSMG_Bit(1, SMG_Duanma[i]); //第一位顯示SMG_Duanma[i]
Delay(200);
ShowSMG_Bit(2, SMG_Duanma[j]); //第二位顯示SMG_Duanma[j]
Delay(200);
}
}
void ShowSMG()
{
for(i = 0; i<=9; i++)
for(j = 0; j <= 9; j++)
{
ShowSMG_Bit(1, SMG_Duanma[i]); //第一位顯示SMG_Duanma[i]
DelaySMG(200);
ShowSMG_Bit(2, SMG_Duanma[j]); //第二位顯示SMG_Duanma[j]
DelaySMG(200);
}
}
void main()
{
while(1)
{
ShowSMG();
}
}
```