Example tutorials for C # serial communication

Source: Internet
Author: User
Because to participate in a small project, the relay must be serial control, so the two days to learn the basic serial programming. Colleagues there is a Java serial communication package, but downloaded from the Internet, relatively messy, difficult to accurately grasp the serial communication process and content. Therefore, the individual through the study of online Daniel's method, using C # to achieve the basic serial communication programming. The following summary of the results of learning, I hope to help you.

First, the introduction of serial communication

Serial interface (serial port) is a device that can convert parallel data characters from the CPU into sequential serial data streams, and can convert the accepted serial data stream to parallel data characters to the CPU. The general circuit that accomplishes this function is called the serial interface circuit.

The concept of serial port communication (Serial Communications) is very simple, with the serial port bitwise (BIT) sending and receiving bytes. Although it is slower than parallel communication by Byte (byte), the serial port can receive data with another line while sending data using one line. 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.

1. Baud rate: This is a parameter that measures the symbol transfer rate. Refers to the signal is modulated after the change in the unit time, that is, the number of times the carrier parameter changes in the unit time, such as 960 characters per second, and each character format contains 10 bits (a starting bit, 1 stop bit, 8 data bits), the baud rate is 960Bd, bit rate is 10 bits * 960/sec = 9600bps.

2. Data bits: This is the parameter that measures the actual data bits in the communication. When the computer sends a packet, the actual data is often not 8-bit, and the standard values are 6, 7, and 8 bits. The standard ASCII code is 0~127 (7-bit), and the extended ASCII code is 0~255 (8-bit).

3. Stop bit: Used to represent the last few of a single package. Typical values are 1, 1.5, and 2 bits. Since the data is timed on the transmission line, and each device has its own clock, it is likely that there is a small difference between the two devices in the communication. So the stop bit is more than just the end of the transmission, and provides the opportunity for the computer to calibrate the clock synchronization.

4. Check bit: A simple error-checking method in serial communication. There are four methods of error detection: Occasional, odd, high and low. Of course, no check bit is also possible.

Second, C # Serial Programming class

Starting with the. NET Framework 2.0, C # provides the SerialPort class for implementing serial control. namespaces: System.IO.Ports. Refer to the MSDN documentation for a detailed description of the members. The fields, methods, and events that are commonly used are described below.

1. Characters commonly used section:

Name Description
PortName Gets or sets the communication port
BaudRate Gets or sets the serial baud rate
DataBits Gets or sets the standard data bit length for each byte
Parity Gets or sets the parity check protocol
StopBits Gets or sets the standard number of stop bits per byte

2. Common methods:

Name Description
Close Close the port connection, set the IsOpen property to false, and release the internal Stream object
Getportnames Gets an array of serial port names for the current computer
Open Open a new serial port connection
Read Read from the SerialPort input buffer
Write Writing data to the serial port output buffer

3. Common events:

Name Description
DataReceived Represents the method that will handle the data receiving event for the SerialPort object

Three, basic usage

The following combined with a relay has been given the basic use of serial communication, for reference.

  1 using System;  2 using System.Windows.Forms;  3 using System.IO.Ports;  4 using System.Text;         5 6 Namespace Traveller_serialportcontrol 7 {8 Public partial class Form1:form 9 {10//Define Port class 11 Private SerialPort Comdevice = new SerialPort (); Public Form1 () () (InitializeComponent) (); Initralconfig (); 16} <summary> 18///configuration initialization of//</summary> private void Initralconfig (             ) 21 {22//query host on the existing serial port ComboBox_Port.Items.AddRange (Serialport.getportnames ()); 24 25             if (ComboBox_Port.Items.Count > 0) (combobox_port.selectedindex = 0; 28             } (Else) {combobox_port.text = "serial port not detected"; 32} 33 Combobox_baudrate.selectedindex = 5; Combobox_databits.selectedindex = 0;            35 Combobox_stopbits.selectedindex = 0; Combobox_checkbits.selectedindex = 0; Panax Notoginseng picturebox_status.backgroundimage = Properties.Resources.red;             38 39//To Comdevice.datareceived (is an event) registers a method com_datareceived, when the port class receives information, it automatically calls com_datareceived method 40 comdevice.datareceived + = new Serialdatareceivedeventhandler (com_datareceived);         +//<summary> 44///If the Comdevice.datareceived event occurs, the data received from the serial port is displayed to the receiving end of the dialog box 45 </summary>//<param name= "sender" ></param>//<param name= "E" ></             Param>-private void Com_datareceived (object sender, Serialdatareceivedeventargs e) 49 {50 Open receive buffer (byte[] Redatas = new Byte[comdevice.bytestoread]; 52//Read data from serial port Comdevice.read (redatas, 0, redatas.length); 54//implementation of data decoding and display AddData (Redatas); +//<sumMary> 59///decoding process (///</summary>//<param name= "Data" > Serial port Communication method varies by serial port and needs to be queried Serial port related information to obtain </param> public void AddData (byte[] data) (Radiobutton_hex.checke d) (+ StringBuilder sb = new StringBuilder (); (int i = 0; i < D Ata. Length; i++). AppendFormat ("{0:x2}" + "", Data[i]); Addcontent (sb.) ToString (). ToUpper ()); Radiobutton_ascii. Checked) addcontent (New ASCIIEncoding (). GetString (data)); Radiobutton_utf8. Checked) addcontent (New UTF8Encoding (). GetString (data)); (radiobutton_unicode.checked) addcontent (New U Nicodeencoding (). GetString (dATA));                 -----StringBuilder SB = new StringBuilder (); 88 for (int i = 0; i < data. Length; i++). AppendFormat ("{0:x2}" + "", Data[i]); Addcontent (sb.) ToString (). ToUpper ());  94}//<summary> 97//Receive-side dialog displays messages 98//</summary> <param name= "content" ></param>100 private void Addcontent (string content) 101 { 102 BeginInvoke (New MethodInvoker (delegate103 {104 textbox_recei Ve.              AppendText (content); )); 106}107 108///&LT;SUMMARY&GT;109//serial switch///&LT;/SUMMARY&GT;11 1//<param name= "sender" ></param>112///<param name= "E" ></param>113 pri vate voidButton_switch_click (object sender, EventArgs e) (comboBox_Port.Items.Count <= 0) 116             {117 MessageBox.Show ("No serial port found available, check Hardware Device") 118 return;119}120 121 if (Comdevice.isopen = = false) 122 {123//Set serial port related properties 124 Comdevice.portname = ComboBox_Port.SelectedItem.ToString (); comdevice.baudrate = Convert.ToInt32 (combobox_baudrate.selecte Ditem.tostring ()); 126 comdevice.parity = (Parity) Convert.ToInt32 (comboBox_CheckBits.SelectedIndex.ToString                 ()); 127 comdevice.databits = Convert.ToInt32 (comboBox_DataBits.SelectedItem.ToString ()); 128                 Comdevice.stopbits = (stopbits) Convert.ToInt32 (comboBox_StopBits.SelectedItem.ToString ()); 129 try130 {131//Open serial port Comdevice.open (); 133 BUTTON_SEND.E       nabled = true;134          }135 catch (Exception ex) 136 {137 MessageBox.Show (ex.                 Message, "Failed to open serial port successfully", MessageBoxButtons.OK, Messageboxicon.error); 138 return;139}140 Button_switch.text = "Off"; 141 picturebox_status.backgroundimage = Properties.Resources.gree                     n;142}143 else144 {145 try146 {147                 Close the serial port 148 comdevice.close (); 149 button_send.enabled = false;150 }151 catch (Exception ex) {153 MessageBox.Show (ex).  Message, "Serial Port off Error", MessageBoxButtons.OK, Messageboxicon.error); 154}155 Button_switch.text             = "on"; 156 picturebox_status.backgroundimage = properties.resources.red;157}158 159 combobox_port.enabled =! Comdevice.isopen;160 combobox_baudrate.enabled =! comdevice.isopen;161 combobox_databits.enabled =! comdevice.isopen;162 combobox_stopbits.enabled =! comdevice.isopen;163 combobox_checkbits.enabled =! comdevice.isopen;164}165 166 167//<summary>168//message encoded and sent 169//&LT;/SU         mmary>170//<param name= "sender" ></param>171//<param name= "E" ></param>172 private void Button_send_click (object sender, EventArgs e) 173 {174 if (textBox_Receive.Text.Le Ngth > 0) 175 {176 Textbox_receive.appendtext ("\ n"); 177}178 179 byt e[] SendData = null;180 181 if (radiobutton_hex.checked) 182 {183 SendData = Strtoh Exbyte (TextBox_Send.Text.Trim ()); 184}185 Else if (radiobutton_ascii. Checked) 186 {187 SendData = encoding.asCII. GetBytes (TextBox_Send.Text.Trim ()); 188}189 Else if (Radiobutton_utf8. Checked) {191 senddata = Encoding.UTF8.GetBytes (TextBox_Send.Text.Trim ()); 192} 193 else if (radiobutton_unicode.checked) 194 {195 SendData = Encoding.Unicode.GetB Ytes (TextBox_Send.Text.Trim ()); 196}197 else198 {199 SendData = Strtoh Exbyte (TextBox_Send.Text.Trim ());}201 202 senddata (senddata); 203}204 205// <summary>206////This function passes the encoded message to the serial port 207///</summary>208//<param name= "Data" >&lt             ;/param>209//<returns></returns>210 public bool SendData (byte[] data) 211 {212 if (Comdevice.isopen) 213 {214 try215 {216//messages are transmitted Pass to the serial port 217 comdevice.write (data, 0, data.                 Length); 218 return true;219}220 catch (Exception ex) 221 {222 MessageBox.Show (ex.              Message, "Send Failed", MessageBoxButtons.OK, Messageboxicon.error); 223}224}225 else226             {227 MessageBox.Show ("Serial Port Not Open", "error", MessageBoxButtons.OK, messageboxicon.error); 228 }229 return false;230}231 232//<summary>233//16 binary Encoding 234//&LT ;/summary>235//<param name= "hexstring" ></param>236//<returns></returns>23 7 Private byte[] Strtohexbyte (string hexstring) 238 {239 hexstring = Hexstring.replace ("", "") if ((hexstring.length% 2)! = 0) HexString + = ""; 241 byte[] returnbytes = new byte[hexstring .          length/2];242 for (int i = 0; i < returnbytes.length; i++) 243       Returnbytes[i] = Convert.tobyte (hexstring.substring (i * 2, 2). Replace ("", ""), +); 244 return returnbytes;245}246 247//The following two instructions are designed to combine a relay 248 priv ate void Button_on_click (object sender, EventArgs e) 249 {textbox_send.text = "005a540001010000b0"; 251}252 253 private void Button_off_click (object sender, EventArgs e) 254 {255 TextBox _send.text = "005A540002010000B1"; 256}257}258}

Basic software Implementation Interface

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.