Olá a todos
Dei uma alterada no meu código, e agora consigo comparar a distância, entretanto o controle do carrinho ainda está bem ruim.
Por favor deixem sugestões, ideias, melhorias etc....
segue o código novo:
#include "Ultrasonic.h"
#include <AFMotor.h>
#include <Servo.h>
AF_DCMotor motor1(1, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
AF_DCMotor motor2(2, MOTOR12_64KHZ); // create motor #2, 64KHz pwm
Ultrasonic ultrasonic(2);
Servo myservo; // create servo object to control a servo
// a maximum of eight servo objects can be created
int pos = 15; // variable to store the servo position ;
int Rdist , Ldist;
void setup() {
Serial.begin(9600);
myservo.attach(10); // attaches the servo on pin 10 to the servo object
motor1.setSpeed(165); // set the speed to 200/255
motor2.setSpeed(255); // set the speed to 200/255
myservo.write(90);
}
void loop() {
// int i;
// Yellow();
myservo.write(90);
ultrasonic.MeasureInCentimeters();
// Serial.print(ultrasonic.RangeInCentimeters); //Prints to Serial Monitor
//Serial.print("cm");
if (ultrasonic.RangeInCentimeters >= 40)
{
// Green();
forward();
}
else if (ultrasonic.RangeInCentimeters < 35 && ultrasonic.RangeInCentimeters >20){
// Yellow();
myservo.write(50);
delay(1500);
ultrasonic.MeasureInCentimeters();
stop();
Rdist = ultrasonic.RangeInCentimeters;
Serial.print(Rdist); //Prints to Serial Monitor
Serial.println("DIR");
myservo.write(140);
delay(1500);
ultrasonic.MeasureInCentimeters();
Ldist = ultrasonic.RangeInCentimeters;
Serial.print(Ldist); //Prints to Serial Monitor
Serial.println("ESQ");
stop();
delay(500);
if (Rdist > Ldist){
right();
delay(500);
}
else if (Ldist>Rdist){
left();
delay(500);
}
else
stop();
}
if (ultrasonic.RangeInCentimeters < 15 && ultrasonic.RangeInCentimeters > 0){
// Red();
stop();
backward();
}
}
//-------------------------------------------------------------------------------
//Funçao motor
void forward()
{
motor1.run(FORWARD);
motor2.run(FORWARD); // turn it on going forward
}
void backward()//
{
motor1.run(BACKWARD);
motor2.run(BACKWARD); // the other way
}
void right()//
{
motor1.setSpeed(255);
motor2.setSpeed(255);
motor1.run(BACKWARD);
motor2.run(FORWARD);
// delay(500);
}
void left()//
{
motor2.setSpeed(255);
motor1.setSpeed(255);
motor2.run(BACKWARD);
motor1.run(FORWARD);
// delay(500);
}
void stop()//
{
motor1.run(RELEASE);
motor2.run(RELEASE); // stopped
}
Obrigado a todos pela ajuda.