This example program uses the COM-1(USB)H RS-232C 1-port type assigned to COM1 over a USB connection and receives data sent from a device using data received event processing and reads data asynchronously from the receive buffer.For example, this method is effective for reading received data when barcode data has been read or when an instrument has finished taking a measurement.This example program uses a delegate and the Invoke method to display received data in a text box.
Start Visual Basic 2005, create a new project, and create a form like that shown to the left.Paste the SerialPort component on the form.Check the SerialPort component properties (communication settings such as the baud rate).
Add the processing for when the connect button and the disconnect button are clicked.Write the following code on Form1.vb.When you double-click each object (button, etc.), if the object is a button, the procedure to code the processing when the button is pressed will open.Write the code for the processing you want to perform here.
Private Sub Button1_Click(... : Processing when the connect button is pressed Try ' Start of exception handling If SerialPort1.IsOpen = True Then ' Port has been opened MessageBox.Show("Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub End If SerialPort1.PortName = TextBox1.Text ' Stores the name of the port to open SerialPort1.Open() ' Opens the port Catch ex As Exception ' Exception handling MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error) End Try SerialPort1.RtsEnable = True ' Turn RTS ON End Sub
Private Sub Button2_Click(... : Processing when the disconnect button is pressed If SerialPort1.IsOpen = True Then ' Port has been opened SerialPort1.Close() ' Closes the port End If End Sub
Declare a delegate Delegate Sub DataDelegate(ByVal sdata As String)
Define the method (function) that will be called by the Invoke method Private Sub PrintData(ByVal sdata As String) TextBox2.Text = sdata End Sub
Private Sub SerialPort1_DataReceived(ByVal... : Code the processing when the data received event occurs Dim ReceivedData As String = " " ' Declare variable for received data Try ReceivedData = SerialPort1.ReadLine ' Receive the data Catch ex As Exception ReceivedData = ex.Message ' Exception handling End Try ' Declare delegate to method to execute by Invoke method and display received data Dim adre As New DataDelegate(AddressOf PrintData) Me.Invoke(adre, ReceivedData) End Sub
To PageTop