|
这是我调的小车前进后退左转右转的简单代码。
- #include"reg52.h"
- #define key_vaule1 1
- #define key_vaule2 2
- #define key_vaule3 3
- #define key_vaule4 4
- sbit key1=P3^2;
- sbit key2=P3^4;
- sbit key3=P3^6;
- sbit key4=P3^7;
- sbit IA1=P0^0;
- sbit IB1=P0^1;
- sbit IA2=P0^2;
- sbit IB2=P0^3;
- int ms_10=0;
- int keypress = 0;
- //按键抬起的任务执行函数
- void HandleKeyPress()
- {
- switch(keypress)
- {
- case key_vaule1:
- IA1=1;IB1=0;
- IA2=1;IB2=0;
- break;
- case key_vaule2:
- IA1=0;IB1=1;
- IA2=0;IB2=1;
- break;
- case key_vaule3:
- IA1=1;IB1=0;
- IA2=0;IB2=0;
- break;
- case key_vaule4:
- IA1=0;IB1=0;
- IA2=1;IB2=0;
- break;
- }
- }
- void keyScan()
- {
- static unsigned char state=0;
- unsigned char temp;
- if(key1==0) temp=key_vaule1;
- else if (key2==0) temp=key_vaule2;
- else if (key3==0) temp=key_vaule3;
- else if (key4==0) temp=key_vaule4;
- else temp=0;
- switch (state)
- {
- case 0: if(temp!=0) state=1;break; //检测是否有低电平出现
- case 1: state=2; break; //延时10ms
- //case 2:按键已经被按下,此时把temp的数值付给keypress就可以知道是那个按键被按下
- case 2: if(temp!=0) {state=3;keypress=temp;HandleKeyPress();} else state=0; break;
- case 3: if(temp==0) {state=0;IA1=0;IB1=0;IA2=0;IB2=0;} break;
- }
- }
- void main()
- {
- TMOD = 0x01;
- TH0 = (65536-1000)/256;
- TL0 = (65536-1000)%256;
- EA = 1;
- ET0 = 1;
- TR0 = 1;
-
- while(1)
- {
- if(ms_10>10)
- {
- ms_10 = 0;
- keyScan();
- }
- }
- }
- void timer0() interrupt 1
- {
- TH0 = (65536-1000)/256;
- TL0 = (65536-1000)%256;
- ms_10++;
- }
复制代码
|
评分
-
查看全部评分
|