[英]How to send 4 bytes data ( byte[] ) from C# to Arduino and read it from Arduino?
在我的另一篇文章中,我試圖從arduino發送4字節數據(一個長整數)並在C#應用程序中讀取它。 它完成了。 但這次我需要做相反的事情。 這是我與C#代碼相關的部分;
private void trackBar1_Scroll(object sender, EventArgs e)
{
int TrackSend = Convert.ToInt32(trackBar1.Value); //Int to Int32 conversion
byte[] buffer_2_send = new byte[4];
byte[] data_2_send = BitConverter.GetBytes(TrackSend);
buffer_2_send[0] = data_2_send[0];
buffer_2_send[1] = data_2_send[1];
buffer_2_send[2] = data_2_send[2];
buffer_2_send[3] = data_2_send[3];
if (mySerial.IsOpen)
{
mySerial.Write(buffer_2_send, 0, 4);
}
}
這是對應的Arduino代碼;
void setup()
{
Serial.begin(9600);
}
unsigned long n = 100;
byte b[4];
char R[4];
void loop()
{
//Receiving part
while(Serial.available() == 0){}
Serial.readBytes(R, 4); // Read 4 bytes and write it to R[4]
n = R[0] | (R[1] << 8) | (R[2] << 16) | (R[3] << 24); // assembly the char array
//Sending part
IntegerToBytes(n, b); // Convert the long integer to byte array
for (int i=0; i<4; ++i)
{
Serial.write((int)b[i]);
}
delay(20);
}
void IntegerToBytes(long val, byte b[4])
{
b[3] = (byte )((val >> 24) & 0xff);
b[2] = (byte )((val >> 16) & 0xff);
b[1] = (byte )((val >> 8) & 0xff);
b[0] = (byte )((val) & 0xff);
}
當我運行應用程序時,它正確發送到127.當我開始發送大於127的值時,arduino發送給我-127,-126,...等等。 我不知道問題是從C#發送還是從Arduino讀取的一部分。
我找到了解決方案。 在我收到byte array
作為char array
我在代碼中再次將char數組轉換為字節數組。
byte D[4];
D[0] = R[0];
D[1] = R[1];
D[2] = R[2];
D[3] = R[3];
你為什么不使用工會? 這將使您的代碼更簡單,更易讀:
union {
byte asBytes[4];
long asLong;
} foo;
[...]
if (Serial.available() >= 4){
for (int i=0;i<4;i++){
foo.asBytes[i] = (byte)Serial.read();
}
}
Serial.print("letto: ");
Serial.println(foo.asLong);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.