How to separate Characters and Numbers from Incoming String from serial port?

Hi,

I am sending "up89" and "down35" from the serial port to Arduino. The characters "up" & "down" will be the same but the number next to them will change. It will in two-digit only.

I want to split them into two variable for example:

If "up78" is coming then value1 = up and value2 = 78 same for down. I tried by sending a "," between then and splitting with strtok but I wasn't able to. Is there any other way to do so.

How can I do it?

Can you change "up" and "down" to "u" and "d"? That would make it much easier.

  if (Serial.available() >= 3)
  {
    int value2;
    char command = Serial.read();
    switch (command)
    {
    case 'u': value2 = Serial.parseInt();
      // Do the UP stuff here
      break;

    case 'd': value2 = Serial.parseInt();
      // Do the DOWN stuff here
      break;

    default: Serial.print("Unexpected character: \'");
      Serial.print(letter);
      Serial.println("\'");
    }
  }

This may even work with "up" and "down" since .parseInt() should skip any non-digits ("p" or "own").

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).

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

...R

Assuming that your strings ("downXX or "upXX") are followed by Newline character ('\n'), the following sketch correctly catches your string and puts the character part in array named char myData1[] and integer part in variable int y.

char myData[20] = "";
char myData1[20] = "";
char myData2[2] = "";
int j = 0, k = 0, y;

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

void loop()
{
  byte n = Serial.available();
  if (n != 0)
  {
    byte m = Serial.readBytesUntil('\n', myData, 20);
    for (int i = 0; i < m; i++)
    {
      char x = myData[i];
      if (isdigit(x) == 0)
      {
        myData1[j] = x;  //storing only the charcaters
        j++;
      }
      else
      {
        myData2[k] = x;  //storing only the non-charcaters
        k++;
        if (k == 2)
        {
          y = atoi(myData2);  //making the integer part
        }
      }
    }
    Serial.println(myData1);  //shows: down
    Serial.println(y, DEC);   //shows: 45
    memset(myData, 0, sizeof myData);  //array reset
    memset(myData1, 0, sizeof myData1); //array reset
    memset(myData2, 0, sizeof myData2); //array reset
    j = 0;
    k = 0;
  }
}

smchar.png

smchar.png