Read serial input in C#

NET%20LogoHere’s a simple code snippet to read the serial inputs in C#. I had to use this code several times when working with arduino like devices.

Hope you’ll enjoy it.
Catch you next time and keep it bug free !

    using System;
    using System.IO.Ports;

    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            new Program();
        }

        // Create the serial port with basic settings
        // port name, bauds, parity, packet size and stop bits.
        private SerialPort port = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.Two);

        private Program()
        {
            // Called when data received through serial
            port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

            // Can crash if the port is already used, haven't found a way to detect it...
            try
            {
                // Start to listen
                port.Open();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            // Just avoid console to return
            Console.ReadKey();
        }

        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            // Write the incoming data
            Console.Write(port.ReadExisting());
        }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s