- Home /
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[i].GetComponent<Peltier>().hot;
char charTemp = (char) peltiers[i].GetComponent<Peltier>().temp;
peltierInfo += tempHot.ToString();
peltierInfo += charTemp.ToString();
}
sp.WriteLine(peltierInfo);
Debug.Log(peltierInfo);
sp.BaseStream.Flush();
peltierInfo = "";
}
Any help would be greatly appreciated! Thanks!
Arduino Code:
void loop() {
int serialIndex = 0;
int i2cIndex = 0;
while (0 < Serial.available()) { // loop through all the received bytes
char bufferByte = 0;
bufferByte = Serial.read();
serialBuffer[serialIndex] = (byte) bufferByte; // put current index byte in array
serialIndex ++; // add index.
if(serialIndex%12==0 && serialIndex != 0){
sendBytes(0);
}
}
//sendBytes(0);
delay(50);
}
void sendBytes(int slave){
byte i2cBuffer[12];
int bufferIndex = slave * 12;
for(int i = 0; i < 12; i++){
i2cBuffer[i] = serialBuffer[i + bufferIndex];
}
Wire.beginTransmission(slave+1);
Wire.write(i2cBuffer, 12);
Wire.endTransmission();
}
Answer by gameplay4all · Mar 22, 2017 at 01:53 PM
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
This was the answer i didn't knew i was looking for! Thanks a bunch, the communication works like a charm now! :).
Answer by _dns_ · Mar 22, 2017 at 02:51 PM
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.
Your answer
Follow this Question
Related Questions
parseInt givin' me issues! 2 Answers
Convert Text to float 3 Answers
How to convert a string to int array in Unity C# 1 Answer
How to turn a String to an Int? 5 Answers
Convert int to string and back again 2 Answers