Losing data when communicating with C#

Question:

My Arduino continuously sends data to my C# application via Serial port . However, I notice that the first values ​​sent by Arduino are simply disappearing, sometimes adding more numbers, sometimes less, and always only at the beginning of the application. Example:

Arduino sends -> "0 1 100 1023 45 67 …"

C# gets -> "1023 45 67…" or "1 100 1023 45 67…"

I'm currently printing on Serial as follows:

//ARDUINO:

int CANAL1, CANAL2, CANAL3;

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    analogReference(DEFAULT);
    CANAL1 = analogRead(A0);
    Serial.print(CANAL1,DEC);
    Serial.print(" ");
    CANAL2 = analogRead(A1);  
    Serial.print(CANAL2,DEC);
    Serial.print(" ");
    CANAL3 = analogRead(A2);
    Serial.print(CANAL3,DEC);
    Serial.print(" ");
}

And in my C# application, data reception is done as follows:

//C#

string RxString = "";

private void SerialCOM_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if (SerialCOM.IsOpen)
    {
        SerialPort sData = (SerialPort)sender;
        {
            RxString += sData.ReadExisting();
        }
    }
}

This type of problem could not happen in my application, as it would trigger problems with other functions.

Is there something wrong with receiving or sending information? I've done and redone this many times and every time this problem happens.

Answer:

See if the code below works. In the method you receive the data. This is usually how I get data from Arduino.

private List<byte> byte_buffer = new List<byte>();

private void SerialCOM_DataReceived(object sender, SerialDataReceivedEventArgs e) {

byte_buffer.Clear();
while (SerialCOM.BytesToRead > 0) {
  byte_buffer.Add((byte)SerialCOM.ReadByte());
}
}

The received data is added to a List. If you want, you can use byte_buffer.ToString() to print the received string.

I apologize in case of any mistake. I'm on my cell phone, I can't test until I get home.

Scroll to Top