Introduction of C # serial port and implementation of simple serial communication program

Source: Internet
Author: User

Tag: Send data false Run program design RS485 file Application device nbsp

Introduction of C # serial port and implementation of simple serial communication program

Weekend, nothing to do, write a simple serial communication tool, also is this weekend has come, nonsense, direct to the theme

Introduction of Serial port

Serial interface, also known as serial communication interface or serial communication interface (usually referred to as COM interface), is a serial communication mode extension interface. (As for the details, own Baidu)

Serial application:

Industrial use more, such as: Data acquisition, equipment control, and so on, many are using serial communication to achieve! If you are careful, you will find that the current home state network intelligent watt-hour meter with RS485 communication bus (a serial bus) and RS232 can be transformed (of course, non-professional who will not idle egg pain, lying on the meter blind, at most also see how many degrees of electricity)

RS232 DB9 Introduction: 1.

2. Pin Description:
    1. Carrier Detection (DCD)
    2. Accept data (RXD)
    3. Emit data (TXD)
    4. Data Terminal Ready (DTR)
    5. Signal Ground (SG)
    6. Data Ready (DSR)
    7. Request Send (RTS)
    8. Clear Send (CTS)
    9. Ringing Indication (RI)
3. Physical Map:

Here is my purchase XX company's a USB to serial cable: This head is a male, the other end is a USB port

Stupid kid. Serial tool Run Diagram: 1. Open program

2. Send a line of string hellobenxh, directly link the send and receive pins can be tested (PIN 2 accepts data (RXD) and 3 emitted data (TXD)) Direct link,

C # code implementation: using SerialPort1. Instantiate a SerialPort
1 private SerialPort Comdevice = new SerialPort ();
2. Initialize parameter bindings to receive data events
1 public void init () 2         {3             btnsend.enabled = false; 4             CbbComList.Items.AddRange (Serialport.getportnames ()) ; 5             if (CbbComList.Items.Count > 0) 6             {7                 cbbcomlist.selectedindex = 0; 8             } 9             Cbbbaudrate.selectedindex = 5;10             cbbdatabits.selectedindex = 0;11             cbbparity.selectedindex = 0;             Cbbstopbits.selectedindex = 0;13             picturebox1.backgroundimage = properties.resources.red;14             comdevice.datareceived + = new Serialdatareceivedeventhandler (com_datareceived);//Binding             event         
3. Open the Serial button event
 1//<summary> 2//Open serial 3//</summary> 4//<param name= "Sender" ></par  Am> 5//<param name= "E" ></param> 6 private void Btnopen_click (object sender, EventArgs e) 7 {8 if (cbbComList.Items.Count <= 0) 9 {Ten MessageBox.Show ("No serial port found, please Check the line!                 "); return;12}13 if (Comdevice.isopen = = false) 15 {16 Comdevice.portname = CbbComList.SelectedItem.ToString (); comdevice.baudrate = Convert.ToInt32 (cbbb AudRate.SelectedItem.ToString ()); comdevice.parity = (Parity) Convert.ToInt32 (CbbParity.SelectedIndex.ToS Tring ()); comdevice.databits = Convert.ToInt32 (cbbDataBits.SelectedItem.ToString ());                 Omdevice.stopbits = (stopbits) Convert.ToInt32 (cbbStopBits.SelectedItem.ToString ()); try22              {23       Comdevice.open (); btnsend.enabled = true;25}26 catch (Except Ion ex) {MessageBox.Show (ex.                 Message, "Error", MessageBoxButtons.OK, Messageboxicon.error); return;30}31              Btnopen.text = "Close serial port"; picturebox1.backgroundimage = properties.resources.green;33}34                     else35 {try37 {comdevice.close (); 39                      btnsend.enabled = false;40}41 catch (Exception ex) 42 {43 MessageBox.Show (ex.                  Message, "Error", MessageBoxButtons.OK, Messageboxicon.error),}45 btnopen.text = "Open serial port"; 46 Picturebox1.backgroundimage = properties.resources.red;47}48 cbbcomlist.enabl ed =!            Comdevice.isopen;50 cbbbaudrate.enabled =! comdevice.isopen;51 cbbparity.enabled =! comdevice.isopen;52 cbbdatabits.enabled =! comdevice.isopen;53 cbbstopbits.enabled =! COMDEVICE.ISOPEN;54}
4. Send data
 1//<summary> 2//Send data 3//</summary> 4//<param name= "Sender" ></par             Am> 5//<param name= "Data" ></param> 6 public bool SendData (byte[] data) 7 {8 if (Comdevice.isopen) 9 {try11 {COMDEVICE.W Rite (data, 0, data.                 LENGTH);//Send data return true;14}15 catch (Exception ex) 16 {MessageBox.Show (ex.             Message, "Error", MessageBoxButtons.OK, Messageboxicon.error);}19}20 Else21             {MessageBox.Show ("Serial Not Open", "error", MessageBoxButtons.OK, Messageboxicon.error); 23}24 return false;25}26///&LT;SUMMARY&GT;28//Send Data button Event///</summar Y&GT;30//<param name= "sender" ></param>31//<p Aram Name= "E" ></param>32 private void Btnsend_click (object sender, EventArgs e) 33 {34 byte[] SendData = null;35 (rbtnsendhex.checked) PNs {senddata = Strtohex                 Byte (TxtSendData.Text.Trim ());}40 else if (rbtnsendascii.checked) 41 {42 SendData = Encoding.ASCII.GetBytes (TxtSendData.Text.Trim ());}44 Else if (rbtnsendutf8.chec             ked) {senddata = Encoding.UTF8.GetBytes (TxtSendData.Text.Trim ()); 47}48 else if (rbtnsendunicode.checked) $ {senddata = Encoding.Unicode.GetBytes (txtsenddat A.text.trim ()); Wuyi}52 else53 {senddata = Encoding.ASCII.GetBytes (tx TSendData.Text.Trim ());}56 if (this. SendData (senddata)//Send Data Success count (LBLSENDCOUNT.INV)Oke (New MethodInvoker (Delegate60 {lblsendcount.text = (int). Parse (Lblsendcount.text) + txtSendData.Text.Length). ToString ();}64 Else65 {66 67}68 69}70 ///&LT;SUMMARY&GT;72///String conversion 16 byte array of bytes///</summary>74//<param name= "he Xstring "></param>75//<returns></returns>76 private byte[] Strtohexbyte (String HexS                 Tring) hexstring = Hexstring.replace ("", "" "); ((hexstring.length% 2)! = 0) 80 HexString + = ""; Bayi byte[] returnbytes = new byte[hexstring.length/2];82 for (in t i = 0; i < returnbytes.length; i++) Returnbytes[i] = Convert.tobyte (hexstring.substring (i * 2, 2). Replace ("", ""), +); return returnbytes;85}
5. Reception and data output
 1//<summary> 2///Receive data 3//</summary> 4//<param name= "Sender" ></par Am> 5//<param name= "E" ></param> 6 private void Com_datareceived (object sender, Serialdat Areceivedeventargs e) 7 {8 byte[] Redatas = new Byte[comdevice.bytestoread]; 9 comdevice. Read (Redatas, 0, redatas.length);//reads the data. AddData (Redatas);//output data}12///&LT;SUMMARY&GT;14//Add data//</summary&             GT;16//<param name= "Data" > byte array </param>17 public void AddData (byte[] data) 18 {19                 if (rbtnhex.checked), {StringBuilder sb = new StringBuilder (); 22 for (int i = 0; i < data. Length; i++) at $ sb. AppendFormat ("{0:x2}" + "", Data[i]);}26 addcontent (sb.) ToString ().        ToUpper ()); 27     }28 else if (rbtnascii.checked) {addcontent (New ASCIIEncoding (). GetString (data),}32 else if (rbtnutf8.checked), {addcontent (NE W utf8encoding (). GetString (data));}36 else if (rbtnunicode.checked) PNS {addcontent (New UnicodeEncoding (). GetString (data));}40 else41 {}42 lblrevcount.invoke (new Me Thodinvoker (delegate44 {lblrevcount.text = (int. Parse (lblrevcount.text) + data. Length). ToString ());}48//<summary>51////input to display area///&LT;/SU         mmary>53//<param name= "content" ></param>54 private void Addcontent (string content) 55 {. BeginInvoke (New MethodInvoker (Delegate57 {CHKAUTOLINE.CHECked && txtshowdata.text.length>0) {txtshowdata.appendtext ("\ r \ n"); 61 }62 Txtshowdata.appendtext (content); 63}); 64}
6. Clear Data Area Events
1//<summary> 2//         Clear Reception area 3//         </summary> 4//         <param name= "Sender" ></param> 5< c5/>///<param name= "E" ></param> 6         private void Btnclearrev_click (object sender, EventArgs e) 7         {8< C8/>txtshowdata.clear (); 9}10///<SUMMARY>12///Empty Send area///</summary>14//         <param name= "sender "></param>15         //<param name=" E "></param>16         private void Btnclearsend_click (object sender, EventArgs e) +         {             txtsenddata.clear ();         

Run the program BXHSerialPort.exe

Source Code Engineering File download

Introduction of C # serial port and implementation of simple serial communication program

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.