Reading serial strings into an array

Hi All,

I have an Arduino receiving serial messages form a monitoring system, the Arduino needs to convert these to CAN bus messages for the HMI. The messages take this format: $-0.073,+1.234,0438,00000,5.45,156 there are 4 data fields that I need to extract from the message to convert to CAN bus.

Using the following code I can receive and display the messages via the terminal:

void serialEvent2()
{
    unsigned char inByte;
    if (Serial2.available() > 0)
    { 
        inByte = Serial2.read();
        Serial.write(inByte);
        if (inByte == '\n')
        {
          Serial.println("");  
        }
    }
}

However I cannot separate this into the 4 fields. I have tried reading it into a char array with the following code but it seems to just fill the array with 255.

void serialEvent2()
{
  unsigned char array[40]={'\0'};
  if(Serial2.available() > 0)
  {
    for (int i=0; i<40; i++)
    {
      array[i] = Serial.read();
    }
  }

  for (int i=0; i<40; i++)
  {
    if (array[i] != '\0')
    {
      //Serial.write(array[i]);
      Serial.print(array[i]);
    }
    else
    {
      Serial.println("");
    }
  }
}

Can you help me to split this message up?

Many thanks

Using the following code I can receive and display the messages via the terminal:

void serialEvent2()

{

That is truly amazing !

What was your real question ?

UKHeliBob:
That is truly amazing !

What was your real question ?

It turns out hitting tab jumps to the post button :frowning: anyway its updated now to what I was trying to say

One glaring mistake is that once you determine that there is at least one character available to read you go ahead and read 40 characters which may, or may not be available.

Can I suggest that you read Serial input basics

Do you have any control over what is sending the data ? If so, can you insert a delimiter between the values being sent ?

As a matter of personal preference I don’t see how the serialEvent function helps, particularly when you start by testing whether any data is available anyway.

Wow, now if I knew that existed it would have saved an awful lot of time.

Thanks very much for the help.

binaryrob:
Wow, now if I knew that existed it would have saved an awful lot of time.

That's why there is a Sticky at the top of the Programming Section titled Useful Links

...R