The concept and simple implementation of C-SERIAL communication

Recently, in the research of serial communication, there are several important concepts. RS-232 is suitable for the connection between PC and upper computer. RS-232 is only limited to point-to-point communication between PC serial port and equipment. It is very simple to connect. Because serial communication is asynchronous, that is to say, you can send data to both ends or more at the same time. The data type between them is byte. The most important parameters of serial communication are baud rate, data bit, stop bit and parity. For two ports to communicate, these parameters must match.

Listen to some of the terms about serial communication, what? What, what is this?

Let me tell you about this "little white": the first baud rate, which is involved in different fields. In serial communication, the signal unit between two serial ports is called the symbol. The signal (symbol) transmitted every minute is the baud rate;

Second data bit, stop bit: listen to the name to know what it means. Before the data transfer process, the machine will recognize what your data is, and then adjust different start and stop bits according to this type.

The third parity: I want to know how big and how long your data is, because the transmission is 1 and 0. The specific parity method is as follows:

Odd check: it means that the number of 1 in the original data sequence (including the bit you want to add) is odd - 1000110 (0). You have to add 0, so there are 3 1's that are already odd, so the number of 1 after you add 0 is odd or odd.

Even check: it means that the number of 1 in the original data sequence (including the bit you want to add) is even --- 1000110 (1) you must add 1, so that the number of 3 1 to be even can only add 1.

If you want to play serial communication or analog serial port in C, you must make a hardware first. Of course, we are doing simulation. Then you can make a simulation tool. I'm ready for you to download it

Link: https://pan.baidu.com/s/1tcdgiwmy0i9bikvgdxanazq extraction code: 9uap

After installation, there will be an icon on the desktop, then open it and add a serial port. See the following figure for details

Now we start to implement the code, create a Winform project of. NET Fwk, and then start our code!

SerialPort sp1 = new SerialPort();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] strCom = SerialPort.GetPortNames();
            if (strCom == null)
            {
                MessageBox.Show("This machine has no serial port!", "Error");
                return;
            }
            foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
            {
                cbCom.Items.Add(com);
            }
            cbCom.SelectedIndex = 0;
            sp1.BaudRate = 9600;
            Control.CheckForIllegalCrossThreadCalls = false;
            sp1.DataReceived += Sp1_DataReceived;

            sp1.DtrEnable = true;
            sp1.RtsEnable = true;
            sp1.ReadTimeout = 1000;
            sp1.Close();
        }

In the window loading, we try to obtain all serial ports of the machine. Through the SerialPort.GetPortNames() method, we will return a string array. If not, we will return null. Among them, we also set the baud rate. Through the DataReceived method under the SerialPort class, we can monitor our data return, and enable the DTR\DTS request mode. Through readt Imeout controls the data read timeout.  

Since we listened to the data return, in this method, we read it through ReadTimeOut.Read, directly from 0 to the end, and the interception is completed.

private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (sp1.IsOpen)     //Judge whether to open the serial port
            {
                //Output current time
                DateTime dt = DateTime.Now;
                txtReceived.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
                Byte[] receivedData = new Byte[sp1.BytesToRead];        //Create receive byte array
                sp1.Read(receivedData, 0, receivedData.Length);         //Read data
                AddContent(new UTF8Encoding().GetString(receivedData));
            }
            else
            {
                MessageBox.Show("Please open a serial port", "Error prompt");
            }
        }

        private void AddContent(string v)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                txtReceived.AppendText(v);
                txtReceived.AppendText("\r\n");
            }));
        }

Of course, the above operations can only be carried out after the serial port is opened. It's still quite difficult to open the serial port, because you need to set various parameters, that is, the concepts I just mentioned. If not, you can't find other ports to access.

private void button2_Click(object sender, EventArgs e)
        {
            if (!sp1.IsOpen)
            {
                try
                { 
                    string serialName = cbCom.SelectedItem.ToString();
                    sp1.PortName = serialName;
                    string strBaudRate = cbBaudRate.Text;
                    string strDateBits = cbDataBits.Text;
                    string strStopBits = cbStop.Text;
                    Int32 iBaudRate = Convert.ToInt32(strBaudRate);
                    Int32 iDateBits = Convert.ToInt32(strDateBits);
                    sp1.BaudRate = iBaudRate;       //Baud rate
                    sp1.DataBits = iDateBits;       //Data bits
                    switch (cbStop.Text)            //Stop bit
                    {
                        case "1":
                            sp1.StopBits = StopBits.One;
                            break;
                        case "1.5":
                            sp1.StopBits = StopBits.OnePointFive;
                            break;
                        case "2":
                            sp1.StopBits = StopBits.Two;
                            break;
                        default:
                            MessageBox.Show("Error: parameter is incorrect!", "Error");
                            break;
                    }
                    switch (cbCheck.Text)             //Check bit
                    {
                        case "nothing":
                            sp1.Parity = Parity.None;
                            break;
                        case "Odd check":
                            sp1.Parity = Parity.Odd;
                            break;
                        case "Even check":
                            sp1.Parity = Parity.Even;
                            break;
                        default:
                            MessageBox.Show("Error: parameter is incorrect!", "Error");
                            break;
                    }

                    if (sp1.IsOpen == true)
                    {
                        sp1.Close();
                    }

                    //Set necessary controls not available
                    cbCom.Enabled = false;
                    cbBaudRate.Enabled = false;
                    cbDataBits.Enabled = false;
                    cbStop.Enabled = false;
                    cbCheck.Enabled = false;
                    sp1.Open();     //Open serial port
                    button2.Text = "Close the serial port";
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Error:" + ex.Message, "Error");
                    return;
                }
            }
            else
            {
                cbCom.Enabled = true;
                cbBaudRate.Enabled = true;
                cbDataBits.Enabled = true;
                cbStop.Enabled = true;
                cbCheck.Enabled = true;
                sp1.Close();                    //Close the serial port
                button2.Text = "Open serial port";
            }
        }

Finally, we sent it. Just now we used Read to receive it. Of course, sending is very simple. It's Write

private void button1_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            if (!sp1.IsOpen) //If it doesn't open
            {
                MessageBox.Show("Please open the serial port first!", "Error");
                return;
            }
            String strSend = txtSendStr.Text;
            try
            {
                sendData = Encoding.UTF8.GetBytes(txtSendStr.Text.Trim());
                sp1.Write(sendData, 0, sendData.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message, "Error");
            }

        }

It's still very simple.

Tags: encoding

Posted on Thu, 14 May 2020 01:13:55 -0700 by Yeti