I am trying to send integers over serial, and can get single numbers to work with code below, but as soon as I use 10 or 100 it treats each digit as a new line. I have tried to use serial.readString then convert to an int afterwards, but this is throwing an error also.
int varX = 0;
int varY = 0;
int varZ = 0;
int varCounter = 0;
void setup() {
Serial.begin(115200);
grabNewVars();
}
void grabNewVars()
{
while (varCounter < 3)
{
if (Serial.available() > 0) {
if (varCounter ==0)
{
varX = Serial.parseInt();
}
if (varCounter ==1)
{
varY = Serial.parseInt();
}
if (varCounter ==2)
{
varZ = Serial.parseInt();
}
varCounter++;
}
}
}
void loop()
{
Serial.println("varX = " + String(varX));
Serial.println("varY = " + String(varY));
Serial.println("varZ = " + String(varZ));
Serial.println("variables received, run main loop");
delay(100000);
}
First think of Serial as really really really S. L. O. W.
Serial is like your penpal sends you a postcard once a week with a single character on it. You can do thousands of things while waiting for the next character. So don't waste weeks of your time chained up to the mailbox with Serial.parseInt().
Your program should concentrate on doing the thing that it does. If it is a robot cookimg dinner then it should be walking around the house doing things all the time. One of those things is checking the mailbox, of course.
If a postcard arrives, look at it and put it on the kitchen table. Keep doing stuff.
If the postcard is a special one which completes a message, now your robot can read the entire message off the table and do what it says. "Special" might be the carriage-return or enter key. That is encoded as '\n' in C code.
What is sending those "integers"? If it's Serial Monitor you are not sending integers but the ascii representation of that But okay, .parseInt() should just parse that for you to an int. But, it will time out if you send the digits to slow. The default is 1000ms, see Serial.setTimeout(); So you need to send your command pretty quick after boot (within 1 second) or it will just read 0.
Serial.println("varX = " + String(varX));
You should already try to not use Strings (but to use strings) but only using it to concatenate is extra ugly... Just do:
Serial.print("varX = ");
Serial.println(varX);
There is NO difference in what serial is sending but uses a lot less memory and no possibility for your memory to turn into Swiss cheese.
[edit]Totally agree with what MorganS says but if you only need to parse some values when you boot the whole blocking method you use now is workable.