Send many ints from Unity To Arduino.

Hi Guys,

I’m trying to send many ints to my “masterArduino”.
Because the SerialPort object only send strings. I’ve tried many things including:

  • Creating a string from ints ( didn’t work because the size of the string.length is dynamic).
  • Then i tried to convert these ints to chars, this because all values are between 0-255, then put the char into a string and send it.

This sort of works. However i think there is no value for 0 in char world. So the data is not right. But there must be a better way?

void sendInfo()
    {
          for (var i = 0; i < peltiers.Length; i++)
        {
            char tempHot = (char) peltiers*.GetComponent<Peltier>().hot;*

char charTemp = (char) peltiers*.GetComponent().temp;*
peltierInfo += tempHot.ToString();
peltierInfo += charTemp.ToString();
}
sp.WriteLine(peltierInfo);
Debug.Log(peltierInfo);
sp.BaseStream.Flush();
peltierInfo = “”;
}
Any help would be greatly appreciated! Thanks!

Try using Int.ToString("D5") or something similar. This forces the number to be displayed with 5 digits. So 345.ToString("D7") returns 0000345. Now just split the received string into segments of 7 or how many digits you need (3 in the case of 0-255) on the arduino side and cast them to Ints!

Good luck!

-Gameplay4all

Hi, one way to convert binary information to a string is use Base64 encoding, it was designed exactly for that (and to minimize size too).

Check “System.Convert.ToBase64String()” and “System.Convert.FromBase64String()”. I don’t know what kind of environment you have on Arduino side, but Base64 encoding/decoding is quite standard in many languages/libraries.