/*******************************************
//利用51定时器产生PWM波来调节电机速度
//速度变化范围从0-100可调
//使用三路做寻迹使用,哪一路检测在黑线哪一路为
//高电平
//没检测到黑线表示有反射 对应输出低电平信号
*********************************************/
#include #define uint unsigned int #define uchar unsigned char /*电机四个接口定义*/ sbit in1=P0^0; sbit in2=P0^1; sbit in3=P0^2; sbit in4=P0^3; /*计时器*/ uchar j,k,i,a,A1,A2,second,minge,minshi; sbit dula=P2^6; sbit wela=P2^7; uchar code table[]={0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x77,0x7c, 0x39,0x5e,0x79,0x71}; uchar code table2[]={0xbf,0x86,0xdb,0xcf, 0xe6,0xed,0xfd,0x87, 0xff,0xef,0xf7,0xfc, 0xb9,0xde,0xf9,0xf1}; void delay(uchar i) { for(j=i;j>0;j--) for(k=110;k>0;k--); } void display(uchar sh_c,uchar g_c,uchar min_ge,uchar min_shi) { dula=1; P0=table[sh_c]; dula=0; P0=0xff; wela=1; P0=0xfb; wela=0; delay(5); dula=1; P0=table[g_c]; dula=0; P0=0xff; wela=1; P0=0xf7; wela=0; delay(5); dula=1; P0=table[min_shi]; dula=0; P0=0xff; wela=1; P0=0xfe; wela=0; delay(5); dula=1; P0=table2[min_ge]; dula=0; P0=0xff; wela=1; P0=0xfd; wela=0; delay(5); } /*左、中、右三路循迹传感器接口定义*/ sbit zuo=P1^0; sbit zhong=P1^1; sbit you=P1^2; /*避障接口定义*/ sbit bz_zuo=P1^3; sbit bz_zhong=P1^4; sbit bz_you=P1^5; uchar count = 0; /*利用定时器0定时中断,产生PWM波*/ void Init_timer() { TH0 = (65535-10)/256; TL0 = (65535-10)%256; TMOD = 0x01; TR0 = 1; ET0 = 1; EA = 1; } /*左轮速度调节程序*/ void zuolun(uchar speed) { if(count <= speed) //count计数变量 { in1 = 1; in2 = 0; } else { in1 = 0; in2 = 1; } } void youlun(uchar speed) { if(count<= speed) { //同上 in3 = 1; in4 = 0; } else { in3 = 0; in4 = 1; } } void Inline() { uchar temp; temp =P1; //检测黑线信号 switch(temp) { case 0x01:zuolun(0); youlun(90);break; 正 //左侧循迹传感器压线,小车向左前修 case 0x02:zuolun(100);youlun(100);break; //中间循迹传感器压线,保持直走 此处两值使电机速度保持相同 case 0x04:zuolun(90); youlun(0);break; 正 //右侧循迹传感器压线,小车向右前修 case 0x08:zuolun(90); youlun(0);break; //左侧避障传感器有信号小车右转 case 0x10:zuolun(90); youlun(0);break; //中间避障传感器有信号小车左转 case 0x20:zuolun(90); youlun(0);break; //右侧避障传感器有信号小车左转 } /* if(zuo==1) { zuolun(10); youlun(50); } else if(zhong==1) { zuolun(99); youlun(99); } else if(you==1) { zuolun(50); youlun(10); } */ } void main() //主函数 { Init_timer(); //调用函数 while(1) { Inline(); minge=0; minshi=0; second++; if(second==60) second=0,minge++; A1=second/10; A2=second%10; if(minge==10) minge=0,minshi++; for(a=200;a>0;a--) { display(A1,A2,minge,minshi); }; } } void Timer0_int()interrupt 1 //定时器中断计数 { TH0 = (65535-10)/256; TL0 = (65535-10)%256; count ++; if(count >= 100) { count = 0; } } 因篇幅问题不能全部显示,请点此查看更多更全内容