italiano y Español debajo
When I start it, one of the two servos rotates perfectly, but one of them needs a little push to spin. This also happens whenever I change its direction, it will stop and won't move unless I give it a push (always the same servo) . Does anyone know how to solve this?
I'm using an Arduino Uno
Questo e' il mio codice. Ogni volta che inizio il mio codice uno dei due servo ruota correttamente, ma l'altro ha bisogno di una piccola spinta per partire. Lo fa anche ogni volta che cambia direzione (sempre lo stessso servo). Sapete per caso come risolverlo?
Este es mi codigo. Cada vez que empiezo el programa, uno de los dos servos rotea correctamente, pero el otro necesita una pequeño empujon. Tambien pasa cuando cambio la direccion (siempre el mismo servo) . ¿Alguien sabe como resolverlo?
My code / il mio codice / mi codigo
#include <Servo.h>
#define servo_pin 2
#define trigPin 3
#define echoPin 4
#define blservo 5
#define brservo 6
typedef enum {
right = -1,
forward = 0,
left = 1
} tristate;
tristate BL = forward;
tristate BR = forward;
Servo SR_servo;
Servo BL_servo;
Servo BR_servo;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
BR_servo.attach(brservo);
BL_servo.attach(blservo);
SR_servo.attach(servo_pin);
}
void go_right(){
if(BL != right){
BL_servo.writeMicroseconds(1700);
}
if(BR != right){
BR_servo.writeMicroseconds(1700);
}
BL = BR = right;
delay(1500);
}
void go_left(){
if(BL != left){
BL_servo.writeMicroseconds(1300);
}
if(BR != left){
BR_servo.writeMicroseconds(1300);
}
delay(1500);
}
void go_forward(){
if(BL != forward){
BL_servo.writeMicroseconds(1700);
}
if(BR != forward){
BR_servo.writeMicroseconds(1300);
}
delay(1500);
}
int get_distance() {
int distance;
long duration; // variable for the duration of sound wave travel
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
return distance;
}
void loop() {
if(get_distance() < 20){
BL_servo.writeMicroseconds(1500);
BR_servo.writeMicroseconds(1500);
int rightd;
int leftd;
SR_servo.write(180);
delay(500);
leftd = get_distance();
SR_servo.write(0);
delay(500);
rightd = get_distance();
Serial.println("--------------------------------------");
Serial.print("right distance: ");
Serial.println(rightd);
Serial.print("left distance: ");
Serial.println(leftd);
if(max(rightd, leftd) == leftd){
Serial.println("Go left!");
go_left();
}
else{
Serial.println("Go right!");
go_right();
}
SR_servo.write(90);
}
else{
go_forward();
}
}