Example of C serial communication program

  • 2020-05-26 09:56:34
  • OfStack

Creates a namespace for the C# serial communication program

The most reused class in the System.IO.Ports namespace is the SerialPort class.

Create SerialPort object for C# serial communication program

By creating the SerialPort object, we can control the whole process of serial communication in the program.

The SerialPort class method we will use:

ReadLine() : reads the value of a new line of 1 from the input buffer. If not, NULL is returned
WriteLine(string) : writes to the output buffer
Open() : opens a new serial connection
Close () : closed


SerialPort sp = new SerialPort (); 

By default, the DataBits value is 8, StopBits is 1, and the communication port is COM1. These can all be reset in the following properties:

BaudRate: baud rate of serial port
StopBits: the number of stop bits per byte
ReadTimeout: stop time when a read operation does not complete. Units in milliseconds
There are quite a few other public properties, check out MSDN for yourself.

Create hardware knowledge of the serial port of the C# serial port communication program

During data transmission, each byte of data is transmitted over a single cable. The package includes the start bit, the data, and the end. Once the first bit comes out, the next bit comes in, maybe 5,6,7, or 8 bits, depending on your Settings. The same baud rate and data number must be set for sending and receiving.

Create a cat-free mode for the C# serial communication program

The cables without Modem mode simply cross the transmission and reception lines. The same DTR & DSR and RTS & CTS also needs to cross. Here, we have three lines. Interconnect 2 and 3 (2pin of segment 1 connects 3pin), connecting 5pin at both ends.

Create the C# serial port communicator sample program

If you want to use the default property, press the "Save Status" button, and if you want to change the property, press "Property". After setting, you can communicate.

The code for the main window


#region Using directives  
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Windows.Forms;  
using System.IO.Ports;  

#endregion  
namespace Serialexpample
{
    partial class Form1 : Form
    {
        //create instance of property page  
        //property page is used to set values for stop bits and  
        //baud rate  
        PropertyPage pp = new PropertyPage();
        //create an Serial Port object  
        SerialPort sp = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }
        private void propertyButton_Click(object sender, EventArgs e)
        {
            //show property dialog  
            pp.ShowDialog();
            propertyButton.Hide();
        }
        private void sendButton_Click(object sender, EventArgs e)
        {
            try
            {
                //write line to serial port  
                sp.WriteLine(textBox.Text);
                //clear the text box  
                textBox.Text = "";
            }
            catch (System.Exception ex)
            {
                baudRatelLabel.Text = ex.Message;
            }
        }
        private void ReadButton_Click(object sender, EventArgs e)
        {
            try
            {
                //clear the text box  
                textBox.Text = "";
                //read serial port and displayed the data in text box  
                textBox.Text = sp.ReadLine();
            }
            catch (System.Exception ex)
            {
                baudRatelLabel.Text = ex.Message;
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("Do u want to Close the App");
            sp.Close();
        }
        private void startCommButton_Click(object sender, EventArgs e)
        {
            startCommButton.Hide();
            sendButton.Show();
            readButton.Show();
            textBox.Show();
        }
        //when we want to save the status(value)  
        private void saveStatusButton_Click_1(object sender, EventArgs e)
        {
            //display values  
            //if no property is set the default values  
            if (pp.bRate == "" && pp.sBits == "")
            {
                dataBitLabel.Text = "BaudRate = " +
                 sp.BaudRate.ToString();
                readTimeOutLabel.Text = "StopBits = " +
                sp.StopBits.ToString();
            }
            else
            {
                dataBitLabel.Text = "BaudRate = " +
                 pp.bRate;
                readTimeOutLabel.Text = "StopBits = " + pp.sBits;
            }  // create C# Serial communication program 
            parityLabel.Text = "DataBits = " +
             sp.DataBits.ToString();
            stopBitLabel.Text = "Parity = " +
             sp.Parity.ToString();
            readTimeOutLabel.Text = "ReadTimeout = " +
              sp.ReadTimeout.ToString();
            if (propertyButton.Visible == true)
                propertyButton.Hide();
            saveStatusButton.Hide();
            startCommButton.Show();
            try
            {
                //open serial port  
                sp.Open();
                //set read time out to 500 ms  
                sp.ReadTimeout = 500;
            }
            catch (System.Exception ex)
            {
                baudRatelLabel.Text = ex.Message;
            }
        }
    }
}

Create C# serial communication program property setting dialog code:


#region Using directives  
using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  

#endregion  
namespace Serialexpample
{
    partial class PropertyPage : Form
    {
        //variables for storing values of baud rate and stop bits  
        private string baudR = "";
        private string stopB = "";
        //property for setting and getting baud rate and stop bits  
        public string bRate
        {
            get
            {
                return baudR;
            }
            set
            {
                baudR = value;
            }
        }
        public string sBits
        {
            get
            {
                return stopB;
            }
            set
            {
                stopB = value;
            }
        }
        public PropertyPage()
        {
            InitializeComponent();
        }
        private void cancelButton_Click(object sender, EventArgs e)
        {
            this.bRate = "";
            this.sBits = "";
            //close form  
            this.Close();
        }
        private void okButton_Click_1(object sender, EventArgs e)
        {
            //here we set the value for stop bits and baud rate.  
            this.bRate = BaudRateComboBox.Text;
            this.sBits = stopBitComboBox.Text;
            //  
            this.Close();
        }
    }
}

C# serial communication program to create the relevant content to introduce you here, hope to know you create C# serial communication program steps and matters needing attention.


Related articles: