【问题标题】:How to send 4 bytes data ( byte[] ) from C# to Arduino and read it from Arduino?如何将 4 字节数据( byte[] )从 C# 发送到 Arduino 并从 Arduino 读取?
【发布时间】:2014-05-10 11:59:04
【问题描述】:

在我的另一篇文章中,我试图从 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 读取。

【问题讨论】:

    标签: c# serial-port arduino send


    【解决方案1】:

    我找到了解决方案。在我收到byte array 作为char array 之后,我在代码中再次将字符数组转换为字节数组。

    byte D[4];
    
    D[0] = R[0];
    D[1] = R[1];
    D[2] = R[2];
    D[3] = R[3];
    

    【讨论】:

    【解决方案2】:

    你为什么不使用工会?这将使您的代码更简单,更具可读性:

    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);
    

    【讨论】:

    • 是的,这是一种方便的方式。谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多