Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Serial Communication in C#

0.00/5 (No votes)
11 Nov 2007 1  
Serail Communication in .Net connecting GSM Modem

Introduction

If there is an interaction between pc to hardware most of the time we are communicating either through serial port or parallel. Here we will see how serial communication is done in .Net 2003 using Microsoft communication control (Mscomm). There are of course many ways we can communicate serially without using Mscomm control.

Communication happens through com ports in PC. We choose a com port open it. Before we open com port we are going to set com properties like baud rate, parity bit, handshaking, input mode etc.

Mscomm control allows you to establish connection to a serial port connect to another computer or modem, issue commands and responds to various events.

Adding Mscomm control in .Net

Note: MSCOMM32.OCX is a registered Microsoft component it comes with Visual basic 6.0

Go to Tools -> Add/Remove Items.

Click on Com Components tab.

Click on browse then go to Windows - > System 32 folder

Choose file type as Com components, choose MSCOMM32.OCX click on open.

Click on Ok button of Customize Toolbox.

Setting Mscomm properties before opening com port

Select and add the "Microsoft Communications Control, version 6.0" control

(Telephone control) onto your form. Set its name property to com

Using the code

Collapse
    
private void InitComPort() 
{ 

           // Set the com port to be 1 


           com.CommPort = 1; 

           // Trigger the OnComm event whenever data is received 


           com.RThreshold = 1; 

           // Set the port to 9600 baud, no parity bit, 8 data bits, 1 stop bit (all standard) 


           com.Settings = "9600, n, 8, 1"; 

           com.RTSEnable=true; 

           // No handshaking is used 


           com.Handshaking = MSCommLib.HandshakeConstants.comNone; 

           // Use this line instead for byte array input, best for most communications 


           com.InputMode = MSCommLib.InputModeConstants.comInputModeText; 

           // Read the entire waiting data when com.Input is used 


           com.InputLen = 0; 

           // Don't discard nulls, 0x00 is a useful byte 


           com.NullDiscard = false; 

           // Attach the event handler 


           com.OnComm += new System.EventHandler(this.OnComm); 

} 

Call InitComPort() method in form load or in form's constructor after InitializeComponent(). Note: We can set the input mode property of com to Text mode or binary mode. OnComm Event

OnComm Event

The OnComm event is used to handle the communication events. The OnComm also handles communication errors.

In order to call OnComm event of comm component we have to set Rthreshold property to 1 and attach an event handler. We can either loop through input buffer if input buffer count is greater than 0 and read data until some specified time is elapsed and then process the data or you can use OnComm events to receive output data from hardware.

You can either wait for characters to be received

 do
     Application.DoEvents();
 while com.InputBufferCount >= 5 

Wait for five characters to receive and then you can process the read data. Properties of Mscomm

Properties of Mscomm

Break Property:

If the break property is set to true suspends the transmission of characters until you set it false. If you want you can place a timer where you can set some delay and set the break property to false.

CTS Property:

Clear to send property usually sent from modem to computer to indicate the transmission can proceed. If CTS property returns true when polled you can send command.

Com port property:

You can set the com port value between 1 to 16. If port doesn't exist Mscomm generates device error 68.

In Buffer Count:

It refers to the number of characters waiting in the buffer that you can read, if InBufferCount > 0 you can read the data.

CommEvent Property:

Returns the most recent error or event occurred, to determine the actual event or error occurred you must reference commEvent property.

Communication errors:

comEventBreak -> a break signal is received.

comEventFrame -> Hardware detected a framing error.

comEventOverrun -> a character was not read from the hardware, before the next character arrived and was lost.

comEventRxOver -> Receive buffer overflow.

comEventRxParity -> Hardware detected a parity error.

comEventTxFull -> Transmit buffer full.

comEventDCB -> unexpected error retrieving Device control block for the port.

Communication events:

comEvSend: There is fewer than SThreshold number of characters in transmitting buffer.

comEvReceive: Received RThreshold number of characters. This event is generated continuously until you read the data from the receiving buffer.

comEvCTS: change is clear to send line.

comEvDSR: change in data set ready line, this event is generated only when DSR changes from 1 to 0.

comEvCD: changes in Carrier detect line.

comEvRing: Ring detected note some UART's may not support this.

comEvEOF: End of file character received.

Output property:

Is used to write a stream of data to transmit buffer. You can write either in text or binary mode. If in text mode you can send a string or else byte array in case of binary mode.

Port Open:

Setting the PortOpen property to true opens comm port.

Note: make sure that a com port is set to valid port number.

RThreshold Property:

If RThreshold property is set to zero OnComm events is not generated, if you want to read the response you can poll and read.

If RThreshold is not set to zero, OnComm event is generated and comEvent Property is set to comEvReceive. You can read RThreshold number of bytes from receiving buffer.

SThreshold Property:

Setting SThreshold property to 0 disables generating OnComm event for data transmission. If you want to generate comEvSend event to occur once the number of character crosses SThreshold value.

If say SThreshold is set to 1, comEvSend event is generated when the transmitting buffer is completely empty.

Settings Property:


It is used to set baud rate, parity check, number of data bits, stop bit.

Syntax: object. Setting = <value>

Value is composed of "BBBB, P, D, S"

Where BBBB -> baud rate

P -> parity bit

D -> number of data bits

S -> number of stop bits

The default value "9600, N, 8, 1"

OutBufferCount Property:

Returns the number of characters currently waiting in the transmitting buffer. You can also use this to clear the transmitting buffer by setting OutBufferCount property to 0.

OutBufferSize Property:

Returns the total size of the transmitting buffer, default value is 512 bytes.

NullDiscard Property:

If set to false Null characters are transferred from port to receiving buffer it is set by default. If not to receive then set this property to true.

Handshaking Property:

Handshaking property ensures that data is not lost due to buffer overrun. When the data from the hardware is received and directly read without moving into receiving buffer there may be chances of losing some characters because the characters may arrive too quickly. You can use Handshaking property and synchronize the communication.

The Handshaking property can be set to following values

comNone -> No handshaking.

comXonXoff -> XON/XOFF handshaking.

comRTS -> Request to send / Clear to send handshaking.

comRTSXonXoff -> both request to send and XON/XOFF handshaking.

InputMode Property:

It determines how the data will be retrieved through input property; you can read the data either is string or binary data in byte array.

Using Code

Here we will see how you can Serial communicate is done between 2 systems using GSM Modems

The following things are done here

Dial GSM number from one system by clicking Dial button from one system.

From another system send command to accept the call (Data).

You will get a response CONNET 9600 when the connection is established between 2 modems connected to different systems.

Once the data call is established you can send data, it's received on other end.

Similarly you can send data from another system.

To send message after connection type some messages and click on Send button.

To disconnect the connection you can disconnect in any end just by closing the com port. In GUI you should click on Disconnect button.

Note: after connecting GSM modem dial from one system by clicking Dial button, on other system you will get the response as RING, RING now you can connect by specifying command ATA\n and then send CONNECT 9600\n which will establish the connection.

Initialize com port by calling InitComPort().

public Form1() 
{ 
        // Initialize Form Components 

           InitializeComponent(); 
        // Initialize the COM Port control 

           InitComPort(); 
}

The OnComm event shown below receives when ever there is a response from hardware. Note the Input mode of com port is set to Textmode so that you can process the text read. Sleep for a while until you receive full response then read the response using com.Input. ProcessResponseText is used to display the response in Rich Text box.

Collapse
private void OnComm(object sender, EventArgs e) 
{ 

        // Wait for Some mili-seconds then process 

        // The response. 

        Thread.Sleep(200); 
        if (com.InBufferCount > 0) 
        { 
            try 
            {   

                // If you want to receive data in Binary mode 


                // Remove below 2 comment lines // and comment lines for Process response in 


                // Text mode. 


                //byte[] b1=(byte[])com.Input; 


                //ProcessResponseBinary(b1); 


                // Process response in Text mode. 


                string response=(string)com.Input; 

                ProcessResponseText(response); 

            } 
            catch(Exception ex) 
            { 
                MessageBox.Show(ex.Message, this.Text, 
                MessageBoxButtons.OK,MessageBoxIcon.Information); 
            } 
        } 
} 

The input string contains CONNECT 9600 when the connection is established from GSM Modem. Note: while you communicate between 2 systems using GSM modem, say for example by using WaveComm modem. The SIM must be enabled for making data calls in such case after connection you can send data across the system.

If you receive Text data as response

private void ProcessResponseText(string input) 
{ 

        // Send incoming data to a Rich Text Box 

        if( input.Trim().Equals("RING")) 
        { 
            Message.Text="Ring..."; 
        } 
        else 
        if( input.Trim().Equals("CONNECT 9600")) 
        { 
            MessageBox.Show(input.Trim(), this.Text, 
            MessageBoxButtons.OK,MessageBoxIcon.Information); 
        } 
        else 
        { 
            MessageBox.Show(input.Trim(), this.Text, 
            MessageBoxButtons.OK,MessageBoxIcon.Information); 
            Message.Text=input.Trim(); 
        }
        
        // Append output response to RichText Box

        rtfTerminal.AppendText(input + "\n");
}

When the user clicks on Dial Button send AT command to dial other modem. The command for dialing is ATD\n.

private void btn_dial_Click(object sender, System.EventArgs e) 
{ 

        if( txt_phoneno.Text.Trim().Equals("")) 
        { 
            MessageBox.Show("Please Specify Phone Number", this.Text, 
            MessageBoxButtons.OK,MessageBoxIcon.Information); 
            txt_phoneno.Focus(); 
            return; 
        } 

        if(! com.PortOpen ) 
        com.PortOpen=true; 

        // GSM Command Dial a Modem 

        // ATD<phonenumber>\n 


        string gsm_command="ATD"; 
        string phone_number=txt_phoneno.Text.Trim(); 
        string command1=gsm_command + phone_number + "\n"; 
        byte[]command_to_dial=System.Text.ASCIIEncoding.Default.GetBytes (command1); 
        com.Output=command_to_dial; 
        Message.Text="Dialing..."; 

} 

To disconnect connection the Disconnect Button is clicked which will set com.PortOpen to false

private void btn_disconnect_Click(object sender, System.EventArgs e) 
{ 

        // If com port is open then close it 

        // to disconnect connection 


        if( com.PortOpen ) 
        { 
            com.PortOpen=false; 
            MessageBox.Show("Disconnected...", this.Text, 
            MessageBoxButtons.OK,MessageBoxIcon.Information); 
            Message.Text=""; 
            rtfTerminal.Text=""; 
        } 
} 

To send messages click on Send Button after typing some messages. If you are communicating using GSM modem by sending commands then you have to send a byte array. Or else you can send messages as plain text.

private void btn_sendmessage_Click(object sender, System.EventArgs e) 
{ 

        string msg=""; 
        if( txt_sendmessage.Text.Trim().Equals("")) 
        { 
            MessageBox.Show("Please Specify Command", this.Text, 
            MessageBoxButtons.OK,MessageBoxIcon.Information); 
            txt_sendmessage.Focus(); 
            return; 
        } 

        if(! com.PortOpen ) 
        com.PortOpen=true; 

        // To send text messages 

        // If you are using GSM Modem and you want to send 

        // Command then use GetByes of your message 

        // To send Byte data from com port 


        msg=txt_sendmessage.Text.Trim() + "\n"; 
        com.Output = System.Text.ASCIIEncoding.Default.GetBytes(msg); 

        // Or Else If systems are connected with Serial 

        // Cable, Output simple text directly 

        // com.Output= txt_sendmessage.Text; 


        Message.Text="Message Sent...."; 
} 

Points of Interest

Communicating through Serial port is very interesting topic, that too using GSM modems you can do lot many things like you can programmatically send SMS , remote communication etc.

Conclusion

Nice playing with Serial port , This serial demo project would'nt be completed unless I thank Noah Coad (noah@coad.net) becuase of him I learnt Serial communication , worked and modified his sample code and communicated with GSM modem.

Reference

Click Here to Noah Coad' s Serial Communication Artical

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here