简体   繁体   中英

SerialPort reading process doesn't work properly in C#

I'm developing an application which communicates with my electronic circuit via Port 4. I can send data from the PC to the circuit without a problem; I then get data back from the circuit. However, when I try to get data from my circuit for the second time, I receive incorrect data from it. Any pointers on how to solve this?

This is C# code:

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); 
}

This is Arduino code:

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);
    }
  }
}

I found the solution.

I changed this code

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
            serialPort1.Read(Received_Byte, 0, 10); 
}

into this one

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());
            }
    }

Thanks everyone for helping me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM