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)
Direction | VRx | VRy |
---|---|---|
Middle | 505 | 497 |
Up | 505 | 1 |
Down | 505 | 1020 |
Left | 1 | 497 |
Right | 1020 | 497 |
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)
Cutebenj67
May 14, 2020 at 2:16 pmThis makes loads of sense
obadmin
May 15, 2020 at 3:15 pmThanks 😉