AT89C52、CAP(电容30pF)、CAP-ELEC(点解电容10uF,空心为正极,斜线填充为负bai极)、CRYSTAL(晶振12Mhz)、RX8(排阻)、RES(电阻)、LED-YELLOW(黄色LED)、BUTTON(按键)、7SEG-COM-AN-GRN(共阳数码管)。
#include<reg51.h> //包含头文件 #define uchar unsigned char #define uint unsigned int //宏定义 uchar ModeNo; //灯闪烁的模式 uint Speed; //闪烁的速度 uchar tCount=0; //进入定时器控制速度 uchar Idx; //调速变量 uchar mb_Count=0; bit Dirtect=1; uchar code DSY_CODE[]={0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90}; uint code sTable[]={0,1,3,5,7,9,15,30,50,100,200,230,280,300,350}; void Delay(uint x) //延时函数 { uchar i; while (x--) for(i=0;i<120;i++); } uchar GetKey() //按键函数 { uchar K; if(P2==0xFF) //没有按键按下 return 0; //返回0 Delay(10); //延时 switch(P2) //有按键按下 { case 0xFE: K=1; break; //k1按下 case 0xFD: K=2; break; case 0xFB: K=3; break; default: K=0; //其他状态,k=0 } while(P2!=0xFF); //按键释放 return K; //返回按键信息 } void Led_Demo(uint Led16) //LED状态右移 { P1=(uchar)(Led16 & 0x00FF); P0=(uchar)(Led16 >>8); } void T0_TNT() interrupt 1 //定时器工作 { if (++tCount < Speed) return; //对应不同的速度 tCount=0; switch (ModeNo) { case 0: Led_Demo(0x0001 << mb_Count);break; //模式0,最右侧的灯亮,然后向左移 case 1: Led_Demo(0x8000 >> mb_Count);break; //模式1,最左侧的灯亮,然后向右移 case 2: if(Dirtect) Led_Demo(0x000F << mb_Count); //模式2,四个灭灯左右移 else Led_Demo(0xF000 >> mb_Count); if(mb_Count==15) Dirtect =!Dirtect; break; case 3: if(Dirtect) Led_Demo(~(0x000F << mb_Count)); //模式3,四个亮灯左右移 else Led_Demo(~(0xF000 >> mb_Count)); if(mb_Count==15) Dirtect =!Dirtect; break; case 4: if(Dirtect) Led_Demo(0x003F << mb_Count); //模式4,6个灭灯左右移 else Led_Demo(0xFC00 >> mb_Count); if(mb_Count==15) Dirtect =!Dirtect; break; case 5: if(Dirtect) Led_Demo(0x0001 << mb_Count); //模式5,一个灭灯左右移 else Led_Demo(0x8000 >> mb_Count); if(mb_Count==15) Dirtect =!Dirtect; break; case 6: if(Dirtect) Led_Demo(~(0x0001 << mb_Count));//模式6,一个亮灯左右移 else Led_Demo(~(0x8000 >> mb_Count)); if(mb_Count==15) Dirtect =!Dirtect; break; case 7: if(Dirtect) Led_Demo(0xFFFE << mb_Count); //模式7,向右亮向左亮 else Led_Demo(0x7FFF >> mb_Count); if(mb_Count==15) Dirtect =!Dirtect; break; } mb_Count=(mb_Count+1)%16; } void KeyProcess(uchar Key) //切换速度 { switch(Key) //按键按下 { case 1: Dirtect=1; //切换模式 mb_Count=0; ModeNo=(ModeNo+1)%8; P3=DSY_CODE[ModeNo]; break; case 2: if(Idx>1) //速度减 Speed=sTable[--Idx]; break; case 3: if(Idx<15) Speed=sTable[++Idx]; //速度加 } } void main() //主函数 { uchar Key; P0=P1=P2=P3=0xFF; //IO口都复位 ModeNo=0; //变量清零 Idx=4; //速度默认开机4 Speed=sTable[Idx]; //4档速度对应的延时数 P3=DSY_CODE[ModeNo]; //P3口赋值初始状态 IE=0x82; //定义寄存器 TMOD=0x00; //定时器工作状态 TR0=1; //开启定时器0 while(1) //进入while循环 { Key=GetKey(); //读取按键状态 if(Key!=0) //如果有按键按下 KeyProcess(Key); //根据按键状态切换速度 } }
原文:https://www.cnblogs.com/lirongyun/p/14291949.html