Recipe 14.33. Performing Serial IO


Recipe 14.33. Performing Serial I/O

Problem

You need to communicate with a device connected to one of the serial ports on the user's workstation.

Solution

Sample code folder: Chapter 14\SerialIO

Use the My.Computer.Ports.OpenSerialPort() method to create a bidirectional System.IO.Ports.SerialPort instance.

Discussion

The 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:

  • For a single byte, use com1Port.ReadByte().

  • For multiple bytes, use com1Port.Read().

  • For a single character as an Integer, use com1Port.ReadChar().

  • For a complete text line, use com1Port.ReadLine().

  • For all pending characters, use com1Port.Existing().

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.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net