Search code examples
c#.netserial-portserial-communication

how to write and read to serialPort in same time?


I have some device that i need to make a connection using SerialPort. This device receiving commands from my side and also sending data to me. I doing all the send/receive in same class => same thread.

I have been connected to this device and i succeed to send/receive command and data from/to this device.

One of the command that i need to send every 25 milliseconds is 'give me your status' - that mean that i asking the device to send be back some struct with data.

In case i missing some receiving data ... when i doing 'serialPortStream.BytesToRead' ( test if there are some data to get ) will i find on my ByteReading the older buffer that i did not rad yet ? how many packages i will have there in case i missed the last package that i needed to read or maybe the new data received will delete the old data that alread received before ?


Solution

  • Use an OnRecieveData handler that saves the data to a ConcurrentQueue or something similar.

    namespace Test
    {   class Program
        {
            const int bufSize = 2048;
            static void Main(string[] args)
            {
    
                Byte[] buf = new Byte[bufSize]; 
                SerialPort sp = new SerialPort("COM1", 115200);
                sp.DataReceived += port_OnReceiveData; // Add DataReceived Event Handler
    
                sp.Open();
    
                // Wait for data or user input to continue.
                Console.ReadLine();
    
    
                sp.Close();
            }
    
            private static void port_OnReceiveData(object sender,  SerialDataReceivedEventArgs e)
            {
                SerialPort port = (SerialPort) sender;
                switch(e.EventType)
                {
                    case SerialData.Chars:
                    {
                        Byte[] buf = new Byte[bufSize];
                        port.Read(buf, 0, bufSize)
                        Console.WriteLine("Recieved data! " + buf.ToString());
                        break;
                    }
                    case SerialData.Eof:
                    {
                        // means receiving ended
                        break;
                    }
                }
            }
        }
    }