Visual Basic – Serial communication
With this script you can send data to a serial port:
Needed:
- Listbox
First in the FORM LOAD section load the connected comports to the listbox:
1 2 3 4 5 6 7 |
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'Haal COM Poorten op For Each sp As String In My.Computer.Ports.SerialPortNames ListBox1.Items.Add(sp) ListBox1.SelectedIndex = 0 'selecteer altijd een optie (de eerste) Next End Sub |
Create a function for easy serial comport writing (using the comport selected in the listbox):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Public Function SendSerialData(data As String, Optional ByVal timeout As Integer = 1000) 'Send strings to a serial port. Dim mijndata As String = "" On Error Resume Next Using com1 As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort(ListBox1.SelectedItem) com1.BaudRate = 9600 com1.DataBits = 8 com1.Parity = IO.Ports.Parity.None com1.StopBits = IO.Ports.StopBits.One com1.ReadTimeout = timeout com1.WriteTimeout = 1000 com1.NewLine = vbCr 'vbCrLf com1.DiscardInBuffer() com1.WriteLine(data) End Using End Function |
to write to the serial port use:
SendSerialData("MyString")