Detailed usage of the SerialPort control

Source: Internet
Author: User


Recently in the communication protocol, about the SerialPort class DataReceived event can not trigger the problem, find a lot of information, finally found a good.

1. Brief introduction

With the popularity of USB, serial communication has been applied to many aspects of daily life, USB is a high-speed serial communication protocol, USB interface is very complex, often used in the need to transfer large amounts of data, such as U disk, camera, printer and so on. In addition to the more luxurious USB port, in the industrial and embedded industry, a large number of used is another ancient serial protocol, RS-232 serial port. RS-232 is a very concise low-speed serial port communication interface, it can simultaneously carry out the work of data receiving and sending.

2.. NET 2.0 support for the serial port

. NET 2.0 provides support for serial communication capabilities, and the classes can be found under namespace System.IO.Ports, the most important of which is the SerialPort class.

By creating a new SerialPort object, we can do it in. NET program to control the whole process of serial communication.

3. Setting the serial port properties using SerialPort

For serial communication, some related parameters need to be set, which can be done by setting the properties of the SerialPort class. The serial port properties mainly include

. PortName serial name, COM1, COM2 and so on.
. BaudRate baud rate, that is, the speed of serial communication, serial communication between the two sides of their baud rate needs the same, if the PC connected to other non-PC systems, generally, the baud rate is determined by the non-PC system.
. Parity parity check. You can select the values in the enumeration parity
. DataBits Data bits
. StopBits stop bit, you can choose to enumerate the values in StopBits
. Handshake handshake Mode, that is, data flow control mode, you can choose to enumerate the values in handshake

4. Open and close the serial port

After you create a SerialPort object and set the serial port properties, you can open the serial port via the Open () method. After the data is read and written, the serial port can be closed via the close () method.

According to experience, for some systems, after opening the serial port, you also need to set the rtsenable to true, in order to read and write data, otherwise it can not read and write data normally.

5. Read and write row data

When communicating with each other, it is generally necessary to define the communication protocol, even if the simplest is to send a text chat through the serial port program.

Typically, when a party presses a carriage return, the text of its data is sent to the other party along with a newline character. In this communication case, the protocol frame is defined by a newline character, each frame data is separated by a newline character, which makes it easy to identify the message sent by the communication.

In the example above, you can use WriteLine () to send the data and use ReadLine () to read the data. After the WriteLine sends the data, the newline character is also sent to the other person as data. ReadLine () reads data until a newline character is encountered, and then returns a String that represents a single line of information. Line breaks can be set through the SerialPort property newline. In general, Windows uses CRLN as a newline character, whereas under Linux, line breaks are represented by only one ln.

The ReadLine () method is blocked until it encounters a newline character and returns. If you have not encountered a newline character while reading the data, throw a timeoutexception after waiting for readtimeout time. By default, ReadTimeout is Infinitetimeout. In this way, the ReadLine is blocked until a new row of data arrives.

The WriteLine () method is also blocked and can cause timeoutexception exceptions if the other party cannot receive data in a timely manner.

Since the ReadLine () and WriteLine () methods are both blocking, when the program uses SerialPort for serial communication, it is generally necessary to leave the read and write operations to other threads to avoid the program not responding because of blocking.

6. Read or write a section or character data

For byte or character data, read the data using the Read () method, which requires a byte or character array as a parameter to hold the read data, and the result returns the actual number of bytes or characters read. Write Data uses the Write () method, which can send byte arrays, character data, or strings to the other party.

If the communication between the two exchanges of data byte stream data, to build a used serial communication program, then the two sides should define the data frame format. Usually the data frame is defined by the frame head and the frame tail.

Sending the data is simple, just send the constructed data with the write () method.

Receiving data is more complex, the traffic is in the form of byte stream, by calling the Read () method does not ensure that the data read is a complete frame. Therefore, each read data needs to be integrated together, the integrated data analysis, in accordance with the defined frame format, through the frame head and frame tail, the frame information from the byte stream extraction, so as to obtain meaningful information.

In addition to reading data using the Read () method, you can also use the readexisting () method to read data. This method reads the data that is currently available to be read and returns it as a string.

7. Event

SerialPort provides the DataReceived event. The event is triggered when there is data coming in. The triggering of the event is determined by the operating system, and when there is data arriving, the event is triggered in the worker thread. The secondary thread has a lower priority, so it does not ensure that every byte of data arrives when the event is triggered.

When you use this event to receive data, it is best to define the communication protocol format and add the frame head and frame tail. When receiving data in the DataReceived event, the data is buffered in an array or a string, and when the received full data containing the frame head and the frame end is processed, and in order to receive the data effectively, the data can be read each time. Join the System.Threading.Thread.Sleep method to demonstrate.

8. Other
Using jumpers to make the serial port 2nd, 3 pin connection, can be implemented on the local computer serial communication, so, through the serial port of the 2nd, 3-pin connection can be detected on the program.

. Bytestoread This property returns the number of bytes that can be read.

Method name



Close the port connection, set the IsOpen property to False, and release the internal Stream object


Open a new serial port connection


Reads data bytes from the SerialPort input buffer


Reads a byte synchronously from the SerialPort input buffer


Synchronously reads a character from the SerialPort input buffer


Read the NewLine value in the input buffer all the time


A string that has been read to the specified value in the input buffer


is overloaded. Writing data to the serial port output buffer


Writes the specified string and NewLine values to the output buffer



Emptying the receive buffer data

Clear the output buffer to go to the data

Property Description




Gets the underlying Stream object of the SerialPort object


Gets or sets the serial baud rate


Gets or sets the interrupt signal status


Gets the number of bytes of data in the receive buffer


Gets the number of bytes of data in the send buffer


Gets the status of the port's carrier detection line


Get the status of a "can send" row


Gets or sets the standard data bit length for each byte


Gets or sets a value that indicates whether Null bytes are ignored when transferred between the port and the receive buffer


Get the status of the data Set Ready (DSR) signal


Gets or sets a value that enables the data Terminal ready (DTR) signal during serial communication


Gets or sets the byte encoding of the text conversion before and after the transfer


Gets or sets the handshake protocol for serial port data transfer


Gets a value that indicates the open or closed state of the SerialPort object


Gets or sets the value used to interpret the end of the ReadLine () and WriteLine () method calls


Gets or sets the parity check protocol


Gets or sets a byte that replaces invalid bytes in the data stream when a parity error occurs


Gets or sets the communication port, including but not limited to all available COM ports


Gets or sets the size of the SerialPort input buffer


Gets or sets the number of milliseconds before a time-out occurs when the read operation does not complete


Gets or sets the number of bytes in the internal input buffer before the DataReceived event occurs


Gets or sets a value that indicates whether the request-send (RTS) signal is enabled in serial communication


Gets or sets the standard number of stop bits per byte


Gets or sets the size of the serial port output buffer


Gets or sets the number of milliseconds before a time-out occurs when the write operation does not complete

Detailed usage of the SerialPort control

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: 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.