簡體   English   中英

從Arduino發送長整數值並從C#應用程序接收它們?

[英]Sending Long integer values from Arduino and receiving them from C# app?

正如標題所說的那樣,我試圖從arduino發送Long integer數值,並從我的C#應用​​程序接收它。

我的Arduino代碼是

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

在調試代碼之后,它只是將接收到的值寫入文本框。 我只能看到一個值,並且如果有機會,它也會改變幾次。

我的long to byte[]byte[] to long轉換有什么問題?

BitConverter繪制直線圖。 它不知道耐力。 將分配順序從3、2、1、0更改為0、1、2、3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM