Problems with serial.available

hello good day forum

I have a question to solve, as I am reading through the serial port I receive too much information, and this causes the routine to be activated up to 14 times. I tried to use if but it didn't work, now I show you with switch case:

#include <Servo.h>
Servo myservo;
char lectura;
int ENA = 10;
int IN1 = 9;
int IN2 = 8;
int ENB = 5;
int IN3 = 6;
int IN4 = 7;

void setup() {
  Serial.begin(9600);
  pinMode (ENA, OUTPUT);
  pinMode (ENB, OUTPUT);
  pinMode (IN1, OUTPUT);
  pinMode (IN2, OUTPUT);
  pinMode (IN3, OUTPUT);
  pinMode (IN4, OUTPUT);
  myservo.attach(3);
  myservo.write(45);
  delay(1000);
}

void loop() {
 if(Serial.available() > 0){ //Olfatea la comunicacion serial
    lectura = Serial.read();
    Adelante();
    switch (lectura) {
      case '1':
        myservo.write(0);
        delay(1000);
        break;
      case '2':
        myservo.write(75);
        delay(1000);
        break;
      case '3':
        delay(6000);
        Parada();
        Izquierda();
        delay(8000);
        Derecha();
        delay (8000);
        Parar();
        break;
    }
  }
}

void Derecha () {
  //Direccion motor A
  digitalWrite (IN1, HIGH);
  digitalWrite (IN2, LOW);
  analogWrite (ENA, 255); //Velocidad motor A
}

void Adelante () {
  //Direccion motor A
  digitalWrite (IN3, LOW);
  digitalWrite (IN4, HIGH);
  analogWrite (ENB, 255); //Velocidad motor A
}
void Parada() {
  //Direccion motor A
  digitalWrite (IN3, LOW);
  digitalWrite (IN4, LOW);
  analogWrite (ENB, 0); //Velocidad motor A
}

void Izquierda () {
  //Direccion motor A
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
  analogWrite (ENA, 255); //Velocidad motor A
}

void Parar () {
  //Direccion motor A
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, LOW);
  analogWrite (ENA, 0); //Velocidad motor A
}

Any advice to solve it?


(added by Moderator: in a - now removed - parallel post this was another question to that same/very similar code)

Since you are using quite long delays in your code chances are very high, that your serial buffer gets new data while waiting.
You may want to flush the entire buffer after handling one case so that you have a clean state for the next time round.

2 Likes

Hi Jesus,
I learned A LOT from this resource. I recommend you give it a look, please.

1 Like