Class
Serial
Warning
This item was deprecated in version 2019r2. Please use SerialConnection as a replacement.
Description
Serial controls are used to perform Serial communications.
Properties
Name |
Type |
Read-Only |
Shared |
---|---|---|---|
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
✓ |
|||
Methods
Name |
Parameters |
Returns |
Shared |
---|---|---|---|
Lines() As Integer |
|||
ParamArray Lines As Integer |
|||
[Encoding As TextEncoding] |
|||
Count As Integer, [Enc As TextEncoding] |
|||
[Encoding As TextEncoding] |
|||
Data As String |
|||
Events
Name |
Parameters |
Returns |
---|---|---|
ChangedLines() As Integer |
Constants
Baud Rates
To set the Baud rate, assign the desired class constant to the Baud property. To get the baud rate, compare the value of the Baud property to the constants in this table.
Baud Rate |
Value |
Constant |
---|---|---|
300 |
0 |
Baud300 |
600 |
1 |
Baud600 |
1200 |
2 |
Baud1200 |
1800 |
3 |
Baud1800 |
2400 |
4 |
Baud2400 |
3600 |
5 |
Baud3600 |
4800 |
6 |
Baud4800 |
7200 |
7 |
Baud7200 |
9600 |
8 |
Baud9600 |
14400 |
9 |
Baud14400 |
19200 |
10 |
Baud19200 |
28800 |
11 |
Baud28800 |
38400 |
12 |
Baud38400 |
57600 |
13 |
Baud57600 |
115200 |
14 |
Baud115200 |
230400 |
15 |
Baud230400 |
Setting nonstandard baud rates is supported only on Windows and macOS and above. On macOS, the system supports arbitrary baud rates by passing the request along to the driver. If the driver supports the passed baud rate, then it is set (or approximated).
On Linux, some non-standard baud rates are possible to achieve by using the Setserial system call and setting your baud rate to a special value.
LineChangeNotification
The following class constants can be used to determine line state changes.
Class Constants |
Description |
---|---|
LineCTS |
Clear to send. |
LineDCD |
Data carrier detect. |
LineDSR |
Data set ready. |
LineDTR |
Data Terminal Ready |
LineRTS |
Request to Send |
LineRI |
Ring Indicator |
Parity
The following class constants can be used to get or set the parity using the Parity property.
Class Constant |
Description |
---|---|
ParityNone |
No parity. |
ParityOdd |
Odd parity. |
ParityEven |
Even parity. |
Stop Bits
The following class constants can be used to get or set the number of stop bits using the Stop property.
Class Constant |
Description |
---|---|
StopBits1 |
1 stop bit. |
StopBits15 |
1.5 stop bits. |
StopBits2 |
2 stop bits. |
Bits
The following class constants can be use to set the number of bits using the Bits property.
Class Constant |
Description |
---|---|
Bits5 |
5 bits. |
Bits6 |
6 bits. |
Bits7 |
7 bits. |
Bits8 |
8 bits. |
Error Codes
The following class constants can be used to test the LastErrorCode value.
Class Constant |
Description |
---|---|
NoError |
No error code. |
AccessDenied |
Access denied. |
PortNotFound |
Port not found. |
InvalidOptions |
Invalid options. |
BreakCondition |
Hardware detected a break condition. Usually due to a signal rate mismatch. |
FramingError |
Hardware detected a framing error. Occurs when the designated "start" and "stop" bits are not valid. |
Refer to this link for additional information on each error:
http://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter
Property descriptions
Serial.Baud
Baud As Integer
The rate at which data will be sent and received (see the Baud Rate chart in the Notes section, below).
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
The “Baud” class constants can be used to get or set the Baud rate. To do this, check the value of Baud against one or more class constants. See the table in the section "Baud Rates", below.
To set the Baud rate, assign the desired class constant to the Baud property. To get the baud rate, compare the value of the Baud property to the constants in this table.
Baud Rate |
Value |
Class Constant |
---|---|---|
300 |
0 |
Baud300 |
600 |
1 |
Baud600 |
1200 |
2 |
Baud1200 |
1800 |
3 |
Baud1800 |
2400 |
4 |
Baud2400 |
3600 |
5 |
Baud3600 |
4800 |
6 |
Baud4800 |
7200 |
7 |
Baud7200 |
9600 |
8 |
Baud9600 |
14400 |
9 |
Baud14400 |
19200 |
10 |
Baud19200 |
28800 |
11 |
Baud28800 |
38400 |
12 |
Baud38400 |
57600 |
13 |
Baud57600 |
115200 |
14 |
Baud115200 |
230400 |
15 |
Baud230400 |
Setting nonstandard baud rates is supported only on Windows and macOS. On macOS, the system supports arbitrary baud rates by passing the request along to the driver. If the driver supports the passed baud rate, then it is set (or approximated).
On Linux, some non-standard baud rates are possible to achieve by using the Setserial system call and setting your baud rate to a special value.
The following example sets the Baud rate in the Open event of the window. The Baud rate can also be set in the IDE.
Serial1.Baud = Serial.Baud9600
Serial.Bits
Bits As Integer
The number of bits. This can be set in the IDE or via code.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
The following class constants are available:
Value |
Class Constant |
---|---|
0 |
Bits5 |
1 |
Bits6 |
2 |
Bits7 |
3 |
Bits8 |
The number of bits can be set in the IDE or by code, for example, in the Open event of the window. For example:
Serial1.Bits = Serial.Bits7
Serial.BytesAvailable
BytesAvailable As Integer
The number of bytes of data are available in the internal receive buffer.
This property is read-only.
TextField1.Text = Me.BytesAvailable.ToString
Serial.BytesLeftToSend
BytesLeftToSend As Integer
The number of bytes left in the queue remaining to be sent.
This property is read-only.
This enables you to create a synchronous socket without needing to subclass it.
Serial.ClearToSend
ClearToSend As Boolean
Use to read the state of the ClearToSend line.
This property is read-only.
The code below is from Examples/Communication/Hardware/Serial/Line State Change Tester:
' Loop over each line that has changed and print
' out the new state of the line.
Dim i As Integer
For Each i In changedLines
Select Case i
Case Serial.LineCTS
MsgBox("CTS is now " + HighLow(Me.ClearToSend))
Case Serial.LineRTS
MsgBox("RTS is now " + HighLow(Me.RequestToSend))
Case Serial.LineDCD
MsgBox("DCD is now " + HighLow(Me.DataCarrierDetect))
Case Serial.LineDSR
MsgBox("DSR is now " + HighLow(Me.DataSetReady))
Case Serial.LineDTR
MsgBox("DTR is now " + HighLow(Me.DataTerminalReady))
Case Serial.LineRI
MsgBox("RI is now " + HighLow(Me.RingIndicator))
End Select
Next
The HighLow function returns the printable message. It is:
If b Then
Return "asserted"
Else
Return "negated"
End If
Serial.CTS
CTS As Boolean
Enables CTS (Clear to Send) flow control. Signal to the far end that there is space in the receive buffer. Allows DTS to transmit.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
Serial.DataCarrierDetect
DataCarrierDetect As Boolean
Enables you to read the state of the DataCarrierDetect line.
This property is read-only.
Serial.DataSetReady
DataSetReady As Boolean
Enables you to read the state of the DataSetReady line.
This property is read-only.
Serial.DataTerminalReady
DataTerminalReady As Boolean
Sets the state of the data terminal line.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
Serial.DTR
DTR As Boolean
Enables DTR (Data Terminal Ready) flow control.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
Serial.Handle
Handle As Integer
This is the control's internal descriptor and it can be used with Declare statements. This replaces Win32DriverHandler, MacInDriverRefNum, and MacOutDriverRefNum.
This property is read-only.
Serial.LastErrorCode
LastErrorCode As Integer
Contains the last known error in the Serial control.
Error class constants are as follows:
The following class constants can be used to test the LastErrorCode value.
Class Constant |
Value |
Description |
---|---|---|
NoError |
0 |
No error code. |
AccessDenied |
100 |
Access denied. |
PortNotFound |
101 |
Port not found. |
InvalidOptions |
102 |
Invalid options. |
BreakCondition |
103 |
Hardware detected a break condition. Usually due to a signal rate mismatch. |
FramingError |
104 |
Hardware detected a framing error. Occurs when the designated "start" and "stop" bits are not valid. |
LastErrorCode can be set as well as read. This is useful for subclassing a Serial.
Introduced 2006r2
There are many other platform-specific error codes that vary based on the operating system and version. Here are some links for further information:
Windows XP: http://support.microsoft.com/kb/310123
Windows Vista: http://technet.microsoft.com/en-us/library/cc771355(v=ws.10).aspx
Linux: http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html
macOS: http://osstatus.com/
Serial.Parity
Parity As Integer
The parity that is being used.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
You can use the following class constants instead of the numbers to check or set the parity. They are:
Value |
Class Constant |
---|---|
0 |
ParityNone |
1 |
ParityOdd |
2 |
ParityEven |
This example sets the parity in the Open event of the window.
Serial1.Parity = Serial.ParityOdd
Serial.RequestToSend
RequestToSend As Boolean
Sets the state of the RequestToSend line.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
Serial.RingIndicator
RingIndicator As Boolean
Enables you to read the state of the RingIndicator line.
This property is read-only.
Serial.SerialPort
SerialPort As SerialPort
Used to identify the Serial port to which the Serial control will communicate.
The code below is from Examples/Communication/Hardware/Serial/Line State Change Tester:
' Populate the popup menu with all of the
' serial ports the system has installed.
Dim count As Integer
count = System.SerialPortCount
For i As Integer = 0 To count - 1
PopupMenu1.AddRow(System.SerialPort(i).Name)
Next
Serial.Stop
Stop As Integer
The number of stop bits being used.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
You can use the following class constants instead of the numbers to check or set the number of stop bits. They are:
Value |
Class Constant |
Description |
---|---|---|
0 |
StopBits1 |
1 stop bits |
1 |
StopBits15 |
1.5 stop bits |
2 |
StopBits2 |
2 stop bits |
This example sets the number of Stop bits in the Open event of the window.
Serial1.Stop = Serial.StopBits1
Serial.XON
XON As Boolean
Enables XON flow control.
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
This example enables XON flow control.
Serial1.XON = True
Method descriptions
Serial.ClearBreak
ClearBreak
Clears the break signal on the control immediately, without the need to call the Reset method. Available on Windows and macOS.
Serial1.ClearBreak
Serial.Close
Close
Closes the Serial port.
Serial.EndOfFile
EndOfFile As Boolean
Returns True when there's no more data left to read.
This code reads the rows and columns of data from a tab-delimited text file into a ListBox:
Var f As FolderItem
Var textInput As TextInputStream
Var rowFromFile As String
f = FolderItem.ShowOpenFileDialog("text/plain") ' defined as a FileType
If f <> Nil Then
textInput = TextInputStream.Open(f)
textInput.Encoding = Encodings.UTF8
Do
rowFromFile = textInput.ReadLine
Var values() As String = rowFromFile.Split(Chr(9))
ListBox1.ColumnCount = values.Count
ListBox1.AddRow("")
Var col As Integer
For Each value As String In values
ListBox1.CellTextAt(ListBox1.LastAddedRowIndex, col) = value
col = col + 1
Next
Loop Until textInput.EndOfFile
textInput.Close
End If
This example reads each pair of bytes from a file and writes them in reverse order to a new file. The user chooses the source file using the Open-file dialog box and saves the new file using the Save as dialog box. The EOF property is used to terminate the Do...Loop.
Var readFile As FolderItem = FolderItem.ShowOpenFileDialog("text")
If readFile <> Nil Then
Var ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
ReadStream.LittleEndian = True
Var writeFile As FolderItem = FolderItem.ShowSaveFileDialog("", "")
If writeFile <> Nil Then
Var writeStream As BinaryStream = BinaryStream.Create(writeFile, True)
writeStream.LittleEndian = True
Do Until ReadStream.EndOfFile
writeStream.WriteInt8(ReadStream.ReadInt8)
Loop
writeStream = Nil
End If
readStream = Nil
End If
Serial.Flush
Flush
Immediately sends the contents of internal write buffers to disk or to the output stream.
This function can be useful in point-to-point communication over sockets and similar connections: To optimize for transmission performance, some types of output streams try to collect small pieces of written data into one larger piece for sending instead of sending each piece out individually. By calling Flush, the data collection is stopped and the data is sent without further delay, reducing latency.
When using this on a stream that ends up as a file on disk, it is useful, too: Any short parts of previously written data are written to disk right away, ensuring the data is actually on disk if the application terminates abruptly, e.g. due to a crash.
Avoid calling this method too often. For example, do not call it between successive Write calls because you'll slow down performance without getting much benefit.
A typical use case would look like this:
mySocket.Write("you typed: ")
mySocket.Write(key)
mySocket.Write(".")
mySocket.Flush
Serial.LeaveDTROnClose
LeaveDTROnClose
Tells the Serial control not to negate DTR on close. The Serial port must be open for this method to function.
Serial1.LeaveDTROnClose
Serial.LineChangeNotification
LineChangeNotification(Lines() As Integer)
When a line state changes, the LineStateChanged event occurs and passes an array of lines whose state has changed.
Serial.LineChangeNotification
LineChangeNotification(ParamArray Lines As Integer)
When a line state changes, the LineStateChanged event occurs and passes an array of lines whose state has changed.
To select which lines to watch or see which lines have changed, please use the new constants added to the Serial class for this purpose:
Name |
Description |
---|---|
LineCTS |
ClearToSend |
LineDCD |
DataCarrierDetect |
LineDSR |
DataSetReady |
LineDTR |
DataTerminalReady |
LineRTS |
RequestToSend |
LineRI |
RingIndicator |
Use the ClearToSend, DataCarrierDetect, etc. properties to get the state of each line.
Serial.LookAhead
LookAhead([Encoding As TextEncoding]) As String
Returns all the unread characters in the buffer without deleting them from the buffer. The optional Encoding parameter enables you to specify the text encoding of the data to be returned. Use the Encodings module to specify a text encoding.
This example stores the lookahead text in a TextField.
TextField1.Text = Serial1.LookAhead(Encodings.UTF8)
Serial.Open
Open As Boolean
Attempts to open the Serial port. Returns True if the port was opened and False if it was not.
Serial.Poll
Poll
Causes the control's properties to update and causes the DataAvailable event to execute if any new data is available.
Serial1.Poll
Serial.Read
Read(Count As Integer, [Enc As TextEncoding]) As String
Reads Count bytes from the input stream and returns a String.
If provided, the optional parameter Enc specifies the text encoding to be defined for the String to be read.
If Count is higher than the amount of bytes currently available in the stream, all available bytes will be returned. Therefore, make sure to always consider the case that you get less than you requested. To see if you received all requested bytes, check the returned string's String property (avoid using Length as it may give a different number if the encoding is not nil).
If not enough memory is available, you get back an empty string.
This example reads the first 1000 bytes from a BinaryStream.
Var readFile As FolderItem = FolderItem.ShowOpenFileDialog("text/plain")
If readFile <> Nil Then
Var ReadStream As BinaryStream = BinaryStream.Open(readFile, False)
ReadStream.LittleEndian = True
TextArea1.Text = ReadStream.Read(1000, Encodings.UTF8)
End If
Serial.ReadAll
ReadAll([Encoding As TextEncoding]) As String
Returns all incoming data available in the buffer as a String.
The optional Encoding parameter enables you to specify the text encoding of the data to be read. Use the Encodings module to specify a text encoding.
Serial.Reset
Reset
Resets the port's baud and byte format.
The Serial port must be open for this method to function.
Changes to the Serial device are queued so that you can modify multiple properties of it without them all taking effect immediately. For instance, you can set the baud, parity and stop bits as one operation instead of three. The same thing applies to the line state properties. Once you've made all your changes, you need to call .Reset on the Serial device to reset the device to the new settings.
Serial1.Reset
Serial.SetBreak
SetBreak
Sets the break signal on the control immediately, without the need to call the Reset method.
Serial1.SetBreak
Serial.Write
Write(Data As String)
Writes the passed data to the output stream.
Note that in order to make sure that the data actually ends up on disk or gets sent to the socket it is connected to, the stream must either get closed or the Flush method be called. Otherwise, the data, if small, may end up temporarily in a write buffer before either a certain time has passed or more data is written. This buffering increases performance when writing lots of small pieces of data, but may be causing unwanted delays when another process, e.g. the other end of a socket connection, is waiting for the data. Consider calling the Flush method to reduce latencies that this buffering may cause in such cases.
If Write fails, an IOException will be raised.
This example displays the Save As dialog box and writes the contents of the TextArea1 to a text file.
Var f As FolderItem
Var stream As BinaryStream
f = FolderItem.ShowSaveFileDialog(FileTypes1.Text, "Untitled.txt")
If f<> Nil Then
stream = BinaryStream.Create(f, True)
stream.Write(TextArea1.Text)
stream.Close
End If
Serial.XmitWait
XmitWait
Waits until all data sent to the Serial port with the Write method has been sent.
Serial1.XmitWait
Event descriptions
Serial.DataAvailable
DataAvailable
Occurs when data has been received.
Serial.Error
Error
Occurs when there is an error with the Serial control. Available on Windows and macOS.
Serial.LineStateChanged
LineStateChanged(ChangedLines() As Integer)
When a line state changes, the LineStateChanged event occurs and passes an array of lines whose state has changed.
Notes
Note
Changing property values does not automatically change the state of the hardware, you must call Reset or re-Open the connection in order for the change to take effect.
The Serial control can be instantiated via code since it is not a subclass of Control. This allows you to easily write code that does communications without adding the control to a window.
The Serial control can be used to communicate via multiple Serial ports at once. You can use the properties of the System module to determine the number of Serial ports on the computer and get an array of those ports. You should create an interface to allow the end user to choose the desired port, since Serial ports are different on different machines and platforms.
When data is received by a Serial port connection, the DataAvailable event handler will automatically execute. In this event handler, you would then use the Read or ReadAll functions to access the data in the Serial port buffer. These functions remove the data from the Serial port buffer as they return the data. If you need to read the data from the Serial port buffer without removing it from the buffer, use the LookAhead property. This buffer will use as much memory as it needs from the memory available so there is no need for it to be resized.
Because the Write method is handled asynchronously, you may need to use the XmitWait method to force your app to wait until it has finished sending the data out the Serial port.
On macOS and Linux, your app gets exclusive rights to the Serial port when opening it. This means that another application cannot also open the Serial port after your app has opened it, unless the user is running as root.
Communicating with usb devices
Most USB devices have a chip in them that makes them appear as a Serial device. Typically this chip is a FTDI chip. If the device has this chip, you can communicate with the device with the SerialPort class. If that does not work for you, the Monkeybread plug-in has USB support for a handful of specific types of devices.
Sample code
The following code opens the Serial port. It assumes that the Serial1 control has been added to a window.
If Serial1.Open Then
MsgBox("The serial port is open.")
Else
MsgBox("The serial port could not be opened.")
End if
When the Serial device sends data back to the Serial control that is open, the Serial control's DataAvailable event fires. The data is transferred into a memory buffer. In the DataAvailable event handler, you use the Read or ReadAll methods to get some or all of the data from the buffer. Choose the Read method when you want to get a specific number of bytes (characters) from the buffer. Choose the ReadAll method to get all of the data in the buffer. In both cases, the data returned from the buffer is removed from the buffer to make room for more incoming data. If you need to examine the data in the buffer without removing it from the buffer, you can call the LookAhead method.
This example appends any incoming data to a TextArea.
Sub DataAvailable()
TextArea1.Text = TextArea1.Text + Me.ReadAll
End Sub
Both the Read and ReadAll methods of the Serial class take an optional parameter that enables you to specify the encoding. Use the Encodings module to get the desired encoding and pass it as a parameter. For example, the code above has been modified to specify that the incoming text uses the ANSI encoding, a standard on Windows:
Sub DataAvailable()
TextArea1.Text = TextArea1.Text + Me.ReadAll(Encodings.WindowsANSI)
End Sub
You can send data to the Serial device at any time as long as you have opened the Serial port with the Serial control's Open method. You send data using the Serial control's Write method. The data you wish to send must be a string, as the Write method accepts only a string as a parameter.
If Serial1.Open Then
Serial1.Write(TextArea1.Text)
Else
MsgBox("The serial port could not be opened.")
End If
The Write method is performed asynchronously. This means that the next line of code following the Write method can already be executing before all the data has actually been sent to the Serial device. If you need your code to wait for all data to be sent to the Serial device before continuing, call the Serial control's XmitWait method immediately following a call to the Write method.
The following code directs the Serial control to communicate using Serial port zero (Modem port).
Serial1.SerialPort = System.SerialPort(0)
You detect line state changes by passing an array or a ParamArray of line states that you want to watch. In the first instance, you can do it like this. The objects cCTS, cDTD, and so forth are checkboxes that the user sets to indicate which lines to watch.
' Set up an array of the line states that
' you want to watch.
Dim watchThese(-1) As Integer
If cCTS.Value Then ' checkbox for CTS..
watchThese.Append(Serial.LineCTS)
End If
If cDCD.Value Then
watchThese.Append(Serial.LineDCD)
End If
If cDSR.Value Then
watchThese.Append(Serial.LineDSR)
End If
If cDTR.Value Then
watchThese.Append(Serial.LineDTR)
End If
If cRTS.Value Then
watchThese.Append(Serial.LineRTS)
End If
If cRI.Value Then
watchThese.Append(Serial.LneRI)
End If
' Set the lines that we want to watch. Note
' that calling this function will clear any lines
' that we were watching previously, it doesn't
' append.
Serial1.LineChangeNotification(watchThese)
To use a ParamArray, you pass the class constants for the line states you want to watch. You don't need to set up a real array.
Serial1.LineChangeNotification(Serial.LineRI, Serial.LineDTR, Serial.LineCTS)
Compatibility
All project types on all supported operating systems.
See also
Object parent class; SerialDevice class; System module; Readable, Writeable class interfaces; Connecting to a Serial Device