接了3个红外探测,一个稳压电路,一个驱动,和一个arduino主板,四个车轮和车轮电机。
1.小车样子
2.倒车动作
#define STOP 0 //定义五个运动状态 #define FORWARD 1 #define BACKWARD 2 #define TURNLEFT 3 #define TURNRIGHT 4 int LeftMotor1 = 6; //车轮接口 int LeftMotor2 = 7; int RightMotor1 = 4; int RightMotor2 = 5; int ena=9; //电机使能ena和enb int enb=10; int trac1=11; //trac1~3分别是三个红外接口 int trac2=12; int trac3=8; int data[3]; //用来接受三个红外状态 int flag=0; void setup() //初始化设置 { Serial.begin(9600); pinMode(LeftMotor1, OUTPUT); pinMode(LeftMotor2, OUTPUT); pinMode(RightMotor1, OUTPUT); pinMode(RightMotor2, OUTPUT); pinMode(ena,OUTPUT); pinMode(enb,OUTPUT); pinMode(trac1,INPUT); pinMode(trac2,INPUT); pinMode(trac3,INPUT); } void loop() //循环进行trace函数 { while(1) trace(); //循迹函数 } void motorRun(int cmd)//运动状态 { switch(cmd) { case FORWARD://前进 { digitalWrite(LeftMotor1, HIGH); //高电流 digitalWrite(LeftMotor2, LOW); //低电流 digitalWrite(RightMotor1, HIGH); digitalWrite(RightMotor2, LOW); break;} case BACKWARD://返回 {digitalWrite(LeftMotor1, LOW); digitalWrite(LeftMotor2, HIGH); digitalWrite(RightMotor1, LOW); digitalWrite(RightMotor2, HIGH); break;} case TURNLEFT://左转 { digitalWrite(RightMotor1, HIGH); digitalWrite(RightMotor2, LOW); digitalWrite(LeftMotor1, LOW); digitalWrite(LeftMotor2, HIGH); break;} case TURNRIGHT://右转 { digitalWrite(LeftMotor1,HIGH ); digitalWrite(LeftMotor2, LOW); digitalWrite(RightMotor1,LOW); digitalWrite(RightMotor2, HIGH); break;} default://停止 {digitalWrite(LeftMotor1, LOW); digitalWrite(LeftMotor2, LOW); digitalWrite(RightMotor1, LOW); digitalWrite(RightMotor2, LOW);} } } void trace() { data[0]= digitalRead(11);//红外输入 data[1]= digitalRead(12); data[2]= digitalRead(8); analogWrite(ena,255); //pwm波调满 analogWrite(enb,255); motorRun(FORWARD); if(data[0]==0) { while(data[1]) //右边红外检测到时,右转 { data[1]= digitalRead(12); analogWrite(ena,255); analogWrite(enb,255); motorRun(TURNRIGHT); } } if(data[2]==0) { while(data[1]) //左边红外检测到时,左转 { data[1]= digitalRead(12); analogWrite(ena,255); analogWrite(enb,255); motorRun(TURNLEFT); } } data[0]= digitalRead(11);//红外输入 data[1]= digitalRead(12); data[2]= digitalRead(8); if(data[2]==0&&data[0]==0&&data[1]==0) //当小车三个红外同时检测到时 { motorRun(FORWARD); //先往前运动150ms delay(150); motorRun(STOP); delay(3000); //停3s analogWrite(ena,255); //给倒退时电机的使能 analogWrite(enb,255); motorRun(BACKWARD); //倒退1s delay(1000); motorRun(TURNRIGHT); //先让车头右转500ms delay(500); data[1]= digitalRead(12); //更新中间红外的状态 while(data[1]==1) //车头持续右转 { data[1]= digitalRead(12); //随时更新中间红外状态,没有检测到白线就持续右转 motorRun(TURNRIGHT); } } } } }
这是我初学C语言和Arduino时和两个队友做出的小车,用来参加了一个小比赛。挺感谢我的两个队友,不是她们的话这小车都不能顺利的跑起来。当时这个倒车加摆头还是挺惊艳的。总之,这次调小车的过程还是带给我很多快乐和回忆,同时也学会了好多东西。