Posts: 7
Joined: Fri Jan 13, 2012 10:02 am

Joystick registers double

Mon May 20, 2019 3:10 pm

Hi all,
I am having some interesting behaviour with my sense hat. I wrote some code to be invoked on button press with the joystick. I noticed it seems to be being run twice. So, I took some code from teh getting started tutorial and modified it a touch.

If I run the code below. For every button press of the joystick I get the direction printed twice. Is this intended behaviour and I missed something? It seems far too consistent for a hardware fault IMO.

If this is intended, how do I react to the button press but only call the function once and not twice?

Here is the code...

Code: Select all

from sense_hat import SenseHat

sense = SenseHat()

# Define the functions
def up():
    print 'up'

def down():
    print 'down'

def left():
    print 'left'

def right():
    print 'right'

def middle():
    print 'middle'

# Tell the program which function to associate with which direction
sense.stick.direction_up = up
sense.stick.direction_down = down
sense.stick.direction_left = left
sense.stick.direction_right = right
sense.stick.direction_middle = middle

while True:
    pass  # This keeps the program running to receive joystick events

Posts: 3802
Joined: Fri Jun 08, 2012 6:03 pm

Re: Joystick registers double

Tue May 21, 2019 12:39 pm

I believe you can add a check to the callback function to tell whether the event was triggered by pressing the joystick or releasing it.

According to the tutorial ( ... nse-hat/10)

Code: Select all

def up():
    if event.action == 'pressed':
        print("Pressed Up")
Or the official documentation says that this is the syntax but I presume both work (

Code: Select all

if event.action != ACTION_RELEASED:
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

Posts: 2298
Joined: Tue Jan 19, 2016 2:17 pm
Location: Sydney, Nova Scotia, Canada

Re: Joystick registers double

Tue May 21, 2019 7:56 pm

I did it this way, just a snippet of my full code.
Each button has three functions. Pressed, released, and held.
And there are 5 buttons, up, down, left, right and center.

Code: Select all


sense = SenseHat()

def pushed_up(event):
    if event.action == ACTION_PRESSED:
       sense.low_light = False
def pushed_down(event):
    if event.action == ACTION_PRESSED:
       sense.low_light = True

sense.stick.direction_up = pushed_up
sense.stick.direction_down = pushed_down
sense.stick.direction_left = pushed_left
sense.stick.direction_right = pushed_right
sense.stick.direction_middle = pushed_middle

Return to “Astro Pi”