从Arduino的发送长整型值和C#应用程序接受他们? [英] Sending Long integer values from Arduino and receiving them from C# app?

查看:364
本文介绍了从Arduino的发送长整型值和C#应用程序接受他们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题给它拿走我想刚刚从Arduino的发送长整型值,并从我的C#应用​​程序接收它。

As title gives it away I am trying to just send Long integer values from arduino and receiving it from my C# application.

我的Arduino code是

My Arduino code is

void setup()
{
  Serial.begin(9600);
}

long n;
byte b[4];

void loop()
{
  n=500;
   for (int i=0; i<10; i++)
   {
     n = n+20;
  IntegerToBytes(n, b);
  for (int i=0; i<4; ++i)
  {
  Serial.write((int)b[i]);
  }
  delay(1000);
   }  
}

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

和相关的C#code是

And related C# code is

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            if (mySerial.IsOpen)
            {
                int bytes = mySerial.BytesToRead;

                byte[] byte_buffer = new byte[4];
                mySerial.Read(byte_buffer, 0, 4);
                if (bytes == 4)
                {
                    SerialConverted_LONGValue = BitConverter.ToInt32(byte_buffer, 0);
                }
            }
        }

在我调试code,它只是接收到的值写入一个文本框。我能看到的只是一个值,如果任何机会,它改变了几次,也是如此。

After I debug the code it just writes the received value to a textbox. I can see just one value, and if any chance, it changes couple of times, as well.

什么是错我的长为byte [] 字节[]长转换?

推荐答案

BitConverter做直线图。它不知道字节序。从3更改分配的顺序,2,1,0比0,1,2,3。

BitConverter does a straight map. It does not know about endianess. Change the order of assignment from 3, 2, 1, 0 to 0, 1, 2, 3.

这篇关于从Arduino的发送长整型值和C#应用程序接受他们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆