Using the SerialPort class in C # to implement serial communication (updated continuously)

Source: Internet
Author: User

In the. NET Framework2. 0 provides the SerialPort class, which mainly realizes serial port data communication and so on. This article will I in the learning process from the network collected from the relevant information to write for your reference. The main properties of the Class (table 1) and methods (table) are described below.2). If you need more information, please log in to http://Msdn.microsoft.com/zh-cn/library/system.io.ports.serialport (vs.80). aspx view. read COM port data using System.IO.Ports http://www.devasp.net/net/articles/display/727.html  Table 1 common property name descriptions for SerialPort classes BaseStream get the underlying Stream of SerialPort objects Object BaudRate Gets or sets the serial baud rate breakstate Gets or sets the interrupt signal state Bytestoread Gets the number of bytes of data in the receive buffer Bytestowrite gets the number of bytes of data in the send buffer cdholding Gets the status of the port's carrier detection line ctsholding Gets the status of the "can send" row databits Gets or sets the standard data bit length for each byte discardnull Gets or sets a value that indicates whether the Null byte is ignored when it is transferred between the port and the receive buffer Dsrholding gets the status of the data Set Ready (DSR) signal dtrenable Gets or sets a value that enables the data Terminal ready (DTR) signal during serial communication Encoding Gets or sets the byte encoding of the text conversion before and after the transfer handshake Gets or set The handshake protocol for serial port data transmission IsOpen Gets a value that indicates the open or closed state of the SerialPort object NewLine Gets or sets the value used to interpret the end of the ReadLine () and WriteLine () method calls Parity Gets or sets the parity school Verification Protocol Continuation table name Description Parityreplace Gets or sets a byte that replaces invalid bytes in the data flow when a parity error occurs portname Gets or sets the communication port, including but not limited to all available COM ports readbuffersize get or sets the size of the SerialPort input buffer readtimeout Gets or sets the number of milliseconds before a timeout occurs when the read operation is not completed receivedbytesthreshold Gets or sets the datareceived Number of bytes in the internal input buffer before the event rtsenable Gets or sets a value that indicates whether the request-send (RTS) signal is enabled in serial communication stopbits Gets or sets the standard number of stop bits per byte writebuffersize                   Gets or sets the size of the serial port output buffer writetimeout Gets or sets the milliseconds before the time-out when the write operation is incomplete 2                                  Common methods for the SerialPort class name description close the port connection, set the IsOpen property to False, and release the internal Stream object open opens a new The serial port connection read from the SerialPort input buffer reads readbyte from the SerialPort input buffer synchronously reads a byte ReadChar synchronously reads a character from the SerialPort input buffer ReadLine Read all the time The NewLine value in the input buffer readto has been read into the input buffer and the string specified in value Write has been overloaded. Writes data to the serial port output buffer WriteLine writes the specified string and NewLine values to the output buffer using the SerialPort class method: Method One: First addusingSystem.IO;usingSystem.IO.Ports;1... SerialPort com is defined inside the class;2... Open serial COM=NewSerialPort (); Com. BaudRate=115200; Com. PortName="COM1"; Com. DataBits=8; Com. Open ();//Open the serial port3... Send data byte[] TxData={1,2,3,4,5,6,7,8 }; Com. Write (TxData,0,8);4... Receive Data4. 1 Using Event reception This. com. DataReceived + =NewSystem.IO.Ports.SerialDataReceivedEventHandler ( This. ondatareceived);Private voidOndatareceived (Objectsender, Serialdatareceivedeventargs e)4. 2 Use the thread to receive data to start a thread to receive it.        Defines the Thread _readthread within the class; BOOL_keepreading; start thread after opening the serial port _keepreading=true; _readthread=NewThread (Readport); _readthread.start (); thread function [C-Sharp ] View plaincopy on.Private voidReadport () Geneva. {  Geneva. while(_keepreading)Geneva. {   to.if(COM. IsOpen) .. {   -.byte[] Readbuffer =New byte[COM. Readbuffersize +1];  ,.Try   the. {  Ten.//If There is bytes available on the serial port, One.//Read returns up to ' count ' bytes, but would not block (wait) A.//For the remaining bytes. If there is no bytes available -.//On the serial port, Read would block until at least one byte -.//is available on the port, up until the readtimeout milliseconds the.//with elapsed, at which time a timeoutexception would be thrown.  -.intCount = com. Read (Readbuffer,0, com.  Readbuffersize);  -. String Serialin = System.Text.Encoding.ASCII.GetString (Readbuffer,0, Count);  -.if(Count! =0)   +.//bytetohexstr (Readbuffer);  -.  Threadfunction (Bytetohexstr (Readbuffer,count));  +. }   A.Catch(timeoutexception) {} at. }   -.Else   -. {   -. TimeSpan WaitTime =NewTimeSpan (0,0,0,0, -);  -.  Thread.Sleep (WaitTime);  -. }   in. }   -.} Method Two: Use the Serialpor control that comes with C #. 1... In the toolbox, in components, select the Serialpor control to add. 2... Set up the serial port and open Serialport1.portname="COM1"; Serialport1.baudrate=9600; Serialport1.open ();3... Write data can use write or the following function Serialport1.writeline (str);4... Adding events to receive dataPrivate voidSerialport1_datareceived (Objectsender, Serialdatareceivedeventargs e) Some common problems in using C # SerialPort class DataReceived event GUI real-time processing method (from [email protected] View) MSDN: When data is received from a SerialPort object, the DataReceived event is raised on the worker thread. Because this event is raised on a worker thread rather than on the main threads, an attempt to modify some elements in the main thread, such as a UI element, throws a thread exception. If it is necessary to modify the elements in the main Form or Control, you must use the Invoke postback change request, which will be executed on the correct thread. In order to display the data read in a worker thread to a Form control on the main thread, only the following code instance is implemented by the Invoke method: [ C-Sharp ] View plaincopy on.Private voidSerialport1_datareceived (Objectsender, Serialdatareceivedeventargs e) Geneva. {  Geneva.intSdatetemp = This. Serialport1.readbyte (); Geneva.//reads a byte of data in a string to. This. Tb_receivedate.invoke ( ..//executes a delegate invoke on the thread that owns the underlying window handle of this control (Delegate) -.//that is, the delegate is executed in the parent window form of the Textbox_receivedate control.  ,.NewMethodInvoker ( the./*represents a delegate that can execute any method in managed code that is declared void and does not accept any parameters. You can use this delegate when invoking a control's Invoke method or when you need a simple delegate and do not want to define it yourself. */  Ten.Delegate{                    One./*The anonymous method, a new feature of C#2.0, is a program code-writing technique that allows programmers to pass a complete block of code as a parameter, which allows them to design an event responder directly using a delegate the following is the function you want to implement on the main thread but one thing to be aware of, It is not appropriate to handle too many methods here because the C # message mechanism is a message pipeline response mechanism, and if the time it takes to process statements on the main thread is too long to cause the main UI thread to block, stop responding, or respond smoothly, your main form interface will be delayed or blocked*/                      A. This. Tb_receivedate.appendtext (Sdatetemp.tostring ());//output to main window text control -. This. Tb_receivedate.text + =" ";}  -. )   the.  );  -.} How to know which serial port the current computer has to add a ComboBox control on the form.  Then use ComboBox1.Items.AddRange (System.IO.Ports.SerialPort.GetPortNames ()); orstring[] Portlist =System.IO.Ports.SerialPort.GetPortNames ();  for(inti =0; i < portlist.length; ++i) {stringName =Portlist[i];            COMBOBOX1.ITEMS.ADD (name); For details, refer to http://msdn.microsoft.com/zh-tw/library/system.io.ports.serialport.getportnames.aspx

Using the SerialPort class in C # to implement serial communication (updated continuously)

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.