Arduino UNO - char array with numbers to different int values

Hi all,

I have been searching and trying around but at the moment I am stuck. I am trying to do the following:

I have a char array which comes in via the Arduino WiFi Shield:

char charBuffer[255];
...
int rxLen = Udp.read(packetBuffer,255);

The char array will look as follows:

*cmd|id|Length|data1|data2|data3#

The goal is to do the following:

int inCMD;
int inID;
int inLENGTH;
int inDATA[8];

inCMD = cmd;        //range:  0 <-> 99   --> so max 2 chars in the array
inID = id;          //range:  0 <-> 999  --> so max 3 chars in the array
inLENGTH = Length;  //range:  0 <-> 8    --> so always 1 char in the array
inDATA[0] = data1;  //range:  0 <-> 999  --> so max 3 chars in the array per dataX
inDATA[1] = data2;
inDATA[2] = data3;

The * is to mark the start of the array.
The | is to separate all data from each other.
The # is to mark the end of the array.

How can I now go through the char array and take out the different variables I need and transform them in the ints that I need? I just need a starting hand, to get me on my way :slight_smile: I am not that familiar with working with chars and Strings.

How can I now go through the char array and take out the different variables

That sounds remarkably like why strtok() was developed.

and transform them in the ints that I need?

That sounds remarkably like why atoi() was developed.

Hello Paul !

Thanks a lot, it’s up and running :slight_smile: :slight_smile:

For whom would need “a” solution, here it is:

char packetBuffer[] = "*|10|125|8|23|254|1|0|255|1|0|255#"; 
const int  MAX_STRING_LEN = 44;
char stringBuffer[MAX_STRING_LEN+1];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.flush();
}

void loop() {
  char *str;
  char *p;
  int i=0;
  
  int CMD,ID,LENGTH;
  int DATA[15];
  int PAYLOAD[8];
  strncpy(stringBuffer, packetBuffer, MAX_STRING_LEN); 
  
  for( str = strtok_r(stringBuffer, "|", &p);       
       str;                                        
       str = strtok_r(NULL, "|", &p)                
     )
  {
    DATA[i]=atoi(str);
    i++;
  }
  for(i=0;i<15;i++){
    Serial.println(DATA[i]);  
  }
  
  CMD=DATA[1];
  ID=DATA[2];
  LENGTH=DATA[3];
  for(i=4;i<LENGTH+4;i++){
    PAYLOAD[i-4]=DATA[i];
  }

  Serial.print("CMD: ");
  Serial.println(CMD);
  Serial.print("ID: ");
  Serial.println(ID);
  Serial.print("LENGTH: ");
  Serial.println(LENGTH);
  for(i=0;i<LENGTH;i++){
    Serial.print("Data: ");
    Serial.println(PAYLOAD[i]);
  }
  
  delay(500000);
}