This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Preface:

Last time, the blogger explained the configuration of serial control Serialport. This issue explains the sending and receiving of Serialport. The Serialport serial communication control provides a lot of methods for the communication between the host computer and the microcontroller, which can be convenient for everyone to use and is very simple to use.

Once a day to prevent puppy love:

1.SerialPort configure the SerialPort control to send messages

1.1 With the project of the last article, I set up the project based on that project. If you can’t, you can see the last article of the blogger and put a link (Juejin. Cn/post / 702183…), we first need to set up the interface, send box, receive box, send button

SerialPort provides several interfaces:

public void Write(byte[] buffer, int offset, int count); Writes a specified number of bytes to a serial port using data from the buffer. // buffer: an array of bytes containing the data to be written to the port. // offset: the zero byte offset in the buffer parameter from which bytes are copied to the port. // count: number of bytes to be written. public void Write(string text); Writes the specified string to the serial port. Text: Indicates the output string. public void Write(char[] buffer, int offset, int count); Writes a specified number of characters to a serial port using data from the buffer. // buffer: an array of characters containing the data to be written to the port. // offset: the zero byte offset in the buffer parameter from which bytes are copied to the port. // count: the number of characters to write. public void WriteLine(string text); / / to the specified string and System. IO. Ports. SerialPort. NewLine value written to the output buffer. // text: The string to write to the output buffer.Copy the code
  1. 3. Double-click the send button to automatically generate the method function and write the method we send:

1.4 code is as follows: you can use it directly, provided that your interface is the same as that of the blogger, pay attention to the interface control is not corresponding to the trigger of the blogger function, not to change the trigger of the interface, refer to the previous article.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Serilport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
	   System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void SearchAndAddSerialToComboBox(object sender, EventArgs e)
        {
            string Buffer;
            comboBox1.Items.Clear();    // Records that were scanned before the early Qing Dynasty
            for (int i = 0; i < 20; i++)
            {
                try
                {
                    Buffer = "COM" + i.ToString(); / / get COM1-20
                    serialPort1.PortName = Buffer;     // Get COM information
                    serialPort1.Open();                 // Open the serial port
                    comboBox1.Items.Add(Buffer);
                    comboBox1.Text = Buffer; // Add serial port to get recordset
                    serialPort1.Close();                 // Close the serial port
                }
                catch { }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.PortName = comboBox1.Text;
                serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text, 10);
                serialPort1.DataBits = Convert.ToInt32(comboBox3.Text, 10);
                if (comboBox4.Text == "None") { serialPort1.Parity = Parity.None; }
                else if (comboBox4.Text == "Odd check") { serialPort1.Parity = Parity.Odd; }
                else if (comboBox4.Text == "Even check") { serialPort1.Parity = Parity.Even; }
                else if (comboBox4.Text == "Mark") { serialPort1.Parity = Parity.Mark; }
                else if (comboBox4.Text == "Space check") { serialPort1.Parity = Parity.Space; }
                if (comboBox5.Text == "1")
                {
                    serialPort1.StopBits = StopBits.One;
                }
                else if (comboBox5.Text == "1.5")
                {
                    serialPort1.StopBits = StopBits.OnePointFive;
                }
                else if (comboBox5.Text == "1.5")
                {
                    serialPort1.StopBits = StopBits.Two;
                }
                //serialPort1.ReadTimeout(2000);
                serialPort1.Open();
                button2.Enabled = false;// The open serial button is unavailable
                //button3.Enabled = true; // Close the serial port
            }
            catch
            {
                MessageBox.Show("Port error, please check serial port"."Error"); }}private void button1_Click(object sender, EventArgs e)
        {
            string str = textBox2.Text;// Get the data of the send box
            byte[] Data = new byte[1];// as a container for sending
            if (serialPort1.IsOpen)// Check whether our serial port is open
            {
                for (int j = 0; j < str.Length; j++)// Iterating through our send statement, bloggers now send one by one
                {
                    if (str[j] == ' ')// Our send statement is separated by Spaces, which we need to iterate through
                    {
                        continue;
                    }
                    else
                    {
                        try
                        {
                            Data[0] = Convert.ToByte(str.Substring(j, 2), 16);//substring is a hexadecimal string of 2 bytes from STR at position j
                        }
                        catch
                        {
                            MessageBox.Show("Please check the input hexadecimal data format is wrong");
                        }
                        try
                        {
                            serialPort1.Write(Data, 0.1);// This means sending data, starting at position 0, with a value.
                            j++;
                        }
                        catch
                        {
                            MessageBox.Show("Failed to send port, system will close current serial port error");
                            serialPort1.Close();// Close the serial port
                        }
                    }

                }
            }
        }
    }
}

Copy the code

2. Configure the SarilPort serial port control to receive data

2.1 Understand the interface of the SerialPort receiving method

public int Read(char[] buffer, int offset, int count); From System. IO. Ports. SerialPort read some characters in the input buffer, then these character written character at the specified offset in the array. // buffer: An array of bytes to which input is written. // offset: the offset in the buffer to write bytes to. // count: maximum number of bytes read. If count is greater than the number of bytes in the input buffer, fewer bytes are read. public int Read(byte[] buffer, int offset, int count); From the System. IO. Ports. SerialPort input buffer read some bytes and those bytes written to the specified offset in the array. // buffer: An array of bytes to which input is written. // offset: the offset in the buffer to write bytes to. // count: maximum number of bytes read. If count is greater than the number of bytes in the input buffer, fewer bytes are read. public int ReadByte(); From the System. IO. Ports. SerialPort input buffer in synchronous read a byte. public int ReadChar(); From the System. IO. Ports. SerialPort synchronous read a characters in the input buffer. public string ReadExisting(); On the basis of the coding, read System. IO. Ports. SerialPort object flow and input all immediately available bytes in the buffer. public string ReadLine(); Has been read in the input buffer System. IO. Ports. SerialPort. The NewLine value. public string ReadTo(string value); All the way to the specified value string in the input buffer. Value: Indicates where the read operation stops.Copy the code

2.2. Create a receiving function based on the screenshot, and SerialPort automatically receives data

2.3 If you do not want to use the loop, you can take a one-time read out of the data, so that it will not be so troublesome, carefully read its own interface, find their own interface, I send my code to everyone for reference:

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte data = 0; int len = 0; int bufsize = (int)serialPort1.BytesToRead; While (len < bufsize) {data = (byte) serialPort1.readbyte (); // get the serial port value len++; string str = Convert.ToString(data, 16).ToUpper(); Textbox1.appendtext (" 0" + STR); textBox1.appendText (" 0" + STR); } else { textBox1.AppendText(" " + str); / / two values at the front and a space-delimited}} textBox1 AppendText (System. Environment. NewLine); / / a newline serialPort1. DiscardInBuffer (); // Clear the previous cache}Copy the code

3. Show, SerialPort send and receive, bloggers here just have a single chip microcomputer, to show you, if interested in this, you can also use virtual SerialPort, simulation play.

Raised: “Interthread operation invalid: never accessed by the thread that created the control ‘textBox1’.” (System. InvalidOperationException), need to add code to add in Form1 System. Windows. Forms. Control. CheckForIllegalCrossThreadCalls = false; Disallow capturing calls to the wrong thread.

Conclusion:

Blogger is simply introduced, SerialPort c # serial port control sending and receiving, and showed the students interested in this area can learn, bloggers are just a beginner, because in a recent work on a project to learn, to learn c # classmates is few, I hope you don’t like do not spray, creation is not easy, thumb up, attention and comments.