There are a few things I want to comment on your code-example:
there are almost no explaining comments.
The code has no boundary-checking of the array newCommand.
This means if a too long string (more than 9 bytes) is send over the serial interface the wrong places in RAM get overwritten.
You are using a global defined variable of type String.
This could lead to eat up all RAM-memory over time and then crash the program
I have never seen befor using variable-type float for millis(). Does this reliably work over a long time?
Here is a version that uses the library SafeString which can be downloaded with the library-manager of the Arduino-IDE
#include <SafeString.h>
const byte maxRcvdBytes = 10;
// personal naming-convention suffix _SS indicates a S)afe-S)tring
createSafeString(newCommand_SS, (maxRcvdBytes) ); //+1 for the terminating zero
createSafeString(Command_SS, (maxRcvdBytes) );
const byte Red = 10;
const byte Green = 11;
const byte Blue = 9;
const char endChar = 0x0D; // carriage return is hex-value 0D and is used as the terminating byte
int idx = 0;
char rcvdChar;
unsigned long currTime = 0;
unsigned long prevTime = 0;
boolean blink = false;
void setup() {
pinMode(Red, OUTPUT);
pinMode(Green, OUTPUT);
pinMode(Blue, OUTPUT);
Command_SS = "off";
newCommand_SS = "";
Serial.begin(9600);
prevTime = millis();
}
void readFromSerial() {
while (Serial.available() > 0) {
char rcvdChar = Serial.read();
// for debuging purposes uncomment these lines
//to see each received character in the serial monitor
/*
Serial.print("reveived #");
Serial.print(rcvdChar);
Serial.println("#");
*/
if ( (rcvdChar == endChar) ) { // End of input or max Command_SS-length reached
Command_SS = newCommand_SS;
newCommand_SS = "";
Serial.print("Command_SS received: ");
Serial.println(Command_SS);
idx = 0;
}
else {
newCommand_SS += rcvdChar; // add new received char to SafeString
idx++;
}
}
}
void setLights() {
if (Command_SS == "off")
{
digitalWrite(Red, LOW);
digitalWrite(Green, LOW);
digitalWrite(Blue, LOW);
return;
}
if (Command_SS == "red")
{
digitalWrite(Red, blink);
digitalWrite(Green, LOW);
digitalWrite(Blue, LOW);
return;
}
if (Command_SS == "green")
{
digitalWrite(Red, LOW);
digitalWrite(Green, blink);
digitalWrite(Blue, LOW);
return;
}
if (Command_SS == "blue")
{
digitalWrite(Red, LOW);
digitalWrite(Green, LOW);
digitalWrite(Blue, blink);
return;
}
}
void setBlink(int delay) {
currTime = millis();
if (currTime - prevTime >= delay)
{
prevTime = currTime;
// the attention-mark is the not-operator !true = false !false = true
blink = !blink; // invert the status of variable blink
Serial.print("Blinking LED ");
Serial.print(Command_SS);
Serial.print(" ");
Serial.println(blink);
}
}
void loop() {
readFromSerial();
setBlink(1000);
setLights();
}
best regards Stefan