. NET 2.0 Serial Communication Class SerialPort usage sorting
1. 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, and the USB interface is very complicated, it is usually used in places where a large amount of data needs to be transmitted.
Such as USB flash drives, cameras, and printers. In addition to USB, the more luxurious serial port, in industrial control and embedded industry, a large number of use is another ancient serial port protocol, RS-232 serial port. RS-
232 is a very simple low-speed serial communication interface that can receive and send data at the same time.
2 .. NET 2.0 support for serial ports
. NET 2.0 provides support for the serial communication function. You can find related classes under the namespace system. Io. ports. The most important of these classes is the SerialPort class.
By creating a new SerialPort object, we can control the whole process of serial communication in the. NET program.
3. Use SerialPort to set serial port Properties
For serial communication, you need to set some relevant parameters. You can set the SerialPort class attributes. Serial Port attributes mainly include
. Portname serial port name, COM1, com2, etc.
. Baudrate baud rate, that is, the speed of serial communication. The baud rate of both parties for serial communication must be the same. If you use a PC to connect to other non-PC systems, generally, the baud rate is determined by the non-PC system.
. Parity parity. You can select values in the enumerated parity.
. Databits data bit
. Stopbits stop bit. You can select the value in the enumerated stopbits.
. Handshake handshake mode, that is, data stream control mode, you can select the value in the enumeration handshake
4. Enable and disable the serial port
After creating a SerialPort object and setting the serial port properties, you can open the serial port through the open () method. After data is read/written, you can close the serial port by using the close () method.
Based on experience, for some systems, after enabling the serial port, you also need to set rtsenable to true to read and write data. Otherwise, data cannot be read and written normally.
5. Read/write row data
When both parties communicate, they generally need to define the communication protocol, even though the simplest program that sends text chat through the serial port.
Generally, when one party presses the carriage return, it sends the text of the data together with the line break to the other party. In this communication case, the Protocol Delimiter is defined by a line break, and each token data is separated by line breaks, so that it is easy to identify the information sent by the dual-sending communication.
In the preceding example, you can use writeline () to send data and Readline () to read data. After writeline sends the data, it will also send the line break as the data
To the other party. When Readline () is used to read data, a linefeed is returned, indicating a row of information. You can use the SerialPort
Newline. In general, Windows uses crln as a line break, while in Linux, linefeed is represented by only one ln.
The Readline () method is blocked until a line break is returned. If the line break is not encountered during data reading,
Timeoutexception. By default, readtimeout is infinitetimeout. In this way, Readline is always in the blocking status,
Until a new row of data arrives.
The writeline () method is also blocked. If the other party cannot receive data in time, it will cause a timeoutexception exception.
Since the Readline () and writeline () methods are both blocking, when the program uses SerialPort for serial communication, read/write operations should generally be handled by other threads, avoid program non-response due to blocking.
6. Read/write bytes or character data
For bytes or character data, the read () method is used to read data. This method requires a byte or character array as a parameter to save the read data, returns the number of bytes or characters actually read. Use the write () method to write data. This method can send byte arrays, character data, or strings to the other party.
If both parties need to build a serial communication program to exchange data bit byte stream data, the two parties should define the data segment format. Generally, the data sequence is defined by the sequence header and the sequence end.
Sending data is relatively simple. You only need to send the constructed data using the write () method.
Receiving data is complicated, and communication is in the form of byte streams. Calling the read () method once does not ensure that the data read is complete. Therefore, you need to integrate the data read each time in
To analyze the integrated data. According to the defined bytes format, the bytes information is extracted from the byte stream through the Expires header and the suffix, so that meaningful information can be obtained.
In addition to using the read () method to read data, you can also use the readexisting () method to read data. This method reads the data that can be read and returns the data in the form of a string.
7. Event
SerialPort provides datareceived events. This event is triggered when data enters. The trigger of this event is determined by the operating system. When data arrives, this event is triggered in the auxiliary thread. The priority of the auxiliary thread is relatively low. Therefore, this event cannot be triggered when data in each byte arrives.
When using this event to receive data, it is best to define the communication protocol format and add the Expires header and expires tail. When receiving data in a datareceived event, the data is cached in an array or a string. When the received complete data contains the Expires header and the end of the expires, it is processed. In addition, to effectively receive data, you can add system after each data read. threading. thread. sleep method.
8. Others
Use a jumper to connect the 2nd and 3 pins of the serial port to Realize Serial Communication on the local computer. Therefore, the program can be detected through the 2nd and 3 pins of the serial port.
. Bytestoread this attribute returns the number of bytes that can be read.
Method Name |
Description |
Close |
Close the port connection, set the isopen attribute to false, and release the internal Stream object. |
Open |
Open a new serial port connection |
Read |
Number of bytes read from the SerialPort input buffer |
Readbyte |
Synchronously reads one byte from the SerialPort input buffer |
Readchar |
Synchronously read one character from the SerialPort input buffer |
Readline |
Reads the newline value from the input buffer. |
Readto |
Reads the string of the specified value in the input buffer all the time. |
Write |
Overloaded. Write Data to the output buffer of the serial port |
Writeline |
Writes the specified string and newline value to the output buffer. |
Discardinbuffer Discardoutbuffer |
Clear Received Buffer data Clear output buffer to data |
Attribute description
Name |
Description |
Basestream |
Obtain the basic Stream Object of the SerialPort object |
Baudrate |
Get or set the serial baud rate |
Breakstate |
Obtains or sets the interrupt signal status. |
Bytestoread |
Obtain the number of bytes of data in the receiving buffer. |
Bytestowrite |
Obtains the number of bytes of data in the sending buffer. |
Cdholding |
Obtains the status of the Carrier Detection Line on the port. |
Ctsholding |
Obtain the status of the "sendable" Row |
Databits |
Obtains or sets the length of standard data bits for each byte. |
Discardnull |
Gets or sets a value that indicates whether null bytes are ignored during transmission between the port and the receiving buffer. |
Dsrholding |
Obtain the status of the data set-up (DSR) Signal |
Dtrenable |
Gets or sets a value that enables DTR signals during serial communication. |
Encoding |
Obtains or sets the byte encoding for text conversion before and after transmission. |
Handshake |
Obtains or sets the handshake protocol for serial port data transmission. |
Isopen |
Gets a value indicating whether the SerialPort object is enabled or disabled. |
Newline |
Gets or sets the value used to explain the end of the call of the Readline () and writeline () methods. |
Parity |
Obtain or set the Parity Check protocol |
Parityreplace |
Gets or sets a byte that replaces the invalid byte in the data stream in case of a parity error. |
Portname |
Obtains or sets communication ports, including but not limited to all available COM ports. |
Readbuffersize |
Gets or sets the size of the SerialPort input buffer. |
Readtimeout |
Gets or sets the number of milliseconds before the read operation has timed out before it has been completed. |
Receivedbytesthreshold |
Obtains or sets the number of bytes in the input buffer before the datareceived event occurs. |
Rtsenable |
Gets or sets a value indicating whether to enable the request sending (RTS) signal in serial communication. |
Stopbits |
Obtains or sets the standard stop bits for each byte. |
Writebuffersize |
Obtains or sets the size of the serial port output buffer. |
Writetimeout |
Gets or sets the number of milliseconds before the time-out occurs when the write operation is not completed. |