Jump to content

Button to create event on hold and release


ShmoeMo
 Share

Recommended Posts

Hey guys, i'm wanting to make an application so i can control an Arduino based rc tank or car (not sure yet) from my laptop over bluetooth. How can i make it so when i press and hold a button it still triggers an event? as normally they only trigger an event after the release of the button. I want it like this so when i press and hold it sends a forward command and when i release it sends a stop command (not the best way as it could possibly run away if connection is lost but it wont be fast).  I did find another post of someone asking the same question for a camera but they where extremely vague on how they did it. This is more just a proof of concept and if i can get it to work reliably i want to bring in a joystick to control the vehicle and use the buttons for other things. Maybe rc tank battles with a buddy 😃 as i will be integrating a FPV camera and reciever into the application if i can get a webcam connection to be reliable as i have had alot of problems in testing the camera. 

Link to comment
Share on other sites

  • Moderators

ShmoeMo,

A quick and dirty way:

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

Global $bPressed = False

$hGUI = GUICreate("Test", 500, 500)

$cLabel = GUICtrlCreateLabel("Not Pressed", 10, 10, 200, 40)
GUICtrlSetFont($cLabel, 24)
GUICtrlSetBkColor($cLabel, 0xCCFFCC)

$cButton = GUICtrlCreateButton("Push!", 10, 100, 100, 30)

GUISetState()

While 1

    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $GUI_EVENT_PRIMARYDOWN ; Mouse pressed
            $aCInfo = GUIGetCursorInfo()
            If $aCInfo[4] = $cButton Then ; If over button
                If $bPressed = False Then
                    $bPressed = True
                    GUICtrlSetData($cLabel, "PRESSED!!!")
                    GUICtrlSetBkColor($cLabel, 0xFFCCCC)
                EndIf
            EndIf
        Case $GUI_EVENT_PRIMARYUP ; Mouse released
            $bPressed = False
            GUICtrlSetData($cLabel, "Not Pressed")
            GUICtrlSetBkColor($cLabel, 0xCCFFCC)

    EndSwitch

    ; And if the mouse slips off the button
    If $bPressed Then
        $aCInfo = GUIGetCursorInfo()
        If $aCInfo[4] <> $cButton Then
            $bPressed = False
            GUICtrlSetData($cLabel, "Not Pressed")
            GUICtrlSetBkColor($cLabel, 0xCCFFCC)
        EndIf
    EndIf

WEnd

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Oooooo thats getting close. Any way i can do it without having to mouse off the button?

Also just found in my testing as i am modifying and old arduino coms app i wrote if i send a string over serial to a device like an arduino or nodemcu that doesnt have its serial port open it will instantly bsod my pc 🤣🤣🤣🤣🤣🤣🤣

Edited by Melba23
Removed quote
Link to comment
Share on other sites

  • Moderators

ShmoeMo,

When you reply in future, please use the "Reply to this topic" button at the top of the thread or the "Reply to this topic" editor at the bottom rather than the "Quote" button - I know what I wrote and it just pads the thread unnecessarily. Thanks in advance for your cooperation.

Try this:

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

Global $bPressed = False

$hGUI = GUICreate("Test", 500, 500)

$cLabel = GUICtrlCreateLabel("Not Pressed", 10, 10, 200, 40)
GUICtrlSetFont($cLabel, 24)
GUICtrlSetBkColor($cLabel, 0xCCFFCC)

$cButton = GUICtrlCreateButton("Push!", 10, 100, 100, 30)

GUISetState()

While 1

    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
        Case $GUI_EVENT_PRIMARYDOWN
            $aCInfo = GUIGetCursorInfo()
            If $aCInfo[4] = $cButton Then
                If $bPressed = False Then
                    $bPressed = True
                    GUICtrlSetData($cLabel, "PRESSED!!!")
                    GUICtrlSetBkColor($cLabel, 0xFFCCCC)
                EndIf
            EndIf
        Case $GUI_EVENT_PRIMARYUP, $cButton
            $bPressed = False
            GUICtrlSetData($cLabel, "Not Pressed")
            GUICtrlSetBkColor($cLabel, 0xCCFFCC)

    EndSwitch

WEnd

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Hmmm, i cant seem to get it to work inside my main function (Arduino_Controller). If i have a while 1 anywhere inside that function it doesn't seem to execute when called from the previous function (the first) and the script just sits inside my system tray paused but no errors are being listed/logged and i cannot unpause it. And if i have the switch section in without a while 1 i can't use the [4] argument? in the "If $aCInfo[4] = $Forward_but Then" section. If i remove [4] my script runs fine but the button press/release is not detected. Sorry if im a spud 🤣 and the fact my script is pretty messy. I need to clean it up and remove some not needed stuff. I pasted my entire script as its not very big.

 

#include <CommMG.au3>
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <ColorConstants.au3>


Global $CMPort = 1
Global $CmBoBaud = 9600
Global $sportSetError = ''
Global $CmboDataBits = 8
Global $CmBoParity = "none"
Global $CmBoStop = 1
Global $setflow = 2



Opt("GUIOnEventMode", 1)
$Form1 = GUICreate("" ,200, 120)
GUISetOnEvent($GUI_EVENT_CLOSE,"_ExitFunction")
$combo1 = GUICtrlCreateCombo("Select Com Port", 8, 10, 185, 20)

;~List's All available Com Ports
GUICtrlSetData(-1, _CommListPorts())


$combo2 = GUICtrlCreateCombo("Select Baud Rate", 8, 30, 185, 20)
GUICtrlSetData(-1, "4800|9600|19200|38400")
$confirm = GUICtrlCreateButton("Confirm", 15, 70, 171, 41)
GUICtrlSetOnEvent($confirm,"ComboConfirm")


GUISetState(@SW_SHOW)

While 1
    Sleep(100)
WEnd

Func Arduino_Controller()

_CommSetPort($CMPort, $sportSetError, $CmBoBaud, $CmboDataBits, $CmBoParity, $CmBoStop, $setflow)
If @error Then
MsgBox(16,"Error!","Can't connect to Arduino on port - "&$CMPort)
Exit
EndIf
_CommSetRTS(0)
_CommSetDTR(0)

;~ Opt("GUIOnEventMode", 1)
$Form1 = GUICreate("FPV Wireless RC Control V.1", 500, 500)
Global $Input_1 = GUICtrlCreateInput("Enter text here", 10, 470, 400, 20)
GUISetOnEvent($GUI_EVENT_CLOSE,"_ExitFunction")

;~Speed adjustment
Global $movement_speed = GUICtrlCreateSlider( 325, 300, 100, 30)
GUICtrlSetLimit(-1, 100, 0)
GUICtrlSetData(-1, 0)
GUISetOnEvent(-1, "movespeed_update")
Global $Label1 = GUICtrlCreateLabel("", 420,333, 20, 20)
GUICtrlSetData($Label1, GUICtrlRead($movement_speed))
$SpeedSet = GUICtrlCreateButton("Set Speed", 345, 330, 60,20)
GUICtrlSetOnEvent($SpeedSet, "movespeed_update")
GUICtrlCreateLabel ("Movement Seed", 335, 285)
GUICtrlCreateLabel ("Min", 309, 301)
GUICtrlCreateLabel ("Max", 425, 301)



$Button1 = GUICtrlCreateButton("Turn On / Off", 16, 16, 171, 41)
GUICtrlSetOnEvent($Button1,"LED_ON_OFF")
$Button2 = GUICtrlCreateButton("Blink 10 Times", 16, 56, 171, 41)
GUICtrlSetOnEvent($Button2,"LED_BLINK_10")
$Button3 = GUICtrlCreateButton("Send", 415, 470, 75, 20)
GUICtrlSetOnEvent($Button3,"Send_String")

;~Direction Controls & labels
$forward_but = GUICtrlCreateButton("Foward", 200, 150,100,50)
$stop_but = GUICtrlCreateButton("Stop", 200, 225,100,50)
$reverse_but = GUICtrlCreateButton("Reverse", 200, 300,100,50)
$left_but = GUICtrlCreateButton("Left", 75, 225,100,50)
$right_but = GUICtrlCreateButton("Right", 325, 225,100,50)

$forward_label = GUICtrlCreateLabel ("1", 225, 301, 80, 80)


;~Detection of direction button press
Global $Forward_Pressed = False

While 1

    Switch GUIGetMsg()
        Case $GUI_EVENT_PRIMARYDOWN
            $aCInfo = GUIGetCursorInfo()
            If $aCInfo[4] = $forward_but Then
                If $Forward_Pressed = False Then
                    $Forward_Pressed = True
                    GUICtrlSetBkColor($forward_label, 0xFFCCCC)
                    GUICtrlSetBkColor($forward_but, $COLOR_RED)

                EndIf
            EndIf
        Case $GUI_EVENT_PRIMARYUP, $forward_but
            $Forward_Pressed = False
            GUICtrlSetBkColor($forward_label, "green" )


    EndSwitch

WEnd

GUISetState(@SW_SHOW)


EndFunc

;~other functions
Func movespeed_update()
GUICtrlSetData($Label1, GUICtrlRead($movement_speed))

EndFunc

Func LED_ON_OFF()
_CommSendByte(1)
EndFunc

Func LED_BLINK_10()
_CommSendByte(2)
EndFunc

Func Send_String()
$arduino = GUICtrlRead($Input_1)
_CommSendString($arduino)
    MsgBox(0,"Message Sent", $arduino)
    ConsoleWrite($arduino)
EndFunc

Func ComboConfirm()
$CMPort = GUICtrlRead($combo1)
$CmBoBaud = GUICtrlRead($combo2)

;~Trims the word com from the variable
$CMPort = StringReplace ($CMPort, "com", "")

ConsoleWrite($CMPort &@LF &$CmBoBaud)
GUIDelete($Form1)
Arduino_Controller()
EndFunc

Func _ExitFunction()
     Exit
EndFunc

 

Link to comment
Share on other sites

Try to make a replicable snippet of your script.  We cannot help you much since we cannot run it.  Remove everything that relates to Arduino, see if you observe the same behavior.

Link to comment
Share on other sites

  • Moderators

ShmoeMo,

You are mixing OnEvent and MessageLoop modes in that script - never a good idea unless there is a very good reason and you know exactly what you are doing.

Here is modified version of your script which does react as you want:

;#include <CommMG.au3>
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <ColorConstants.au3>

Opt("GUIOnEventMode", 1)

Global $CMPort = 1
Global $CmBoBaud = 9600
Global $sportSetError = ''
Global $CmboDataBits = 8
Global $CmBoParity = "none"
Global $CmBoStop = 1
Global $setflow = 2

Global $forward_but, $forward_label

$Form1 = GUICreate("", 200, 120)
GUISetOnEvent($GUI_EVENT_CLOSE, "_ExitFunction")
$combo1 = GUICtrlCreateCombo("Select Com Port", 8, 10, 185, 20)
;~List's All available Com Ports
;GUICtrlSetData(-1, _CommListPorts())
$combo2 = GUICtrlCreateCombo("Select Baud Rate", 8, 30, 185, 20)
GUICtrlSetData(-1, "4800|9600|19200|38400")
$confirm = GUICtrlCreateButton("Confirm", 15, 70, 171, 41)
GUICtrlSetOnEvent($confirm, "ComboConfirm")

GUISetState(@SW_SHOW)

While 1
    Sleep(100)
WEnd

Func Arduino_Controller()

    #cs
    _CommSetPort($CMPort, $sportSetError, $CmBoBaud, $CmboDataBits, $CmBoParity, $CmBoStop, $setflow)
    If @error Then
        MsgBox(16, "Error!", "Can't connect to Arduino on port - " & $CMPort)
        Exit
    EndIf
    _CommSetRTS(0)
    _CommSetDTR(0)

    #ce

;~ Opt("GUIOnEventMode", 1)
    $Form1 = GUICreate("FPV Wireless RC Control V.1", 500, 500)
    Global $Input_1 = GUICtrlCreateInput("Enter text here", 10, 470, 400, 20)
    GUISetOnEvent($GUI_EVENT_CLOSE, "_ExitFunction")
    GUISetOnEvent($GUI_EVENT_PRIMARYDOWN, _ButtonDown)
    GUISetOnEvent($GUI_EVENT_PRIMARYUP, _ButtonUp)


;~Speed adjustment
    Global $movement_speed = GUICtrlCreateSlider(325, 300, 100, 30)
    GUICtrlSetLimit(-1, 100, 0)
    GUICtrlSetData(-1, 0)
    GUISetOnEvent(-1, "movespeed_update")
    Global $Label1 = GUICtrlCreateLabel("", 420, 333, 20, 20)
    ;GUICtrlSetData($Label1, GUICtrlRead($movement_speed))
    $SpeedSet = GUICtrlCreateButton("Set Speed", 345, 330, 60, 20)
    GUICtrlSetOnEvent($SpeedSet, "movespeed_update")

    GUICtrlCreateLabel("Movement Seed", 335, 285)
    GUICtrlCreateLabel("Min", 309, 301)
    GUICtrlCreateLabel("Max", 425, 301)



    $Button1 = GUICtrlCreateButton("Turn On / Off", 16, 16, 171, 41)
    GUICtrlSetOnEvent($Button1, "LED_ON_OFF")
    $Button2 = GUICtrlCreateButton("Blink 10 Times", 16, 56, 171, 41)
    GUICtrlSetOnEvent($Button2, "LED_BLINK_10")
    $Button3 = GUICtrlCreateButton("Send", 415, 470, 75, 20)
    GUICtrlSetOnEvent($Button3, "Send_String")

;~Direction Controls & labels
    $forward_but = GUICtrlCreateButton("Forward", 200, 150, 100, 50)
    $stop_but = GUICtrlCreateButton("Stop", 200, 225, 100, 50)
    $reverse_but = GUICtrlCreateButton("Reverse", 200, 300, 100, 50)
    $left_but = GUICtrlCreateButton("Left", 75, 225, 100, 50)
    $right_but = GUICtrlCreateButton("Right", 325, 225, 100, 50)

    $forward_label = GUICtrlCreateLabel("1", 225, 301, 80, 80)


;~Detection of direction button press
    Global $Forward_Pressed = False

    GUISetState(@SW_SHOW)


EndFunc   ;==>Arduino_Controller

Func _ButtonDown()

    $aCInfo = GUIGetCursorInfo()
    Switch $aCInfo[4]
        Case $forward_but
        If $Forward_Pressed = False Then
            $Forward_Pressed = True
            GUICtrlSetBkColor($forward_label, 0xFFCCCC)
            GUICtrlSetBkColor($forward_but, $COLOR_RED)
        EndIf
        
        ; You will need to add cases for any other controls that you want to use in the same mmanner
        
    EndSwitch


EndFunc

Func _ButtonUp()
    $Forward_Pressed = False
    GUICtrlSetBkColor($forward_label, "green")
    GUICtrlSetBkColor($forward_but, $COLOR_GREEN)
EndFunc


;~other functions
Func movespeed_update()
    GUICtrlSetData($Label1, GUICtrlRead($movement_speed))

EndFunc   ;==>movespeed_update

Func LED_ON_OFF()
    ;_CommSendByte(1)
EndFunc   ;==>LED_ON_OFF

Func LED_BLINK_10()
    ;_CommSendByte(2)
EndFunc   ;==>LED_BLINK_10

Func Send_String()
    $arduino = GUICtrlRead($Input_1)
    ;_CommSendString($arduino)
    MsgBox(0, "Message Sent", $arduino)
    ConsoleWrite($arduino)
EndFunc   ;==>Send_String

Func ComboConfirm()
    $CMPort = GUICtrlRead($combo1)
    $CmBoBaud = GUICtrlRead($combo2)

;~Trims the word com from the variable
    $CMPort = StringReplace($CMPort, "com", "")

    ConsoleWrite($CMPort & @LF & $CmBoBaud)
    GUIDelete($Form1)
    Arduino_Controller()
EndFunc   ;==>ComboConfirm

Func _ExitFunction()
    Exit
EndFunc   ;==>_ExitFunction

There are still some weird effects with some of the labels, but you should know what you want to see and can manage to sort that.

M23

 

 

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...