标签:信号 bsp for uri nbsp log define 中断 ++
1 #include<reg52.h> 2 #define uint unsigned int 3 #define uchar unsigned char 4 sbit left1=P1^0; 5 sbit left2=P1^1; 6 sbit right1=P1^2; 7 sbit right2=P1^3; 8 sbit Trig=P1^4; 9 sbit Echo=P1^5; 10 sbit c_0=P2^0; 11 sbit c_1=P2^1; 12 sbit c_2=P2^2; 13 sbit c_3=P2^3; 14 long Th1,Tl1; 15 uint how=0; 16 uint distance=0; 17 uint time=0; 18 bit Timeup=0; 19 20 uint state=0; // 0为待定 1为壁障 2为遥控 21 uint avoidstate=0; // 0为前进探索 1为停止确定 2为后退 3为左转 4为继续前进(不探测) 22 uint t=0; //pwm 23 uint count=5; //占空比 24 25 26 void delay_20us() 27 { 28 uchar a ; 29 for(a=0;a<50;a++); 30 } 31 uint measuring() 32 { char Rxback=1; 33 //初始化 34 35 Th1=0; 36 Tl1=0; 37 Timeup=0; 38 39 ET1=1; //开启定时器1中断 40 TR1=0; 41 TH1=0; 42 TL1=0; 43 44 Trig=1; 45 delay_20us(); 46 Trig=0; 47 while(Echo==0);//等待信号返回 48 TH1=0; 49 TL1=0; 50 TR1=1; 51 while(Rxback) 52 { 53 if(Echo==0||Timeup==1) 54 { 55 TR1=0; 56 Th1=TH1; 57 Tl1=TL1; 58 TR1=1; 59 Rxback=0; 60 } 61 } 62 time=(Th1*256+Tl1); 63 distance=((unsigned long)(340)*time)/2000; //单位mm 64 if(distance<30||distance>900) 65 distance=0; //去除错误数据 66 return distance; 67 } 68 void delayms(uint ms) 69 { 70 uint i,j; 71 for(i=ms;i>0;i++) 72 for(j=110;j>0;j++); 73 } 74 void left() 75 { 76 left1=1; 77 left2=0; 78 right1=1; 79 right2=1; 80 } 81 void right() 82 { 83 right1=1; 84 right2=0; 85 left1=1; 86 left2=1; 87 } 88 void run() 89 { 90 left1=1; 91 left2=0; 92 right1=1; 93 right2=0; 94 } 95 void stop() 96 { 97 left1=1; 98 left2=1; 99 right1=1; 100 right2=1; 101 } 102 void judgement() 103 { 104 if(how<=150&&how>=40&&avoidstate==0) 105 { 106 avoidstate=1; 107 } 108 } 109 void time0() interrupt 1 //pwm 控制 state 0为待定 1为壁障 2为循迹 3为遥控 110 { 111 TL0 = 0x00; //设置定时初值20ms 112 TH0 = 0xB8; //设置定时初值 113 t++; 114 if(t>=20) 115 { 116 t=0; 117 } 118 if(t<=count) 119 { 120 if(state==1) 121 { 122 judegement(); 123 if(avoidstate==0) 124 run(); 125 if(avoidstate==1) 126 { leftgo(); 127 delayms(5); 128 avoidstate=0; 129 } 130 } 131 if(state==2) 132 { if(c_0==1) 133 run(); 134 else 135 { if(c_1==1) 136 left(); 137 else 138 { if(c_2==1) 139 right(); 140 else 141 { if(c_3==1) 142 stop(); 143 } 144 } 145 } 146 } 147 } 148 else 149 { 150 stop(); 151 } 152 } 153 void T0_time() interrupt 3 154 { 155 Timeup=1; 156 } 157 void main() 158 { 159 state=2; // 停止等待状态 160 161 left1=1; //初始化电机 162 left2=1; 163 right1=1; 164 right2=1; 165 166 167 TMOD=0x11; // 0&1计时器可用 168 TL0 = 0x00; //设置定时20ms 169 TH0 = 0xB8; 170 ET0=1; 171 TR0=1; 172 TR1=0; 173 EA=1; 174 delayms(5); 175 run(); 176 while(1) 177 { if(state==1) 178 {how=measuring(); } 179 } 180 }
一个假期的努力 后来比赛的时候就用到了~
果然前人栽树后人乘凉啊!
标签:信号 bsp for uri nbsp log define 中断 ++
原文地址:http://www.cnblogs.com/tao-zhu-forever/p/7532135.html