Logical Error with Processing Strings and Serial Communication

Hey all!

I'm having a logical error with my code (I think). I'm trying to make a receiver that takes in x and y accelerometer integer values like so:

x0
y100
x-10
y-4
x-150
y160

My receiver code aims to read a character if bluetooth is available, then add it to a string. If it detects a newline escape character, "\n", it does some processing then clears the string to prep for a new line. This part of the code works fine and I've tested it many times on my Arduino Uno.

My problem arises when processing the string. The processing part detects for an x or y at the beginning of the code and returns the integer value to its corresponding variable. It works most of the time, but every few seconds it returns an absurdly big value (think -25266) for a few entries, and half of the time returns 0. The min and max values I should be outputting range about from -160 to 160.

My guess is that something's happening with the buffer being overwritten/being read too much?

A useful note is that myString.toInt returns 0 if it detects a noninteger character.

How do I fix these problems? Here's my code:

if (bluetooth.available () > 0) {
    c = bluetooth.read ();
    if (c == '\n') {
      if (message.startsWith ("x")) {
        xPos = (message.substring (1).toInt ());
      }
      if (message.startsWith ("y")) {
        yPos = (message.substring (1).toInt ());
      }
      Serial.print ("the x is ");
      Serial.print (xPos);
      Serial.print ("\t");
      Serial.print ("the y is ");
      Serial.println (yPos);
      message = "";
    }
    else {
      message = message + c;
    }
  }

Are “xPos”, “yPos”, “message” declared locally?

I haven't tested it yet but maybe it's because of the negative sign at the beginning? This is how toInt() is defined in the documentation:

The input String should start with an integer number. If the String contains non-integer numbers, the function will stop performing the conversion.

toInt reference

I think the problem is in the parts of the sketch that you did not post. Please include enough of the sketch that it compiles and demonstrates the problem.

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. This can happen after the program has been running perfectly for some time. Just use cstrings - char arrays terminated with '\0' (NULL).

...R