Results 1 to 8 of 8

Thread: VB2013 GUI Form build

  1. #1

    Thread Starter
    New Member
    Join Date
    Dec 2023
    Posts
    11

    VB2013 GUI Form build

    Can someone help please?

    I have been building a GUI to connect up to Arduino Mega Mini Pro board to run CNC GRBL. where, I am only utilising the GRBL to run B & C rotational axis (yes, the GRBL is 5 axis library). So, the GRBL compiles and loads up onto the Mega Mini Pro, just fine.

    The GUI is all good (I think) with its own little connection form that allows me to choose port and baud rate and connect.

    I load up the relevant G-Code and before I can press the run button, the GRBL seems to be receiving the instruction as soon as I load it up on the text display. also the highlight, meant to move one line at the time, but that isn't whats happening!

    Also, the Realtime display for the B & C aren't displaying anything at all! all though I can see on the output window of the VB2013, that GUI is talking to GRBL and GRBL is talking back as well as the display data is updated and sent back by GRBL, yet not displayed on the GUI!

    Also the buttons for +B,-B,+C,-C aren't working well either. meaning, there are intermittent responds from them, even though I've added delays for time to respond!

    not sure what I can do to make this GUI work.

    Can you help please?

    I am attaching the code here for both main form and the connection sub form, I am posting the image of the GUI here.

    for the moment, I am not attempting anything with MPG.

    Main GUI:

    Name:  GUI face for VB forum.JPG
Views: 199
Size:  35.6 KB


    Code:
    Imports System.IO.Ports
    Imports System.IO
    Imports System.Windows.Forms
    
    Public Class CNC4thand5thAxisControlGUI
        Private WithEvents serialPort As New SerialPort()
        Private gCodeLines As List(Of String)
        Private currentLineIndex As Integer = 0
        Private isPaused As Boolean = False
        Private bPosition As Double = 0.0
        Private cPosition As Double = 0.0
        Private incomingDataBuffer As String = String.Empty
        Private isExecutionComplete As Boolean = False
        Private isGRBLReady As Boolean = True ' Indicates if GRBL is ready for next command
        Private WithEvents tmrPosition As New Timer() ' Timer for position updates
    
        ' Initialize and start the timer for real-time position updates
        Private Sub tmrPosition_Tick(sender As Object, e As EventArgs) Handles tmrPosition.Tick
            If serialPort.IsOpen Then
                serialPort.WriteLine("?") ' Send status request to GRBL
            End If
        End Sub
    
        ' Form Load event
        Private Sub CNC4thand5thAxisControlGUI_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            gCodeLines = New List(Of String)
            serialPort.BaudRate = 115200
            serialPort.DataBits = 8
            serialPort.Parity = Parity.None
            serialPort.StopBits = StopBits.One
            serialPort.Handshake = Handshake.None
    
            ' Timer setup
            tmrPosition.Interval = 500 ' Poll every 500ms
            tmrPosition.Start() ' Start the timer to poll GRBL for position updates
        End Sub
    
        ' Clear Code Button
        Private Sub btnClearCode_Click(sender As Object, e As EventArgs) Handles btnClearCode.Click
            txtGCode.Clear()
            gCodeLines.Clear()
            currentLineIndex = 0
            isExecutionComplete = False
        End Sub
    
        ' Load G-Code
        Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
            Dim openFileDialog As New OpenFileDialog
            openFileDialog.Filter = "G-Code Files (*.txt)|*.txt|All Files (*.*)|*.*"
            If openFileDialog.ShowDialog() = DialogResult.OK Then
                gCodeLines = File.ReadAllLines(openFileDialog.FileName).ToList()
                txtGCode.Text = String.Join(Environment.NewLine, gCodeLines)
                Console.WriteLine("G-code loaded. Total lines: " & gCodeLines.Count.ToString())
            End If
        End Sub
    
        ' Run G-Code
        Private Sub btnRun_Click(sender As Object, e As EventArgs) Handles btnRun.Click
            If serialPort.IsOpen Then
                If gCodeLines.Count = 0 Then
                    MessageBox.Show("No G-code loaded. Please load a G-code file.")
                    Return
                End If
                isPaused = False
                currentLineIndex = 0
                isExecutionComplete = False
                SendNextGCodeLine()
            Else
                MessageBox.Show("Serial port is not open. Please connect to the Arduino.")
            End If
        End Sub
    
        ' Send the next line of G-Code
        Private Sub SendNextGCodeLine()
            If currentLineIndex < gCodeLines.Count AndAlso Not isPaused Then
                Dim line As String = gCodeLines(currentLineIndex).Trim()
                If Not String.IsNullOrEmpty(line) Then
                    ' Send the line to GRBL
                    serialPort.WriteLine(line & vbLf)
    
                    ' Log the sent line in the output console
                    Console.WriteLine("Sending G-code line " & (currentLineIndex + 1) & ": " & line)
    
                    ' Highlight the line being sent
                    HighlightCurrentLine(currentLineIndex)
                End If
            ElseIf currentLineIndex >= gCodeLines.Count Then
                isExecutionComplete = True ' Mark execution as complete
                Console.WriteLine("No more G-code lines to send.")
            End If
        End Sub
    
        ' Highlight G-Code Line
        Private Sub HighlightCurrentLine(lineIndex As Integer)
            If lineIndex >= 0 AndAlso lineIndex < txtGCode.Lines.Length Then
                txtGCode.Select(0, txtGCode.TextLength)
                txtGCode.SelectionBackColor = Color.White
                Dim start As Integer = txtGCode.GetFirstCharIndexFromLine(lineIndex)
                Dim length As Integer = txtGCode.Lines(lineIndex).Length
                txtGCode.Select(start, length)
                txtGCode.SelectionBackColor = Color.Cyan
                txtGCode.ScrollToCaret()
            End If
        End Sub
    
        ' Connect to Serial Port
        Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
            Dim connectForm As New ConnectForm
            If connectForm.ShowDialog() = DialogResult.OK Then
                serialPort.PortName = connectForm.SelectedPort
                serialPort.BaudRate = connectForm.SelectedBaudRate
                Try
                    serialPort.Open()
                    MessageBox.Show("Connected to " & connectForm.SelectedPort & " at " & connectForm.SelectedBaudRate & " baud rate.")
                Catch ex As Exception
                    MessageBox.Show("Error opening serial port: " & ex.Message)
                End Try
            End If
        End Sub
    
        ' Disconnect Serial Port
        Private Sub btnDisconnect_Click(sender As Object, e As EventArgs) Handles btnDisconnect.Click
            If serialPort.IsOpen Then
                serialPort.Close()
                MessageBox.Show("Serial port disconnected.")
            End If
        End Sub
    
        ' Handle response from GRBL and send the next G-code line
        Private Sub serialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
            Try
                incomingDataBuffer &= serialPort.ReadExisting()
    
                If incomingDataBuffer.Contains(vbLf) Then
                    Dim lines As String() = incomingDataBuffer.Split({vbLf}, StringSplitOptions.RemoveEmptyEntries)
    
                    For Each response As String In lines
                        Me.Invoke(Sub() Console.WriteLine("GRBL Response: " & response))
    
                        ' If 'ok' is received, move to the next line or unlock jogging
                        If response.Contains("ok") Then
                            Me.Invoke(Sub()
                                          isGRBLReady = True ' Ready for the next jog or G-code command
                                          IncrementLineAndSend() ' Send the next line if in G-code run
                                      End Sub)
                        End If
    
                        ' Handle GRBL status responses (for position updates)
                        If response.StartsWith("<") Then
                            Me.Invoke(Sub() ParsePosition(response)) ' Parse position feedback from GRBL
                        End If
                    Next
    
                    ' Clear the buffer after processing the data
                    incomingDataBuffer = String.Empty
                End If
            Catch ex As Exception
                Me.Invoke(Sub() MessageBox.Show("Error reading from serial port: " & ex.Message))
            End Try
        End Sub
    
        ' Increment the current line index and send the next G-code line
        Private Sub IncrementLineAndSend()
            If currentLineIndex < gCodeLines.Count - 1 Then
                currentLineIndex += 1 ' Move to the next line
                SendNextGCodeLine() ' Send the next line
            Else
                isExecutionComplete = True ' No more lines to send
                Console.WriteLine("All G-code lines have been sent.")
            End If
        End Sub
    
        ' Parse GRBL Position
        Private Sub ParsePosition(response As String)
            Try
                ' Log the full GRBL response for debugging purposes
                Console.WriteLine("Parsing GRBL Position: " & response)
    
                Dim parts As String() = response.Split("|"c)
                For Each part As String In parts
                    If part.StartsWith("B:") Then
                        bPosition = Convert.ToDouble(part.Replace("B:", "").Trim())
                        Console.WriteLine("Parsed B Position: " & bPosition)
                    ElseIf part.StartsWith("C:") Then
                        cPosition = Convert.ToDouble(part.Replace("C:", "").Trim())
                        Console.WriteLine("Parsed C Position: " & cPosition)
                    End If
                Next
    
                ' Update the labels with real-time positions
                Me.Invoke(Sub()
                              lblBPosition.Text = "B Pos: " & bPosition.ToString("F3")
                              lblCPosition.Text = "C Pos: " & cPosition.ToString("F3")
                          End Sub)
    
            Catch ex As Exception
                ' Log the error to identify parsing issues
                Console.WriteLine("Error parsing GRBL position data: " & ex.Message)
            End Try
        End Sub
    
        ' Manual Jogging for B and C axes with GRBL readiness check
        Private Sub btnJogBPositive_Click(sender As Object, e As EventArgs) Handles btnJogBPositive.Click
            If serialPort.IsOpen AndAlso isGRBLReady Then
                serialPort.WriteLine("G91 G0 B10" & vbLf) ' Move B+10 degrees relative
                Console.WriteLine("Jogging B+10 degrees.")
                isGRBLReady = False ' Wait for "ok" before allowing next command
            End If
        End Sub
    
        Private Sub btnJogBNegative_Click(sender As Object, e As EventArgs) Handles btnJogBNegative.Click
            If serialPort.IsOpen AndAlso isGRBLReady Then
                serialPort.WriteLine("G91 G0 B-10" & vbLf) ' Move B-10 degrees relative
                Console.WriteLine("Jogging B-10 degrees.")
                isGRBLReady = False
            End If
        End Sub
    
        Private Sub btnJogCPositive_Click(sender As Object, e As EventArgs) Handles btnJogCPositive.Click
            If serialPort.IsOpen AndAlso isGRBLReady Then
                serialPort.WriteLine("G91 G0 C10" & vbLf) ' Move C+10 degrees relative
                Console.WriteLine("Jogging C+10 degrees.")
                isGRBLReady = False
            End If
        End Sub
    
        Private Sub btnJogCNegative_Click(sender As Object, e As EventArgs) Handles btnJogCNegative.Click
            If serialPort.IsOpen AndAlso isGRBLReady Then
                serialPort.WriteLine("G91 G0 C-10" & vbLf) ' Move C-10 degrees relative
                Console.WriteLine("Jogging C-10 degrees.")
                isGRBLReady = False
            End If
        End Sub
    
        ' Close Serial Port
        Private Sub CNC4thand5thAxisControlGUI_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
            If serialPort.IsOpen Then serialPort.Close()
        End Sub
    End Class
    
    
    
    Connection sub form:
    
    Imports System.IO.Ports
    
    Public Class ConnectForm
        Public Property SelectedPort As String
        Public Property SelectedBaudRate As Integer
    
        Private Sub ConnectForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ' Populate available COM ports
            cmbPort.Items.AddRange(SerialPort.GetPortNames())
    
            ' Populate Baud rate options
            cmbBaudRate.Items.Add("9600")
            cmbBaudRate.Items.Add("115200") ' Standard for GRBL
            cmbBaudRate.Items.Add("250000")
        End Sub
    
        ' OK button handler
        Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
            ' Set selected port and baud rate
            If cmbPort.SelectedItem IsNot Nothing AndAlso cmbBaudRate.SelectedItem IsNot Nothing Then
                SelectedPort = cmbPort.SelectedItem.ToString()
                SelectedBaudRate = Convert.ToInt32(cmbBaudRate.SelectedItem.ToString())
                Me.DialogResult = DialogResult.OK
                Me.Close()
            Else
                MessageBox.Show("Please select both a COM port and Baud rate.")
            End If
        End Sub
    
        ' Cancel button handler
        Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
            Me.DialogResult = DialogResult.Cancel
            Me.Close()
        End Sub
    End Class

    Name:  GUI connection face for VB forum.JPG
Views: 183
Size:  6.7 KB
    Last edited by VisKataboman2; Oct 5th, 2024 at 09:48 AM.

  2. #2

    Thread Starter
    New Member
    Join Date
    Dec 2023
    Posts
    11

    Re: VB2013 GUI Form build

    There are many people looking at my post,but no-one has replied yet!

    Can someone diagnose and tell me what I am doing wrong?

  3. #3

    Thread Starter
    New Member
    Join Date
    Dec 2023
    Posts
    11

    Re: VB2013 GUI Form build

    No one??!! Really????
    Everyone just looking but not responding!!!, it's ridiculous. I thought this is where the experts comes to help!!!.
    I really need to know what I am doing wrong with VB.net coding on VB2013 (VS2013).
    The G code instructions are seems to be sent line by line (atleat on the output window its visible that way), however, just hoping over, atleat that's how it looks on the text editor on the GUI, the highlights just jumps.

    And there is absolutely no display of the axis locations in real time or otherwise. I can see on the output window that the information is sent back from the board, however, it's not displayed on GUI!!
    Surely, some experts here who have done something like this before who can shed some light!!!

  4. #4
    PowerPoster yereverluvinuncleber's Avatar
    Join Date
    Feb 2014
    Location
    Norfolk UK (inbred)
    Posts
    2,621

    Re: VB2013 GUI Form build

    You haven't done enough digging of your own yet. You have to debug and come up with a solid technical error for users here to assist you with. At the moment you have a non-working program that could be broken in any way and you want help with it. It isn't the sort of problem people will help you with.

    You: "Doctor, doctor, I'm ill!"
    Doc: "What is it, what is wrong with you?"
    You: "I don't know, I just thought you'd fix it."

    Do some digging, Try to figure out what is really wrong with breakpoints &c and then when you have a real concrete issue that you can describe in detail, then come back and do so here.

    Remember we aren't free coders here, we are here to help when the person shows the correct approach and needs a little help.

    Note: you provide no information about the environment and you did not attach your project.

    Finally, very few will be working with 2013 and attempting to talk to an Arduino. Now, you have reduced the pool of people who want to help you even further by complaining!
    https://github.com/yereverluvinunclebert

    Skillset: VMS,DOS,Windows Sysadmin from 1985, fault-tolerance, VaxCluster, Alpha,Sparc. DCL,QB,VBDOS- VB6,.NET, PHP,NODE.JS, Graphic Design, Project Manager, CMS, Quad Electronics. classic cars & m'bikes. Artist in water & oils. Historian.

    By the power invested in me, all the threads I start are battle free zones - no arguing about the benefits of VB6 over .NET here please. Happiness must reign.

  5. #5
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,827

    Re: VB2013 GUI Form build

    The way the DataReceived is handling data you might be dropping some amount of characters.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  6. #6

    Thread Starter
    New Member
    Join Date
    Dec 2023
    Posts
    11

    Re: VB2013 GUI Form build

    Oh, I was just thinking on that line . But, wasn't able to pin point. Can you please tell me in depth of what you are thinking. Is the response timing is too quick? Should I slow that down a little may be? Should I see any sort of 'flickering' from the display maybe? Which I don't see.
    Last edited by VisKataboman2; Oct 8th, 2024 at 12:55 AM.

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,451

    Re: VB2013 GUI Form build

    Don't look at the number of views on a thread, it's meaningless. The VAST majority of the 'visitors' to a thread will be web bots crawling posts for search engines and the like. You can see this by starting a thread and noticing that the number of visitors starts marching upwards at a pretty fast rate, despite there not being all that many people on the forum at any one time. Those are views, just not meaningful views. Bots rarely answer, and when they do, it's just spam.

    Still, you must have some theory as to what is happening. Put a breakpoint in the relevant code and have a look. Are you getting what you expect to get at the time you expect to get it? For example, put a breakpoint in DataReceived. Are you getting complete messages? Are you getting all the messages you expect? It's easy to leave something unread in a buffer, or to stitch messages together incorrectly.
    My usual boring signature: Nothing

  8. #8
    Wall Poster TysonLPrice's Avatar
    Join Date
    Sep 2002
    Location
    Columbus, Ohio
    Posts
    3,900

    Re: VB2013 GUI Form build

    Quote Originally Posted by Shaggy Hiker View Post
    Don't look at the number of views on a thread, it's meaningless. The VAST majority of the 'visitors' to a thread will be web bots crawling posts for search engines and the like. You can see this by starting a thread and noticing that the number of visitors starts marching upwards at a pretty fast rate, despite there not being all that many people on the forum at any one time. Those are views, just not meaningful views. Bots rarely answer, and when they do, it's just spam.

    Still, you must have some theory as to what is happening. Put a breakpoint in the relevant code and have a look. Are you getting what you expect to get at the time you expect to get it? For example, put a breakpoint in DataReceived. Are you getting complete messages? Are you getting all the messages you expect? It's easy to leave something unread in a buffer, or to stitch messages together incorrectly.
    That made me think about what I read about a "honey pot" test. In the article I read at the time, many years ago, it was just a test to see how long an unprotected computer could be online without being attacked. It wasn't very long at all. I tried to find the article and ran into a "honey pot" test I hadn't heard of. Kind of a reverse trap.

    "In computer security terms, a cyber honeypot works in a similar way, baiting a trap for hackers. It's a sacrificial computer system that’s intended to attract cyberattacks, like a decoy. It mimics a target for hackers, and uses their intrusion attempts to gain information about cybercriminals and the way they are operating or to distract them from other targets."

    https://www.kaspersky.com/resource-c...-is-a-honeypot
    Please remember next time...elections matter!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width