-1

When I am sending hex numbers via computer to the arduino leonardo, it sometimes won't react, but the serial monitor says that it was sent. My code;

    void setup()
{
  Serial.begin(9600);
  pinMode(9, OUTPUT);
  pinMode(A0, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop()
{
  delay(100); // Wait for 100 millisecond(s)
  Serial.println(Serial.read());
  if (Serial.read() == 49) {
    Serial.println("left");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 50) {
    Serial.println("right");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 51) {
    Serial.println("backwards");
    analogWrite(9, 1023);
    digitalWrite(A0, LOW);
    analogWrite(10, 1023);
    digitalWrite(11, LOW);
  }
  if (Serial.read() == 52) {
    Serial.println("forwards");
    analogWrite(9, 1023);
    digitalWrite(A0, HIGH);
    analogWrite(10, 1023);
    digitalWrite(11, HIGH);
  }
  if (Serial.read() == 48) {
    Serial.println("stop");
    analogWrite(9, 0);
    digitalWrite(A0, LOW);
    analogWrite(10, 0);
    digitalWrite(11, LOW);
  }
}

When I send the numbers 1,2,3,4, and 0, it reads what the command does. Pins A0 and D11 are direction control for the motor controller, and pins D9 and D10 are speed.

it is kinda a mess.

1
  • 2
    the serial monitor prints a different byte from the one that controls the motors
    – jsotola
    Commented Nov 2, 2023 at 4:01

1 Answer 1

3
Serial.println(Serial.read());
if (Serial.read() == 49) {

You are doing two reads here, not one. So you are reading and displaying, and then reading a second byte (not the one you displayed).

Much better would be:

int cmd = Serial.read();
Serial.println(cmd);
if (cmd == 49)  {
  ... do something ...
} else if (cmd == 50)  {
  .. do something else ...
}

And so on.

Also, why use numbers when you can show the ASCII characters? eg.

int cmd = Serial.read();
Serial.println(cmd);
if (cmd == '1')  {
  ... do something ...
} else if (cmd == '2')  {
  .. do something else ...
}

You may also want to consider using:

if (!Serial.available())
    return;

That way you don't test for serial data that does not exist.

Why the delay?

1
  • When I made it delay, it seemed to work better. Commented Nov 3, 2023 at 15:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.