Question

So, what I'm trying to do is run a piece of code when a button is pressed (I'll use the right-arrow key for the time being), and keep running it in a loop until that key is released.

So, my current code looks something like this (I've simplified it, because it's using SerialPorts, and is not easy to understand code):

Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

    Select Case e.KeyCode

        Case Keys.Right

            Do Until (CODE LOOKING FOR RIGHT-ARROW KEY RELEASE)
                SerialPort1.Write("right")
            Loop

            e.Handled = True
            SerialPort1.Close()
End Sub

Ultimately, what I'm trying to do is control and arduino through the serial port function. I've wired it up to a cheap rc car (I usually have a few arduino projects on the go), and have code which allows me to control it by arrow keys in the IDE itself.

However, I have limited VB.NET knowledge (I've only been at it a few years), so I'm kinda struggling along with the help of Google, which was a god end while trying to work out how to keep the serialport open (it kept closing due to a logic error in my code).

The goal is that once I can control it by arrow keys in VB.NET, I can set up a more advanced program which will allow pre-programming routes (for example, I can try to "teach" the car sets of instructions so that I can get it to automatically follow a circuit, and load various pre-programmed routes into it). I'd also plan an on-screen gui to show what button was pressed, and whatever else I think of.

Also, given this is a prototype, I intend to eventually hook up the arduino and VB program to my hobby grade rc, and see if I can get the computer program, with pre-programmed isntructions, to beat my round my track.

Well, after that little essay, I guess it's just thanks in advance, and any advice in other areas of my project is also appreciated =)

Was it helpful?

Solution

Why make this complicated. It looks like you want to send something as long as the key is down, and then close the port when it is released.

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Right AndAlso keydelay >= 1 Then
        Debug.WriteLine("DWN") 'SerialPort1.Write("right")
        e.Handled = True
    ElseIf e.KeyCode = Keys.Right Then
        keydelay += 1
    End If
End Sub

Dim keydelay As Integer = 0

Private Sub Form1_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
    If e.KeyCode = Keys.Right Then
        keydelay = 0
        Debug.WriteLine("UP") 'SerialPort1.Close()
    End If
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top