TA的每日心情 开心 2018-5-29 13:32
签到天数: 1 天
[LV.1]初来乍到
//#include <Servo.h>
int Left_motor_go=8;
int Left_motor_back=9;
int Right_motor_go=10;
int Right_motor_back=11;
const int SensorRight = 3;
const int SensorLeft = 5;
const int SensorM= 4;
int SL;
int SR;
int SM;
void setup()
{
//初始化电机驱动IO为输出方式
pinMode(Left_motor_go,OUTPUT); // PIN 8 (PWM)
pinMode(Left_motor_back,OUTPUT); // PIN 9 (PWM)
pinMode(Right_motor_go,OUTPUT);// PIN 10 (PWM)
pinMode(Right_motor_back,OUTPUT);// PIN 11 (PWM)
pinMode(SensorRight, INPUT); //定义右循迹红外传感器为输入
pinMode(SensorLeft, INPUT); //定义左循迹红外传感器为输入
pinMode(SensorM, INPUT);
Serial.begin(9600);
}
//void run(int time) // 前进
void r()
{
digitalWrite(Right_motor_go,HIGH);
digitalWrite(Right_motor_back,LOW);
analogWrite(Right_motor_go,30);
analogWrite(Right_motor_back,0);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,HIGH);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,30);
//delay(time * 100);
}
//void brake(int time) //刹车,停车
void brake()
{
digitalWrite(Right_motor_go,LOW);
digitalWrite(Right_motor_back,LOW);
digitalWrite(Left_motor_go,LOW);
digitalWrite(Left_motor_back,LOW);
//delay(time * 100);//执行时间,可以调整
}
//void left(int time) //左转(左轮不动,右轮前进)
void right()
{
digitalWrite(Right_motor_go,HIGH); //
digitalWrite(Right_motor_back,LOW);
digitalWrite(Left_motor_go,HIGH); //
digitalWrite(Left_motor_back,LOW);
analogWrite(Right_motor_go,250);//
analogWrite(Right_motor_back,0);
analogWrite(Left_motor_go,250);//
analogWrite(Left_motor_back,0);
}
//void right(int time) //
void left()
{
digitalWrite(Right_motor_go,LOW);
digitalWrite(Right_motor_back,HIGH);
analogWrite(Right_motor_go,0);
analogWrite(Right_motor_back,150);//
digitalWrite(Left_motor_go,LOW);//
digitalWrite(Left_motor_back,HIGH);
analogWrite(Left_motor_go,0);
analogWrite(Left_motor_back,150);//
}
//==========================================================
int i=1;
void loop()
{
while(1)
{
SR = digitalRead(SensorRight);
SL = digitalRead(SensorLeft);
SM = digitalRead(SensorM);
if(SL == LOW&& SR ==LOW&&SM==LOW)//都是黑线
{
switch(i)
{
case 1:
Serial.println(i);
delay(100);
i++;
left();//第一次都是黑线,左转
break;
case 2:
Serial.println(i);
delay(100);
r();//第二次都是黑线,前进
i=2;
break;
}
}
if(SL == HIGH && SR == HIGH&&SM==HIGH)
r();
if (SL == LOW && SR == HIGH&&SM==LOW)
left();
if (SL == HIGH && SR == LOW&&SM==LOW)
right();
if (SL == HIGH && SR == LOW&&SM==HIGH)//
right();//左前右后,右
else if (SR == HIGH && SL == LOW&&SM==HIGH) //
left();
else if(SL == HIGH && SR == HIGH&&SM==LOW) // 都是白色, 停止
r();//都是亮,前进,都是HIGH
}
}
这个程序是可以跑单线的,但是在赛道分支口那里,不能保证三个传感器同时识别到黑线。
另外switch函数里面,delay函数我感觉有点问题。我的switch函数的想法是,第一次往左转。但是它有时候并不能准确的同时识别到黑色
.