Sending strings over Serial to Arduino

Multi tool use
Sending strings over Serial to Arduino
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 == '') {
// ...do something with String...
if(incomingString == "hello") {
Serial.println("Hello World!");
}
incomingString = "";
}
}
}
Can anyone point me in the right direction?
Thanks
2 Answers
2
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.
incomingString += incomingByte
char *
The result is that your if
condition is effectively doing this: if ("hello" == "hello") ...
. Obviously they're not equal, so the condition always fails.
if
if ("hello" == "hello") ...
I believe the solution is just to make sure you don't append the byte if it's null.
incomingString += incomingByte; if (incomingByte == '') {
if (incomeByte) incomingString += incomingByte; else {
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 = "";
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Agree. And according this, @AdeptInvention should replace
incomingString += incomingByte; if (incomingByte == '') {
withif (incomeByte) incomingString += incomingByte; else {
.– LS_ᴅᴇᴠ
Nov 8 '13 at 14:33