Search code examples
c#arduinoserial-portserial-communication

C# communication from Arduino to a UI written in WPF


I want to receive data via serial port. I want to show this data in a textbox on a UI written in C# -- WPF

I understand that the UI and the comms. run on 2 different threads, but I am unable to get much further.

How can I do this?


Solution

  • They don't necessarily need to run on different threads. Generally with a serial port class, it will have a callback mechanism when data is received, which you can hook in your WPF models. Have you read the official MS documentation?

    From this article (3rd item on Google for "wpf serial port communication example")

    Receiving Data

    Now that we have a serial port, it important to set up a function call for every time the serial port has data to be read out. This is far more efficient that producing a thread, polling for data and waiting for a time out exception. To do this, we simply introduce the following code:

    serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
    

    This will call the Recieve function every time data is received. Within this function, we read the data out to a String called recieved_data and then we Invoke a function to write this data to our form. To enable Invoke, we have to include:

    using System.Windows.Threading;
    
    private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        // Collecting the characters received to our 'buffer' (string).
        recieved_data = serial.ReadExisting();
        Dispatcher.Invoke(DispatcherPriority.Send, 
        new UpdateUiTextDelegate(WriteData), recieved_data);
    }