C # Serial SerialPort operation

Source: Internet
Author: User

 

Currently, most hardware devices use serial port technology to connect to computers. Therefore, serial port application development is becoming more and more common. For example, if the computer does not have an Nic installed, it can transmit some information data from the local computer to another computer, so it can be achieved through serial communication. Run this program, enter the data to be transferred in the "send data" text box, click the "send" button to send the data to the selected port number, and click the "receive" button, the transmitted data is received in the "receive data" text box. 13.1.

Technical Points

The SerialPort class is provided in. NET Framework 2.0, which implements serial data communication. The following describes the main attributes (Table 13.1) and methods (Table 13.2) of this class ).

Table 13.1 common attributes of the SerialPort class

 

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

Continue table

 

Name

 

Description

 

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.

Table 13.2 common methods of the SerialPort class

 

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

 

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.

Note: If you use a jumper to connect the serial port with 2nd or 3 pins, you can achieve serial communication on the local computer. Therefore, you can detect the program through the serial port with 2nd or 3 pins. The serial port section 13.2 is shown in.

Figure 13.2 serial port section

Implementation Process

(1) create a new project named ex13_01. The default form is form1.

(2) In the form1 form, two buttons are added for sending and receiving data, and two textbox controls are added for inputting sent data and displaying received data.

(3) Main program code.

Private void button#click (Object sender, eventargs E)

{

Serialport1.portname = "COM1 ";

Serialport1.baudrate = 9600;

Serialport1.open ();

Byte [] daTa = encoding. Unicode. getbytes (textbox1.text );

String STR = convert. tobase64string (DATa );

Serialport1.writeline (STR );

MessageBox. Show ("data is sent successfully! "," System prompt ");

}

Private void button2_click (Object sender, eventargs E)

{

Byte [] daTa = convert. frombase64string (serialport1.readline ());

Textbox2.text = encoding. Unicode. getstring (DATa );

Serialport1.close ();

MessageBox. Show ("data received successfully! "," System prompt ");

}

Let alone

Based on this instance, you can implement the following functions.

Remote monitoring of the recipient's computer screen.

The lower computer control program.

Instance 419 closes the peer computer through serial port

Instance description

In network applications, data is transmitted through the network card. Therefore, you can use socket technology to remotely close the computer. If no Nic is installed on the computer, how can I disable the computer remotely? In this example, the serial port is used to shut down the peer computer. The program running result is 13.3.

Technical Points

This instance uses the attributes and methods of the SerialPort class. For details, see "sending data through serial port ". The following describes the datareceived events of the SerialPort class. The datareceived event is the main application technology of this instance. The datareceived event indicates the method that will process the data receiving event of the SerialPort object. The serial receiving event can be caused by any items in the serialdata enumeration. The operating system determines whether to trigger this event. Therefore, it may not necessarily report all parity errors.

Note: The development and testing of this instance are all completed by the local computer. You only need to use the jumper to connect the 2nd and 3-pin serial ports. You can achieve serial communication on the local computer. For jumper connection, see Figure 13.2.

Implementation Process

(1) create a new project named ex13_02. The default form is form1.

(2) In the form1 form, two buttons are added to enable the communication serial port and disable the other computer respectively.

(3) Main program code.

Private void button#click (Object sender, eventargs E)

{

// Open the serial port

Serialport1.portname = "COM1 ";

Serialport1.open ();

Button1.enabled = false;

Button2.enabled = true;

} // Data Receiving Event, waiting for receiving the shutdown command

Private void serialport1_datareceived (Object sender, serialdatareceivedeventargs E)

{

Byte [] daTa = convert. frombase64string (serialport1.readline ());

String STR = encoding. Unicode. getstring (DATa );

Serialport1.close ();

If (STR = "shutdown ")

{

PROCESS p = new process ();

P. startinfo. filename = "cmd.exe ";

P. startinfo. useshellexecute = false;

P. startinfo. redirectstandardinput = true;

P. startinfo. redirectstandardoutput = true;

P. startinfo. redirectstandarderror = true;

P. startinfo. createnowindow = true;

P. Start ();

P. standardinput. writeline ("shutdown/s ");

P. standardinput. writeline ("exit ");

}

} // Send the shutdown command

Private void button2_click (Object sender, eventargs E)

{

If (button2.text = "Disable computer ")

{

// Send shutdown command data

Byte [] daTa = encoding. Unicode. getbytes ("shutdown ");

String STR = convert. tobase64string (DATa );

Serialport1.writeline (STR );

Button2.text = "cancel shutdown ";

}

Else

{

Button2.text = "turn off the computer ";

Button1.enabled = true;

Button2.enabled = false;

// Cancel Shutdown

PROCESS p = new process ();

P. startinfo. filename = "cmd.exe ";

P. startinfo. useshellexecute = false;

P. startinfo. redirectstandardinput = true;

P. startinfo. redirectstandardoutput = true;

P. startinfo. redirectstandarderror = true;

P. startinfo. createnowindow = true;

P. Start ();

P. standardinput. writeline ("shutdown/");

P. standardinput. writeline ("exit ");

}

}

One problem found in my test software is that when the data sent is less than or equal to 8 bits, everything works normally. If the data sent is larger than 8 bytes, the data received in the datareceived event is divided into two segments, the first segment is 8 bits, and the second segment is the remaining bytes, which is strange, as mentioned in msdn, the data sent each time cannot be correctly received. You need to refer to the bytestoread attribute to determine the data volume to be read, so the solution I have come up with is:

Int datalength = SerialPort. bytestoread;

Int I = 0;

Stringbuilder sb = new stringbuilder ();

While (I <datalength)

{

Byte [] DS = new byte [1024];

Int Len = SerialPort. Read (DS, 0,1024 );

SB. append (encoding. ASCII. getstring (DS, 0, Len ));

I + = Len;

}

Console. Write (SB, tostring ());

This strange method can solve the problem. Later I thought it might be determined by the serial port's working method. I look forward to other solutions.

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.