So the following code works on a hardware serial port, but when used with SoftwareSerial the String is corrupted. What am I missing?
while (mySDI12.available() > 0)
{
inChar = (char)mySDI12.read(); // get the new byte:
inputString += inChar; // Concatenate char into string
receivedString = String(inputString); // String constructor, char array to object
if (inChar == '!') ///Test for SDI12 termination character
{
RequestReceived = true;
Serial.println(inputString);
Serial.println(receivedString);
inChar = 'X';
inputString = "";
receivedString = "";
mySDI12.flush();
break;
}
}
Result in Terminal window:
0C! - Char array displays fine
¹ - String Object unintelligible
Post all of your code.
This part of your code is wrong
inputString += inChar; // Concatenate char into string
receivedString = String(inputString); // String constructor, char array to object
If "inputString" is a String object ( you have not posted where this is declared, so who knows ), then the following line makes no sense.
In general, using the String class on the arduino is a bad idea.
String inputString = "";
String receivedString = "";
boolean RequestReceived = false;
char inChar = 'X';
void setup(){
Serial.begin(9600);
while(!Serial){};
mySDI12.begin();
}
void loop()
{
while (mySDI12.available() > 0)
{
inChar = (char)mySDI12.read(); // get the new byte:
inputString += inChar; // Concatenate char into string
receivedString = String(inputString); // String constructor, char array to object
if (inChar == '!') ///Test for SDI12 termination character
{
RequestReceived = true;
Serial.println(inputString);
Serial.println(receivedString);
inChar = 'X';
inputString = "";
receivedString = "";
mySDI12.flush();
break;
}
}
You say that you have problem with SoftwareSerial but don't use it in the code that you posted. As has been pointed out, inputString is already a String so why cast it to a String ?
receivedString = String(inputString); // String constructor, char array to objectJudging by the comment inputString may at one time have been a C style string because the comment does not make sense at the moment.
String libraries in Arduino need a String object not an Array of chars, hence the String = String(ArrayOfChars).
Youraagh:
String libraries in Arduino need a String object not an Array of chars, hence the String = String(ArrayOfChars).
But inputString is not an array of chars, it is a String.
From your code
String inputString = "";
Need help with Char Array to String Object
Some time in the past the below was posted to the forum.
void setup(void)
{
}
void loop(void)
{
byte byteArray[5];
strcpy((char *)byteArray,"0123");
String myString = String((char *)byteArray);
}