About serial interfaces

Source: Internet
Author: User

Serial Port is also called "Serial Port". It is mainly used for serial data transmission. Common RS-232 with general computer applications (using 25-pin or 9-pin connectors) and half duplex RS-485 for industrial computer applications with full duplex RS-422.

Serial interface according to electrical standards and protocols, including RS-232-C, RS-422, RS485, USB and so on. RS-232-C, RS-422 and RS-485 standards only regulate the electrical characteristics of the interface, does not involve connectors, cables or protocols. USB is a new interface standard developed in recent years and is mainly used in the field of high-speed data transmission.
RS-232-C
Also known as standard serial port, it is currently the most commonly used serial communication interface. In 1970, it was jointly developed by the American Association of Electronic Industry (EIA) and Bell systems, modem manufacturers and computer terminal manufacturers for serial communication. Its full name is "Technical Standard for Serial Binary data exchange interfaces between data terminal devices (DTE) and data communication devices (DCE ". The traditional RS-232-C interface standard has 22 wires and adopts the Standard 25-core d plug-in seat. The simplified 9-core d-socket has been used since ibm pc/. So far, 25-core plug-in blocks are rarely used in modern applications. Generally, a computer has two serial ports: COM1, com2, and 9-pin D-interface. Currently, many mobile phone data lines or logistics receivers are connected to computers using a comport. RS-422
In order to improve the shortcomings of short distance and low rate of RS-232 communication, a balanced communication interface is defined in RS-422 to increase the transmission rate to 10 Mb/s, the transmission distance is extended to 4000 feet (when the speed is lower than kb/s), and a maximum of 10 receivers can be connected on a balanced bus. RS-422 is a one-way, balanced transmission specification for single-host transmission and multi-host receiving. It is named as TIA/EIA-422-A standard. RS-485
In order to expand the scope of application, EIA also established RS-422 standards on the basis of RS-485 in 1983, added multi-point, two-way communication capability, that is, allow multiple transmitters to connect to the same bus, at the same time, the driving capability and conflict protection characteristics of the transmitter are added, and the common mode range of the bus is extended, which is named Tia/EIA-485-A standard. Universal Serial Bus (Universal Serial Bus)
USB is a new peripheral interface standard that is widely used on computers and initiated by several major vendors, such as Intel, Microsoft, Compaq, IBM, NEC, and northern Telcom. The USB interface is a four-pin interface on the computer motherboard. The two middle pins transmit data and the two sides supply power to the peripherals. USB interface speed, simple connection, no external power supply, transmission speed 12 Mbps, new USB 2.0 up to 480 Mbps; maximum cable length 5 meters, USB cable has four lines: two signal lines and two power lines can provide a 5 volt power supply. The USB cable can also be shielded or unshielded. The transmission speed of the shielded cable can reach 12 Mbps, which is expensive, the unshielded cable speed is 1.5 Mbps, but the price is low. USB can be connected to up to 127 devices in series. Hot swapping is supported. The latest USB 3.0 specification is available. RJ-45 Interface
Is the most common interface for Ethernet. RJ45 is a common name, which refers to the eight locations (8-pin) defined by IEC (60) 603-7 using the International connector standard) modular Jack or plug.

 

Serial Port Properties

1. portname: Default Value of Serial Port name: COM1

The serial port is a file for the operating system. If you set portname to a serial port name (that is, the file name) that does not exist on the local machine, for example, "COM7" or "comk", opening () will fail to open the serial port, the message "port COM7 does not exist" is displayed ".

2. baudrate gets or sets the serial baud rate bit/s. The default value is 9600.

Bit Rate = baud rate X binary digits corresponding to a single modulation state.

RS232 is to use a maximum distance of 30 m on close-range transmission.

RS485 is used for long distance transmission with a maximum distance of 1200 m

3. databits: Get or set the length of standard data bits for each byte. The default value is 8.

When a computer sends an information package, the actual data is not 8 bits, and the standard values are 5, 7, and 8 bits. The setting depends on the information you want to transmit. For example, the standard ASCII code is 0 ~ 127 (7 digits ). The extended ASCII code is 0 ~ 255 (8 digits ). If the data uses simple text (Standard ASCII code), each packet uses 7-bit data. Each package

It refers to a byte, including the start/stop bits, data bits, and parity bits. Because the actual data bit depends on the selection of the communication protocol, the term "package" refers to any communication situation.

4. stopbits get or set the standard stop bits of each byte. Default Value: One

Used to represent the last digit of a single package. The typical values are 1, 1.5, and 2. Because the data is scheduled on the transmission line, and each device has its own clock, it is very likely that there is a small non-synchronization between the two devices in the communication. Therefore, the stop bit is not only the end of the transmission, but also the opportunity for the computer to correct the clock synchronization. Applicable to the number of Stop bits

The more, the higher the degree of tolerance for different clock synchronization, but the slower the data transmission rate.

5. Parity gets or sets the default value of the Parity Check protocol to none.

A simple error checking method in serial communication. There are four error checking methods: Even, Odd, tall, and low. Of course, it is acceptable that there is no checkpoint. In the case of parity and odd parity, the serial port sets the parity bit (one digit after the data bit), and uses a value to ensure that the transmitted data has even or Odd logic highs. For example, if the data is 011, perform parity verification.

The number of bits is 0, which ensures that the number of bits in the logic is an even number. If it is an odd check,

Check bit 1, so there are three logic High. High-level and low-level check data, simple location logic high or low-level Logic validation. In this way, the receiving device can know the status of a single position, and has the opportunity to determine whether there is noise that interferes with communication or whether there is transmission or reception.

 

Three methods of reading/writing through the serial port (COM:

The 1st method is to use the SerialPort class, which is a serial control launched by Microsoft in. net2.0, but must be. net2.0.
The 2nd method is to use APIs to write serial communication. Although it is difficult, you can easily implement the various functions you want.
The first method is to use the original MSComm control in Visual Studio 3rd. This is the simplest and most convenient method, but you need to register it.

 

Serial port operations and related method events under. Net:

In. NET 2.0 +, you have provided components for serial port operations.

Allows you to easily perform data reading and writing through the serial port.

Some important methods and events are explained as follows:

1. open () open a new serial port connection

2. Close () to close the port connection, set the isopen attribute to false, and release the internal Stream object.

3. Read (byte [], Int, INT) the input buffer reads some bytes and writes those bytes to the offset specified in the byte array.

4. readbyte () synchronously reads a byte from the SerialPort input buffer

5. readchar () synchronously reads one character from the SerialPort input buffer

6. readexisting () reads the stream of the SerialPort object and all immediately available bytes in the input buffer based on the encoding.

6. Readline () reads the newline value from the input buffer.

7. readto () always reads the string of the specified value in the input buffer

8. Write (string) writes the specified string to the serial port.

9. Write (byte [], Int, INT) writes a specified number of characters to the serial port using the data in the buffer zone

10. writeline () writes the specified string and newline value to the output buffer.

11. discardinbuffer () discards the data in the receiving buffer.

12. discardoutbuffer () discards the data in the sending buffer.

12. Obtain the serial port name array of the current computer using static getportnanes ().

13. How to receive events from datareceive event data

It is not guaranteed that each byte received by the connection will trigger the datareceived event. Use the bytestoread attribute to determine the amount of data to be read in the buffer zone. When receiving data from the SerialPort object, the datareceived event is triggered on the auxiliary thread.

14. pinchanged event serial pin change event Method

Triggered when the SerialPort object enters the breakstate, but not when the port exits the breakstate. The pinchanged event will be triggered on the auxiliary thread.

15. errorreceived event error event Method

If a parity error occurs on the last byte of the stream, an additional byte with a value of 126 will be added to the input buffer. The pinchanged event will be triggered on the auxiliary thread.

 

CodeExample:
         # Region Open serial port Private   Void Btnopencom_click ( Object Sender, eventargs e ){ String _ Scom = String . Empty; // Serial number              If (Checkissltcom ( Ref _ Scom )){ Try { String _ Sdatebits = This . Cbdatebits. Text. Trim (); // Data bit                      String _ Sbondrate = This . Cbbondrate. Text. Trim (); // Baud rate                      String _ Sstopbit = This . Cbstopbit. Text. Trim (); // Stop bit                      String _ Sparity = This . Cbparity. Text. Trim (); // Verify Initopencom (_ scom, _ sdatebits, _ sbondrate, _ sparity, _ sstopbit); toolstripstatuslabel. Text =String . Format ( "The serial port number {0} is successfully enabled }." , _ Scom );} Catch (Exception ex) {toolstripstatuslabel. Text = String . Format ( "Opening serial port number: {0} failed! Cause: {1 }." , _ Scom, Ex. Message. Trim (); SerialPort. Dispose ();} Finally {Writelog (toolstripstatuslabel. Text, logtype. wirtelog );}}} # Endregion 
         # Region Initialize serial port Private   Void Initopencom ( String _ Scom, String _ Sdatebits, String _ Sbondrate, String _ Sparity, String _ Sstopbit ){ If (SerialPort. isopen) SerialPort. close (); SerialPort. portname = _ scom; SerialPort. baudrate = convert. toint32 (_ sbondrate); SerialPort. databits = convert. toint32 (_ sdatebits ); Switch (_ Sstopbit ){ Case   "1" : SerialPort. stopbits = stopbits. One;Break ; Case   "1.5" : SerialPort. stopbits = stopbits. onepointfive; Break ; Case   "2" : SerialPort. stopbits = stopbits. Two; Break ; Default : SerialPort. stopbits = stopbits. None; Break ;} SerialPort. databits = convert. toint32 (_ sdatebits ); Switch (_ Sparity ){Case   "Even" : SerialPort. Parity = parity. Even; Break ; Case   "Odd" : SerialPort. Parity = parity. Odd; Break ; Case   "Space" : SerialPort. Parity = parity. space; Break ; Case   "Flag" : SerialPort. Parity = parity. mark; Break ; Case   "None" : SerialPort. Parity = parity. None; Break ;} SerialPort. open ();} # Endregion 
# RegionDetermine whether the selected serial port is validPrivate BoolCheckissltcom (Ref String_ Scom ){If(String. Isnullorempty (cbcom. Text. Trim () {devoperate. showtooltip <comboboxedit> (tooltipcontroller,"Select the serial port number! ", Cbcom );Return False;} _ Scom = cbcom. Text. Trim ();Return True;}# Endregion
 # Region Close serial port Private   Void Btnclosecom_click (Object Sender, eventargs e ){ String _ Scom = String . Empty; // Serial number              If (Checkissltcom ( Ref _ Scom )){ Try { If (SerialPort. isopen) SerialPort. Close (); toolstripstatuslabel. Text = String . Format ( "The serial port number is disabled successfully: {0 }." , _ Scom );} Catch (Exception ex) {toolstripstatuslabel. Text = String . Format ( "Closing serial port number: {0} failed! Cause: {1 }." , _ Scom, Ex. Message. Trim (); SerialPort. Dispose ();} Finally {Writelog (toolstripstatuslabel. Text, logtype. wirtelog );}}} # Endregion 
         # Region Serial Port Data Receiving Event Private   String Scomstr = String . Empty; Private   Void Serialport_datareceived (Object Sender, serialdatareceivedeventargs e ){ Try { Byte [] _ Readbuffer = New   Byte [SerialPort. readbuffersize]; Lock (_ Readbuffer. syncroot ){ Int _ Nbytesread = SerialPort. Read (_ readbuffer, 0, _ readbuffer. Length ); String _ Sstrtmpcom = bytehelper. bytetohexstr (_ readbuffer, _ nbytesread); scomstr + = _ sstrtmpcom; If (Onserialportreceived! =Null ) Onserialportreceived (_ sstrtmpcom ); If (! Ckcomrecivefilter. Checked) writelog ( String . Format ( "Receipt: {0 }." , _ Sstrtmpcom), logtype. wirtelog ); If (Scomstr. startswith ( "68" ) & Scomstr. endswith ( "16" )){ If (Ckcomrecivefilter. Checked) writelog ( String . Format ( "Receipt: {0 }." , Scomstr), logtype. wirtelog ); If (Onserialportreceivedbys! = Null ) Onserialportreceivedbys (bytehelper. hexstrtobytearray (scomstr), 0); scomstr = String . Empty; _ readbuffer = Null ;}}} Catch (Exception ex) {writelog ( String . Format ( "Receiving exception, cause: {0 }" , Ex. Message. Trim (), logtype. dialoglog );}} # Endregion 

Running Effect

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.