[英]Sending Long integer values from Arduino and receiving them from C# app?
As title gives it away I am trying to just send Long integer
values from arduino and receiving it from my C# application. 正如标题所说的那样,我试图从arduino发送Long integer
数值,并从我的C#应用程序接收它。
My Arduino code is 我的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);
}
And related C# code is 和相关的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. 我只能看到一个值,并且如果有机会,它也会改变几次。
What is wrong with my long to byte[]
and byte[] to long
conversion? 我的long to byte[]
和byte[] to long
转换有什么问题?
BitConverter does a straight map. BitConverter绘制直线图。 It does not know about endianess. 它不知道耐力。 Change the order of assignment from 3, 2, 1, 0 to 0, 1, 2, 3. 将分配顺序从3、2、1、0更改为0、1、2、3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.