I have an Arduino that I use to move some servos. The Arduino has the following code:
#include<Servo.h>
//Creamos los objetos servo
Servo servo;
Servo servo2;
Servo servo3;
Servo servo4;
int enviado; //Aqui enviamos el numero completo
int num; //Numero del servo
int posicion; //Posicion del servo
void setup()
{
//Inicializamos los Servos
servo.attach(9);
servo2.attach(10);
servo3.attach(11);
servo4.attach(6);
//Inicializamos la comunicacion por Serial
Serial.begin(9600);
}
void loop()
{
if(Serial.available() >= 1)
{
/*
1- Leer un numero entero por serial
2- Calculamos su modulo por 10 (sera el numero del motor)
3- Dividir el entero inicial por 10
4- Lo que quede, sera la posicion del motor
*/
enviado = Serial.parseInt();
num = enviado%10;
enviado = enviado/10;
posicion = enviado;
//Hora de mover los servos!
if(num == 1)
{
servo.write(posicion);
}
else if(num == 2)
{
servo2.write(posicion);
}
else if(num == 3)
{
servo3.write(posicion);
}
else if(num == 4)
{
servo4.write(posicion);
}
}
}
The problem I have is that when I send the information necessary for the servo that I want to move to where I want, there is a delay between the time I press the button and the servo moves.
I don't know if the Arduino takes time to calculate what I command it to know what to do or if I'm doing something wrong.
The problem you are experiencing is because the function
Serial.parseInt()
waits for a delimiter character that ends the integer or waits for the maximum timeout set by default to 1 second inSerial.SetTimeout()
:Which means that:
So when you type a number, the function waits for you to send something that ends the number (for example, a carriage return, a space, or any delimiter). Otherwise, it waits for 1000 ms until the input of the integer is finished.
I recommend you to send a delimiter along with the number through the serial port. This way you will avoid the problem that you are suffering in this other question .