Help with Arduino via Serial

2

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 necessary information so that the servo that I want to move to where I want there is a delay between which I pulse the between and the servo moves.

I do not know if the Arduino is slow to calculate what I'm sending him to know what he should do or if I'm doing something wrong.

    
asked by Orizzon 21.10.2017 в 16:08
source

1 answer

2

The problem you suffer is because the function Serial.parseInt() waits to receive a delimiter character that ends the whole number or wait for the end of the maximum waiting time set by default to 1 second in Serial.SetTimeout() :

  

Parsing stops when no characters have been read for a configurable time-out value, or a non-digit is read

Which means:

  

The analysis ends when characters have not been read for a configurable time, or a non-digit character is read

So when you press a number the function waits for you to send something that ends the number (for example, a return of the car, a space or any delimiter). Otherwise wait for 1000 ms until the input of the whole number is finished.

I recommend sending a delimiter along with the number through the serial port. This way you will avoid the problem you are suffering in this other question .

    
answered by 23.10.2017 / 10:46
source