C # Serial Port and MODEM communication
09: 52643 people read comments (8) collect reports
Recently, I tried serial data transmission. in C #, there is actually a good SerialPort class that makes communication between serial ports easy and easy to control.
1. The basic attributes of SerialPort are given below:
Serialport1.portname = "COM1"; // open the port of the specified serial port, or com2.
Serialport1.baudrate = 9600; // baud rate, which is a term in communication. You can check the relevant information, generally 9600.
Serialport1.databits = 8; // transmits data bits and transmits several binary data at a time.
Serialport1.parity = parity. None; // check, which can be divided into three types: Odd verification, even verification, and non-validation.
Serialport1.stopbits = stopbits. One; // The stop bit.
Serialport1.dtrenable = true; // enable the data terminal at the beginning. it corresponds to the tr signal on the modem. If the light is not on, data cannot be transmitted. Therefore, this sentence should be added to MODEM communication. prepare the terminal device.
Serialport1.rtsenable = true; // The request is sent.
Serialport1.encoding = encoding. ASCII; // encoding can be defined because the data is sent in byte arrays.
The encoding formats include ASCII (English only), Unicode (Chinese and English can be transmitted), and ut8 (Chinese and English.
Note that if you use write (byte [], intstart, int length), You 'd better determine the encoding by yourself, instead of setting serialport1.encoding = encoding. ASCII. For example:
When you want to transmit
String strsend = "hackenliu ";
Then, convert strsend to byte [] format as follows:
Byte [] DATA = encoding. ASCII. getbytes (strsend );
Serialport1.write (data, 0, Data. Length); // The data is sent.
In encoding, you can select the preceding ASCII, uicode, or ut8. However, you must note that the encoding of the recipient must be the same.
2. Open the serial port:
If (serialport1.isopen)
{
Serialport1.close ();
Serialport1.open ();
}
Else
Serialport1.open ();
Lblshow. Text = "Serial Port enabled ";
3. Send data:
The SerialPort class provides many data sending functions, including write (PARAM) and writeline ();
4. receive data:
Add events of the SerialPort class
Privatevoid serialport1_datareceived (Object sender, system. Io. Ports. serialdatareceivedeventargs E)
When there is data, it will automatically receive.