Class SerialPort
Represents a serial port resource.
public sealed class SerialPort : IDisposable
- Inheritance
-
SerialPort
- Implements
- Inherited Members
- Extension Methods
Constructors
SerialPort(string, int, Parity, int, StopBits)
Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, data bits, and stop bit.
public SerialPort(string portName, int baudRate = 9600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One)
Parameters
portName
stringThe port to use (for example, COM1).
baudRate
intThe baud rate.
parity
ParityOne of the Parity values.
dataBits
intThe data bits value.
stopBits
StopBitsOne of the StopBits values.
Exceptions
- IOException
The specified port could not be found or opened.
- ArgumentException
The specified port is already opened.
Properties
BaseStream
Gets the underlying Stream object for a SerialPort object.
public Stream BaseStream { get; }
Property Value
Exceptions
- InvalidOperationException
The stream is closed. This can occur because the Open() method has not been called or the Close() method has been called.
BaudRate
Gets or sets the serial baud rate.
public int BaudRate { get; set; }
Property Value
Exceptions
- ArgumentOutOfRangeException
The baud rate specified is less than or equal to zero, or is greater than the maximum allowable baud rate for the device.
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
BytesToRead
Gets the number of bytes of data in the receive buffer.
public int BytesToRead { get; }
Property Value
- int
The number of bytes of data in the receive buffer.
Exceptions
- InvalidOperationException
The port is not open.
DataBits
Gets or sets the standard length of data bits per byte.
public int DataBits { get; set; }
Property Value
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
- ArgumentOutOfRangeException
The data bits value is less than 5 or more than 8.
Handshake
Gets or sets the handshaking protocol for serial port transmission of data using a value from Handshake.
public Handshake Handshake { get; set; }
Property Value
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
- ArgumentOutOfRangeException
The value passed is not a valid value in the Handshake enumeration.
InvertSignalLevels
Gets or sets a value indicating whether the logic level of the RX and TX signals are inverted.
public bool InvertSignalLevels { get; set; }
Property Value
Remarks
When the signal levels are not inverted (reads false) the RX, TX pins use the standard logic levels (VDD = 1/idle, GND = 0/mark). Setting this property to true, will invert those signal levels, which will become inverted (VDD = 0/mark, GND= 1/idle). Some targets may not support this setting and accessing it will throw a NotSupportedException exception. This is a .NET nanoFramework property only. Doesn't exist on other .NET platforms.
Exceptions
- InvalidOperationException
Trying to set this property when the SerialPort is already opened and the driver doesn't support it.
- NotSupportedException
Trying to set this property on a target that does not support signal inversion.
IsOpen
Gets a value indicating whether the SerialPort is open or closed.
public bool IsOpen { get; }
Property Value
Exceptions
- ArgumentNullException
The IsOpen value passed is null.
- ArgumentException
The IsOpen value passed is an empty string ("").
Mode
Gets or sets the Serial Mode.
public SerialMode Mode { get; set; }
Property Value
Remarks
This is a .NET nanoFramework property only.
NewLine
Gets or sets the value used to interpret the end of a call to the ReadLine() and WriteLine(string)(System.String) methods.
public string NewLine { get; set; }
Property Value
Exceptions
- ArgumentException
The property value is empty or the property value is null.
Parity
Gets or sets the parity-checking protocol.
public Parity Parity { get; set; }
Property Value
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
PortName
Gets the port for communications.
public string PortName { get; }
Property Value
Remarks
.NET nanoFramework doesn't support changing the port.
ReadBufferSize
Gets or sets the size of the SerialPort input buffer.
public int ReadBufferSize { get; set; }
Property Value
- int
The size of the input buffer. The default is 256.
Remarks
Implementation of this property for .NET nanoFramework it's slightly different from .NET.
- There is only one work buffer which is used for transmission and reception.
- When the SerialPort is Open() the driver will try to allocate the requested memory for the buffer. On failure to do so, an OutOfMemoryException exception will be throw and the Open() operation will fail.
Exceptions
- ArgumentOutOfRangeException
The ReadBufferSize value is less than or equal to zero.
- InvalidOperationException
The ReadBufferSize property was set while the stream was open.
ReadTimeout
Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish.
public int ReadTimeout { get; set; }
Property Value
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
- ArgumentOutOfRangeException
The read time-out value is less than zero and not equal to Infinite.
ReceivedBytesThreshold
Gets or sets the number of bytes in the internal input buffer before a DataReceived event occurs.
public int ReceivedBytesThreshold { get; set; }
Property Value
- int
The number of bytes in the internal input buffer before a DataReceived event is fired. The default is 1.
Exceptions
- ArgumentOutOfRangeException
The ReceivedBytesThreshold value is less than or equal to zero.
StopBits
Gets or sets the standard number of stopbits per byte.
public StopBits StopBits { get; set; }
Property Value
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
WatchChar
Sets a character to watch for in the incoming data stream.
public char WatchChar { get; set; }
Property Value
Remarks
This property is specific to .NET nanoFramework. There is no equivalent in the System.IO.Ports API. When calling any of the Read function with a buffer, no matter if the requested quantity of bytes hasn't been read, only the specific amount of data will be returned up to the character. Also if this character is received in the incoming data stream, an event is fired with it's SerialData parameter set to WatchChar.
WriteBufferSize
Gets or sets the size of the serial port output buffer.
public int WriteBufferSize { get; set; }
Property Value
- int
The size of the output buffer. The default is 256.
Remarks
Implementation of this property for .NET nanoFramework it's slightly different from .NET.
- There is only one work buffer which is used for transmission and reception.
- When the SerialPort is Open() the driver will try to allocate the requested memory for the buffer. On failure to do so, an OutOfMemoryException exception will be throw and the Open() operation will fail.
Exceptions
- ArgumentOutOfRangeException
The WriteBufferSize value is less than or equal to zero.
- InvalidOperationException
The WriteBufferSize property was set while the stream was open.
WriteTimeout
Gets or sets the number of milliseconds before a time-out occurs when a write operation does not finish.
public int WriteTimeout { get; set; }
Property Value
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
- ArgumentOutOfRangeException
The read time-out value is less than zero and not equal to Infinite.
Methods
Close()
Closes the port connection, sets the IsOpen property to false, and disposes of the internal Stream object.
public void Close()
Exceptions
- IOException
The port is in an invalid state. -or- An attempt to set the state of the underlying port failed. For example, the parameters passed from this SerialPort object were invalid.
Dispose()
Dispose the Serial Port.
public void Dispose()
Finalize()
Destructor.
protected override void Finalize()
GetPortNames()
Gets an array of serial port names for the current computer.
public static string[] GetPortNames()
Returns
- string[]
An array of serial port names for the current computer.
Open()
Opens a new serial port connection.
public void Open()
Exceptions
- InvalidOperationException
The specified port on the current instance of the SerialPort. is already open.
- ArgumentException
One (or more) of the properties set to configure this SerialPort are invalid.
- OutOfMemoryException
Failed to allocate the request amount of memory for the work buffer.
Read(byte[], int, int)
Reads a number of bytes from the SerialPort input buffer and writes those bytes into a byte array at the specified offset.
public int Read(byte[] buffer, int offset, int count)
Parameters
buffer
byte[]The byte array to write the input to.
offset
intThe offset in buffer at which to write the bytes.
count
intThe maximum number of bytes to read. Fewer bytes are read if count is greater than the number of bytes in the input buffer.
Returns
- int
The number of bytes read.
Exceptions
- ArgumentNullException
The buffer passed is null.
- InvalidOperationException
The specified port is not open.
- ArgumentOutOfRangeException
The offset or count parameters are outside a valid region of the buffer being passed. Either offset or count is less than zero.
- ArgumentException
Offset plus count is greater than the length of the buffer.
- TimeoutException
No bytes were available to read.
ReadByte()
Synchronously reads one byte from the SerialPort input buffer.
public int ReadByte()
Returns
Exceptions
- InvalidOperationException
The specified port is not open.
- TimeoutException
The operation did not complete before the time-out period ended. -or- No byte was read.
ReadExisting()
Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object.
public string ReadExisting()
Returns
- string
The contents of the stream and the input buffer of the SerialPort object.
Exceptions
- InvalidOperationException
The specified port is not open.
ReadLine()
Reads up to the NewLine value in the input buffer.
public string ReadLine()
Returns
Exceptions
- InvalidOperationException
The specified port is not open.
- TimeoutException
The operation did not complete before the time-out period ended. -or- No bytes were read.
Write(byte[], int, int)
Writes a specified number of bytes to the serial port using data from a buffer.
public void Write(byte[] buffer, int offset, int count)
Parameters
buffer
byte[]The byte array that contains the data to write to the port.
offset
intThe zero-based byte offset in the buffer parameter at which to begin copying bytes to the port.
count
intThe number of characters to write.
Exceptions
- ArgumentNullException
The buffer passed is null.
- InvalidOperationException
The specified port is not open.
- ArgumentOutOfRangeException
The offset or count parameters are outside a valid region of the buffer being passed. Either offset or count is less than zero.
- ArgumentException
Offset plus count is greater than the length of the buffer.
- TimeoutException
The operation did not complete before the time-out period ended.
Write(string)
Writes the specified string to the serial port.
public void Write(string text)
Parameters
text
stringThe string for output.
Exceptions
- InvalidOperationException
The specified port is not open.
- ArgumentNullException
Text is null.
- TimeoutException
The operation did not complete before the time-out period ended.
WriteByte(byte)
Writes a byte to the serial port.
public void WriteByte(byte value)
Parameters
value
byteThe byte to write to the port.
Exceptions
- InvalidOperationException
The specified port is not open.
- TimeoutException
The operation did not complete before the time-out period ended.
WriteLine(string)
Writes the specified string and the NewLine value to the output buffer.
public void WriteLine(string text)
Parameters
text
stringThe string to write to the output buffer.
Exceptions
- ArgumentNullException
The text parameter is null.
- InvalidOperationException
The specified port is not open.
- TimeoutException
The WriteLine(string)(System.String) method could not write to the stream.
Events
DataReceived
Indicates that data has been received through a port represented by the SerialPort object.
public event SerialDataReceivedEventHandler DataReceived