Skip to main content

 none
Assigning certain portions of text to text boxes in VS 2019. RRS feed

  • Question

  • Hi All.

    My first post, and thank you in advance for your time and help.

    I am a TOTAL NOOB and am not VS literate, so I do not understand all of the complex code needed to do what I would like, The code below is not mine it is hacked together from stuff on the net that I can make sense of..... Sort of.

    I would like to be able to display certain portions of the serial monitor/ port text into specific text boxes in my vb.form.

    The serial port is an Arduino uno with the software serial library loaded, below is what is coming from a Victron MPPT, (it's a solar charge controller) it spits out this text and the changes to the second row of data every second. 

    Below is what is displayed on the serial port/ monitor:

    PID	            0xA04B
    FW	            142
    SER#            HQ154037ESU
    V	             53420
    I	             20700
    VPV	             83560
    PPV	             1101
    CS	             3
    MPPT            2
    ERR	             0
    LOAD           ON
    H19	             455010
    H20	             1
    H21	             675
    H22	             807
    H23	             1427
    HSDS            311
    Checksum
     -:A5010000001000000FFFFFFFFB41439130000000000000000000000DF0200008B00F12937011C

    The first row tells me what part of the system /device the reading is from, the second row is the value I would like displayed in certain text boxes.... There are two circle progress bars one of which must be able to display the VPV reading. Any Help will be welcomed.

    Thank you.

    Regards:

    Charles

    The code I have hacked together is as follows:

    Imports System Imports System.IO.Ports Public Class frmVictronmultiread Private Sub FrmVictronmultiread_Load(sender As Object, e As EventArgs) Handles MyBase.Load PanelConnection.Focus() MPPTWATT.Value = 0 BMVSOC.Value = 0 ComboBoxBaudrate.SelectedIndex = 0 End Sub Private Sub ComboBoxPort_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxPort.SelectedIndexChanged PanelConnection.Focus() End Sub

    Private Sub ComboBoxPort_DropDown(sender As Object, e As EventArgs) Handles ComboBoxBaudrate.DropDown PanelConnection.Focus() End Sub

    Private Sub ComboBoxPort_Click(sender As Object, e As EventArgs) Handles ComboBoxPort.Click If LabelStatus.Text = "status : Connected" Then MsgBox("Connection in progres, please Disconnect first to change CommPort", MsgBoxStyle.Critical, "Warning") Return End If End Sub Private Sub ComboBoxBaudrate_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBoxBaudrate.SelectedIndexChanged PanelConnection.Focus() End Sub Private Sub ComboBoxBaudrate_DropDown(sender As Object, e As EventArgs) Handles ComboBoxBaudrate.SelectedIndexChanged PanelConnection.Focus() End Sub Private Sub ComboBoxBaudrate_Click(sender As Object, e As EventArgs) Handles ComboBoxBaudrate.Click If LabelStatus.Text = "status : Connected" Then MsgBox("Connection in progress, please Disconnect first to change Baud Rate", MsgBoxStyle.Critical, "Warning") Return End If End Sub Private Sub ButtonScanPort_Click(sender As Object, e As EventArgs) Handles ButtonScanPort.Click PanelConnection.Focus() If LabelStatus.Text = "status : Connected" Then MsgBox("Connection in progres, please Disconnect first to scan new Port", MsgBoxStyle.Critical, "Warning") Return End If ComboBoxPort.Items.Clear() Dim myPort As Array Dim i As Integer myPort = IO.Ports.SerialPort.GetPortNames() ComboBoxPort.Items.AddRange(myPort) i = ComboBoxPort.Items.Count i -= i Try ComboBoxPort.SelectedIndex = i ButtonConnect.Enabled = True Catch ex As Exception MsgBox("Com Port not detected", MsgBoxStyle.Critical, "Warning") ComboBoxPort.Text = "" ComboBoxPort.Items.Clear() Return End Try ComboBoxPort.DroppedDown = True End Sub

    Private Sub ButtonConnect_Click(sender As Object, e As EventArgs) Handles ButtonConnect.Click PanelConnection.Focus() Try SerialPort1.BaudRate = ComboBoxBaudrate.SelectedItem SerialPort1.PortName = ComboBoxPort.SelectedItem SerialPort1.Open() TimerSerial.Start() LabelStatus.Text = "status : Conenected" ButtonConnect.SendToBack() ButtonDisconnect.BringToFront() PictureBoxStatus.BackColor = Color.Green Catch ex As Exception MsgBox("please check the hardware, Com and Baud Rate And try again.", MsgBoxStyle.Critical, "Connection Failed") End Try End Sub Private Sub ButtonDisconnect_Click(sender As Object, e As EventArgs) Handles ButtonDisconnect.Click PanelConnection.Focus() TimerSerial.Stop() SerialPort1.Close() ButtonDisconnect.SendToBack() ButtonConnect.BringToFront() LabelStatus.Text = "Status : Disconnected" PictureBoxStatus.Visible = True PictureBoxStatus.BackColor = Color.Red End Sub Private Sub CheckedListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) End Sub Private Sub PanelConnection_Paint(sender As Object, e As PaintEventArgs) Handles PanelConnection.Paint End Sub Private Sub LabelBaudRate_Click(sender As Object, e As EventArgs) Handles LabelBaudRate.Click End Sub Private Sub TimerSerial_Tick(sender As Object, e As EventArgs) Handles TimerSerial.Tick 'StrSerialIn = SerialPort1 .ReadExisting "--> read incoming serial data If PictureBoxStatus.Visible = True Then PictureBoxStatus.Visible = False ElseIf PictureBoxStatus.Visible = False Then PictureBoxStatus.Visible = True End If End Sub Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged End Sub Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged End Sub Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged End Sub End Class


    Sunday, September 15, 2019 3:45 PM

All replies

  • Hi

    Your question regarding the splitting and adding to textboxes is very straightforward. However, to do so needs the data collected from the external source - is that part working? Assuming it is, then what has the data been stored in - a single string, a List, an array - what exactly?


    Regards Les, Livingston, Scotland

    Sunday, September 15, 2019 6:12 PM
  • Hi Les,

    Exactly as you are reading it in the first box.

    It's all readable data. 

    The only thing I'll have to define to make it readable to VS is the PID  That equates to the model number of  a device.

    The data is written over every second with new data from the device

    Regards

    Charles

    0xA04B

    Sunday, September 15, 2019 6:29 PM
  • Hi

    Still need to know what the data is 'read'into. The data arrives at the serial port - then - where do you direct it? Perhaps into a List(Of String), or maybe into a String Array() ?

    Need to know what 'container' is filled with the data.

    Please do not refer to something as 'first box' - is it a multiline TextBox perhaps? Use the control name if referring to a control.


    Regards Les, Livingston, Scotland



    • Edited by leshay Sunday, September 15, 2019 6:43 PM
    Sunday, September 15, 2019 6:41 PM
  • Hi Les.

    I do apologize, the "first box" I was referring to was the first code box in my OP.

    I copied that text from the serial monitor window in VS.

    It is not going anywhere else yet as I am not sure what to do next.

    I'm like a dog that was let out of the garden and have caught the car, now I don't know what to do with it. If you'll excuse the pun.

    Regards

    Charles

    Sunday, September 15, 2019 6:54 PM
  • Hi

    No need to apologize, we all have to start somewhere.

    OK, first things first.

    Assuming you started a New Project.

    Do you have a Project Form - default would be Form1?

    Are there any controls on the Form - such as ComboBoxes, TextBoxes or any of the myriad of available controls?


    Regards Les, Livingston, Scotland

    Sunday, September 15, 2019 7:09 PM
  • Hi Les.

    Yes I do.

    The GUI has been made.

    Form1.vb

    Public Class frmVictronmultiread

    I am not yet able to insert pictures. My account has not yet been verified.

    Regards

    Charles

    Sunday, September 15, 2019 7:17 PM
  • Hi

    OK, do you have a Butto1 and a ListBox1 on the Form?

    BTW: I will try, but, since I do not have a serial port to test code on I may have to bow out - lets see how far we get.


    Regards Les, Livingston, Scotland



    • Edited by leshay Sunday, September 15, 2019 7:38 PM
    Sunday, September 15, 2019 7:30 PM
  • Hi

    Here is some test code. Please try this as a new stand alone project. Put a ListBox1, TextBox1 and Button1 on Form1, copy/replace Form1 code with this.

    Once ready, try running. With luck, you should have a list of serial port names, select the one you use for your incoming data and click Button1. With further luck, you should have the data in TextBox1.

    ' Form1 with ListBox1, TextBox1
    ' and Button1
    Option Strict On
    Option Explicit On
    Public Class Form1
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' this codejust toset up UI
    		With ListBox1
    			.Location = New Point(4, 4)
    			.Size = New Size(70, ClientSize.Height - 44)
    			.IntegralHeight = False
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left
    			.Font = New Font("Arial", 12)
    		End With
    		With TextBox1
    			.Multiline = True
    			.Location = New Point(ListBox1.Right + 4, 4)
    			.Size = New Size(ClientSize.Width - ListBox1.Width - 12, ClientSize.Height - 44)
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Right
    			.Font = New Font("Arial", 12)
    		End With
    		With Button1
    			.Location = New Point(4, ListBox1.Bottom + 4)
    			.Text = "READ"
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
    		End With
    
    		GetSerialPortNames()
    
    		'ListBox1.Items.Add("COM1")
    		'ListBox1.Items.Add("COM2")
    		'ListBox1.Items.Add("COM3")
    		'ListBox1.Items.Add("COM4")
    		ListBox1.SelectedIndex = 0
    	End Sub
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		TextBox1.Text = ReceiveSerialData(ListBox1.SelectedItem.ToString)
    	End Sub
    	Function ReceiveSerialData(port As String) As String
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-receive-strings-from-serial-ports
    		' Receive strings from a serial port.
    		Dim returnStr As String = ""
    
    		Dim com1 As IO.Ports.SerialPort = Nothing
    		Try
    			com1 = My.Computer.Ports.OpenSerialPort(port)
    			com1.ReadTimeout = 10000
    			Do
    				Dim Incoming As String = com1.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."
    		Catch ex2 As IO.IOException
    			returnStr = "ERROR: " & ex2.Message
    		Finally
    			If com1 IsNot Nothing Then com1.Close()
    		End Try
    		Return returnStr
    	End Function
    	Sub GetSerialPortNames()
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-show-available-serial-ports
    		' Show all available COM ports.
    		For Each sp As String In My.Computer.Ports.SerialPortNames
    			ListBox1.Items.Add(sp)
    		Next
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Sunday, September 15, 2019 8:16 PM
  • Hi Les.

    Sorry I had to bug out. It was late and my bed was calling loudly...

    Once I am home I will try out your appended code. I will carefully follow your instructions and as soon as my email/ Account has been verified I'll post a pic of the GUI. I have labels text boxes and Buttons.

    Am at work now so will not be able to check before 16H00 local time +2 Hrs GMT. 

    Will revert back then.

    Regards

    Charles


    Monday, September 16, 2019 6:53 AM
  • HI Les,

    Ok.

    I've done exactly as directed.

    The results. There is nothing in the text box at all no matter how long I wait.

    If I disconnect the MPPT from the Arduino then I get the timeout error message.

    If  I don't plug in the Arduino it also gives me an error.

    The Com port is also recognized by the software. 

    So the app knows that something is in coming from the Arduino because I get no warnings until I either stop the program or disable the MPPT so that there is no data on the serial monitor.

    Regards

    Charles.


    Monday, September 16, 2019 2:55 PM
  • Hi

    Here is amended code - please try (just replace all with this)

    Changes are emboldened.

    Presumably you have required port setup information,if so,edit block accordingly.

    As before,I can't check any of this code due to no serial post(s)

    Option Strict On
    Option Explicit On
    ' Form1 with ListBox1, TextBox1
    ' and Button1
    Imports System.IO.Ports
    
    Public Class Form1
    	Dim SP As New SerialPort
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' this codejust toset up UI
    		With ListBox1
    			.Location = New Point(4, 4)
    			.Size = New Size(70, ClientSize.Height - 44)
    			.IntegralHeight = False
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left
    			.Font = New Font("Arial", 12)
    		End With
    		With TextBox1
    			.Multiline = True
    			.Location = New Point(ListBox1.Right + 4, 4)
    			.Size = New Size(ClientSize.Width - ListBox1.Width - 12, ClientSize.Height - 44)
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Right
    			.Font = New Font("Arial", 12)
    		End With
    		With Button1
    			.Location = New Point(4, ListBox1.Bottom + 4)
    			.Text = "READ"
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
    		End With
    		GetSerialPortNames()
    
    		'ListBox1.Items.Add("COM1")
    		'ListBox1.Items.Add("COM2")
    		'ListBox1.Items.Add("COM3")
    		'ListBox1.Items.Add("COM4")
    		ListBox1.SelectedIndex = 0
    	End Sub
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Dim SPName As String = ListBox1.SelectedItem.ToString
    		' amend these values if your
    		' setup is different
    		With SP
    			.PortName = SPName
    			.BaudRate = 9600
    			.Parity = Parity.None
    			.StopBits = StopBits.One
    			.DataBits = 8
    			.Handshake = Handshake.None
    			.ReadTimeout = 1000
    			.RtsEnable = True
    		End With
    		TextBox1.Text = ReceiveSerialData(SP)
    	End Sub
    	Function ReceiveSerialData(port As SerialPort) As String
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-receive-strings-from-serial-ports
    		' Receive strings from a serial port.
    		Dim returnStr As String = ""
    		Try
    			port.Open()
    			Do
    				Dim Incoming As String = port.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."
    		Catch ex2 As IO.IOException
    			returnStr = "ERROR: " & ex2.Message
    		Finally
    			port.Close()
    		End Try
    		Return returnStr
    	End Function
    	Sub GetSerialPortNames()
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-show-available-serial-ports
    		' Show all available COM ports.
    		For Each sp As String In My.Computer.Ports.SerialPortNames
    			ListBox1.Items.Add(sp)
    		Next
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Monday, September 16, 2019 3:55 PM
  • HI Les.

    Still the same.

    Regards

    Charles

    Monday, September 16, 2019 5:05 PM
  • Hi

    Do you have any information of the serial transmission settings from your external device?

    I believe the settings I posted in the last post were the defaults and may need to be adjusted to suit your device transmission.


    Regards Les, Livingston, Scotland

    Monday, September 16, 2019 5:44 PM
  • Hi Les,

    I did change the Baud rate as it runs at 19200,

    the rest was correct as is. I get the feeling that the Arduino has to do something else to send the data

    to VS, But I do not know what, I am currently using the same sketch that I use to communicate with the actual Victron VE Direct software, so theoretically it should work as is because the Victron software can read and communicate with the device as is....

    I'm bugging out again in a bit to go to bed as I have an early start again tomorrow.

    Once again, thank you for your help..

    Regards

    Charles

    Monday, September 16, 2019 5:56 PM
  • @Les: Please forgive the intrusion, but it looks like the MS example reads lines of characters from the serial port into a String variable, and does so until the serial port stops sending, at which point the string is displayed in a TextBox.

    I get the impression that Charles' setup never stops sending data, so nothing will ever be displayed and the UI will always be non-responsive.

    Could be wrong, of course :-)

    Monday, September 16, 2019 6:09 PM
  • Hi

    Your external device may use either Print() or Write() to output on the serial port. From the description you gave, it must be using Print() as your expected incoming is a String.

    See Write()

    See Print()

    If it is using Write, then the whole code needs to be changed to accomodate incoming Byte stream.

    *

    Also, you can add this line to see if the loop is waiting or not - add the highlighted line only.

    	Function ReceiveSerialData(port As SerialPort) As String
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-receive-strings-from-serial-ports
    		' Receive strings from a serial port.
    		Dim returnStr As String = ""
    		Try
    			port.Open()
    			Do
    				Dim Incoming As String = port.ReadLine()
    				TextBox1.AppendText(Incoming & vbCrLf)
    				If Incoming Is Nothing Then
    					Exit Do
    				Else


    Regards Les, Livingston, Scotland


    • Edited by leshay Monday, September 16, 2019 6:14 PM
    Monday, September 16, 2019 6:12 PM
  • HI Les,

    At work again.

    Sorry I think I did not make it clear in my laymen s terms please do forgive me.

    Yes, the device is CONSTANTLY sending the data it does this once a second to "refresh"

    the data, the checksum line at the end signals the end of the data transmission and the PID line is the start, but yes as SPC said it does not stop it is constantly sending this data.

    I do not know if this changes anything, please let me know.

    Just to recap. 

    the baud rate is 19200

    the stop bits etc are all standard.

    I would like to be able to display the second row of changing data into certain text boxes that I have allocated on my form, I will post in the code for the Arduino's serial if that will be of any help.

    Regards Charles

    #include <SoftwareSerial.h>
     
    SoftwareSerial Switch(3, 5);
    
    void setup() {
      // initialize both serial ports:
      Serial.begin(19200);
      Switch.begin(19200); // RX 3 TX 5
    }
    
    void loop() {
      // read from port 1, send to port 0:
      if (Switch.available()) {
        int inByte = Switch.read();
        Serial.write(inByte);
      }
    
      // read from port 0, send to port 1:
      if (Serial.available()) {
        int inByte = Serial.read();
       Switch.write(inByte);
      }
    }


    Tuesday, September 17, 2019 6:07 AM
  • Hi

    Seems your incoming data is from a Write() method on Arduno, The code we are trying is expecting strings. Please try this new version which is now expecting Integer data. There is an additional Label1 - this is an attempt to visually see any action from the port and is not of any importance to the code. Just overwrite the code you have with this and lets see if anything happens.

    Option Strict On
    Option Explicit On
    ' Form1 with ListBox1, TextBox1
    ' Label1 and Button1
    Imports System.IO.Ports
    Public Class Form1
    	Dim SP As New SerialPort
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' this codejust toset up UI
    		With ListBox1
    			.Location = New Point(4, 4)
    			.Size = New Size(70, ClientSize.Height - 44)
    			.IntegralHeight = False
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left
    			.Font = New Font("Arial", 12)
    		End With
    		With TextBox1
    			.Multiline = True
    			.Location = New Point(ListBox1.Right + 4, 4)
    			.Size = New Size(ClientSize.Width - ListBox1.Width - 12, ClientSize.Height - 44)
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Right
    			.Font = New Font("Arial", 12)
    		End With
    		With Button1
    			.Location = New Point(4, ListBox1.Bottom + 4)
    			.Text = "READ"
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
    		End With
    		With Label1
    			.Location = New Point(Button1.Right + 12, ListBox1.Bottom + 7)
    			.Font = New Font("Arial", 12)
    		End With
    		GetSerialPortNames()
    
    		'ListBox1.Items.Add("COM1")
    		'ListBox1.Items.Add("COM2")
    		'ListBox1.Items.Add("COM3")
    		'ListBox1.Items.Add("COM4")
    		ListBox1.SelectedIndex = 0
    	End Sub
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Dim SPName As String = ListBox1.SelectedItem.ToString
    		' amend these values if your
    		' setup is different
    		With SP
    			.PortName = SPName
    			.BaudRate = 9600
    			.Parity = Parity.None
    			.StopBits = StopBits.One
    			.DataBits = 8
    			.Handshake = Handshake.None
    			.ReadTimeout = 1000
    			.RtsEnable = True
    		End With
    		TextBox1.Text = ReceiveSerialData(SP)
    	End Sub
    	Function ReceiveSerialData(port As SerialPort) As String
    		' Receive Bytes from a serial port.
    		Dim returnStr As String = ""
    		Try
    			port.Open()
    			Do
    				Dim Incoming As Integer = port.ReadByte()
    				Label1.Text = Incoming.ToString
    				If Incoming < 0 Then
    					Exit Do
    				Else
    					returnStr &= Chr(Incoming)
    				End If
    			Loop
    		Catch ex As TimeoutException
    			returnStr = "Error: Serial Port read timed out."
    		Catch ex2 As IO.IOException
    			returnStr = "ERROR: " & ex2.Message
    		Finally
    			port.Close()
    		End Try
    		Return returnStr
    	End Function
    	Sub GetSerialPortNames()
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-show-available-serial-ports
    		' Show all available COM ports.
    		For Each sp As String In My.Computer.Ports.SerialPortNames
    			ListBox1.Items.Add(sp)
    		Next
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Tuesday, September 17, 2019 9:51 AM
  • Hi Les,

    Thank you for all your help, it is appreciated.

    As soon as I am home I'll try it and let you know, if there is any more data you require please let me know.

    Once again thank you.

    regards

    Charles

    Tuesday, September 17, 2019 10:09 AM
  • HI Les.

    I'm now getting an Exception Unhandlled Error.

    Which reads as Follows

    "

    System.NullReferenceException: 'Object reference not set to an instance of an object.'

    System.Windows.Forms.ListBox.SelectedItem.get returned Nothing."

    It is on the code beneath when I click the read button, I am sorry but I still can't post pictures due to my email not being confirmed, I do not understand what is going on as I am signed in and I did click the validation link, so I do not know what is going on. I screen shot the error and will put a link in for ibb so that you can view it yourself, and then the form design window as well.

    https://ibb.co/Ydz2Mnc
    https://ibb.co/4YTjMfH

    Regards

    Charles

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim SPName As String = ListBox1.SelectedItem.ToString ' amend these values if your ' setup is different With SP .PortName = SPName .BaudRate = 19200

    .Parity = Parity.None .StopBits = StopBits.One .DataBits = 8 .Handshake = Handshake.None .ReadTimeout = 1000 .RtsEnable = True End With TextBox1.Text = ReceiveSerialData(SP) End Sub









    Tuesday, September 17, 2019 3:10 PM
  • Hi

    Strange one. You did get the list of COM ports previous runs - didn't you?

    If you are using one port only (say COM1) then we can get rid of all the port selection code.

    In the meantime, try an overwrite with the following: (changes emboldened)

    Option Strict On
    Option Explicit On
    ' Form1 with ListBox1, TextBox1
    ' Label1 and Button1
    Imports System.IO.Ports
    Public Class Form1
    	Dim SP As New SerialPort
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' this codejust toset up UI
    		With ListBox1
    			.Location = New Point(4, 4)
    			.Size = New Size(70, ClientSize.Height - 44)
    			.IntegralHeight = False
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left
    			.Font = New Font("Arial", 12)
    		End With
    		With TextBox1
    			.Multiline = True
    			.Location = New Point(ListBox1.Right + 4, 4)
    			.Size = New Size(ClientSize.Width - ListBox1.Width - 12, ClientSize.Height - 44)
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Top Or AnchorStyles.Left Or AnchorStyles.Right
    			.Font = New Font("Arial", 12)
    		End With
    		With Button1
    			.Location = New Point(4, ListBox1.Bottom + 4)
    			.Text = "READ"
    			.Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
    		End With
    		With Label1
    			.Location = New Point(Button1.Right + 12, ListBox1.Bottom + 7)
    			.Font = New Font("Arial", 12)
    		End With
    
    		' these are just for me
    		'ListBox1.Items.Add("COM1")
    		'ListBox1.Items.Add("COM2")
    		'ListBox1.Items.Add("COM3")
    		'ListBox1.Items.Add("COM4")
    
    		GetSerialPortNames()
    
    		If ListBox1.Items.Count > 0 Then
    			ListBox1.SelectedIndex = 0
    		Else
    			MessageBox.Show("Can't find any COM ports")
    			End
    		End If
    	End Sub
    	Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    		Dim SPName As String = ListBox1.SelectedItem.ToString
    		' amend these values if your
    		' setup is different
    		With SP
    			.PortName = SPName
    			.BaudRate = 9600
    			.Parity = Parity.None
    			.StopBits = StopBits.One
    			.DataBits = 8
    			.Handshake = Handshake.None
    			.ReadTimeout = 1000
    			.RtsEnable = True
    		End With
    		TextBox1.Text = ReceiveSerialData(SP)
    	End Sub
    	Function ReceiveSerialData(port As SerialPort) As String
    		' Receive Bytes from a serial port.
    		Dim returnStr As String = ""
    		Try
    			port.Open()
    			Do
    				Dim Incoming As Integer = port.ReadByte()
    				Label1.Text = Incoming.ToString
    				If Incoming < 0 Then
    					Exit Do
    				Else
    					returnStr &= Chr(Incoming)
    				End If
    			Loop
    		Catch ex As TimeoutException
    			returnStr = "Error: Serial Port read timed out."
    		Catch ex2 As IO.IOException
    			returnStr = "ERROR: " & ex2.Message
    		Finally
    			port.Close()
    		End Try
    		Return returnStr
    	End Function
    	Sub GetSerialPortNames()
    		' https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-show-available-serial-ports
    		' Show all available COM ports.
    		For Each sp As String In My.Computer.Ports.SerialPortNames
    			ListBox1.Items.Add(sp)
    		Next
    	End Sub
    End Class


    Regards Les, Livingston, Scotland


    • Edited by leshay Tuesday, September 17, 2019 5:47 PM
    Tuesday, September 17, 2019 5:47 PM
  • Hi

    Without reading in depth, a few web sites  seem to suggest a 'hanshake' needs to be established between Arduino and PC to allow connection, and some other references - can you confirm that other Serial comms have/do work between Arduino and a PC with the settings you have?


    Regards Les, Livingston, Scotland


    • Edited by leshay Tuesday, September 17, 2019 9:59 PM
    Tuesday, September 17, 2019 8:37 PM
  • Good morning Les.

    I can confirm that the Arduino does in fact work with the exact same sketch on my laptop that also has the Arduino IDE and the Victron connect app on it.

    I am through Visual Studios serial monitor, able to see the serial port working when I connect to the Arduino , I can see the data printed in the serial monitor from the Arduino containing the MPPT Data.

    So I can confirm that it is all working, I am sorry but am very illiterate when it comes to programming.

    If the serial monitor does a hand shake with the Arduino then I suppose that I will have to find out how to do that. 

    What I have noticed is the following, the Arduino has a tx/rx set of leds on it, when I plug it into the USB port both leds come on, only when I connect through the app or serial monitor does the TX led start to flash as it is transmitting the data from the MPPT to either the app or the serial monitor.

    The rest of the time even when connecting through the VS code and UI it just remains on. so no transmission then is what I would presume.

    The UI that you programmed is picking up the correct com port so there is no problem with that part of the programming, the correct port is being seen by the Ui.

    Regards

    Charles


    Wednesday, September 18, 2019 5:44 AM
  • Hi

    OK, then I am at a loss on how to progress any further.

    *

    Did that last code change I posted cure the trouble with the exception you saw?

    *

    I will continue for the moment in searching for further information but doubt that I will find any final solution to overcome the fact that I am unable to test any code this end.


    Regards Les, Livingston, Scotland

    Wednesday, September 18, 2019 11:39 AM
  • Hi Les. 

    I will test the code that you sent last when I'm home this evening, I had a prior engagement last night that I had to attend to so could not test it.

    I'll revert back as soon as I have tested it.

    Thanks for your help.

    Regards 

    Charles

    Wednesday, September 18, 2019 12:11 PM
  • Hi

    After a lot of reading, and not 100% sure of this, I believe that the Arduino Uno cannot be read from a serial port in the normal way, instead, needs a driver on the PC which will then expose a Arduino port for use on the PC. As well as that, it would seem there is software that when installed on a PC allows easy access to the Arduino for sending 'sketches' to it (I have no interest in learning what such sketches are - I think they are just another way of saying 'some code')

    Anyway, I think we are at a dead end - unless the latest version of the code does spring into life and displays something/anything.


    Regards Les, Livingston, Scotland

    Wednesday, September 18, 2019 2:57 PM
  • Hi Les.

    I also did a bit of research and happened upon a guy named Martyn Curry.

    He wrote the following code which works.

    'Simple example of receiving serial data
    'written in Visual Basic 2013
    '
    
    Imports System
    Imports System.IO.Ports
    
    Public Class Form1
        Dim comPORT As String
        Dim receivedData As String = ""
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Timer1.Enabled = False
            comPORT = ""
            For Each sp As String In My.Computer.Ports.SerialPortNames
                comPort_ComboBox.Items.Add(sp)
            Next
        End Sub
    
    
        Private Sub comPort_ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles comPort_ComboBox.SelectedIndexChanged
            If (comPort_ComboBox.SelectedItem <> "") Then
                comPORT = comPort_ComboBox.SelectedItem
            End If
        End Sub
    
    
        Private Sub connect_BTN_Click(sender As Object, e As EventArgs) Handles connect_BTN.Click
            If (connect_BTN.Text = "Connect") Then
                If (comPORT <> "") Then
                    SerialPort1.Close()
                    SerialPort1.PortName = comPORT
                    SerialPort1.BaudRate = 19200
                    SerialPort1.DataBits = 8
                    SerialPort1.Parity = Parity.None
                    SerialPort1.StopBits = StopBits.One
                    SerialPort1.Handshake = Handshake.None
                    SerialPort1.Encoding = System.Text.Encoding.Default
                    SerialPort1.ReadTimeout = 10000
    
                    SerialPort1.Open()
                    connect_BTN.Text = "Dis-connect"
                    Timer1.Enabled = True
                    Timer_LBL.Text = "Timer: ON"
                Else
                    MsgBox("Select a COM port first")
                End If
            Else
                SerialPort1.Close()
                connect_BTN.Text = "Connect"
                Timer1.Enabled = False
                Timer_LBL.Text = "Timer: OFF"
            End If
    
    
        End Sub
    
    
        Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
            receivedData = ReceiveSerialData()
            RichTextBox1.Text &= receivedData
        End Sub
    
    
        Function ReceiveSerialData() As String
            Dim Incoming As String
            Try
                Incoming = SerialPort1.ReadExisting()
                If Incoming Is Nothing Then
                    Return "nothing" & vbCrLf
                Else
                    Return Incoming
                End If
            Catch ex As TimeoutException
                Return "Error: Serial Port read timed out."
            End Try
    
        End Function
    
    
        Private Sub clear_BTN_Click(sender As Object, e As EventArgs) Handles clear_BTN.Click
            RichTextBox1.Text = ""
        End Sub
    
    
    End Class


    I've run it and it works, as I said, when you install the Arduino IDE the Driver is automatically installed, now I have amended some of the code to my project and now I have the readings coming into a textbox, but I now need to separate the different lines into the pre-defined text boxes for each line, I now need help to do this, and to then have it refresh the text boxes when it reads again so that they can be updated.

    Below is what I am getting in the text box now, I need the second row to be entered into their own dedicated text box on the form.

    PID	                 0xA04B
    FW	                 142
    SER#	         HQ154037ESU
    V	                 54410
    I	                 2200
    VPV	                 99950
    PPV	                 123
    CS	                 5
    MPPT	         1
    ERR	                 0
    LOAD	         ON
    H19	                456723
    H20          	485
    H21	                1309
    H22	                329
    H23	                1228
    HSDS	        315
    Checksum	Û

    Regards

    Charles


    Wednesday, September 18, 2019 3:50 PM
  • Hi Les.

    I also did a bit of research and happened upon a guy named Martyn Curry.

    He wrote the following code which works.


    I've run it and it works, as I said, when you install the Arduino IDE the Driver is automatically installed, now I have amended some of the code to my project and now I have the readings coming into a textbox, but I now need to separate the different lines into the pre-defined text boxes for each line, I now need help to do this, and to then have it refresh the text boxes when it reads again so that they can be updated.

    Below is what I am getting in the text box now, I need the second row to be entered into their own dedicated text box on the form.

    Hi

    Glad you found a solution, sorry I couldn't.

    Here is some code that will display (any) of the lines Title and Value in 2 TextBoxes. This example uses only TextBox2 and TextBox2 (RichTextBoix1 has the Incoming data), but any pair of values can be sent to any pair of TextBoxes (or Labels) if required. Here, I only deal with the two items you mentioned.

    The Sub SetText will search the Incoming RichTextBoix1 for the Title supplied and will put the Title and Value to the 2 TextBoxes.

    The callto the Sub SetText can be added to the code where the data is refreshed (Timer Tick) so that each time the data is collected, then the TextBox values will be updated.

    The actual data does bot need to be displayed as I have in RichTextBoix1 , but,the code I post below needs a multiloine RichTextBoix1 to be loaded with the incoming data each time. Such a TextBox need not be displayed if not needed though.

    BTW: this RichTextBoix1 is the 'Container' I asked about in the very early posts.

    This code is just an example and can easily be altered  to suit your needs.

    Option Strict On
    Option Explicit On
    Public Class Form1
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		RichTextBox1.Text =
    "PID	                 0xA04B
    FW	                 142
    SER#	         HQ154037ESU
    V	                 54410
    I	                 2200
    VPV	                 99950
    PPV	                 123
    CS	                 5
    MPPT	         1
    ERR	                 0
    LOAD	         ON
    H19	                456723
    H20          	485
    H21	                1309
    H22	                329
    H23	                1228
    HSDS	        315
    Checksum	Û"
    
    		SetText("FW")
    
    	End Sub
    	Sub SetText(Needed As String)
    		For Each line As String In RichTextBox1.Lines
    			If line.StartsWith(Needed) Then
    				Dim s() As String = line.Split(New String() {" ", vbTab}, StringSplitOptions.RemoveEmptyEntries)
    				TextBox2.Text = s(0)
    				TextBox3.Text = s(1)
    			End If
    		Next
    	End Sub
    End Class
    



    Regards Les, Livingston, Scotland




    • Edited by leshay Wednesday, September 18, 2019 4:45 PM
    Wednesday, September 18, 2019 4:32 PM
  • HI Les,

    Wow, thanks I'll Look into this and then let you know how I come on with it.

    Ah! Ok now I understand the container bit thank you for that, another bit I can stick into the grey matter.

    Regards

    Charles

    Wednesday, September 18, 2019 4:55 PM
  • Good Morning Les.

    I would like to ask if it is at all possible to break the code down for me,

    I do not understand what is happening in the code and I think that I am messing something up

    as I am getting errors, Would it be possible for you to use the information that I have given in an example of the code, while explaining what each part should do, I think that I am messing something up in the workings of the code.

    As I said I am a complete noob.

    Thank you for all your time and effort thus far. 

    Regards

    Charles

    Thursday, September 19, 2019 5:45 AM
  • Hi

    Don't worry, we will get there eventually.

    Basically,  you need to:

    A)  Set up the parameters for the SerialPort

    B)  Have a function that collects the data from Arduino

    C)  Have a routine to search and display the desired fields.


    In the code below, I do not do A) above, have a Sub for B) which uses test data but has directions for you to substitute with a call to ypur own ReceiveSerialData(). There is a Timer Tick event handler which calls for fresh data each cycle.

    NOTE: for debugging, I have added a Label1 which is there just to show the Timer cycles and can/should be removed in the real code (the Label1 removed from UI and code removed as shown in comments)

    ' Form1 with TextBox1, TextBox1
    ' Timer1 and Label1
    Option Strict On
    Option Explicit On
    Public Class Form1
    	' this RichTextBox1 is NOT displayed
    	' and is only used as a 'Container'
    	Dim RichTextBox1 As New TextBox
    	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    		' you would have a call to set up the
    		' serial port
    
    
    		' set up the Timer1
    		With Timer1
    			' set milliseconds for calls
    			' to Tick event handler
    			.Interval = 2000
    
    			' enable the Timer1
    			.Enabled = True
    		End With
    	End Sub
    	Function GetData() As String
    		' ========== REMOVE ==========
    		' fill container with example of
    		' Incoming strings so you do not
    		' need this bit of code.
    		' In your code, add the Incoming to
    		' this TextBox (clear it first using
    		' TextBox1.Clear
    
    		Dim s As String =
    "PID	                 0xA04B
    FW	                 142
    SER#	         HQ154037ESU
    V	                 54410
    I	                 2200
    VPV	                 99950
    PPV	                 123
    CS	                 5
    MPPT	         1
    ERR	                 0
    LOAD	         ON
    H19	                456723
    H20          	485
    H21	                1309
    H22	                329
    H23	                1228
    HSDS	        315
    Checksum	Û"
    		' this is ONLY for test - you should
    		' remove everything berween and including
    		' the =============== lines
    		Return s
    		' ========== REMOVE ==========
    
    
    		' this is for YOU only - uncomment
    
    		' ========= UNCOMMENT ========
    		'		Return ReceiveSerialData()
    	End Function
    	Sub SetText(Needed As String)
    		' get fresh data into RichTextBox1
    		RichTextBox1.Text = GetData()
    
    		' search and display desired fields
    
    		' cycle through the RichTextBox text
    		' lines
    		For Each line As String In RichTextBox1.Lines
    
    			' if the line starts with the name
    			' of the desired filed then
    			' use it
    			If line.StartsWith(Needed) Then
    
    				' split the given line into parts
    				' based on delimeters SPACE and/or
    				' TAB, discarding any empty entries
    				Dim s() As String = line.Split(New String() {" ", vbTab}, StringSplitOptions.RemoveEmptyEntries)
    
    				' assign part 1 of the split to
    				' TextBox1
    				TextBox1.Text = s(0)
    				' assign part 2 of the split to
    				' TextBox1
    				TextBox2.Text = s(1)
    			End If
    		Next
    	End Sub
    	Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    		' get the desired fields from the
    		' data and display in TextBoxes
    		SetText("FW")
    
    
    		' these next lines are just to show
    		' the Timer cycling and can be removed
    		' as well as the actual Label1
    		Static c As Integer = 0
    		c += 1
    		Label1.Text = c.ToString
    	End Sub
    End Class


    Regards Les, Livingston, Scotland

    Thursday, September 19, 2019 12:24 PM