Saturday, December 9, 2017

Serial Port with Efficient Data reading in C#



  • I am  not good at writing but below is few from my collection.
  • Declare the Port variable globally in a form.


    1. SerialPort Port;   
    2. string PORT_NUMBER = "YOUR PORT NUMBER" ;   
  • Set the port properties in Form load. 

try  
{  
   Port = new SerialPort("COM" + PORT_NUMBER.ToString());  
   Port.BaudRate = 115200;  
   Port.DataBits = 8;  
   Port.Parity = Parity.None;  
   Port.StopBits = StopBits.One;  
   Port.Handshake = Handshake.None;  
   Port.DtrEnable = true;  
   Port.NewLine = Environment.NewLine;  
   Port.ReceivedBytesThreshold = 1024;  
   Port.Open();  
  
}  
catch (Exception ex)  
{  
   MessageBox.Show("Error accessing port." + Environment.NewLine + ex.Message, "Port Error!!!", MessageBoxButtons.OK);  
   Port.Dispose();  
   Application.Exit();  
}   
  
  • Above is the basic procedure and easy to understand.
  • Now create following function which will be helpful to read data from serial port simultaneously. 

private void ReadEvent()  
{
byte[] buffer = new byte[2000];  
Action kickoffRead = null;  
kickoffRead = (Action)(() => Port.BaseStream.BeginRead(buffer, 0, buffer.Length, delegate(IAsyncResult ar)  
{  
    try  
    {  
        int count = Port.BaseStream.EndRead(ar);  
        byte[] dst = new byte[count];  
        Buffer.BlockCopy(buffer, 0, dst, 0, count);  
        RaiseAppSerialDataEvent(dst);  
    }  
    catch (Exception exception)  
    {  
        MessageBox.Show(ERROR == > " + exception.ToString());    
    }  
    kickoffRead();  
}, null)); kickoffRead();  
}  

    //To decode the received data from the port.   
    private void RaiseAppSerialDataEvent(byte[] Data)  
    {  
        string Result = Encoding.Default.GetString(Data);  
         TextBox1.Invoke((Action)delegate   
    {  
       TextBox1.Text=Result; TextBox1.Refresh();   
    });   
    }  



    It will keep assigning same event when data received.

    Port.BaseStream.BeginRead 

    Never fails and will give you each and every bit from the Port.
    To invoke this you need to Call Port.WriteLine("AT COMMAND");
    Hope it helps someone who is stuck with ports.
     

    3 comments :

    1. This comment has been removed by the author.

      ReplyDelete
    2. Very good Excellent articular and very helpful , easily apply and run successfully

      ReplyDelete
    3. Wow!!
      Excellent job , easily applicable and
      run successfully.
      Thanks

      ReplyDelete