mie wrote:
is there any documentation on how to use the serialport component in visual basic express edition?
Best I've been able to find follows. I do not still have the online URL.
Ed Tenholder
Documentation guide for
Copyright (c) Microsoft Corporation. All rights reserved.
System.IO.Ports:
SerialPort Class
Represents a connection to a serial communications resource.
public class SerialPort : Component
Remarks:
A SerialPort class provides I/O capabilities over a serial communications resource (e.g. “COM1”). It can be used to control serial hardware or effect port-to-port communication over any standard serial port, through any RS-232 or null-modem cable. The SerialPort component can be placed directly onto a form, and using the properties available at both design- and run-time, you can determine the internal settings of the serial driver, including baud rate, parity, handshaking, etc. Calling Open() on a properly set SerialPort establishes connection over the specified serial resource file.
Several types of communication paradigms can be employed: synchronous read and write methods and event-driven I/O in SerialPort, or exposure as a Stream through SerialPort’s BaseStream property. Pin states can be accessed through synchronous methods or observed asynchronously via the PinChangedEvent.
SerialPort supports adjustable timeouts, event filtration, non-standard port names, and arbitrary text encodings. Its I/O methods allow data to be transmitted and received in the form of single and multiple chars and bytes as well as strings.
SECTION I: PROPERTIES:
BaseStream: public Stream BaseStream { get; }
Property Value: Stream object encapsulated by current SerialPort.
Remarks: Read-only, initially the null object. Can be used to pass to other constructors requiring a Stream (e.g. StreamWriter, etc.). Encapsulates serial-related attributes of the connection but only exposes publicly the contract required by Stream. Changing the “parent” SerialPort (property changes, closing, etc.) will affect the state of the Stream.
BaudRate: public int BaudRate { get; set; }
Property Value: Positive value of baud rate of instance’s serial communication.
Remarks: Defaults to 9600. Baud rate typically takes one of the CBR_xxx values of Winbase.h
CDHolding: public bool CDHolding { get; }
Property Value: Whether the device detects whether a carrier signal exists on the serial port, or equivalently, state of the device’s CD pin. Carrier Detect (CD) is also known as Receive-Line Signal Detect (RLSD).
Remarks: Read-only, and especially important to determine if a connected computer has hung up at any time. Changes in CDHolding are also reflected in the PinChangedEvent thrown with the SerialEvents.PinChanged code.
CtsHolding: public bool CtsHolding { get; }
Property Value: Whether data can be sent, determined by querying the CTS line of the serial port.
Remarks: Read-only, and used in RTS/CTS hardware handshaking. Typically, an attached modem sets the line to indicate that transmission can proceed.
DataBits: public int DataBits { get; set; }
Property Value: Number of data bits per serial byte.
Remarks: Defaults to 8 but must be in the range of [5,8].
DiscardNull: public bool DiscardNull { get; set; }
Property Value: Whether null characters (ASCII value == 0) are transferred from the port to the serial device’s receive buffer.
Remarks: Defaults to false (null characters are transferred). This may be important especially in binary transfers, but often null characters are transmitted upon a connected device turning on or off, etc., so they may be irrelevant.
DsrHolding: public bool DsrHolding { get; }
Property Value: The state of the Data Set Ready (DSR) line on the port.
Remarks: Read-only, and used in DSR/DTR handshaking (Data Terminal Equipment machines). An attached modem sets this line to indicate that it is prepared to operate.
DtrEnable: public bool DtrEnable { get; set; }
Property Value: Whether to enable Data Transmit Ready line (DTR) during serial communication.
Remarks: Defaults to false. Typically enabled during XOn/XOff and RTS/CTS handshaking and modem communication. When DtrEnable is set to True, the Data Terminal Ready line is set to high (on) when the port is opened, and low (off) when the port is closed. When DtrEnable is set to False, the Data Terminal Ready always remains low. Toggling the DtrEnable line causes modem hangup, additionally.
Encoding: public Encoding Encoding { get; set; }
Property Value: Method of encoding and decoding text to and from binary data.
Remarks: Defaults to System.IO.Encoding.ASCIIEncoding. Any arbitrary member of the Encoding class can be used. Used to transform data for ReadLine(), ReadAvailable(), int Read() and int Read(char[]…) methods on the receiving end of input, and Write(string), Write(char[] …) for writing. Not designable since Encoding is a reference type.
EventFilter: public SerialEvents EventFilter { get; set; }
Property Value: Set of flags indicating which of SerialEvents’s twelve port conditions are enabled to fire events.
Remarks: Defaults to SerialEvents.All (i.e. all SerialEvents conditions fire events). Settings to this may render entire events unable to fire. Setting EventFilter to SerialEvents.None does not currently disable the secondary thread listening for events.
Handshake: public Handshake Handshake { get; set; }
Property Value: Protocol for flow control.
Remarks: Defaults to Handshake.None. Some handshaking protocols are incompatible with transfer modes and media; for instance, Handshake.XOnXOff (software flow control) is inherently incompatible with binary data transmission, etc. No such checks are made by the class.
InBreak: public bool InBreak { get; }
Property Value: Whether SerialPort transmission is currently in a break state.
Remarks: Read-only, indicates whether the stop bits are high (non-break state) or low (break state) on the line. This state suspends transmission but allows for receiving. The user may toggle the break state itself with SetBreak() and ClearBreak().
InBufferBytes: public int InBufferBytes { get; }
Property Value: Number of bytes currently available for reading.
Remarks: Read-only. This number reflects the number of bytes in the serial driver’s receive buffer plus any internally buffered bytes resulting from failed Read() calls or trailing lead bytes. Note that this may be different than the number of characters, dependent upon the character encoding.
IsOpen: public bool IsOpen { get; }
Property Value: Whether current port is open for reading and writing.
Remarks: Read-only, initially false. MSComm’s PortOpen could be set to true or false to open or close the stream, but that functionality is reserved for Open() and Close() in the SerialPort object. IsOpen is true after an Open() call and false after a Close() call.
OutBufferBytes: public int OutBufferBytes { get; }
Property Value: Number of bytes currently waiting to be sent.
Remarks: Read-only. This number reflects the number of bytes in the serial driver’s receive buffer. Note that this may be different than the number of characters, dependent upon the character encoding.
Parity: public Parity Parity { get; set; }
Property Value: Method of setting/reading parity bit on each byte serial I/O.
Remarks: Defaults to Parity.None; Parity.None uses no additional parity bit, and all others require one parity bit per transmitted byte. Communication may still work correctly with mismatched parities.
ParityReplace: public byte ParityReplace { get; set; }
Property Value: Sets and returns the (ASCII) character which replaces bytes at which parity errors have occurred.
Remarks: Defaults to ‘?’. Whatever the character, the ErrorEvent still fires (if enabled) with code SerialEvents.RxParity if a parity error is detected upon reception. This property becomes irrelevant if Parity == Parity.None, and parity replacement is turned off by setting ParityReplace to ‘\0’, the null character.
PortName: public string PortName { get; }
Property Value: String representing name of communications resource. Remarks: Defaults to “COM1”, but any serial communications resource is possible. Can be set only when port is not open (IsOpen == false). If passed string begins with a double-slash (literal “\\”) then an ArgumentException is thrown to prevent security leaks.
ReadTimeout: public int ReadTimeout { get; set; }
Property Value: Timeout value for SerialPort Read/ReadLine/ReadCharacters methods. May take the value 0, SerialPort.InfiniteTimeout, or any positive integer.
Remarks: Defaults to SerialPort.InfiniteTimeout, expressed in milliseconds. A zero value indicates that any of these methods must return after processing only immediately available data. With a positive or infinite value, any of these methods wait until data is received if none immediately available; if none is available before ReadTimeout milliseconds have elapsed, each method will return. A method called with an infinite timeout will not return until data is received. Throws an ArgumentOutOfRange exception if set to an integer less than zero.
ReceivedBytesThreshold: public int ReceivedBytesThreshold { get; set; }
Property Value: Number of bytes required in internal receive buffers before ReceivedChars event is fired.
Remarks: Defaults to 1. If set to a value less than one, throws ArgumentOutOfRangeException. If the number of bytes waiting to be read is greater than or equal to this threshold, upon reception of any character, the Receive event will be fired (if enabled through EventFilter).
RtsEnable: public bool RtsEnable { get; set; }
Property Value: Whether to enable Request To Send line (RTS) during serial communication.
Remarks: Defaults to false. Typically enabled during RTS/CTS handshaking and modem communication. When RtsEnable is set to true, the RTS line is high when the port is open and low otherwise.
StopBits: public StopBits StopBits { get; set; }
Property Value: Number of stop bits per serial byte.
Remarks: Defaults to StopBits.One. Note you cannot set myPort.StopBits = (StopBits) 1.5, etc.; instead, one should use the enumerated constants. Rarely does a serial protocol require stop bits setting to anything other than StopBits.One.
WriteTimeout: public int WriteTimeout { get; set; }
Property Value: Timeout value for SerialPort Write methods. May take the value SerialPort.InfiniteTimeout, or any positive integer.
Remarks: Defaults to SerialPort.InfiniteTimeout, expressed in milliseconds. If an entire Write(…) operation is not completed within the specified timeout, each throws a TimeoutException. Throws an ArgumentOutOfRange exception if set to an integer less than zero.
SECTION II: METHODS
CONSTRUCTOR
public SerialPort ();
public SerialPort (string portName);
public SerialPort (string portName, int baudRate);
public SerialPort (string portName, int baudRate, Parity parity);
public SerialPort (string portName, int baudRate, Parity parity, int dataBits);
public SerialPort (string portName, int baudRate, Parity parity,
int dataBits, StopBits stopBits);
Parameters: portName:String indicating communications resource to open.
baudRate: integer baudRate at which to effect serial I/O over port
parity: Parity enum type; Parity-check protocol for I/O over port
dataBits: integer number of data bits per byte for I/O over port
stopBits: StopBits enum type; length of stop bits per byte for I/O over port
Return Value: none
Exceptions: none
Remarks: Simply sets properties of new, closed SerialPort object according to parameters. No argument checking done.
public void ClearBreak()
Parameters: none
Return Value: none
Exceptions:
IOException: an I/O error occurs.
ObjectDisposedException: the underlying stream handle has been closed
Remarks: Clears the break state of a serial communications resource if it is in such a break state. Otherwise, does nothing. In a serial break state, all stop bits are low, and transmission suspended.
public override void Close()
Parameters: none
Return Value: none
Exceptions:
IOException: an I/O error occurs.
ObjectDisposedException: the underlying stream handle has been closed
Remarks: This method calls Dispose with true argument. No error occurs if it is called multiple times. The Finalize method invokes Close so that the file stream is closed before the garbage collector finalizes the object. However, objects writing to the SerialPort, such as a StreamWriter on top of the BastStream, might not have flushed the data from their internal buffers when the call to Finalize closes the stream. To prevent data loss, always call Close on the highest-level object.
public void DiscardInBuffer()
Parameters: none
Return Value: none
Exceptions:
IOException: an I/O error occurs.
ObjectDisposedException: the underlying stream handle has been closed
Remarks: This method deletes the contents of the serial driver’s receive buffer. Any remaining data is discarded.
public void DiscardOutBuffer()
Parameters: none
Return Value: none
Exceptions:
IOException: an I/O error occurs.
ObjectDisposedException: the underlying stream handle has been closed
Remarks: This method deletes the contents of the serial driver’s transmit buffer. Any remaining data is discarded.
protected override Dispose(bool disposing)
Parameters: disposing: whether we’re disposing (true) or finalizing the object (false)
Return Value: none
Exceptions: none
Remarks: This method is called by the public Dispose() method and the Finalize() method. Dispose() invokes the protected Dispose(Boolean) method with the disposing parameter set to true. Finalize invokes Dispose with disposing set to false.
When the disposing parameter is true, this method releases all resources held by any managed objects that this Component references. This method invokes the Dispose() method of each referenced object.
public void Open()
Parameters: none
Return Value: none
Exceptions:
ArgumentException: PortName begins with “\\” or is not a serial file
ArgumentNullException: PortName is null
ArgumentOutOfRangeException: DataBits > 8, DataBits < 5, BaudRate <= 0, BaudRate exceeds serial driver’s maximum, ReadTimeout < 0 and not SerialPort.InfiniteTimeout or writeTimeout <= 0 and not SerialPort.InfiniteTimeout
FileNotFoundException: file named PortName does not exist
UnauthorizedAccessException: insufficient permission to access file PortName
IOException: an I/O error occurred; no threads available
Remarks: Essentially opens a handle to a valid serial communications resource through creating a Stream instance internally. SerialPort is given read-write access to the file, opens asynchronously, and assumes handle ownership. Subsequent attempts to open the same file will fail; no SerialPort objects may share a handle and the handle may not be opened summarily until SerialPort calls Close() or Dispose(). Note that unlike MSComm, the SerialPort constructor does not support an integer argument to denote which port to open, instead insisting on “COM1” or a string; this is to allow all communications resources (which needn’t be named COMX, X a number). This does not support USB ports.
public int ReadByte()
Parameters: none
Return Value: First byte read from stream/buffer or -1 on timeout
Exceptions:
ObjectDisposedException: internal handle to stream was closed.
InvalidOperationException: SerialPort is not open.
IOException: an I/O error occurred.
Remarks: Synchronous method for reading one byte from the communications resource file. If there are internally buffered bytes, reads one and returns, otherwise waits for one on the stream. Returns -1 if timeout expires before one byte received.
public int Read()
Parameters: none
Return Value: First char read from stream/buffer or -1 on timeout
Exceptions:
All overloads:
ObjectDisposedException: internal handle to stream was closed.
InvalidOperationException: SerialPort is not open.
IOException: an I/O error occurred.
Remarks: Synchronous method for reading one byte from the communications resource file. If there are internally buffered bytes, reads one and returns, otherwise waits for one on the stream. Returns -1 if timeout expires before one byte received.
public int Read(byte[] buffer, int offset, int count)
Parameters: buffer: buffer into which bytes are read from the stream
offset: index in buffer at which to begin storing bytes read from stream
count: maximum number of bytes to be read to buffer
Return Value: Number of bytes/chars read from the stream before timeout.
Exceptions:
ObjectDisposedException: internal handle to stream was closed.
InvalidOperationException: SerialPort is not open.
IOException: an I/O error occurred.
ArgumentException: The array length minus offset is less than count.
ArgumentNullException: buffer is null
ArgumentOutOfRangeException: offset or count is less than zero.
Remarks: Synchronous method for reading multiple bytes from the communications resource file. If there are internally buffered bytes and/or immediately available bytes on the stream, reads as many up to count and return if nothing immediately available on the stream; subject to ReadTimeout conditions detailed in the ReadTimeout property.
public int Read(char[] buffer, int offset, int count)
Parameters: buffer: buffer into which chars are read from the stream
offset: index in buffer at which to begin storing chars read from stream
count: maximum number of chars to be read to buffer
Return Value: Number of chars read from the stream before timeout.
Exceptions:
ObjectDisposedException: internal handle to stream was closed.
InvalidOperationException: SerialPort is not open.
IOException: an I/O error occurred.
ArgumentException: The array length minus offset is less than count.
ArgumentNullException: buffer is null
ArgumentOutOfRangeException: offset or count is less than zero.
Remarks: Synchronous method for reading characters from the communications resource file. If there are internally buffered bytes and/or immediately available bytes on the stream, reads as many characters as possible and ret, otherwise waits for one on the stream.
Number of bytes per character depends on SerialPort’s Encoding, which may be fixed- or variable- length. Thus, using “Read(buffer, 0, myPort.InBufferBytes)” is not recommended unless Encoding is a fixed-length encoding with one byte per character (e.g. System.Text.ASCIIEncoding). If count full characters are not received by the timeout’s expiration, as many full characters as possible are returned in string form; any remaining lead bytes will be put in an internal buffer and will be available upon any subsequent read call from the SerialPort.
public string ReadAvailable();
Parameters: none
Return Value: String containing characters corresponding to all bytes immediately available for read (i.e. bytes in serial driver buffer and SerialPort’s internal buffer).
Exceptions:
InvalidOperationException: SerialPort is not open.
IOException: An I/O error occurred.
Remarks: Always returns immediately and thus operates independently of ReadTimeout. If extra lead bytes remain at the end of the available buffered data, they remain in the buffer and are not returned.
public string ReadLine();
Parameters: none
Return Value: String containing the next line available from the buffer and stream, or a null string if none available. String is stripped of the final newline characters.
Exceptions:
InvalidOperationException: SerialPort is not open.
IOException: An I/O error occurred.
Remarks: Synchronous method for reading one line at a time from the communications resource file. If there are internally buffered bytes, reads as many as possible and waits for remaining bytes on the stream until ‘\r’, ‘\n’ or “\r\n” occurs on the stream.
Number of bytes per character depends on SerialPort’s Encoding, which may be fixed- or variable-length.
If a full line of characters are not received by the timeout’s expiration, all bytes are put in an internal buffer and will be available upon any subsequent read call from the SerialPort.
*Implementation notes: If a carriage return character (‘\r’) is read as the last available byte, the method returns immediately rather than waits for a potential ‘\n’ to occur next. There are several advantages and disadvantages to this approach:
*Disadvantages:
1. This means we may drop '\n' onto another read, possibly binary, if it follows in a subsequent transmission but was intended to be read by this ReadLine().
2. Some data is thus corrupted if proper countermeasures are not taken on the part of the user.
*Advantages:
1. We do not hang until timeout if we’ve received “\r” at the end of a transmission.
2. We do not unnecessarily remove any ‘\n’ or 0x0a characters from subsequent transmissions, which may be part of this transmission or not.
3. All flavors of newline are recognized, (‘\r’, ‘\n’, ‘\r\n’) and consistency is maintained with StreamReader.
public void SetBreak()
Parameters: none
Return Value: none
Exceptions:
IOException: an I/O error occurs.
ObjectDisposedException: the underlying stream handle has been closed
Remarks: Sets the break state of a serial communications resource if not in such a break state. Otherwise, does nothing. In a serial break state, all stop bits are low, and transmission suspended.
public void Write(string str)
Parameters: str: string to be written to the port
Return Value: none
Exceptions:
InvalidOperationException: SerialPort is not open, or in break state.
IOException: An I/O error occurred.
Remarks: Synchronous method for writing a specified string to the communications resource file. If there are internally buffered bytes, they are written first. If entire string is not written before the timeout expires, a TimeoutException is thrown.
public void Write(byte[] buffer, int offset, int count)
Parameters: buffer: buffer of bytes to be written to the port
offset: index in buffer at which to begin retrieving write data
count: number of bytes to write to the stream
Return Value: none
Exceptions:
InvalidOperationException: SerialPort is not open, or in break state.
IOException: An I/O error occurred.
ArgumentException: The array length minus offset is less than count.
ArgumentNullException: buffer is null
ArgumentOutOfRangeException: offset or count is less than zero.
Remarks: Synchronous method for writing an array of bytes to the communications resource file. If there are internally buffered bytes, they are written first. If entire array is not written before the timeout expires, a TimeoutException is thrown.
public void Write(char[] buffer, int offset, int count)
Parameters: buffer: buffer of chars to be written to the port
offset: index in buffer at which to begin retrieving write data
count: number of chars to write to the stream
Return Value: none
Exceptions:
InvalidOperationException: SerialPort is not open, or in break state.
IOException: An I/O error occurred.
ArgumentException: The array length minus offset is less than count.
ArgumentNullException: buffer is null
ArgumentOutOfRangeException: offset or count is less than zero.
Remarks: Synchronous method for writing an array of chars to the communications resource file. If there are internally buffered bytes, they are written first. If entire array is not written before the timeout expires, a TimeoutException is thrown. Note that this may require writing more than count bytes, since multiple-byte character encoding are allowed.
SECTION III: EVENTS
public event SerialEventHandler ErrorEvent
public event SerialEventHandler PinChangedEvent
public event SerialEventHandler ReceivedEvent
SECTION IV: SAMPLE CODE FOR COMMON SCENARIOS
Dialing a number via an attached modem:
string num = “234-567-8901”;
using (SerialPort mySerialPort = new SerialPort(“COM1”, 14400)) {
mySerialPort.DtrEnable = true;
mySerialPort.Open();
mySerialPort.Write(“ATDT” + num + “\r\n”);
mySerialPort.Close();
}
Saving incoming data to a file, up to carriage return.
public void SaveSerialToFile (SerialPort sp)
{
string incoming;
using (StreamWriter sw = new StreamWriter(“out.txt”)) {
do {
incoming = sp.ReadLine();
if (incoming != null) {
sw.WriteLine(incoming);
}
}
sw.Close();
}
}
Using the Event Filter to control Event-driven I/O:
SerialPort myPort = new SerialPort (“COM1”, 14400, Parity.Even, 8, StopBits.One);
mySerialPort.EventFilter = SerialEvents.EofReceived | SerialEvents.ReceivedChars;
mySerialPort.ReceviedEvent += new SerialEventHandler(OnReceivedEvent);
// ...
protected void OnReceivedEvent(object source, SerialEventArgs e)
{
StringBuilder sb = new StringBuilder(“”);
switch (e.EventType) {
case SerialEvents.ReceivedChars:
sb.Append(