显示0-99
用8位共阴数码可以通过动态扫描显示0~99,考虑十位和个位,需要用到数组来存放。其中的重要代码是display()函数,firstbit表示从第n个数开始显示,num表示显示的个数,所以若是改变数组tempdata的数组元素,则可以显示更多位的数字,并且8位数码管可以任意选择数码管。主函数中的j++,j==500,是为了在测试硬件时增加循环的次数而达到显示时更加清晰。
#include<reg51.h>
#define DataPort P0
sbit Seg_latch=P2^2;
sbit Bit_latch=P2^3;
unsigned char code Seg_code[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
unsigned char code Bit_code[]={0xfe,0xfd,0xfb,0xf7,0xef,0xdf,0xbf,0x7f};
unsigned char tempdata[2]; //两位数
void display(unsigned char firstbit,unsigned char num);
void delay(unsigned int i)
{
while(i--);
}
void main(void)
{
unsigned int j,num;
num=0;
while(1)
{
j++;
if(j==500)
{
j=0;
num++;
if(num==100)
{
num=0;
}
}
tempdata[0]=num/10; //十位
tempdata[1]=num%10; //个位
display(0,2);
}
}
void display(unsigned char firstbit,unsigned char num) //firstbit从第n个数开始显示,num显示的个数
{
unsigned char i,j;
while(1)
{
for(i=0; i<num; i++)
{
DataPort=0x00;
Seg_latch=1;
Seg_latch=0;
DataPort=Bit_code[i+firstbit]; //位码
Bit_latch=1;
Bit_latch=0;
j=tempdata[i]; //段码
DataPort=Seg_code[j];
Seg_latch=1;
Seg_latch=0;
delay(200);
}
}
}