Send Arduino String to C# via Serial

Asked

Viewed 1,388 times

0

I need to send Arduino Strings to C# in real time via Serial communication.

In the Arduino code I am using the following to send:

if (Serial.available()) //se byte pronto para leitura
{
   switch(Serial.read())      //verifica qual caracter recebido
   {
      case 'T':
          Serial.print("STATUS");
      break:
   }
}

And in C# to receive the string:

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   RxString = serialPort1.ReadExisting();
   Console.WriteLine(RxString);
}

EXIT:

ST

ATUS

ST

ATUS

STAT

US

ST

ATUS

ST

ATUS

STAT

US

S

However, I am getting the broken string. What am I missing? Is there a better way to do this?

  • 3

    Only with this excerpt can not know. Add relevant parts of the code.

  • If possible show the exit, showing the problem and show your code better, otherwise it becomes complicated to help.

  • I just updated you guys. There’s not much in the code.

1 answer

1


This is what is expected of a serial communication.

There is no separation between the data sent and no guarantee that they will all arrive at once.

Following his example, there is no guarantee that a single call to Serial.print cannot reach several parts of your program in C#, as can happen from several consecutive calls to Serial.print made in a very short period all come together at once in your C program#.

So basically it’s up to you to create a way to handle the data correctly, not only to know if the entire data has arrived but also to separate if data comes from more than one message at the same time.

I would say that the most basic that can be a text-based protocol would be the use of a delimiter, for example on Arduin you would mark the end of the message with some character that you are sure will never be used, such as a #

Serial.print("STATUS#");

So in C# you need to do two things, first of all you need to create a buffer to store the data, because it can get less data than necessary, then everything that comes in you add in this buffer, after adding the data in the buffer you check if you have enough data to handle, if you have then you start processing the buffer and only for when you see that the buffer is empty or that the data in it is not enough to process.

//buffer usado para guardar as mensagens, iniciado como uma string vazia
string buffer = "";

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    //sempre recebe os dados adicionando no final do buffer
    buffer += serialPort1.ReadExisting();
    //depois de receber os dados verifica se possui uma mensagem inteira nele
    //devemos fazer isso em um loop pois pode acontecer de chegar mais de uma
    //mensagem ao mesmo tempo
    int idx;
    while((idx = buffer.IndeOf('#')) >= 0)
    {
        //separamos a primeira mensagem do buffer sem o delimitador
        string mensagem = buffer.Substring(0, idx);
        //tratamos ela da forma que for necessário
        Console.WriteLine(mensagem);
        //por fim removemos ela do buffer
        buffer = buffer.Substring(idx + 1);
    }
}

Remembering that any information not processed because it is insufficient was in the buffer, in case the communication for some reason is interrupted and needs to be started again you may need to clean this buffer.

Have to always take into account also that serial communication may not be very reliable, I’ve had a case where communication with a device from time to time lost a byte, It was a limitation of the device hardware and had nothing to do, I had to take this into consideration and ignore when I detected a message that was incomplete.

This same logic applies practically to any type of serial communication, be it a serial port, TCP/IP or Bluetooth using RFCOMM for example.

  • Thank you very much for the instruction Leandro, grade 10! I will put into practice and put the result. I’m making an application to monitor multiple sensors in real time and at the same time. After this communication by COM port, I want to do by TCP/IP or UDP tbm.

  • It worked perfectly! Thank you Leandro.

  • Leandro good night. I had a similar problem with a TCC project and managed to solve, a part of the problem, with the solution you provided.Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.