0

I'm currently experimenting with sending a string to my Arduino Yun and trying to get it to reply back depending on what I send it.

I picked up a framework of some code here and have been experimenting with it but apart from the serial monitor displaying 'ready' I can't make it go any further.

The code is:

//declace a String to hold what we're inputting
String incomingString;

void setup() {
  //initialise Serial communication on 9600 baud
  Serial.begin(9600);
  while(!Serial);
  //delay(4000);
  Serial.println("Ready!");
  // The incoming String built up one byte at a time.
  incomingString = "";
}

void loop () {
  // Check if there's incoming serial data.
  if (Serial.available() > 0) {
    // Read a byte from the serial buffer.
    char incomingByte = (char)Serial.read();
    incomingString += incomingByte;

    // Checks for null termination of the string.
    if (incomingByte == '\0') {
      // ...do something with String...
      if(incomingString == "hello") {
        Serial.println("Hello World!"); 
      }

      incomingString = "";
    }
  } 
}

Can anyone point me in the right direction?

Thanks

1
  • This question has been answered countless times already. Commented Aug 31, 2021 at 23:07

2 Answers 2

1

I suspect the problem is that you're adding the null terminator onto the end of your string when you do: incomingString += incomingByte. When you're working with string objects (as opposed to raw char * strings) you don't need to do that. The object will take care of termination on its own.

The result is that your if condition is effectively doing this: if ("hello\0" == "hello") .... Obviously they're not equal, so the condition always fails.

I believe the solution is just to make sure you don't append the byte if it's null.

Sign up to request clarification or add additional context in comments.

1 Comment

Agree. And according this, @AdeptInvention should replace incomingString += incomingByte; if (incomingByte == '\0') { with if (incomeByte) incomingString += incomingByte; else {.
0

Try This:

String IncomingData = "";
String Temp = "";
char = var;

void setup()
{
Serial.begin(9600);
//you dont have to use it but if you want
// if(Serial) 
{
  Serial.println("Ready");
}
//or
while(!Serial)
{delay(5);}
Serial.println("Ready");
void loop()
{
while(Serial.available())
{
  var = Serial.read();
 Temp = String(var);
 IncomingData+= Temp;
 //or
 IncomingData.concat(Temp);

 // you can try 
   IncomindData += String(var);
}
 Serial.println(IncomingData);
 IncomingData = "";
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.