【发布时间】:2014-05-10 11:59:04
【问题描述】:
在我的另一篇文章中,我试图从 arduino 发送 4 字节数据(一个长整数)并在 C# 应用程序中读取它。它完成了。但这一次我需要做相反的事情。这是我的 C# 代码的相关部分;
private void trackBar1_Scroll(object sender, EventArgs e)
{
int TrackSend = Convert.ToInt32(trackBar1.Value); //Int to Int32 conversion
byte[] buffer_2_send = new byte[4];
byte[] data_2_send = BitConverter.GetBytes(TrackSend);
buffer_2_send[0] = data_2_send[0];
buffer_2_send[1] = data_2_send[1];
buffer_2_send[2] = data_2_send[2];
buffer_2_send[3] = data_2_send[3];
if (mySerial.IsOpen)
{
mySerial.Write(buffer_2_send, 0, 4);
}
}
这是对应的Arduino代码;
void setup()
{
Serial.begin(9600);
}
unsigned long n = 100;
byte b[4];
char R[4];
void loop()
{
//Receiving part
while(Serial.available() == 0){}
Serial.readBytes(R, 4); // Read 4 bytes and write it to R[4]
n = R[0] | (R[1] << 8) | (R[2] << 16) | (R[3] << 24); // assembly the char array
//Sending part
IntegerToBytes(n, b); // Convert the long integer to byte array
for (int i=0; i<4; ++i)
{
Serial.write((int)b[i]);
}
delay(20);
}
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);
}
当我运行应用程序时,它会正确发送直到 127。当我开始发送大于 127 的值时,arduino 会向我发送 -127、-126、.. 等等。我不知道问题是来自 C# 发送还是从 Arduino 读取。
【问题讨论】:
标签: c# serial-port arduino send