03
- May
2020
Posted By : Dave Hartburn
Micro:bit Joystick Module
Dual axis thumb joystick module

These small joystick modules are composed of a single switch (triggered when pushing down), and two potentiometers set by moving the X and Y axis. As well as two power pins, it has three ouput pins, SW, VRy and VRx. VRy and VRx must be connected to analog capable pins, while SW can be read as a digital value.

The switch is a basic push button which connects SW to GND. In order to function, either an external pull-up resistor must be used to Vcc or make use of the internal pull-ups as demonstrated in the code below.

The following code performs the basic read operations and outputs the joystick status tothe serial console:

# Testing a joystick module
# Connections:
#   sw - pin 0
#   VRy - pin 1
#   VRx - pin 2

from microbit import *

jsSW = pin0
jsX = pin2
jsY = pin1

# Configure switch for internal pullup
jsSW.set_pull(jsSW.PULL_UP)

while True:
    sw = jsSW.read_digital()
    jx = jsX.read_analog()
    jy = jsY.read_analog()
    
    print("sw="+str(sw)+", jx="+str(jx)+", jy="+str(jy))
    sleep(500)
DirectionVRxVRy
Middle505497
Up5051
Down5051020
Left1497
Right1020497
The table shows the values of VRx and VRy depending on the maximum position of the joystick. If you want to read these as absolute directions, pick a threshold between to trigger on.

The following code introduces a function to check the direction based on the above values, then change the LED matrix accordingly.

# Testing a joystick module
# Connections:
#   sw - pin 0
#   VRy - pin 1
#   VRx - pin 2

from microbit import *

jsSW = pin0
jsX = pin2
jsY = pin1

# Configure switch for internal pullup
jsSW.set_pull(jsSW.PULL_UP)

def getJSdir():
    # Returns joystick direction when pushed towards the limits
    # 0 = middle, 1 = up, 2 = right, 3 = down, 4 = left
    jx = jsX.read_analog()
    jy = jsY.read_analog()

    if(jy < 100):
        return 1
    if(jx > 900):
        return 2
    if(jy > 900):
        return 3
    if(jx < 100):
        return 4
        
    return 0
    

while True:
    sw = jsSW.read_digital()
    
    d = getJSdir()
    if(d == 0):
        display.show(Image.HAPPY)
    if(d == 1):
        display.show(Image.ARROW_N)
    if(d == 2):
        display.show(Image.ARROW_E)
    if(d == 3):
        display.show(Image.ARROW_S)
    if(d == 4):
        display.show(Image.ARROW_W)
    
    if(sw == 0):
        display.show(Image.COW)
        
    sleep(200)
    

Comments

Leave a Reply to Cutebenj67 Cancel reply