Take a natural course in artificial intelligence, from theory to action, and then click here to enter the portal
Hello, World: Hello, World: Hello, World: Hello, World: Hello, World
1. Conception function
Serial assistant in the development of microcontroller is often used for debugging, the most basic function is the function of receiving and sending, secondly, the serial port before opening some Settings: serial port list selection, baud rate, data bit, check bit, stop bit, so there is a basic prototype; Then in the next article, we will add some extended functions such as ASCII/HEX display, send, send new line function, repeat automatic send function, and display data receiving time.
2. Design the layout
According to the above functions, the entire interface is divided into two parts: set the interface (unzooming) + receive area and send area (zooming), the following to drag and drop control implementation:
1) Container control (Panel)
Panel is a container control, is a container pool of some small controls, used to roughly group the controls, it should be noted that the container is a virtual, will only appear during the design, will not be displayed on the design interface, here we divide the entire interface into 6 container pools, as shown in the figure:
2) Text label control (Lable)
Used to display some text, but not editable; There are two ways to change its display content: one is to directly modify the value of “Text” in the property panel, the other is to modify its properties through code, as shown in the following code; In addition, you can modify the Font property to change the display Font and size, here we choose Microsoft Yahei, 12 point Font;
Label1. Text = "serial port "; // Sets the Text property of the labelCopy the code
3) ComboBox drop-down control
Used to display a drop-down list; There are usually two modes, one is the DropDown mode, you can select the drop-down items, or directly edit; The other mode is the DropDownList mode, which can only be selected from the DropDownList. The two modes can be selected by setting the DropDownStyle property.
So, how do you add drop-down options? For a few drop-down Items, you can add the stop bit to the Items property in the properties panel, as shown in the figure below. If you want the default value to appear, you can change the Text property, but it must be consistent with the drop-down Items:
The other option is to add it directly to the page loading function code, such as baud rate selection, as follows:
private void Form1_Load(object sender, EventArgs e) { int i; // Add for (I = 300; i <= 38400; i = i*2) { comboBox2.Items.Add(i.ToString()); String [] baud = {"43000","56000","57600","115200","128000","230400","256000","460800"}; string[] baud = {"43000","56000","57600","115200","128000","230400","256000","460800"}; comboBox2.Items.AddRange(baud); // Set the default value combobox1. Text = "COM1"; comboBox2.Text = "115200"; comboBox3.Text = "8"; comboBox4.Text = "None"; comboBox5.Text = "1"; }Copy the code
4) Button control (Button)
5) TextBox control
The TextBox control is different from the Label control in that the content of the TextBox control can be modified by the user, which also meets the needs of sending text boxes. By default, TextBox pricing is displayed on a single line. If you want to display multiple lines, you need to set its Multiline property to true.
TextBox APPendText adds new text data from the end of the APPendText method to the TextBox. TextBox continues to APPendText and is not long enough to display the entire text. At this time, we need to enable the Vertical scroll bar of TextBox to track and display the latest text, so we set the value of TextBox property ScrollBars to Vertical.
At this point, our display controls are all added, but there is one of the most important space is not added, this control is called implicit control, it is running in the background, the user can not see, more can not directly control, so also become a component, next we add the most important serial components;
6) SerialPort (SerialPort)
This implicit control is added under the designer, the common properties of the serial port are two, one is the port number (PortName), one is the BaudRate (BaudRate), of course, there are data bits, stop bits, parity bits and so on; The serial port also has an IsOpen attribute. If IsOpen is true, the serial port is started. If IsOpen is flase, the serial port is closed.
After adding the serial port component, we can use it to get the current port of the computer and add it to the optional list as follows:
/ / to get computer currently available serial Ports and add to the list of options comboBox1. Items. The AddRange (System. IO. Ports. SerialPort. GetPortNames ());Copy the code
After startup, you can see the following interface layout (ensure that the USB to serial port CH340 is connected) :
3. Set up the background
After the interface layout is completed, we need to use code to build the whole software background, this part is the most important.
First of all, we first control the open/close serial port, the general idea is: when press the open serial port button, the setting value will be transmitted to the properties of the serial port control, and then open the serial port, the button shows the close serial port, press again, the serial port is closed, the open button;
When we click the open button, some events will occur that we cannot handle when programming, such as the hardware serial port is not connected, the hardware suddenly disconnects when the serial port is opened, these are called exceptions, for these exceptions, C# also has a try.. The catch processing mechanism places the code that may generate an exception in the try, such as opening the serial port and catching the exception in the catch for processing. The detailed code is as follows:
private void button1_Click(object sender, EventArgs e) {try {if (serialPort1.isopen) {// The serial port is already open serialPort1.Close(); // Close the serial port button1.text = "open serial port "; button1.BackColor = Color.ForestGreen; comboBox1.Enabled = true; comboBox2.Enabled = true; comboBox3.Enabled = true; comboBox4.Enabled = true; ComboBox5. Enabled = true; textBox_receive.Text = ""; Textbox_send-text = ""; } else {comboBox1.Enabled = false; comboBox1. comboBox2.Enabled = false; comboBox3.Enabled = false; comboBox4.Enabled = false; comboBox5.Enabled = false; serialPort1.PortName = comboBox1.Text; serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text); serialPort1.DataBits = Convert.ToInt16(comboBox3.Text); if (comboBox4.Text.Equals("None")) serialPort1.Parity = System.IO.Ports.Parity.None; else if(comboBox4.Text.Equals("Odd")) serialPort1.Parity = System.IO.Ports.Parity.Odd; else if (comboBox4.Text.Equals("Even")) serialPort1.Parity = System.IO.Ports.Parity.Even; else if (comboBox4.Text.Equals("Mark")) serialPort1.Parity = System.IO.Ports.Parity.Mark; else if (comboBox4.Text.Equals("Space")) serialPort1.Parity = System.IO.Ports.Parity.Space; if (comboBox5.Text.Equals("1")) serialPort1.StopBits = System.IO.Ports.StopBits.One; Else if (comboBox5. Text. Equals (" 1.5 ")). SerialPort1 StopBits = System. IO. Ports. StopBits. OnePointFive; else if (comboBox5.Text.Equals("2")) serialPort1.StopBits = System.IO.Ports.StopBits.Two; serialPort1.Open(); // Open the serial port button1.text = "close the serial port "; button1.BackColor = Color.Firebrick; }} the catch (Exception ex) {/ / capture possible exceptions and processing / / catch exceptions, create a new object, before can no longer use serialPort1 = new System. IO. Ports. SerialPort (); // Refresh the COM port option combobox1.items.clear (); comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames()); / / ring and display the exception to the user System. Media. SystemSounds. Beep. The Play (); Button1.text = "open serial port "; button1.BackColor = Color.ForestGreen; MessageBox.Show(ex.Message); comboBox1.Enabled = true; comboBox2.Enabled = true; comboBox3.Enabled = true; comboBox4.Enabled = true; comboBox5.Enabled = true; }}Copy the code
Next we build send and receive background code, serial port send and receive are successfully opened in the case of the serial port, so first to determine whether the serial port attribute IsOpen is 1;
There are two methods for serial port sending. One is to send WriteLine as a string, and the other is to send Write (), which can be sent as a string or in hexadecimal format (see next section).
Private void button2_Click(object sender, EventArgs e) {try {if (serialPort1.isopen) { Send serialPort1.write (textbox_send-text); }} the catch (Exception ex) {/ / catch exceptions, create a new object, before can no longer use serialPort1 = new System. IO. Ports. SerialPort (); // Refresh the COM port option combobox1.items.clear (); comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames()); / / ring and display the exception to the user System. Media. SystemSounds. Beep. The Play (); Button1.text = "open serial port "; button1.BackColor = Color.ForestGreen; MessageBox.Show(ex.Message); comboBox1.Enabled = true; comboBox2.Enabled = true; comboBox3.Enabled = true; comboBox4.Enabled = true; comboBox5.Enabled = true; }}Copy the code
Then start the last task — serial port reception. Register a Receive event for the serial port before using serial port reception, which is equivalent to the serial port reception interruption in the microcontroller. Then read the data in the buffer inside the interruption, as shown in the figure.
/ / a serial port receives the event handling private void SerialPort1_DataReceived (object sender, System. IO. Ports. SerialDataReceivedEventArgs e) {}Copy the code
Similarly, there are two methods for serial port reception, one is the hexadecimal read (introduced next), one is the string read, in the code just generated, as follows:
Private void SerialPort1_DataReceived(Object sender, System. IO. Ports. SerialDataReceivedEventArgs e) {try {/ / because to access the UI resources, Invoke((EventHandler)(delegate {textBox_receive.appendText (serialPort1.readexisting ())); })); } the catch (Exception ex) {/ / ring and display the Exception to the user System. Media. SystemSounds. Beep. The Play (); MessageBox.Show(ex.Message); }}Copy the code
This is a separate thread from the main thread. The receive TextBox is created in the main thread, so when we read back the string directly with serialPort1.readexisting (), Textbox_receive.appendtext () AppendText () does not respond at runtime or even raises an exception, as shown in the following figure:
The invoke method is specifically designed to handle access from threads that never created the control. After adding the Invoke method, the serial helper can receive data normally, as shown in the following figure: