Why is the serial port not receiving data? What am I doing wrong?

ryfitzger227

New member
Joined
Nov 21, 2012
Messages
1
Programming Experience
1-3
I'm fairly new to the SerialPort in vb.net and wanted to create a test program.

The program will write to a Basic Stamp 2 (microcontroller) a string of "1", "2", or "3". The microcontroller will then receive it, and decide what to write back. It will write back a string of "11.111", "22.222", or "33.333".

Below is the code that I was trying to use. It's writing to the BS2 fine and the BS2 is sending a string back, but the VB.NET program isn't receiving the data.

VB.NET:
Imports System.IO.Ports

Public Class Form1


    Private WithEvents comPort As New IO.Ports.SerialPort
    Private dataIn As String


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


        If comPort.IsOpen Then
            comPort.Close()
        End If
        Try
            With comPort
                .PortName = "COM5"
                .BaudRate = 9600
                .Parity = IO.Ports.Parity.None
                .DataBits = 8
                .StopBits = IO.Ports.StopBits.One
                .Handshake = IO.Ports.Handshake.None
            End With
            comPort.Open()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try


    End Sub


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


        comPort.Write("1")


    End Sub


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click


        comPort.Write("2")


    End Sub


    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click


        comPort.Write("3")


    End Sub


    Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)


        dataIn = comPort.ReadExisting


        TextBox1.AppendText(dataIn & vbNewLine)


    End Sub
End Class

Please help! What am I doing wrong?!
 
You have declared the SerialPort variable WithEvents, but your DataReceived event handler has no Handles clause.

If you read the DataReceived event help topic you will also see that accessing the UI control from that handler is illegal, and how to handle that.
 

Latest posts

Back
Top