繁体   English   中英

如何从C#向Arduino发送4字节数据(byte [])并从Arduino读取?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM