How to recieve and read data through UART from microcontroller using VB - vb.net

I will be posting my code for whatever I have done till now.
I'm sending data to microcontroller, but now I've to check other way and want to receive data.
I have written code which itself acts as UART. I am using readexisting and able to read some characters which is unrelevent, but I'm not able to read required data.
Imports System.IO.Ports
Public Class Settings
Dim myComPort As New SerialPort
' Call a routine to write a command to turn on an LED and read the response.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SendCommand("7")
End Sub
' Call a routint write a command to turn on an LED and read the response.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SendCommand("A")
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
SendCommand("C")
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
myComPort.BaudRate = CInt(cmbBitRate.SelectedItem)
TextBox4.Text = myComPort.BaudRate
End Sub
' If myComPort is open, finish transmitting.
' Exiting the Using block closes the port and releases its resources.
Sub CloseComPort()
Try
Using myComPort
If (Not (myComPort Is Nothing)) Then
' The COM port exists.
If myComPort.IsOpen Then
' Wait for the transmit buffer to empty.
Do While (myComPort.BytesToWrite > 0)
Loop
End If
End If
End Using
Catch ex As UnauthorizedAccessException
' The port may have been removed. Ignore.
End Try
End Sub
' Set the BaudRate property of myComPort to match the bit rate selected in the combo box.
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBitRate.SelectedIndexChanged
myComPort.BaudRate = CInt(cmbBitRate.SelectedItem)
'TextBox2.Text = ToString(myComPort.BaudRate)
End Sub
' If the previously selected COM port is open, close it.
' Set the PortName property of myComPort to match the port selected in the combo box.
' Call a routine to open the port.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPorts.SelectedIndexChanged
CloseComPort()
myComPort.BaudRate = CInt(cmbBitRate.SelectedItem)
' myComPort.BaudRate = 500
'TextBox2.Text = myComPort.BaudRate
OpenComPort()
End Sub
' Call a routine to close the COM port.
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
CloseComPort()
End Sub
' Call routines to initalize the form and open the selected COM port.
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
InitializeForm()
OpenComPort()
AddHandler myComPort.DataReceived, AddressOf DataReceivedeventHandler
End Sub
' Set up the form and select a default port and bit rate.
Sub InitializeForm()
Dim bitRates(9) As Integer
Dim nameArray() As String
' Find the COM ports on the system.
nameArray = SerialPort.GetPortNames
Array.Sort(nameArray)
' Fill a combo box with the port names.
cmbPorts.DataSource = nameArray
cmbPorts.DropDownStyle = ComboBoxStyle.DropDownList
' Select a default port.
'cmbPorts.SelectedIndex = 1
'Bit rates to select from.
bitRates(0) = 300
bitRates(1) = 600
bitRates(2) = 1200
bitRates(3) = 2400
bitRates(4) = 9600
bitRates(5) = 14400
bitRates(6) = 19200
bitRates(7) = 38400
bitRates(8) = 57600
bitRates(9) = 115200
'Place the bit rates in a combo box.
cmbBitRate.DataSource = bitRates
cmbBitRate.DropDownStyle = ComboBoxStyle.DropDownList
' Select a default bit rate.
' If (Not (cmbBitRate Is Nothing)) Then
'CloseComPort()
'End If
End Sub
' Set port parameters and open the COM port
' associated with the SerialPort object myComPort.
Sub OpenComPort()
Try
' Get the selected COM port's name from the combo box.
If Not myComPort.IsOpen Then
myComPort.PortName = cmbPorts.SelectedItem.ToString
' Get the selected bit rate from the combo box.
If cmbBitRate.SelectedIndex > 0 Then
myComPort.BaudRate = CInt(cmbBitRate.SelectedItem)
TextBox4.Text = myComPort.BaudRate
End If
'myComPort.BaudRate = CInt(cmbBitRate.SelectedItem)
' Set other port parameters.
myComPort.Parity = Parity.None
myComPort.DataBits = 8
myComPort.StopBits = StopBits.One
myComPort.Handshake = Handshake.None
myComPort.ReadTimeout = 3000
myComPort.WriteTimeout = 5000
' Open the port.
myComPort.Open()
End If
Catch ex As InvalidOperationException
MessageBox.Show(ex.Message)
Catch ex As UnauthorizedAccessException
MessageBox.Show(ex.Message)
Catch ex As System.IO.IOException
MessageBox.Show(ex.Message)
End Try
End Sub
' Write a command to the SerialPort object and read the response.
''' <param name= "command"> The command to send. </param>
Private Sub SendCommand(ByVal command As String)
' Dim response As String
Try
'TextBox1.BackColor = Color.MediumPurple
myComPort.Write(command)
'myComPort.ReadTimeout = 1000
' While myComPort.ReadLine = 0
' End While
'If myComPort.IsOpen Then
'myComPort.ReadLine()
'End If
'TextBox6.Text = myComPort.ReadLine
Select Case command
Case "A"
' TextBox6.Text = myComPort.
TextBox1.Text = "Green LED is on"
TextBox1.BackColor = Color.LightGreen
Case "7"
TextBox1.Text = " Red LED is ON"
TextBox1.BackColor = Color.Red
'TextBox6.Text = myComPort.ReadLine
Case "C"
TextBox1.Text = " Both LED's are ON"
TextBox1.BackColor = Color.RoyalBlue
'TextBox6.Text = myComPort.ReadLine
Case Else
End Select
Catch ex As TimeoutException
MessageBox.Show(ex.Message)
Catch ex As InvalidOperationException
MessageBox.Show(ex.Message)
Catch ex As UnauthorizedAccessException
MessageBox.Show(ex.Message)
End Try
End Sub
Public Sub DataReceivedeventHandler(
ByVal sender As Object,
ByVal e As SerialDataReceivedEventArgs)
Dim sp As SerialPort = CType(sender, SerialPort)
Dim indata As String = sp.ReadExisting()
' Dim jndata As String = sp.ReadChar
MsgBox(indata)
'TextBox6.Text = CStr(vbMsgBoxRtlReading)
' MsgBox(jndata)
' Console.WriteLine("Data Received:")
Console.Write(indata)
' ArgumentException.Equals(indata)
End Sub
Public Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
End Sub
'Private Sub DataReceivedEventHandler(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
' Throw New NotImplementedException
'End Sub
End Class

Related

Using RFID in multiple windows forms

Hie there.
I am trying to use RFID tags on different forms. The code I have works fine if in one from. As soon you add it to another form it stops. I have tried using event handlers to no success. Does anyone know how I coud do this.
Here is my code:
Public Class Form1
Dim WithEvents phidgetRFID As Phidgets.RFID
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'To reduce code complexity we assume that there is one PhidgetRFID
'attached to the PC before the program is run.
phidgetRFID = New Phidgets.RFID()
phidgetRFID.Open()
'Defaults for text fields
txtStatus.Text = "Not Connected"
End Sub
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
lvPhidgetInfo.MultiColumn = False
lvPhidgetInfo.Items.Insert(0, "TagID Count")
End Sub
Private Sub phidgetRFID_Attach(ByVal sender As Object, ByVal e As Phidgets.Events.AttachEventArgs) Handles phidgetRFID.Attach
'When the Phidget RFID attaches update the form text boxes
Label1.Text = "Phidget RFID Reader has Attached"
txtStatus.Text = "Connected"
txtNumOutputs.Text = phidgetRFID.outputs.Count
txtSerialNumber.Text = (Str(phidgetRFID.SerialNumber))
phidgetRFID.Antenna = True
CheckBox3.Checked = True
phidgetRFID.LED = True
CheckBox2.Checked = True
End Sub
Private Sub phidgetRFID_Detach(ByVal sender As Object, ByVal e As Phidgets.Events.DetachEventArgs) Handles phidgetRFID.Detach
'If the Phidget RFID detaches close the form
Me.Close()
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'If the form closes and the Phidget RFID is attached Close it.
If phidgetRFID.Attached = True Then
phidgetRFID.close()
End If
End Sub
Private Sub phidgetRFID_Error(ByVal sender As Object, ByVal e As Phidgets.Events.ErrorEventArgs) Handles phidgetRFID.Error
'If the Phidget RFID is not attached when the form opens show
'message box and close the form
MessageBox.Show(e.Description)
Me.Close()
End Sub
Private Sub phidgetRFID_RFIDTag(ByVal sender As Object, ByVal e As Phidgets.Events.TagEventArgs) Handles phidgetRFID.Tag
Static count As Integer
count = count + 1
lvPhidgetInfo.BeginUpdate()
lvPhidgetInfo.Items.Insert(1, e.Tag & " " & count)
lvPhidgetInfo.EndUpdate()
End Sub
Private Sub phidgetRFID_RFIDTagLost(ByVal sender As Object, ByVal e As Phidgets.Events.TagEventArgs) Handles phidgetRFID.TagLost
lvPhidgetInfo.BeginUpdate()
lvPhidgetInfo.Items.Insert(1, e.Tag & " Lost")
lvPhidgetInfo.EndUpdate()
End Sub
I have also tried this and I crushes without reporting an error.
Dim PhidgetRFID As New Phidgets.RFID()
AddHandler PhidgetRFID.Attach, AddressOf rfid_Attach
AddHandler PhidgetRFID.Detach, AddressOf rfid_Detach
AddHandler PhidgetRFID.Tag, AddressOf rfid_Tag
AddHandler PhidgetRFID.TagLost, AddressOf rfid_TagLost
AddHandler PhidgetRFID.Error, AddressOf rfid_Error
PhidgetRFID.open()
PhidgetRFID.waitForAttachment(3000)
Private Sub rfid_Attach(sender As Object, e As AttachEventArgs)
Label3.Text = "RFID reader {0} attached!" & e.Device.SerialNumber.ToString()
'Throw New NotImplementedException
End Sub
Private Sub rfid_Detach(sender As Object, e As DetachEventArgs)
Label4.Text = "RFID reader {0} ditached!" & e.Device.SerialNumber.ToString()
End Sub
Private Sub rfid_Tag(sender As Object, e As TagEventArgs)
Try
txtCardNumber.Text = e.Tag
Dim lastRFIDTag As String = txtCardNumber.Text
phidgetRFID.LED = True
' Throw New NotImplementedException
Catch ex As Exception
MsgBox("" & ex.Message, , "")
End Try
End Sub
Private Sub rfid_TagLost(sender As Object, e As TagEventArgs)
'Throw New NotImplementedException
phidgetRFID.LED = False
End Sub
Plaese help..

Serial data overwrite on visual basic

I am new to visual basic . I am sending data from arduino evey 1s say current. I wanted to print on text box. Here is my code on VB side . Problem i am facing here . I am getting data but Not ovwrwriting .it just print one after the other. I am using VB2010.
VB code
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class frmMain
Dim myPort As Array 'COM Ports detected on the system will be stored here
Delegate Sub SetTextCallback(ByVal [text] As String) 'Added to prevent threading errors during receiveing of data
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames() 'Get all com ports available
cmbBaud.Items.Add(9600) 'Populate the cmbBaud Combo box to common baud rates used
cmbBaud.Items.Add(19200)
cmbBaud.Items.Add(38400)
cmbBaud.Items.Add(57600)
cmbBaud.Items.Add(115200)
For i = 0 To UBound(myPort)
cmbPort.Items.Add(myPort(i))
Next
cmbPort.Text = cmbPort.Items.Item(0) 'Set cmbPort text to the first COM port detected
cmbBaud.Text = cmbBaud.Items.Item(0) 'Set cmbBaud text to the first Baud rate on the list
'SerialPort1.PortName = cmbPort.Text()
'SerialPort1.BaudRate = cmbBaud.Text()
btnDisconnect.Enabled = False 'Initially Disconnect Button is Disabled
End Sub
Private Sub btnConnect_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text()
'Set SerialPort1 to the selected COM port at startup
SerialPort1.BaudRate = cmbBaud.Text()
'Set Baud rate to the selected value on
'Other Serial Port Property
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8 'Open our serial port
SerialPort1.Open()
btnConnect.Enabled = False 'Disable Connect button
btnDisconnect.Enabled = True 'and Enable Disconnect button
End Sub
Private Sub btnDisconnect_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
SerialPort1.Close() 'Close our Serial Port
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
Private Sub btnSend_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SerialPort1.Write(txtTransmit.Text & vbCr) 'The text contained in the txtText will be sent to the serial port as ascii
'plus the carriage return (Enter Key) the carriage return can be ommitted if the other end doe
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting()) 'Automatically called every time a data is received at the serialPort
End Sub
Private Sub ReceivedText(ByVal [text] As String)
'compares the ID of the creating Thread to the ID of the calling Thread
If Me.Current_Read.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.Current_Read.Text &= [text]
End If
End Sub
Private Sub cmbPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If SerialPort1.IsOpen = False Then
SerialPort1.PortName = cmbPort.Text 'pop a message box to user if he is changing ports
Else 'without disconnecting first.
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
Private Sub cmbBaud_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
If SerialPort1.IsOpen = False Then
SerialPort1.BaudRate = cmbBaud.Text 'pop a message box to user if he is changing baud rate
Else 'without disconnecting first.
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
Private Sub RELAY_ON_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RELAY_ON.Click
SerialPort1.Write("1")
End Sub
Private Sub RELAY_OFF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RELAY_OFF.Click
SerialPort1.Write("0")
End Sub
End Class
Arduino Code.
float Output_Current ;
void TakeReading()
{
newaverage = analogRead(A5);
Output_Current = 0.0336666666667*newaverage - 17.17;
}
void loop()
{
Serial.println( Output_Current );
delay(1000);
}

VB program, looping for iterations and excel writing

I'm writing a program for an internship and need some advice. I've done my research but have mostly returned fruitless... I need to loop the "buttonOneClick for one second iterations. The program will send a "P" character, wait one second, send a p, wait one second, etc... Also I need to write the information it receives to an excel spreadsheet. Any help/critiquing of existing code would be greatly appreciated.
Here's what I have:
Public Class Form2
Dim buttonOnePush As Boolean = False
Dim buttonTwoPush As Boolean = False
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Send strings to a serial port.
Using com5 As IO.Ports.SerialPort =
My.Computer.Ports.OpenSerialPort("COM5")
com5.WriteLine("P")
End Using
End Sub
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com5 As IO.Ports.SerialPort = Nothing
Try
com5 = My.Computer.Ports.OpenSerialPort("COM5")
com5.ReadTimeout = 10000
Do
Dim Incoming As String = com5.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com5 IsNot Nothing Then com5.Close()
End Try
Return returnStr
End Function
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
If IsNumeric(TextBox1.Text) AndAlso IsNumeric(TextBox2.Text) Then
TextBox1.Text = CDec(TextBox2.Text)
End If
End Sub
Private Sub TextBox6_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox6.TextChanged
If IsNumeric(TextBox6.Text) AndAlso IsNumeric(TextBox3.Text) Then
TextBox6.Text = CDec(TextBox3.Text)
End If
End Sub
Private Sub TextBox7_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox7.TextChanged
If IsNumeric(TextBox7.Text) AndAlso IsNumeric(TextBox4.Text) Then
TextBox7.Text = CDec(TextBox4.Text)
End If
End Sub
Private Sub TextBox8_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox8.TextChanged
If IsNumeric(TextBox8.Text) AndAlso IsNumeric(TextBox5.Text) Then
TextBox8.Text = CDec(TextBox5.Text)
End If
End Sub
Private Sub TextBox15_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox15.TextChanged
If IsNumeric(TextBox15.Text) AndAlso IsNumeric(TextBox16.Text) Then
TextBox15.Text = Hex(TextBox16.Text)
End If
End Sub
Private Sub TextBox14_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox14.TextChanged
If IsNumeric(TextBox14.Text) AndAlso IsNumeric(TextBox11.Text) Then
TextBox14.Text = Hex(TextBox11.Text)
End If
End Sub
Private Sub TextBox13_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox13.TextChanged
If IsNumeric(TextBox13.Text) AndAlso IsNumeric(TextBox10.Text) Then
TextBox13.Text = Hex(TextBox10.Text)
End If
End Sub
Private Sub TextBox12_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox12.TextChanged
If IsNumeric(TextBox12.Text) AndAlso IsNumeric(TextBox9.Text) Then
TextBox12.Text = Hex(TextBox9.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
buttonTwoPush = True
buttonOnePush = False
Me.Close()
Form1.Close()
End Sub
End Class
Use a Timer to issue that command at one second intervals. Drag a Timer over to your form from the toolbox, and double click on it to get a _Tick method.
Set the .Interval member of the timer in your form's constructor, and use the .Start and .Stop methods to control it.
For the Excel piece, you'll need to add a reference to the project for the Microsoft Excel 12.0 (or 14.0 if you have Excel 2010) Object Library. Find this under the COM tab of the Add Reference dialog which you get by right clicking on the project in the Solution Explorer. See this page for an exhaustive reference (scroll down to the bottom of the page for a quick example in VB.NET).

VB.NET Webbrowser to textbox

I need help getting all of the text from WebBrowser1 to my textbox1.text
I tried
WebBrowser1.Navigate(TextBox3.Text)
TextBox1.Text = WebBrowser1.DocumentText
textbox3 being my website
and textbox1 being were i want all the text.
You have to handle the DocumentCompleted event of WebBrowser control.
Private Sub WebBrowser1_DocumentCompleted(sender As System.Object,
e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
Handles WebBrowser1.DocumentCompleted
TextBox1.Text = WebBrowser1.DocumentText
End Sub
My solution:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' WebBrowser1
' TextBox1
' TextBox2
'
WebBrowser1.ScriptErrorsSuppressed = True ' we would like to suppress scripts error message
WebBrowser1.Navigate("http://codeguru.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
' 1) Get entire html code and save as .html file
TextBox1.Text = WebBrowser1.DocumentText
' HOWTO retry while error UNTIL ok
' this needs to be done because Body.InnerText returns error when called too soon
' 2) Get Body text and save as .txt file
Dim retry As Boolean = True
Dim body As String = ""
While retry
Try
body = WebBrowser1.Document.Body.InnerText
retry = False
Catch ex As System.IO.IOException
retry = True
Finally
TextBox2.Text = body
End Try
End While
End Sub
End Class

Very basic VB.Net & Serial IO issue

After searching around I am still having issues with reading data from a serial port in VB.Net/VS2010. I know the Serial Port works, I can write to the port fine but when reading from it, nothing happens. I have only been programming for the last 3 weeks so am still trying to get my head around it all.
The program must run to capture data from a door logger, I will then be outputting the data to a database (not yet implemented - I want to get this part sorted first).
I have tried using several terminal programs as well as another device which outputs data onto the serial line, with nothing displaying in the textbox tbxIn.
Any help would be greatly appreciated.
Code is below:
Imports System.IO.Ports
Imports System.IO.Ports.SerialPort
Public Class Form1
Dim comPort As IO.Ports.SerialPort = Nothing
Dim sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
tbxIn.Text = e.ToString
End Sub
End Class
PRetty sure this will get you what you need. You DON't need the Serial1 component on the designer. Remove that and use this code:
Private comPort As IO.Ports.SerialPort = Nothing
Private sComPort As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
GetSerialPortNames()
End Sub
Sub GetSerialPortNames()
' Show all available COM ports.
For Each sp As String In My.Computer.Ports.SerialPortNames
lstPorts.Items.Add(sp)
Next
End Sub
Private Sub lstPorts_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstPorts.SelectedIndexChanged
sComPort = lstPorts.SelectedItem
Button1.Enabled = True
End Sub
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Open the serial port using the OpenSerialPort method
Button1.Enabled = False
Button2.Enabled = True
Try
comPort = My.Computer.Ports.OpenSerialPort(sComPort, 9600, IO.Ports.Parity.None, 8, 1)
' comPort.DtrEnable = True
'must add handler
AddHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
comPort.ReadTimeout = 500
Do
comPort.WriteLine("Go")
Dim sIncomming As String = comPort.ReadLine()
tbxIn.Text = sIncomming & vbCrLf
Loop
Catch ex As TimeoutException
tbxIn.Text &= "Error: Serial Port Read Timeout" & vbCrLf
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
comPort.Close()
'remove handler
RemoveHandler comPort.DataReceived, AddressOf SerialPort1_DataReceived
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
tbxIn.Text = e.ToString
End Sub