0
votes

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

2
This question has been answered countless times already.TomServo

2 Answers

0
votes

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.

0
votes

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 = "";
}