【seg.c】
#define DEBUG 0
#include <reg52.h>
#include "ports.h"
unsigned char code seg8[16]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
unsigned int num1=0;
unsigned int num2=8050;
unsigned char ledid=0;
unsigned char interval=0;
unsigned char num3=0;
bit direction=0; //led旋转方向
bit speed_direction=0; //led旋转速度是否减速
unsigned char speed=1; //led旋转速度
void delay(unsigned int n)
{
unsigned char i;
while (n--)
for (i=0;i<115;i++);
}
void seg8_scan(void)
{
unsigned char i;
unsigned int f=1000;
unsigned char pt=0x00;
for (i=0;i<=2;i++)
{
P0=0xff;
SEG8=NBIT(i);
P0=seg8[num1%f/(f/10)];
delay(1);
f/=10;
}
f=10000;
for (i=3;i<=6;i++)
{
if (i==4)
pt=0x80;
else
pt=0x00;
P0=0xff;
SEG8=NBIT(i);
if (i==3 && num2<1000)
P0=0xff;
else
P0=seg8[num2%f/(f/10)]+pt;
delay(1);
f/=10;
}
SEG8=0xff;
}
void key_scan(void)
{
if (!K1)
{
seg8_scan();
seg8_scan();
seg8_scan();
if (!K1)
{
num1++;
if (num1>999)
{
num1=0;
num2+=150;
if (num2>9999)
num2%=100;
}
}
while (!K1)
seg8_scan();
seg8_scan();
seg8_scan();
seg8_scan();
}
if (!K2)
{
seg8_scan();
seg8_scan();
seg8_scan();
if (!K2)
{
num1--;
if (num1>=65530)
num1=999;
else if (num1==0)
{
num2+=100;
if (num2>9999)
num2%=100;
}
}
while (!K2)
seg8_scan();
seg8_scan();
seg8_scan();
seg8_scan();
}
}
void ledflow(void)
{
unsigned char b;
LED|=0x0f;
LED&=NBIT(0);
if (ledid>=4 && ledid<=15)
{
//全亮3s
LED&=0xf0;
ledid++;
if (ledid==16)
{
direction=!direction;
if (direction)
ledid=17;
else
ledid=2;
//更新旋转速度
if (speed_direction)
speed--;
else
speed++;
if (speed>5)
speed_direction=1;
else if (speed==0)
speed_direction=0;
}
}
else
{
if (ledid>=0 && ledid<=2)
{
//正转
ledid++;
if (ledid==3)
ledid=0;
b=ledid+1;
}
else if (ledid>=17 && ledid<=19)
{
//反转
ledid--;
if (ledid==16)
ledid=19;
b=ledid-16;
}
LED&=NBIT(b);
}
}
void main(void)
{
P0=SEG8=0xff;
LED=0xfc;
EA=1;
ET0=1;
TMOD=0x01;
TH0=0x3c;
TL0=0xb0; //50ms
TR0=1;
while (1)
{
seg8_scan();
key_scan();
}
}
void timer0(void) interrupt 1
{
interval++;
if (interval>=speed)
{
interval=0;
ledflow();
num3++;
}
//LED全亮,右边数码管加0.01
#if DEBUG==1
if (num3>=24)
#else
if (num3>=240)
#endif
{
num2++;
if (num2>9999)
num2=0;
num3=0;
ledid=4;
}
TH0=0x3c;
TL0=0xb0; //50ms
}