Serial Port ( RS232 protocol )

Category :




serial port


Serial Port atau lebih popular dengan nama RS232 adalah protocol/interface yang paling banyak digunakan dan popular terutamanya di kalangan pelajar. Rs232 protocol mudah digunakan, incorporated in PC(mostly old PCs), some microcontroller dan tidak memerlukan hardware yg expensive. But today,USB lebih popular kerana mudah, plug n play, and offer higher transfer rates compared to RS232.

I have been using Serial Port for quite some time in a lot of projects. Contohnya, interfacing a robot with external device such as zigbee or bluetooth module. So, i think it's good to write article about serial port/RS232. My objective here is to show the way to write codes to access PC serial port

There are 2 ways to access PC serial port(as far as i know).

  • using mscomm32.ocx
  • .NET object
I prefer the 2nd method because lebih mudah digunakan and i use C#(.NET) a lot. I have written a script in VBA to access serial port from Microsft Excel(using mscomm32.ocx). VBA stand for Visual Basic for Application which is exists in Excel(you probably know it if you're familiar with Excel macro)


.NET component - using C#


If you're familiar with C# or C++ or VB.NET, then it's better jika anda menggunakan .NET component. I will show an example of source code written in C# in this post. First of all, you need to 'define' the component in the project file by a 'using' statement on top of the file.


    using System.IO.Ports;
The above statement will allow you to access serial port component.

    class SerialPortCustom
    {
        SerialPort SP = new SerialPort();      

        public SerialPortCustom()
        {
            SP.BaudRate = 57600;
            SP.Handshake = Handshake.None;
            SP.Parity = Parity.None;
            SP.PortName = " ";
            SP.StopBits = System.IO.Ports.StopBits.One;
            SP.DataBits = 8;
        }
  
 //remaining codes are not displayed ~~~~ 

This is a sample of source code from my past project. I create a class name "SerialPortCustom". This class will handle all the serial port events and function. As you can see, in the class constructor, 6 items were pre-defined. So, my baudrate works at 57600 bps without handshake signal and parity, 1 stop bit and 8 data bits. However, i left portName empty so that i can choose available port later. This just the basic idea how to instantiate .NET serial port component. It is possible if you want to change all the properties in the form later, but you need to write a proper code to handle it.

Next, you must have functions or methods to read data from receive buffer or to write data to transmit buffer. Therefore, you can instantiate event handler for every data received as shown below. However, you can use polling method if your application know the exact time of incoming data/packet.
//instantiate event handler : raised when RX buffer is not empty.
    SP.DataReceived += new SerialDataReceivedEventHandler(SP_DataReceived);
Every data in received buffer will raised the event. Then, it's up to you what you want to do with the data. Just for an example, when the event raised, the method reads up all 4 bytes of the incoming data before calling another function/method as shown below.

 // This event raised if received buffer is full
        public void SP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {        
            stream_buffer[0] = SP.ReadByte();   //read 1st byte
            stream_buffer[1] = SP.ReadByte();   //read another byte and so on
            stream_buffer[2] = SP.ReadByte();
            stream_buffer[3] = SP.ReadByte();
            parsing_display();   //calling another method
        }
Perhaps you also wants to write something through your serial port. Therefore, you can write a function for that purpose. The codes below is just a simple function that accepts 1 byte of data and transmit through serial port(RS232).

 // "write" method
        public void WR_byte(byte byte_data)
        {   
            argv[0] = byte_data;  // argv[] used to hold the data
            SP.Write(argv, 0, 1);  // transmit 1 byte through serial port (com port)
 }
In conclusion, it is easy to use/work with serial port (RS232) using .NET framework. If you are not familiar with C#, you can write in VB and also C++. I wrote the script in VB.NET once for my final year project purpose. The syntax are different but the concept is just the same. Now, let's move on to the next section.


MSCOMM32.OCX - VBA


Selain menggunakan C#/.NET, it is possible to access serial port directly in Microsoft Excel. What you need is just MSCOMM32.ocx and basic knowledge in VBA. However, several steps required before you can start programming.

You need to register the file first so that your VB editor could recognize the components. Place the file in system32 folder and then click start -> run and paste the command below.
    Regsvr32 "C:\Windows\System32\mscomm32.ocx" 
After you completed the lst step, run Microsoft Excel and open VB editor. Same as C#, 2 methods shall be implemented, either event-based or polling method. Polling method is suitable if you know exact time of incoming data.

First, you need to instantiate the object(class).
    Private SerCom As New MSComm 
Then, you need to set properties of the class such as baud rate, handshaking, and so on.
    With SerCom
         .CommPort = com_number
         .Settings = "57600,M,8,1"
         .Handshaking = comNone
         .InputLen = 8
         .InBufferSize = 8
         .NullDiscard = True
         .InputMode = comInputModeText
         .RThreshold = 1
 End With
Next, you can use buttons to enable/disable serial port operation.
    If SerCom.PortOpen = False Then
     SerCom.PortOpen = True                      ' turn on serial port  
       Else
     ' error handling or any code here 
       End If 
My previous project not required event-based method since i know exactly when the transaction will occur.
    ' a piece of code for read and write

     SerCom.InputLen = 0      
    ' Setting InputLen to 0 causes the MSComm control to read the entire
contents of the receive buffer
chdata = Replace(SerCom.Input, vbCrLf, "") ' get a stream of data from the receive buffer ' the codes also remove carriage return and line feed ' access write Public Sub UART_write(ByVal str As String) SerCom.Output = str + vbCrLf ' place any other codes here End Sub
However, if you choose to use event-based method, you need to declare the event first.
    ' declare an event 
    Private WithEvents SerCom As MSCommLib.MSComm
 
     ' this method raised on any event that you define in it.
     Private Sub SerCom_OnComm() 
     If SerCom.CommEvent = 2 Then
      ' read recieve buffer : code goes here 
     ElseIf SerCom.CommEvent = x Then ' x = Communications events/errors
      ' do something else
     End If
     End Sub
Click here for more details.
MSCOMM32.OCX is a native component or API by Microsoft. However, it helps me a lot when my boss asked me to write a macro that can access serial port.
Most PC manufacturer dumps RS232/COM port for USB. However, you can buy RS232(I/O expansion) card or USB to RS232 converter.

2 comments:

Kelly said...

Hello there,

I'm working on the project very much the same with with this http://symqwerty.blogspot.com/2010/02/serial-port-rs232-protocol.html

I'm able to get data from port already, but I'm looking for VB code to control the sensor (transmitter) of RS 232. Could you please help me ....please...
thank you,
Kelly ---> hoa_chieutim@yahoo.com

letthepentalk said...

hello,
I'm trying to make similar application, but using C#. will I be able to do?
It will be very great of you if you can help me out.
Thanks!

Post a Comment