C # do a simple serial communication of the host computer 1, the host computer and the lower machine
The host computer is equivalent to a software system, which can be used to receive data and control data. The data can be manipulated directly by sending a command to the data received. The host computer can receive the signal of the lower machine. The lower machine is a controller that is directly controlled by the device to obtain the condition of the computer. The commands issued by the host computer are first given to the lower machine, and the subordinate machine is then interpreted as the corresponding sequential signal directly to control the corresponding equipment. The lower machine reads the device status data (usually analog), and converts the digital signal back to the host computer. The upper machine can not be used alone, and the lower machine can be used alone.
2. Serial Communication
The serial port corresponds to the interface of the hardware type. For example, the Wireless sensor node sends the signal to the aggregation node, the aggregation node passes the data through the serial port to the computer's upper machine, the upper machine receives the information, and processes.
The serial port is a bitwise (BIT) sent and received bytes. The most important parameters of serial communication are baud rate, data bit, stop bit, and parity check. For two ports that are communicating, these parameters must match.
A, baud rate: This is a parameter that measures the transfer rate of a symbol.
b, Data bits: This is the parameter that measures the actual data bits in the communication.
C, stop bit: Used to represent the last one in a single package. Typical values are 1, 1.5, and 2 bits.
D, parity bit: A simple method of error detection in serial communication.
3. C # code
Using System;Using System.Collections.Generic;Using System.ComponentModel;Using System.Data;Using System.Drawing;Using System.Linq;Using System.Text;Using System.Threading.Tasks;Using System.Windows.Forms;Using System.IO.Ports;Using System.Diagnostics;Namespaceserial2{PublicPartialClassForm1:Form {SerialPort s =New SerialPort ();Instantiating a serial port object can be dragged directly through the front-end control, but it is best to write code in the back-end code so that there is no error copying elsewhere. S is a handle to a serial portPublicForm1 () {InitializeComponent (); Control.checkforillegalcrossthreadcalls =FalseTo prevent cross-thread access errors, button1 is used in many places. Text ="Open serial port";Int[] Item = {9600,115200};Define an item array, traverse each variable A in item, and add it to the list of ComboBox2foreach (int aIn item) {COMBOBOX2.ITEMS.ADD (a.tostring ());} Combobox2.selecteditem = combobox2.items[1];The default is the second variable of the list}PrivatevoidForm1_Load (Object sender, EventArgs e)The form events are configured with port information first. {String[] ports = Serialport.getportnames (); ComboBox1.Items.AddRange (ports); combobox1.selecteditem=combobox1.items[0];Array.Sort (ports); }PrivatevoidButton1_Click (Object sender, EventArgs e)The following explanation is almost clear.try {if (!s.isopen) {s.portname = ComboBox1.SelectedItem.ToString (); s.baudrate = Convert.ToInt32 ( ComboBox2.SelectedItem.ToString ()); S.open (); S.datareceived + = s_datareceived; Button1. Text ="Close serial port";MessageBox.Show ("Serial port is open"); }else {s.close (); s.datareceived-= s_datareceived; button1. Text ="Open serial port"; } }catch (Exception ee) {MessageBox.Show (EE. ToString ()); } }voidS_datareceived (Object sender, Serialdatareceivedeventargs e)Data receive events, read the length of the data assigned to count, if it is 8 bits (the node internal programming is OK), apply a byte type of buff array, s handle to read the data {int count =s.bytestoread;String str=null;if (count = =8) {byte[] Buff =NewByte[count]; S.read (Buff,0, Count);foreach (BYTE itemIn buff)Read the data stored in the buff and convert it to the displayed hexadecimal number {str + = Item. ToString ("X2") +" "; } richTextBox1.Text =system.datetime.now.tostring () +":" + str +"\ n" + richtextbox1.text;This is a cross-thread access RichTextBox, the original program and the DataReceived event are two different threads simultaneously executingif (buff[0] = =0x04If the node is a 04-sent data {ID. Text = buff[0]. ToString ();This is the right section of the upper computer, used to display the processed data temperature, humidity, lighting, dust, ID information. The buff "0" is stored in the ID information of the data, displayed on the label of the IDSwitch (buff[2])Judging the data type buff "0" and Buff "1" represent the low and high of the ID, likewise 2 and 3 represent the low and high of the data type, when the values of 2 and 3 are 1 o'clock, 4 and 5 represent the temperature, 6 and 7 represent the humidity;Case0x01When the values of 2 and 3 are 1, 4 and 5 are temperature, 6 and 7 are humidity {Tem.text = (buff[5] *4 + buff[4] *0.05-30). ToString (); Hum.text = (buff[6] + buff[7]). ToString ();Break }Case0x026 and 7 are illumination {Light.text = (buff[6] + buff[7]). ToString ();Break }Case0x046 and 7 are dust {Dust.text = (buff[6] + buff[7]). ToString ();Break }DefaultBreak } } } }PrivatevoidButton3_Click (Object sender, EventArgs e)Each time a byte is sent {string[] Sendbuff = RichTextBox2.Text.Split ();Splits the input string and determines how many bytes are required to send the Debug.WriteLine ("Send bytes:" +sendbuff. Length);foreach (String itemIn Sendbuff) {int count =1;byte[] Buff =NewByte[count]; buff[0] =Byte. Parse (item, System.Globalization.NumberStyles.HexNumber);//formatted string for hexadecimal numeric s.write (buff, 0, Count);}} private void button2_click (object sender, EventArgs e)//Refresh the value on the right { int count = 1; byte[] Buff = new byte[count]; buff[0] = byte. Parse ("System.Globalization.NumberStyles.HexNumber"); This shows only 04 nodes of information S.write (buff, 0, Count); }}}
(The above rules are in the lab node internal custom rules, testing, the corresponding change outside)
4. Results
5, add four points of knowledge
1) in the place where the program may encounter errors, use try+ two tab key to write the code into a try. For example, the code in this example:
private void button1_click (object sender, EventArgs e) {try {if (!s.isopen) {s.portname = ComboBox1.SelectedItem.ToString (); S.baudrate = Convert.ToInt32 (comboBox2.SelectedItem.ToString ()); S.open (); S.datareceived + = s_datareceived; Button1. Text = "close serial port"; //messagebox.show ("Serial port is Open");} else {s.close (); s.datareceived-= s_datareceived; button1. Text = "open serial port";}} catch (Exception ee) {MessageBox.Show (EE. ToString ()); } }
If the code is not written to a try, one of the possible scenarios is that there are two host machines, and the same serial port is used, and then there will be a conflict and an error will occur. The program terminates and the entire process is completed. If you write to a try and instantiate the catch code that throws the exception, that is, the catch exception is instantiated with a handle, so that the program encounters an error that does not terminate, and the cause of the error occurs. For example, my host computer and online download a host computer at the same time occupy the COM3 serial port (online download of the first occupied COM3), then my host computer in the opening of the serial port will appear error.
2) As far as I am concerned, there is a need to open the serial port and close the serial port two button buttons, but taking into account the place, of course, the most important or if you use two buttons to indicate, when you press the open serial port, if you forget whether to open, it is not to see if it is open, So you can merge into a button control. (The code is still in the section above). (It feels amazing.) In the Button1_Click event, click button First, if the serial port is closed, then open the serial port, and then put Button1. The value of text is assigned to "close the serial port", if the serial port is originally closed, then click the button will be button1. The value of text is assigned "Open serial port" and the received data is emptied. This is a really good way to feel! Hey
3) When a variable or method is entered, all of it will automatically appear in a list, when the "cube" stands for "method", "small pliers" stands for "variable", "Lightning" stands for "event".
4) When an event is generated for an object
For example, enter S. datareceived event will appear automatically, and then "+ =" will be like prompt, press the TAB key. And then it's like a hint.
Pressing the TAB key again automatically generates the DataReceived event handler function.
C # to do a simple serial communication of the host computer