0
由於標題給出了它,我試圖只發送從Arduino的價值Long integer
並從我的C#應用程序接收它。從Arduino發送長整型值並從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
轉換有什麼問題?