This example program uses the COM-1(USB)H RS-232C 1-port type assigned to COM1 over a USB connection and sends the string data entered in the text box including the default delimiter.
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).
The delimiter code means the separating character or separating symbol for the data.The default delimiter code for the SerialPort class is "LF", but this must be configured for the equipment that will be connected.Use the appropriate delimiter code according to the specifications of the connected device.
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 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
Private Sub Button3_Click(... : Processing when the send button is pressed If TextBox2.Text.Length = 0 Then ' Error if there is no send data MessageBox.Show("String input error", MessageBoxButtons.OK, MessageBoxIcon.Error) Exit Sub ' Break out of processing End If Try SerialPort1.WriteLine(TextBox2.Text) ' Write data to the send buffer Catch ex As Exception ' Exception handling MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error) End Try End Sub
To change the delimiter in the code and send the data, write the code as follows.
Dim strSend As String ' String variable to store NewLine strSend = SerialPort1.NewLine ' Get NewLine strSend = strSend.Replace(vbLf, vbCr) ' To convert LF in string to CR SerialPort1.NewLine = strSend ' Store replaced delimiter in NewLine Try SerialPort1.WriteLine(TextBox2.Text) ' Write data to send buffer Catch ex As Exception ' Exception handling MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try
For the Try - Catch - End Try syntax, check the Visual Basic 2005 reference.
To PageTop