Recipe 14.33. Performing Serial I/OProblemYou need to communicate with a device connected to one of the serial ports on the user's workstation. SolutionSample code folder: Chapter 14\SerialIO Use the My.Computer.Ports.OpenSerialPort() method to create a bidirectional System.IO.Ports.SerialPort instance. DiscussionThe following method generically sends data out to the COM1 serial port: Public Sub OutToCOM1(ByVal serialData As String, _ ByVal useLineTermination As Boolean) ' ----- Open COM1 and send the supplied data. Dim com1Port As IO.Ports.SerialPort = Nothing Try ' ----- Access the port. com1Port = My.Computer.Ports.OpenSerialPort("COM1") ' ----- Write the data. If (useLineTermination = True) Then com1Port.WriteLine(serialData) Else com1Port.Write(serialData) End If ' ----- Finished with the port. com1Port.Close( ) Catch ex As Exception MsgBox("Error writing data to serial port: " & _ ex.Message) Finally If (com1Port IsNot Nothing) Then com1Port.Dispose( ) com1Port = Nothing End Try End Sub The opened serial port is bidirectional, so you can also read pending content:
When opening the serial port, different constructors allow you to specify the various handshaking options, including baud rate and stop bits. To access the list of available serial ports, use the My.Computer.Ports.SerialPortNames collection. |