Home Programming Articles C# Articles Reading & Writing to Serial port in Console mode
Reading & Writing to Serial port in Console mode PDF Print E-mail
Written by Michael   
Wednesday, 10 June 2009 16:54

While working on a project at university i had to make use of the RS232 serial port and be able to both transmit and receive data asynchronously. Many examples were available to do this in a GUI form, however examples were limited in terms of using the serial port in console mode.

This article describes the method with which i was able to achieve this.

 

Method

First we create a string named inputbuf to represent the area with which we wish to store the received data. We then create a new SerialPort object and set its properties as with the GUI version.

Then we must declare an event handler for when the serial port receives data. When this happens it calls the function port_OnReceiveDatazz.

 
serialPort1.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
 

The port_OnReceiveDatazz function is fairly self explainatory. First is clears the current contents of the inputbuf and then reads the contents of the hardware buffer into a byte array and then converts each byte in turn to a string, and stores them under the inputbuf variable.

        
private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
{
   inputbuf = "";
   SerialPort spL = (SerialPort) sender;
   byte[] buf = new byte[spL.BytesToRead];
   //Console.WriteLine("DATA RECEIVED!");
   spL.Read(buf, 0, buf.Length);
   foreach (char b in buf)
   {
      inputbuf = (inputbuf + b.ToString());
   }
   //Uncomment next line to write received string to screen
   //Console.WriteLine(inputbuf);
}
        

Something thats important to consider about this approach is that it will only read about 16 characters before clearing the inputbuf. An alternative method would be to NOT clear the inputbuf at the beginning, keep adding chars to the buffer and check if it exceeds a certain length or periodically delete the received data once you have dealt with it.

 

 

Full Listing

/*
 * Created by SharpDevelop.
 * User: Michael Jones
 * Date: 11/02/2009
 * Time: 12:29
 */
using System;
using System.IO.Ports;

namespace ConsoleSerialPort
{    
    class Program
    {
        public static string inputbuf;
        private SerialPort serialPort1 = new SerialPort("COM1");
        
        public static void Main(string[] args)
        {
            new Program();
        }
        
        private Program()
        {
            //--------------
            //Setup Port
            //--------------
            serialPort1.BaudRate=9600;
            serialPort1.DataBits=8;
            serialPort1.Parity=Parity.None;
            serialPort1.StopBits=StopBits.One;
            serialPort1.DtrEnable = true;    // Data-terminal-ready
            serialPort1.RtsEnable = true;    // Request-to-send
            
            //--------------
            //open port
            //--------------
            try
            {
            serialPort1.Open();    
            }
            catch
            {
                //errors
                Console.WriteLine("Unable to open COM1 - ERROR");
                Console.ReadLine();
                Environment.Exit(0);
            }
            serialPort1.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

            //---------------------------
            //If no args go to user mode
            //---------------------------
            
                serialPort1.Write(command);
            
            //--------------------------
            //Close and Exit
            //--------------------------
            serialPort1.Close();
            Environment.Exit(0);
        }
        
        private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
        {
            inputbuf = "";
            SerialPort spL = (SerialPort) sender;
            byte[] buf = new byte[spL.BytesToRead];
            //Console.WriteLine("DATA RECEIVED!");
            spL.Read(buf, 0, buf.Length);
            foreach (char b in buf)
            {
                inputbuf = (inputbuf + b.ToString());
            }
            //Uncomment next line to write received string to screen
            //Console.WriteLine(inputbuf);
        }
        
    }
}
Last Updated on Friday, 17 July 2009 19:36
 
User Rating: / 0
PoorBest      
Copyright © 2012 Michael-Jones.name. All Rights Reserved.