Click here to Skip to main content
16,022,901 members
Home / Discussions / Visual Basic
   

Visual Basic

 
PinnedHOW TO ANSWER A QUESTION PinPopular
Chris Maunder12-Jul-09 22:40
cofounderChris Maunder12-Jul-09 22:40 
PinnedHow to get an answer to your question PinPopular
Chris Maunder10-Nov-05 16:30
cofounderChris Maunder10-Nov-05 16:30 
QuestionVB2013 GUI Form build Pin
Vis Kataboman5-Oct-24 3:32
Vis Kataboman5-Oct-24 3:32 
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, how do I post the image of the GUI?

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

Main GUI:

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

Questionvb.net mysql javascript Pin
AMRO DAMMAM15-Jul-24 20:05
AMRO DAMMAM15-Jul-24 20:05 
AnswerRe: vb.net mysql javascript Pin
Victor Nijegorodov15-Jul-24 21:18
Victor Nijegorodov15-Jul-24 21:18 
AnswerRe: vb.net mysql javascript Pin
Dave Kreskowiak16-Jul-24 4:20
mveDave Kreskowiak16-Jul-24 4:20 
QuestionHow to install Visual basic 6.0 PRO or Visual studio 6.0 using vbinstaller Pin
Blue Moon 202111-Jul-24 21:58
Blue Moon 202111-Jul-24 21:58 
AnswerRe: How to install Visual basic 6.0 PRO or Visual studio 6.0 using vbinstaller Pin
Dave Kreskowiak13-Jul-24 8:59
mveDave Kreskowiak13-Jul-24 8:59 
AnswerRe: How to install Visual basic 6.0 PRO or Visual studio 6.0 using vbinstaller Pin
gvidali15-Jul-24 5:05
gvidali15-Jul-24 5:05 
Questionsimple code ,how i can connect and read record from table in SQL database (VB.NET) Pin
Member 162990357-Jul-24 21:13
Member 162990357-Jul-24 21:13 
AnswerRe: simple code ,how i can connect and read record from table in SQL database (VB.NET) Pin
gvidali8-Jul-24 5:10
gvidali8-Jul-24 5:10 
QuestionHow to use web services in vb.net Pin
yvesauff15-Apr-24 5:15
yvesauff15-Apr-24 5:15 
AnswerRe: How to use web services in vb.net Pin
Dave Kreskowiak15-Apr-24 6:35
mveDave Kreskowiak15-Apr-24 6:35 
QuestionSelected row always visible in datagridview research Pin
medi dimie2-Mar-24 1:53
medi dimie2-Mar-24 1:53 
AnswerRe: Selected row always visible in datagridview research Pin
Richard MacCutchan2-Mar-24 2:58
mveRichard MacCutchan2-Mar-24 2:58 
QuestionResearch in datagridview Pin
medi dimie2-Mar-24 0:52
medi dimie2-Mar-24 0:52 
AnswerRe: Research in datagridview Pin
Richard Deeming3-Mar-24 22:01
mveRichard Deeming3-Mar-24 22:01 
QuestionMy problem is with the Next button. At the last rows, this message appears : System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index' Pin
anis7831-Jan-24 1:46
anis7831-Jan-24 1:46 
AnswerRe: At the last rows, this message appears : System.ArgumentOutOfRangeException Pin
Richard MacCutchan31-Jan-24 2:00
mveRichard MacCutchan31-Jan-24 2:00 
GeneralRe: At the last rows, this message appears : System.ArgumentOutOfRangeException Pin
anis7831-Jan-24 2:37
anis7831-Jan-24 2:37 
GeneralRe: At the last rows, this message appears : System.ArgumentOutOfRangeException Pin
Richard MacCutchan31-Jan-24 2:51
mveRichard MacCutchan31-Jan-24 2:51 
GeneralRe: At the last rows, this message appears : System.ArgumentOutOfRangeException Pin
gvidali2-Feb-24 4:51
gvidali2-Feb-24 4:51 
QuestionVB6 printing bitmap or image on a POS Printer Pin
Member 1491430129-Jan-24 23:37
Member 1491430129-Jan-24 23:37 
AnswerRe: VB6 printing bitmap or image on a POS Printer Pin
RedDk30-Jan-24 8:52
RedDk30-Jan-24 8:52 
GeneralRe: VB6 printing bitmap or image on a POS Printer Pin
Member 1491430130-Jan-24 20:00
Member 1491430130-Jan-24 20:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.