C# 串行端口读取过程在C中无法正常工作
我正在开发一个应用程序,它通过端口4与我的电子电路通信。我可以发送数据从PC到电路没有问题;然后我从电路中获取数据。但是,当我第二次尝试从电路中获取数据时,我从电路中接收到不正确的数据。有关于如何解决这个问题的建议吗 这是C代码:C# 串行端口读取过程在C中无法正常工作,c#,serial-port,arduino,C#,Serial Port,Arduino,我正在开发一个应用程序,它通过端口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)
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);
}
}
}
我找到了解决办法
我更改了这个密码
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());
}
}
谢谢大家帮助我像hyperterm这样的终端程序能用吗?不是这样的。它有四个按钮。连接、断开连接、发送数据和获取数据不是这样的吗?你的电路不在乎有4个按钮,是吗?如果它是通过串行端口进行通信,那么您应该能够使用类似超级终端的东西与它进行通信。只需打开一个具有适当设置的连接,然后尝试发送一个,看看它是否有响应。这是基本的串行通信故障排除。数字==串行。readBytesReceived_数据,6;是错误的,因为==无论如何,你期望什么数据,你收到什么?@MattBurland我连接它,通过单击sendData按钮将数据从PC发送到电路,没有任何问题。如果我在向电路发送数据后试图从电路中获取数据,我将失败。我得到的数据不正确。但是,如果我执行程序并连接电路并尝试获取数据,它就会正常工作。获取数据可以立即正常工作