|
這是我調(diào)的小車前進后退左轉(zhuǎn)右轉(zhuǎn)的簡單代碼。
- #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;
- //按鍵抬起的任務(wù)執(zhí)行函數(shù)
- 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; //檢測是否有低電平出現(xiàn)
- case 1: state=2; break; //延時10ms
- //case 2:按鍵已經(jīng)被按下,此時把temp的數(shù)值付給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++;
- }
復(fù)制代碼
|
評分
-
查看全部評分
|