我正在开发一个通过端口4与我的电子电路通信的应用程序。我可以毫无问题地将数据从PC发送到电路;然后我从电路中获取数据。但是,当我第二次尝试从我的电路中获取数据时,我收到了错误的数据。关于如何解决这个问题的任何指示?
这是C#代码:
byte[] Sent_Byte = {1,2,3,4,5,6};
byte[] Received_Byte = new byte[10];
private void button_sendData_Click(object sender, EventArgs e)
{
// I send this data because the circuit is ready to get data
serialPort1.Write("G");
serialPort1.Write(Sent_Byte, 0, 6);
}
private void button_getData_Click(object sender, EventArgs e)
{
// I send this data because the circuit is ready to send data
serialPort1.Write("A");
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialPort1.Read(Received_Byte, 0, 10);
}
这是Arduino代码:
char Control_OP=0;
char Received_Data[6];
byte Sent_Data[10];
void loop()
{
while(Serial.available())
{
Control_OP = Serial.read(); // determines whether receiving data or sending data
if(Control_OP=='G') // receiving data
{
Number=Serial.readBytes(Received_Data,6);
}
else if(Control_OP=='A') // sending data
{
Serial.write(Sent_Data,10);
}
}
}
答案 0 :(得分:0)
我找到了解决方案。
我更改了此代码
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
serialPort1.Read(Received_Byte, 0, 10);
}
进入这个
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
for (int i = 0; i <Received_Byte.Length; i++)
{
Received_Byte[i] = Convert.ToByte(serialPort1.ReadByte());
}
}
感谢大家帮助我