Professional Documents
Culture Documents
Ports)
Pgina 1 de 11
SerialPort Class
.NET Framework 4.5 Represents a serial port resource.
Inheritance Hierarchy
System.Object 2 System.MarshalByRefObject 3 System.ComponentModel.Component System.IO.Ports.SerialPort Namespace: System.IO.Ports4 Assembly: System (in System.dll)
1
Syntax
VB 'DeclarationPublicClassSerialPort_ InheritsComponent The SerialPort type exposes the following members.
Constructors
Name SerialPort
5
Description Initializes a new instance of the SerialPort class. Initializes a new instance of the SerialPort class using the 7 specified IContainer object. Initializes a new instance of the SerialPort class using the specified port name. Initializes a new instance of the SerialPort class using the specified port name and baud rate. Initializes a new instance of the SerialPort class using the specified port name, baud rate, and parity bit. Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, and data bits. Initializes a new instance of the SerialPort class using the specified port name, baud rate, parity bit, data bits, and stop bit.
SerialPort(IContainer)6 SerialPort(String)
8
Properties
Name BaseStream BaudRate
15 16 17 18 13
Gets or sets the serial baud rate. Gets or sets the break signal state. Gets the number of bytes of data in the receive buffer. Gets the number of bytes of data in the send buffer.
BreakState
BytesToRead
BytesToWrite
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 2 de 11
19
Gets a value indicating whether the component can raise an 3 event. (Inherited from Component .) Gets the state of the Carrier Detect line for the port. Gets the IContainer that contains the Component . (Inherited from Component3.) Gets the state of the Clear-to-Send line. Gets or sets the standard length of data bits per byte. Gets a value that indicates whether the Component is currently 3 in design mode. (Inherited from Component .) Gets or sets a value indicating whether null bytes are ignored when transmitted between the port and the receive buffer. Gets the state of the Data Set Ready (DSR) signal. Gets or sets a value that enables the Data Terminal Ready (DTR) signal during serial communication. Gets or sets the byte encoding for pre- and post-transmission conversion of text. Gets the list of event handlers that are attached to this Component3. (Inherited from Component3.) Gets or sets the handshaking protocol for serial port transmission of data. Gets a value indicating the open or closed status of the SerialPort object. Gets or sets the value used to interpret the end of a call to the 33 34 ReadLine and WriteLine methods. Gets or sets the parity-checking protocol. Gets or sets the byte that replaces invalid bytes in a data stream when a parity error occurs. Gets or sets the port for communications, including but not limited to all available COM ports. Gets or sets the size of the SerialPort input buffer.
3 7 3
21 22
CtsHolding DataBits
23
26
30
Gets or sets the number of milliseconds before a time-out occurs when a read operation does not finish. Gets or sets the number of bytes in the internal input buffer ReceivedBytesThreshold40 41 before a DataReceived event occurs. Gets or sets a value indicating whether the Request to Send 42 RtsEnable (RTS) signal is enabled during serial communication. Site
43 45 46
Gets or sets the ISite44 of the Component3. (Inherited from Component3.) Gets or sets the standard number of stopbits per byte. Gets or sets the size of the serial port output buffer. Gets or sets the number of milliseconds before a time-out occurs when a write operation does not finish.
StopBits
Methods
Name Close48 Description Closes the port connection, sets the IsOpen property to 14 false, and disposes of the internal Stream object.
31
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 3 de 11
CreateObjRef
49
Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject2.)
50 51
DiscardInBuffer
Discards data from the serial driver's receive buffer. Discards data from the serial driver's transmit buffer. Releases all resources used by the Component . (Inherited 3 from Component .) Releases the unmanaged resources used by the SerialPort and optionally releases the managed resources. (Overrides 54 Component.Dispose(Boolean) .) Determines whether the specified object is equal to the current 1 object. (Inherited from Object .) Releases unmanaged resources and performs other cleanup operations before the Component3 is reclaimed by garbage collection. (Inherited from Component3.) Serves as a hash function for a particular type. (Inherited from Object1.) Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject2.) Gets an array of serial port names for the current computer. Returns an object that represents a service provided by the 3 61 Component or by its Container . (Inherited from 3 Component .) Gets the Type of the current instance. (Inherited from 1 Object .) Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject2.) Creates a shallow copy of the current Object . (Inherited from 1 Object .) Creates a shallow copy of the current MarshalByRefObject 2 object. (Inherited from MarshalByRefObject .) Opens a new serial port connection. Reads a number of bytes from the SerialPort input buffer and writes those bytes into a byte array at the specified offset. Reads a number of characters from the SerialPort input buffer and writes them into an array of characters at a given offset. Synchronously reads one byte from the SerialPort input buffer. Synchronously reads one character from the SerialPort input buffer. Reads all immediately available bytes, based on the encoding, in both the stream and the input buffer of the SerialPort object. Reads up to the NewLine
75 32 2 1 63 3
DiscardOutBuffer Dispose52
53
GetHashCode
58
InitializeLifetimeService MemberwiseClone MemberwiseClone 66 (Boolean) Open Read(Byte(), Int32, 68 Int32) Read(Char(), Int32, 69 Int32) ReadByte
70 67 65
64
ReadChar
71
72
73
Reads a string up to the specified value in the input buffer. Returns a String containing the name of the Component , if any. This method should not be overridden. (Inherited from 3 Component .)
76
ToString
74
Write(String)
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 4 de 11
Writes a specified number of bytes to the serial port using data from a buffer. Writes a specified number of characters to the serial port using data from a buffer. Writes the specified string and the NewLine32 value to the output buffer.
Events
Name DataReceived Disposed
79 81 41
Description Represents the method that will handle the data received event of a SerialPort object. Occurs when the component is disposed by a call to the Dispose (Inherited from Component3.)
80
method.
Represents the method that handles the error event of a SerialPort object. Represents the method that will handle the serial pin changed event of a SerialPort object.
Fields
Name InfiniteTimeout Top
83
Remarks
Use this class to control a serial port file resource. This class provides synchronous and eventdriven I/O, access to pin and break states, and access to serial driver properties. Additionally, 14 the functionality of this class can be wrapped in an internal Stream object, accessible 13 through the BaseStream property, and passed to classes that wrap or use streams. The SerialPort class supports the following encodings: ASCIIEncoding , UTF8Encoding , 86 87 UnicodeEncoding , UTF32Encoding , and any encoding defined in mscorlib.dll where the code page is less than 50000 or the code page is 54936. You can use alternate encodings, but 70 88 you must use the ReadByte or Write method and perform the encoding yourself. You use the GetPortNames59 method to retrieve the valid ports for the current computer. If a SerialPort object becomes blocked during a read operation, do not abort the thread. Instead, either close the base stream or dispose of the SerialPort object.
84 85
Examples
The following code example demonstrates the use of the SerialPort class to allow two users to chat from two separate computers connected by a null modem cable. In this example, the users are prompted for the port settings and a username before chatting. Both computers must be executing the program to achieve full functionality of this example. VB ImportsSystem ImportsSystem.IO.Ports ImportsSystem.Threading
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 5 de 11
PublicClassPortChat Shared_continueAsBoolean Shared_serialPortAsSerialPort PublicSharedSubMain() DimnameAsString DimmessageAsString DimsComparerAsStringComparer=StringComparer.OrdinalIgnoreCase DimreadThreadAsThread=NewThread(AddressOfRead) 'CreateanewSerialPortobjectwithdefaultsettings. _serialPort=NewSerialPort() 'Allowtheusertosettheappropriateproperties. _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) 'Settheread/writetimeouts _serialPort.ReadTimeout=500 _serialPort.WriteTimeout=500 _serialPort.Open() _continue=True readThread.Start() Console.Write("Name:") name=Console.ReadLine() Console.WriteLine("TypeQUITtoexit") While(_continue) message=Console.ReadLine() IfsComparer.Equals("quit",message)Then _continue=False Else _serialPort.WriteLine(_ String.Format("<{0}>:{1}",name,message)) EndIfendwhile readThread.Join() _serialPort.Close() EndSub PublicSharedSubRead() While(_continue) Try DimmessageAsString=_serialPort.ReadLine() Console.WriteLine(message) CatchexAsTimeoutException 'DonothingEndTry EndWhile EndSub PublicSharedFunctionSetPortName(ByValdefaultPortNameAsString)AsString DimnewPortNameAsString
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 6 de 11
Console.WriteLine("AvailablePorts:") DimsAsString ForEachsInSerialPort.GetPortNames() Console.WriteLine("{0}",s) Nexts Console.Write("COMport({0}):",defaultPortName) newPortName=Console.ReadLine() IfnewPortName=""Then newPortName=defaultPortName EndIf ReturnnewPortName EndFunction PublicSharedFunctionSetPortBaudRate(ByValdefaultPortBaudRateAsInteger)AsI nteger DimnewBaudRateAsString Console.Write("BaudRate({0}):",defaultPortBaudRate) newBaudRate=Console.ReadLine() IfnewBaudRate=""Then newBaudRate=defaultPortBaudRate.ToString() EndIf ReturnInteger.Parse(newBaudRate) EndFunction PublicSharedFunctionSetPortParity(ByValdefaultPortParityAsParity)AsParity DimnewParityAsString Console.WriteLine("AvailableParityoptions:") DimsAsString ForEachsIn[Enum].GetNames(GetType(Parity)) Console.WriteLine("{0}",s) Nexts Console.Write("Parity({0}):",defaultPortParity.ToString()) newparity=Console.ReadLine() Ifnewparity=""Then newparity=defaultPortParity.ToString() EndIf ReturnCType([Enum].Parse(GetType(Parity),newParity),Parity) EndFunction PublicSharedFunctionSetPortDataBits(ByValdefaultPortDataBitsAsInteger)AsI nteger DimnewDataBitsAsString Console.Write("DataBits({0}):",defaultPortDataBits) newDataBits=Console.ReadLine() IfnewDataBits=""Then newDataBits=defaultPortDataBits.ToString() EndIf ReturnInteger.Parse(newDataBits) EndFunction
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 7 de 11
PublicSharedFunctionSetPortStopBits(ByValdefaultPortStopBitsAsStopBits)As StopBits DimnewStopBitsAsString Console.WriteLine("AvailableStopBitsoptions:") DimsAsString ForEachsIn[Enum].GetNames(GetType(StopBits)) Console.WriteLine("{0}",s) Nexts Console.Write("StopBits({0}):",defaultPortStopBits.ToString()) newStopBits=Console.ReadLine() IfnewStopBits=""Then newStopBits=defaultPortStopBits.ToString() EndIf ReturnCType([Enum].Parse(GetType(StopBits),newStopBits),StopBits) EndFunction PublicSharedFunctionSetPortHandshake(ByValdefaultPortHandshakeAsHandshake) AsHandshake DimnewHandshakeAsString Console.WriteLine("AvailableHandshakeoptions:") DimsAsString ForEachsIn[Enum].GetNames(GetType(Handshake)) Console.WriteLine("{0}",s) Nexts Console.Write("Handshake({0}):",defaultPortHandshake.ToString()) newHandshake=Console.ReadLine() IfnewHandshake=""Then newHandshake=defaultPortHandshake.ToString() EndIf ReturnCType([Enum].Parse(GetType(Handshake),newHandshake),Handshake) EndFunction EndClass
Version Information
.NET Framework Supported in: 4.5, 4, 3.5, 3.0, 2.0 .NET Framework Client Profile Supported in: 4, 3.5 SP1
90
Platforms
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 8 de 11
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported) The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements91.
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also
Reference System.IO.Ports Namespace4
Links Table
1 2 3 4 5 6 7 8 9
http://msdn.microsoft.com/en-us/library/system.object.aspx http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject.aspx http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.aspx http://msdn.microsoft.com/en-us/library/s14dyf47.aspx http://msdn.microsoft.com/en-us/library/15d2aez9.aspx http://msdn.microsoft.com/en-us/library/system.componentmodel.icontainer.aspx http://msdn.microsoft.com/en-us/library/7sbhatw5.aspx http://msdn.microsoft.com/en-us/library/8bt1b81c.aspx http://msdn.microsoft.com/en-us/library/69xzbdd5.aspx http://msdn.microsoft.com/en-us/library/wtfta1zd.aspx http://msdn.microsoft.com/en-us/library/z8d1ykfs.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.basestream.aspx http://msdn.microsoft.com/en-us/library/system.io.stream.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.baudrate.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.breakstate.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestoread.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.bytestowrite.aspx
10 11 12 13 14 15 16 17 18 19
http://msdn.microsoft.com/enus/library/system.componentmodel.component.canraiseevents.aspx
20 21
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.cdholding.aspx
http://msdn.microsoft.com/enus/library/system.componentmodel.component.container.aspx
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 9 de 11
22 23 24
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.ctsholding.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.databits.aspx
http://msdn.microsoft.com/enus/library/system.componentmodel.component.designmode.aspx
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.discardnull.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.dsrholding.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.dtrenable.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.encoding.aspx http://msdn.microsoft.com/en-us/library/system.componentmodel.component.events.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.handshake.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.isopen.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.newline.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readline.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writeline.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.parity.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.parityreplace.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.portname.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readtimeout.aspx
http://msdn.microsoft.com/enus/library/system.io.ports.serialport.receivedbytesthreshold.aspx
41 42 43 44 45 46 47 48 49 50 51 52 53 54
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.rtsenable.aspx http://msdn.microsoft.com/en-us/library/system.componentmodel.component.site.aspx http://msdn.microsoft.com/en-us/library/system.componentmodel.isite.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.stopbits.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writebuffersize.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.writetimeout.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.close.aspx http://msdn.microsoft.com/en-us/library/system.marshalbyrefobject.createobjref.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.discardinbuffer.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.discardoutbuffer.aspx http://msdn.microsoft.com/en-us/library/3cc9y48w.aspx http://msdn.microsoft.com/en-us/library/cekaawx6.aspx http://msdn.microsoft.com/en-us/library/d9yzd5cx.aspx
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 10 de 11
55 56 57 58
http://msdn.microsoft.com/enus/library/system.marshalbyrefobject.getlifetimeservice.aspx
59 60
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx
http://msdn.microsoft.com/enus/library/system.componentmodel.component.getservice.aspx
61 62 63 64
http://msdn.microsoft.com/enus/library/system.marshalbyrefobject.initializelifetimeservice.aspx
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx http://msdn.microsoft.com/en-us/library/ms131262.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx http://msdn.microsoft.com/en-us/library/ms143549.aspx http://msdn.microsoft.com/en-us/library/34t733fh.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbyte.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readchar.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readto.aspx http://msdn.microsoft.com/en-us/library/z819d1t5.aspx http://msdn.microsoft.com/en-us/library/system.string.aspx http://msdn.microsoft.com/en-us/library/y2sxhat8.aspx http://msdn.microsoft.com/en-us/library/ms143551.aspx http://msdn.microsoft.com/en-us/library/1050fs1h.aspx
http://msdn.microsoft.com/enus/library/system.componentmodel.component.disposed.aspx http://msdn.microsoft.com/enus/library/system.componentmodel.component.dispose.aspx
81 82 83 84 85 80
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012
Pgina 11 de 11
86 87 88 89
http://msdn.microsoft.com/enus/library/system.security.permissions.securitypermission.aspx http://msdn.microsoft.com/enus/library/system.security.permissions.securitypermissionflag.aspx
91 90
http://msdn.microsoft.com/en-us/library/8z6watww.aspx
Community Content
2012 Microsoft. All rights reserved.
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport(d=printer).aspx
09/11/2012