Sunday 5 July 2020

Reading USB (Serial) data

Most microcontrollers have an option to output data over the USB link.

It is helpful during development to be able to read state information and other values that allow the developer to see what is happening.

The first thing is to identify which USB port is in use.
            foreach (string port in ports)
            {
                Console.WriteLine(port);
            }
For my set up, COM5 was the one in use.
using (var sp = new System.IO.Ports.SerialPort("COM5", 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One))
            {
                Console.WriteLine("Reading serial port");
                sp.Open();
                while (true)
                {
                    var readData = sp.ReadLine();
                    Console.WriteLine($"[{readData}]");
                }
            }
This will display on the console anything output from the device.