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 ");
} <

Related Article

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.