- #include <reg51.h>
- #define uchar unsigned char
- #define uint unsigned int
- code tabup[]={0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09};
- code tabdowm[]={0x09,0x08,0x0c,0x04,0x06,0x02,0x03,0x01};
- void delay(uint z);
- int i;
- sbit S2=P3^0;
- sbit S3=P3^1;
- sbit S4=P3^2;
- keyval=0;
- void moveup() //正转
- {
- for(i=0;i<8;i++)
- {
- P1=tabup[i];
- delay(1);
- }
- }
- void movedowm() //反转
- {
- for(i=0;i<8;i++)
- {
- P1=tabdowm[i];
- delay(1);
- }
- }
- void delay (uint z)
- {
- uint x,y;
- for(x=z;x>0;x--)
- for(y=110;y>0;y--);
- }
- void stop()
- {
- P1=0xff;
- }
- void main(void)
- {
- TMOD=0x01; //使用定时器T0的模式1
- TR0=0; //给定时器T0赋初值并关闭T0
- TH0=(65536-500)/256; //定时器TH0赋初值为500
- TL0=(65536-500)%256; //定时器TL0赋初值为500
- EA=1; //开总中断
- ET0=1; //定时器T0中断允许
- TR0=1; //启动定时器T0,这里必须要启动,因为大循环里
- while(1) //要给keyval赋值,而赋值语句在中断服务函数里
- {
- switch(keyval) //根据按键值keyval选择待执行的功能
- {
- case 1:moveup(); break; //按键S1按下,正转
- case 2:movedowm(); break; //按键S2按下,反转
- case 3:stop(); break; //按键S3按下,停转
- }
- }
- }
- /*************************************************
- 函数功能:定时器T0的中断服务子程序
- **************************************************/
- void Time0_serve(void) interrupt 1
- {
- TH0=(65536-200)/256; //定时器T0的高8位赋初值
- TL0=(65536-200)%256; //定时器T0的低8位赋初值
- if((P3&0xff)!=0xff) //检测是否有按键按下
- {
- delay(50); //延时一段时间再去检测
- if((P3&0xff)!=0xff) //再次检测是否确实有按键按下
- {
- if(S2==0) //按键S1被按下
- keyval=1; //给keyval赋值
- if(S3==0) //按键S2被按下
- keyval=2; //给keyval赋值
- if(S4==0) //按键S3被按下
- keyval=3; //给keyval赋值
- }
- }
- }
复制代码 |