C # SerialPort class

Source: Internet
Author: User

SerialPort class

Indicates a serial port resource.

Inheritance hierarchy

--------------------------------------------------------------------------------

System. Object
System. externalbyrefobject
System. ComponentModel. Component
System. IO. Ports. SerialPort

 

Namespace: System. IO. Ports
Assembly: System (in System. dll)

Syntax

--------------------------------------------------------------------------------

C #

Public class SerialPort: Component
 
The SerialPort type exposes the following members.

 

Constructor

--------------------------------------------------------------------------------
Name

Description

 

 

SerialPort ()

Initialize a new instance of the SerialPort class.

SerialPort (IContainer)

Use the specified IContainer object to initialize a new instance of the SerialPort class.

SerialPort (String)

Use the specified port name to initialize a new instance of the SerialPort class.

 

SerialPort (String, Int32)

Use the specified port name and baud rate to initialize a new instance of the SerialPort class.

 

SerialPort (String, Int32, Parity)

Use the specified port name, baud rate, and parity bit to initialize a new instance of the SerialPort class.

 

SerialPort (String, Int32, Parity, Int32)

Use the specified port name, baud rate, check bit, and data bit to initialize a new instance of the SerialPort class.

 

SerialPort (String, Int32, Parity, Int32, StopBits)

Use the specified port name, baud rate, parity bit, data bit, and stop bit to initialize a new instance of the SerialPort class.

Attribute

--------------------------------------------------------------------------------

Description

BaseStream

Obtain the basic Stream Object of the SerialPort object.

BaudRate

Gets or sets the serial baud rate.

 
BreakState

Obtains or sets the interrupt signal status.

BytesToRead

Obtains the number of bytes of data in the receiving buffer.

BytesToWrite

Obtains the number of bytes of data in the sending buffer.

CanRaiseEvents

Gets a value indicating whether a component can trigger an event.
(Inherited from Component .)

CDHolding

Obtains the status of the Carrier Detection Line on the port.

Container

Obtain IContainer, which contains Component.
(Inherited from Component .)

 

CtsHolding

Obtain the status of the row that can be sent.

DataBits

Obtains or sets the length of standard data bits for each byte.

 

DesignMode

Gets a value to indicate whether the Component is in the design mode. (Inherited from Component .)

 

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.

 

Events

Obtains the list of Event Handlers appended to this component. (Inherited from component .)

 

Handshake

Obtains or sets the handshake protocol for serial port data transmission.

 

Isopen

Gets a value that indicates whether the SerialPort object is enabled or disabled.

 

Newline

Gets or sets the value used to explain the end of the call to 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

Obtain or set the communication port, 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 times out.

 

ReceivedBytesThreshold

Obtain or set 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.

 

Site

Gets or sets the ISite of Component. (Inherited from Component .)

 

StopBits

Obtains or sets the standard stop bits for each byte.

 

WriteBufferSize

Gets 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.

Method

--------------------------------------------------------------------------------

Description

Close

Close the port connection, set the IsOpen attribute to false, and release the internal Stream object.

 

CreateObjRef

Create an object that contains all the information required to generate a proxy for communication with a remote object. (Inherited from MarshalByRefObject .)

 

DiscardInBuffer

Discards data from the receiving buffer of the serial driver.

 

DiscardOutBuffer

Discard data from the transmission buffer of the serial driver.

 

Dispose ()

All resources used by Component. (Inherited from Component .)

 

Dispose (Boolean)

Put the unmanaged resources occupied by SerialPort and release the managed resources. (Override Component. Dispose (Boolean ).)

 

Equals (Object)

Determines whether the specified object is equal to the current object. (Inherited from Object .)

 

Finalize

Before the Component is reclaimed through garbage collection, release the unmanaged resources and perform other cleanup operations. (Inherited from Component .)

 

GetHashCode

As a hash function of a specific type. (Inherited from Object .)

 

GetLifetimeService

The current lifetime service object that controls the lifetime policy of this instance. (Inherited from MarshalByRefObject .)

 

GetPortNames

Obtains the serial port name array of the current computer.

 

GetService

Returns an object that represents the service provided by Component or its Container. (Inherited from Component .)

 

GetType

The Type of the current instance. (Inherited from Object .)

 

InitializeLifetimeService

The lifetime service object that controls the lifetime policy of this instance. (Inherited from MarshalByRefObject .)

 

MemberwiseClone ()

Creates a superficial copy of the current Object. (Inherited from Object .)

 

MemberwiseClone (Boolean)

Creates a superficial copy of the currently stored albyrefobject object. (Inherited from MarshalByRefObject .)

 

Open

Open a new serial port connection.

 

Read (Byte [], Int32, Int32)

The SerialPort input buffer reads some bytes and writes those bytes to the specified offset in the byte array.

 

Read (Char [], Int32, Int32)

The SerialPort input buffer reads a large number of characters and writes these characters to the offset specified in a character array.

 

ReadByte

Synchronously reads one byte from the SerialPort input buffer.

 

ReadChar

A character is synchronously read from the SerialPort input buffer.

 

ReadExisting

Based on the encoding, read the stream of the SerialPort object and all immediately available bytes in the input buffer.

 

ReadLine

Directly read the NewLine value in the input buffer.

 

ReadTo

Directly read the string of the specified value in the input buffer.

 

ToString

Returns the String containing the Component name (if any ). This method should not be rewritten. (Inherited from Component .)

 

Write (String)

Writes the specified string to the serial port.

 

Write (Byte [], Int32, Int32)

Write the specified number of bytes to the serial port using the data in the buffer zone.

 

Write (Char [], Int32, Int32)

Write a specified number of characters into the serial port using the data in the buffer zone.

 

WriteLine

The specified string and NewLine value are written to the output buffer.

Event

--------------------------------------------------------------------------------

Description

DataReceived

The method that processes the data receiving events of the SerialPort object.

Disposed

It occurs when you call the Dispose method to release a component. (Inherited from Component .)

 

ErrorReceived

Method used to process the error event of the SerialPort object.

 

PinChanged

The method that will handle the serial pin change event of the SerialPort object.

Field

--------------------------------------------------------------------------------

Description

 

InfiniteTimeout

Indicates that timeout should not occur.

Remarks

--------------------------------------------------------------------------------

 

This class is used to control serial port file resources. This class provides synchronous I/O and event-driven I/O, access to pin and interrupt statuses, and access to serial driver attributes. In addition, such functions can be encapsulated in internal Stream objects, accessed through the BaseStream attribute, and can be passed to classes that encapsulate or use streams.

The SerialPort class supports the following encoding: ASCIIEncoding, UTF8Encoding, UnicodeEncoding, UTF32Encoding, and all codes defined in mscorlib. dll whose code page is less than 50000 or 54936. You can use the backup encoding, but you must use the ReadByte or Write method and perform the encoding yourself.

Use the GetPortNames method to retrieve valid ports of the current computer.

If the SerialPort object is blocked during a read operation, do not stop the thread. Conversely, you can disable the basic stream or process SerialPort object.

 

Example

--------------------------------------------------------------------------------

 

The following code example demonstrates how to use the SerialPort class to allow two users to chat on two independent computers connected by a NULL modem cable. In this example, you are prompted to enter the port settings and user name before chatting. The two computers must execute the program at the same time to implement all the functions in this example.

C #

 

Using System;
Using System. IO. Ports;
Using System. Threading;

Public class PortChat
{
Static bool _ continue;
Static SerialPort _ serialPort;

Public static void Main ()
{
String name;
String message;
StringComparer stringComparer = StringComparer. OrdinalIgnoreCase;
Thread readThread = new Thread (Read );

// Create a new SerialPort object with default settings.
_ SerialPort = new SerialPort ();

// Allow the user to set the appropriate properties.
_ SerialPort. PortName = SetPortName (_ serialPort. PortName );
_ SerialPort. BaudRate = SetPortBaudRate (_ serialPort. BaudRate );
_ SerialPort. Parity = SetPortParity (_ serialPort. Parity );
_ SerialPort. DataBits = SetPortDataBits (_ serialPort. DataBits );
_ SerialPort. StopBits = SetPortStopBits (_ serialPort. StopBits );
_ SerialPort. Handshake = SetPortHandshake (_ serialPort. Handshake );

// Set the read/write timeouts
_ SerialPort. ReadTimeout = 500;
_ SerialPort. WriteTimeout = 500;

_ SerialPort. Open ();
_ Continue = true;
ReadThread. Start ();

Console. Write ("Name :");
Name = Console. ReadLine ();

Console. WriteLine ("Type QUIT to exit ");

While (_ continue)
{
Message = Console. ReadLine ();

If (stringComparer. Equals ("quit", message ))
{
_ Continue = false;
}
Else
{
_ SerialPort. WriteLine (
String. Format ("<{0} >:{ 1}", name, message ));
}
}

ReadThread. Join ();
_ SerialPort. Close ();
}

Public static void Read ()
{
While (_ continue)
{
Try
{
String message = _ SerialPort. Readline ();
Console. writeline (Message );
}
Catch (timeoutexception ){}
}
}

Public static string setportname (string defaultportname)
{
String portname;

Console. writeline ("available ports :");
Foreach (string s in SerialPort. GetPortNames ())
{
Console. WriteLine ("{0}", s );
}

Console. Write ("COM port ({0}):", defaultPortName );
PortName = Console. ReadLine ();

If (portName = "")
{
PortName = defaultPortName;
}
Return portName;
}

Public static int SetPortBaudRate (int defaultPortBaudRate)
{
String baudRate;

Console. Write ("Baud Rate ({0}):", defaultPortBaudRate );
BaudRate = Console. ReadLine ();

If (baudRate = "")
{
BaudRate = defaultPortBaudRate. ToString ();
}

Return int. Parse (baudRate );
}

Public static Parity SetPortParity (Parity defaultPortParity)
{
String parity;

Console. WriteLine ("Available Parity options :");
Foreach (string s in Enum. GetNames (typeof (Parity )))
{
Console. WriteLine ("{0}", s );
}

Console. Write ("Parity ({0}):", defaultPortParity. ToString ());
Parity = Console. ReadLine ();

If (parity = "")
{
Parity = defaultPortParity. ToString ();
}

Return (Parity) Enum. Parse (typeof (Parity), parity );
}

Public static int SetPortDataBits (int defaultPortDataBits)
{
String dataBits;

Console. Write ("Data Bits ({0}):", defaultPortDataBits );
DataBits = Console. ReadLine ();

If (dataBits = "")
{
DataBits = defaultPortDataBits. ToString ();
}

Return int. Parse (dataBits );
}

Public static StopBits SetPortStopBits (StopBits defaultPortStopBits)
{
String stopBits;

Console. WriteLine ("Available Stop Bits options :");
Foreach (string s in Enum. GetNames (typeof (StopBits )))
{
Console. WriteLine ("{0}", s );
}

Console. Write ("Stop Bits ({0}):", defaultPortStopBits. ToString ());
StopBits = Console. ReadLine ();

If (stopBits = "")
{
StopBits = defaultPortStopBits. ToString ();
}

Return (StopBits) Enum. Parse (typeof (StopBits), stopBits );
}

Public static Handshake SetPortHandshake (Handshake defaultPortHandshake)
{
String handshake;

Console. WriteLine ("Available Handshake options :");
Foreach (string s in Enum. GetNames (typeof (Handshake )))
{
Console. WriteLine ("{0}", s );
}

Console. Write ("Handshake ({0}):", defaultPortHandshake. ToString ());
Handshake = Console. ReadLine ();

If (handshake = "")
{
Handshake = defaultPortHandshake. ToString ();
}

Return (Handshake) Enum. Parse (typeof (Handshake), handshake );
}
}

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.