VB project - Inside was outside the bounds of the array - vb.net

I'm working with the following VB code:
Option Strict On
Option Infer On
Public Class mainForm
Private readBuffer As String = String.Empty
Private Bytenumber As Integer = 1
Private ByteToRead As Integer = 1
Private byteEnd(2) As Char
Private comOpen As Boolean
Private Sub Form1_FormClosed(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosedEventArgs) _
Handles MyBase.FormClosed
If comOpen Then SerialPort1.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sensorButton.Checked = True
' read avaiable COM Ports:
Dim Portnames As String() = System.IO.Ports.SerialPort.GetPortNames
If Portnames Is Nothing Then
MsgBox("There are no Com Ports detected!")
Me.Close()
End If
cboComPort.Items.AddRange(Portnames)
cboComPort.Text = Portnames(0)
cboBaudRate.Text = "115200"
End Sub
Private Sub btnComOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComOpen.Click
' device params
With SerialPort1
.ParityReplace = &H3B ' replace ";" when parity error occurs
.PortName = cboComPort.Text
.BaudRate = CInt(cboBaudRate.Text)
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = False
.ReceivedBytesThreshold = 1 'threshold: one byte in buffer > event is fired
.NewLine = vbCr ' CR must be the last char in frame. This terminates the SerialPort.readLine
.ReadTimeout = 10000
End With
' check whether device is avaiable:
Try
SerialPort1.Open()
comOpen = SerialPort1.IsOpen
Catch ex As Exception
comOpen = False
MsgBox("Error Open: " & ex.Message)
picOpen.BackColor = Color.Red
End Try
If comOpen Then
picOpen.BackColor = Color.Green
cboComPort.Enabled = False
cboBaudRate.Enabled = False
End If
End Sub
''' <summary>
''' close ComPort
''' </summary>
Private Sub Button_Close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComClose.Click
If comOpen Then
' clear input buffer
SerialPort1.DiscardInBuffer()
SerialPort1.Close()
End If
comOpen = False
picOpen.BackColor = Color.Red
picDataReceived.BackColor = Color.Gray
cboComPort.Enabled = True
cboBaudRate.Enabled = True
End Sub
''' <summary>
''' clear TextBoxes
''' </summary>
Private Sub Button_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
tbRx.Text = String.Empty
txTimer.Stop()
End Sub
''' <summary>
''' write content of Textbox to Port
''' </summary>
Private Sub button_send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
...
End Sub
''' <summary>
''' close app
''' </summary>
Private Sub Button_ende_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
If comOpen Then
' clear input buffer
SerialPort1.DiscardInBuffer()
SerialPort1.Close()
End If
comOpen = False
Me.Close()
End Sub
''' <summary>
''' send control panel key to com port
''' </summary>
''' <param name="sender">return key name</param>
Private Sub Tasten_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Dim key As String = CType(sender, Button).Text
If comOpen Then SerialPort1.Write(key)
End Sub
''' <summary>
''' Timer datareceived event
''' </summary>
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
picDataReceived.BackColor = Color.Gray
Timer1.Enabled = False
End Sub
econdary thread
'''
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles SerialPort1.DataReceived
...
End Sub
Public Sub DoUpdate(ByVal sender As Object, ByVal e As System.EventArgs)
...
End Sub
.....
End Class
The original code is found here: https://code.msdn.microsoft.com/windowsapps/SerialPort-Sample-in-VBNET-fb040fb2
I've modified the code to suit my needs and am seeing the error "Index was outside the bounds of the array" when I run the application from the Debug folder on a separate PC (the files work with no flaws on my PC with Visual Studio). I thought the issue was with my modification, but it looks like the original file cannot be run. I have attempted to initialize the ints "Bytenumber" and "ByteToRead" with a value of 1, bit I still the issue. What could be causing it?
The exception text is:
************** Exception Text **************
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at LMUEngineering.mainForm.Form1_Load(Object sender, EventArgs e) in C:\Users\---\OneDrive\frmMain.vb:line 38
at System.EventHandler.Invoke(Object sender, EventArgs e)
at System.Windows.Forms.Form.OnLoad(EventArgs e)
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Related

Code runs OK on Windows 7 but not on Windows 10 , "Index was outside the bounds of the array"

This code runs on Windows 7 but not on Windows 10. On Windows 10 I get a .NET unhandled exception.
I have made sure that both machines are running dot net 4, the same versions on each PC.
Option Strict On
Option Infer On
Public Class mainForm
Private readBuffer As String = String.Empty
Private Bytenumber As Integer
Private ByteToRead As Integer
Private byteEnd(2) As Char
Private comOpen As Boolean
#Region "form events"
''' <summary>
''' close application and COM Port
''' </summary>
Private Sub Form1_FormClosed(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosedEventArgs) _
Handles MyBase.FormClosed
If comOpen Then SerialPort1.Close()
End Sub
''' <summary>
''' open Windows Form
''' </summary>
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' read avaiable COM Ports:
Dim Portnames As String() = System.IO.Ports.SerialPort.GetPortNames
If Portnames Is Nothing Then
MsgBox("There are no Com Ports detected!")
Me.Close()
End If
cboComPort.Items.AddRange(Portnames)
cboComPort.Text = Portnames(0)
cboBaudRate.Text = "9600"
End Sub
''' <summary>
''' Open Com Port here
''' </summary>
Private Sub btnComOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComOpen.Click
' device params
With SerialPort1
.ParityReplace = &H3B ' replace ";" when parity error occurs
.PortName = cboComPort.Text
.BaudRate = CInt(cboBaudRate.Text)
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Handshake = IO.Ports.Handshake.None
.RtsEnable = False
.ReceivedBytesThreshold = 1 'threshold: one byte in buffer > event is fired
.NewLine = vbCr ' CR must be the last char in frame. This terminates the SerialPort.readLine
.ReadTimeout = 10000
End With
' check whether device is avaiable:
Try
SerialPort1.Open()
comOpen = SerialPort1.IsOpen
Catch ex As Exception
comOpen = False
MsgBox("Error Open: " & ex.Message)
picOpen.BackColor = Color.Red
End Try
If comOpen Then
picOpen.BackColor = Color.Green
cboComPort.Enabled = False
cboBaudRate.Enabled = False
End If
End Sub
''' <summary>
''' close ComPort
''' </summary>
Private Sub Button_Close_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnComClose.Click
If comOpen Then
' clear input buffer
SerialPort1.DiscardInBuffer()
SerialPort1.Close()
End If
comOpen = False
picOpen.BackColor = Color.Red
picDataReceived.BackColor = Color.Gray
cboComPort.Enabled = True
cboBaudRate.Enabled = True
End Sub
''' <summary>
''' clear TextBoxes
''' </summary>
Private Sub Button_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
tbRx.Text = String.Empty
tbTx.Text = String.Empty
End Sub
''' <summary>
''' write content of Textbox to Port
''' </summary>
Private Sub button_send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If comOpen Then SerialPort1.WriteLine(tbTx.Text)
End Sub
''' <summary>
''' close app
''' </summary>
Private Sub Button_ende_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
If comOpen Then
' clear input buffer
SerialPort1.DiscardInBuffer()
SerialPort1.Close()
End If
comOpen = False
Me.Close()
End Sub
''' <summary>
''' send control panel key to com port
''' </summary>
''' <param name="sender">return key name</param>
Private Sub Tasten_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button9.Click, Button8.Click, Button7.Click, _
Button6.Click, Button5.Click, Button3.Click, _
Button4.Click, Button2.Click, ButtonE.Click, _
Button0.Click, ButtonC.Click, Button1.Click
Dim key As String = CType(sender, Button).Text
If comOpen Then SerialPort1.Write(key)
End Sub
''' <summary>
''' Timer datareceived event
''' </summary>
Private Sub Timer1_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Timer1.Tick
picDataReceived.BackColor = Color.Gray
Timer1.Enabled = False
End Sub
#End Region
#Region "ComPort read data"
''' <summary>
''' async read on secondary thread
''' </summary>
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles SerialPort1.DataReceived
If comOpen Then
Try
byteEnd = SerialPort1.NewLine.ToCharArray
' get number off bytes in buffer
Bytenumber = SerialPort1.BytesToRead
' read one byte from buffer
'ByteToRead = SerialPort1.ReadByte()
' read one char from buffer
'CharToRead = SerialPort1.ReadChar()
' read until string "90"
'readBuffer1 = SerialPort1.ReadTo("90")
' read entire string until .Newline
readBuffer = SerialPort1.ReadLine()
'data to UI thread
Me.Invoke(New EventHandler(AddressOf DoUpdate))
Catch ex As Exception
MsgBox("read " & ex.Message)
End Try
End If
End Sub
''' <summary>
''' update received string in UI
''' </summary>
''' <remarks></remarks>
Public Sub DoUpdate(ByVal sender As Object, ByVal e As System.EventArgs)
tbRx.Text = readBuffer
picDataReceived.BackColor = Color.Green
Timer1.Enabled = True
End Sub
#End Region
End Class
You are making an assumption that the array returns at least one object here:
Portnames(0)
Remember a null array and an empty array aren't the same thing. You need to check if the array is empty.
If Portnames Is Nothing OrElse Portnames.Length = 0 Then
MsgBox("There are no Com Ports detected!")
Me.Close()
End If
Note in the documentation, it doesn't specify if returns null or no records. More likely it returns an empty array.
https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.getportnames?view=netframework-4.8

How to save my wlan settings?

I'm currently using Visual Studio 2012. My form code is given below with design screenshots. I am trying to make a virtual hotspot for my PC but I want to add one feature which takes previous SSID and password. My hotspot opens every time with blank text.
Here's my form design:
Form1 Design:
[
Form1 code:
Imports System.Runtime.InteropServices
Imports System.Collections.ObjectModel
Imports System.Text
Imports NativeWifi
Public Class Form1
Public Const WM_NCLBUTTONDOWN As Integer = &HA1
Public Const HT_CAPTION As Integer = &H2`
<DllImportAttribute("user32.dll")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Msg As Integer, ByVal wParam As Integer, _
ByVal lParam As Integer) As Integer
End Function
<DllImportAttribute("user32.dll")> _
Public Shared Function ReleaseCapture() As Boolean
End Function`
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim wlan = New WlanClient()
Dim connectedSsids As Collection(Of [String]) = New Collection(Of String)()
For Each wlanInterface As WlanClient.WlanInterface In wlan.Interfaces
Dim ssid As Wlan.Dot11Ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid
connectedSsids.Add(New [String](Encoding.ASCII.GetChars(ssid.SSID, 0, CInt(ssid.SSIDLength))))
For Each item As String In connectedSsids
Label1.Text = item
Next
Next
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Me.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
ReleaseCapture()
SendMessage(Handle, WM_NCLBUTTONDOWN, _
HT_CAPTION, 0)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If Form2.TextBox1.Text = "" Then
MsgBox("Hotspot name cant be empty", MsgBoxStyle.Critical)
End If
If Form2.TextBox2.TextLength < 8 Then
MsgBox("Password should be 8+ character", MsgBoxStyle.Critical)
If Form2.TextBox2.Text = "" Then
MsgBox("Password cant be empty", MsgBoxStyle.Critical)
End If
Else
Dim process As New Process()
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = True
process.Start("cmd", String.Format("/c {0} & {1} & {2}", "netsh wlan set hostednetwork mode=allow ssid=" & Form2.TextBox1.Text & " key=" & Form2.TextBox2.Text, "netsh wlan start hostednetwork", "pause"))
Form2.CheckBox1.Enabled = False
Form2.TextBox1.Enabled = False
Form2.TextBox2.Enabled = False
MsgBox("Hotspot started Successfully", MsgBoxStyle.Information)
End If
Catch
MsgBox("Failed to Establish a hotspot", MsgBoxStyle.Exclamation)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Process.Start("CMD", "/C netsh wlan stop hostednetwork")
Form2.CheckBox1.Enabled = True
Form2.TextBox1.Enabled = True
Form2.TextBox2.Enabled = True
MsgBox("Hotspot stopped Successfully", MsgBoxStyle.Information)
End Sub
Private Sub Clsbtn_Click(sender As Object, e As EventArgs) Handles Clsbtn.Click
Me.Close()
End Sub
Private Sub Minbtn_Click(sender As Object, e As EventArgs) Handles Minbtn.Click
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
End Sub
Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
Me.Hide()
Form2.Show()
End Sub
End Class
Form2 Design:
[

VB.net RGB color sensor "Integer is not valid"

I'm trying to make VB.net show the data "colors" from my Arduino,
My serial port working great but I have this massage every-time I press connect & weird data show's up
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string " = " to type 'Integer' is not valid.
Can someone help me in this?
this is my code
Public Class Form1
Private _msg As String
Dim R As String
Dim G As String
Dim B As String
Dim iR As String
Dim iG As String
Dim iB As String
Private indata As String
Dim IsConnected As Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each str As String In IO.Ports.SerialPort.GetPortNames()
Ports.Items.Add(str)
Next
If (Ports.Items.Count > 0) Then
Ports.SelectedIndex = 0
End If
IsConnected = False
Status.Text = "Disconnected"
Status.BackColor = Color.MistyRose
Button1.Enabled = True
Button2.Enabled = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (SerialPort1.IsOpen()) Then
Try
SerialPort1.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
IsConnected = False
Status.Text = "Disconnected"
Status.BackColor = Color.MistyRose
Button1.Enabled = True
Button2.Enabled = False
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (SerialPort1.IsOpen = False) Then
SerialPort1.PortName = Ports.SelectedItem
SerialPort1.Open()
IsConnected = True
Status.Text = "Connected"
Status.BackColor = Color.LightGreen
Button1.Enabled = False
Button2.Enabled = True
End If
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'user chose string
'read data waiting in the buffer
Try
Dim msg As String = SerialPort1.ReadExisting()
indata = indata + msg
'Dim where As Integer = InStr(indata, ControlChars.Lf)
Dim where As Integer = InStr(indata, "R=")
If (indata.Length > where + 18) Then
R = indata.Substring(where + 1, 3)
G = indata.Substring(where + 7, 3)
B = indata.Substring(where + 13, 3)
indata = ""
End If
'display the data to the user
_msg = msg
_msg = _msg.Replace(ControlChars.Cr, "")
: DisplayData(msg)
Catch ex As Exception
End Try
End Sub
#Region "DisplayData"
''' <summary>
''' Method to display the data to and
''' from the port on the screen
''' </summary>
''' <remarks></remarks>
<STAThread()> _
Private Sub DisplayData(ByVal msg As String)
DisplayWindow.BeginInvoke(New EventHandler(AddressOf DoDisplay))
End Sub
#End Region
#Region "DoDisplay"
Private Sub DoDisplay(ByVal sender As Object, ByVal e As EventArgs)
'DisplayWindow.SelectedText = String.Empty
'DisplayWindow.SelectionFont = New Font(_DisplayWindow.SelectionFont, FontStyle.Bold)
'DisplayWindow.SelectionColor = MessageColor(CType(_type, Integer))
DisplayWindow.AppendText(_msg)
DisplayWindow.ScrollToCaret()
End Sub
#End Region
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
RL.Text = R
GL.Text = G
BL.Text = B
iR = CInt(R) * CInt(RM.Text)
iG = CInt(G) * CInt(GM.Text)
iB = CInt(B) * CInt(BM.Text)
RF.Text = iR
GF.Text = iG
BF.Text = iB
Try
Label6.BackColor = Color.FromArgb(CType(iR, Byte), CType(iG, Byte), CType(iB, Byte))
Catch ex As Exception
End Try
End Sub
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs)
System.Diagnostics.Process.Start("http://www.narzan.weebly.com/p-1049.html")
End Sub
Private Sub LinkLabel1_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
picOn.Visible = True
SerialPort1.Open()
SerialPort1.Write("^")
SerialPort1.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
picOn.Visible = False
SerialPort1.Open()
SerialPort1.Write("<")
SerialPort1.Close()
End Sub
Private Sub picOn_Click(sender As Object, e As EventArgs) Handles picOn.Click
End Sub
Private Sub RL_Click(sender As Object, e As EventArgs) Handles RL.Click
End Sub
Private Sub RM_TextChanged(sender As Object, e As EventArgs) Handles RM.TextChanged
End Sub
End Class
My problem was from my Arduino code not from VB.net
the solution is to remove "=" from R,G,B
void printColour(){
Serial.print("R = ");
Serial.println(int(colourArray[0]));
Serial.print("G = ");
Serial.println(int(colourArray[1]));
Serial.print("B = ");
Serial.println(int(colourArray[2]));
//delay(2000);
}
so the code will look like that
void printColour(){
Serial.print("");
Serial.println(int(colourArray[0]));
Serial.print("");
Serial.println(int(colourArray[1]));
Serial.print("");
Serial.println(int(colourArray[2]));
//delay(2000);
}
Thanks everyone, everything work great now

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);
}

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