从 Arduino 发送长整数值并从 C# 应用程序接收它们? [英] Sending Long integer values from Arduino and receiving them from C# app?

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

问题描述

由于标题给出了它,我试图从 arduino 发送 Long integer 值并从我的 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 代码是

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#代码是

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

在我调试代码后,它只是将接收到的值写入文本框.我只能看到一个值,如果有机会,它也会改变几次.

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.

我的long到byte[]byte[]到long的转换有什么问题?

What is wrong with my long to byte[] and byte[] to long conversion?

推荐答案

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天全站免登陆