Arduino crash on strcpy();

Hello guys! How are you?

So a little background on the project I'm trying to make work. I would like to use an Arduino Mega to act as a buffer between ROS and a very old (yet accurate) DSP board which provides encoder ticks and and motor control over serial port. This board sends encoder info as HEX numbers in a string format.

So right now, I'm facing a problem. The board sends the info in the form of "V=XXXXXXXX,YYYYYYYY", so I need to split the string line in two char arrays and use a convert function such as strtol. This is what I've done:

unsigned int X = 0;
unsigned int Y = 0;
char bufferX[8];
char bufferY[8];
String str = "";
String str_ = "";

Serial1.find('=');
str = Serial1.readStringUntil(',');
str_ = Serial1.readStringUntil('\n');

strcpy(bufferX, str.c_str());
X = (unsigned int)strtol(&bufferX[1], NULL, 16);

strcpy(bufferY, str_.c_str());
Y = (unsigned int)strtol(&bufferY[1], NULL, 16);

And then Serial.print(); to show the results on the serial console. My problem is that, if I only do one strcpy(); it works perfectly, but not with two, in which case the Mega just reboots and reboots interminably. My guess was that I have made a memory overflow of some sort, but I tried many other solutions like sprintf(); it's all the same.

Could someone lighten me on how I can make this work? I would be super grateful! Thanks! :slight_smile:

Please post your code.

V=XXXXXXXX,YYYYYYYY

char bufferX[8];

Nine into eight doesn't go.

Read Serial Input Basics - updated. No use of String (capital S) and contains a parse example.

First, get rid of the String class; it uses more resources than necessary and is a crutch. Second, your sample input suggests you're expecting an eight digit number, which is larger than an unsigned int can represent. Do you need a unsigned long which can do about 4 billion? Third, learn to use strtok(). The following program gives an example. You'll have to use a conversion function (e.g., atol()) to convert from string to numeric.

char input[20];

void setup() {
  Serial.begin(9600);
}

void loop() {
  char *ptr;
  int charsRead;
  unsigned int X, Y;

  if (Serial.available() > 0) {     // Test input string =  V=11111,65000
    charsRead = Serial.readBytesUntil('\n', input, sizeof(input) - 1);  // Leave room for NULL
    input[charsRead] = '\0';
    ptr = strtok(input, "=,");
    while (ptr) {
      Serial.println(ptr);
      ptr = strtok(NULL, "=,");
    }
  }
}

strcpy() doesn't work on big-S Strings. They are C++ objects and about 30 years newer than strcpy().

Get into the habit of using strncpy() because that won't scribble all over your memory until it crashes.