Serial.read() from Arduino IDE and Python different?

Hi All. I was rather surprised when I was not able to reproduce some simple example of switching RGB LED using the Arduino IDE whereas using Python the same code works as expected.
Is this a bug in Arduino IDE???
Can any one explain me the reason???

I call through Python:
image

The working Arduino code:

int redPin=8;

int greenPin=7;

int bluePin=6;

String myColor;

String msg="What color to switch?";

void setup() {

// put your setup code here, to run once:

Serial.begin(9600);

pinMode(redPin,OUTPUT);

pinMode(greenPin,OUTPUT);

pinMode(bluePin,OUTPUT);

//digitalWrite(redPin,HIGH);

}

void loop() {

// put your main code here, to run repeatedly:

Serial.println(msg);

while (Serial.available()==0){

}

myColor=Serial.readString();

Serial.println(myColor);

if (myColor=="red"){

Serial.print(myColor);

digitalWrite(redPin,HIGH);

digitalWrite(greenPin,LOW);

digitalWrite(bluePin,LOW);

}

if (myColor=="blue"){

Serial.print(myColor);

digitalWrite(redPin,LOW);

digitalWrite(greenPin,LOW);

digitalWrite(bluePin,HIGH);

}

if (myColor=="green"){

Serial.print(myColor);

digitalWrite(redPin,LOW);

digitalWrite(greenPin,HIGH);

digitalWrite(bluePin,LOW);

}

}

Welcome to the Forum!
Please insert your code using the code tags. You can go back and fix your original post.
Read the forum guidelines to see how to properly insert the code and some other good information on making a good post.

What is the line ending in the serial monitor set to? E.g "red" is not the same as "red\r\n".

1 Like

If you do:

if (myColor=="blue")

It compares just a pointer (32bit value), if the address in myColor is the same as the string "blue", which sits somewhere else in memory. It will NEVER be true!

I think, you miss to do this:

if (strcmp(myColor, "blue"") == 0)

If you would use C++ and myColor is an instance of a classe, e.g. String - the comparison (the ==) can be an overloaded operator.
But in C-code - strcmp() is needed.

@tjaekel

OP is using Strings (capital S).

Upps, so it is String. Thank you.
In this case, the == to compare should be implemented (on the String class as operator).
Sorry.
I take back all my C-code related comments. No idea why it fails.

It is not clear to me why the same code works in the online tutorial (Arduino Tutorial 20: Understanding RGB LED's - YouTube) but in my case it fails!!!
I assume it has to work in all versions of Arduino IDE!!!

@ssergii answer the question sterretje asked you:

Thanks for the solution!
few minutes before I have discovered that in Arduino the line ending option was changed to "new line" instead of "No line ending". Therefore in serial monitor all looks similar as before but the result was different! This explains all why python was correct!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.