Joystick

Place code snippets and demo code here
Post Reply
User avatar
Fernando Perez
Posts: 378
Joined: Mon Feb 15, 2021 10:09 pm
Location: Santander (Spain)
Has thanked: 195 times
Been thanked: 267 times

Joystick

Post by Fernando Perez »

I have bought, for a very reasonable price, several joysticks like the one in the image:
image.png
I've written this code to handle them and so far it works satisfactorily:

Code: [Local Link Removed for Guests]

firstTime = 1

xM = 639 : yM = 479
xC = 319 : yC = 239
x  = 0 : y  = 0
x0 = 0 : y0 = 0

up  = 16 : dwn = 17
lft = 21 : rht = 22
mid = 1

pin.mode up,  input, pullup
pin.mode dwn, input, pullup
pin.mode lft, input, pullup
pin.mode rht, input, pullup
pin.mode mid, input, pullup

interrupt mid, mid

while 1
  if pin(dwn) = 0 then y = y + 1
  if pin(up)  = 0 then y = y - 1
  if pin(rht) = 0 then x = x + 1
  if pin(lft) = 0 then x = x - 1

  if x > xM then x = xM
  if y > yM then y = yM
  if x < 0   then x = 0
  if y < 0   then y = 0

  if (x0 <> x) OR (y0 <> y) then
    x0 = x : y0 = y
    gosub moving
  endif

wend

END

' -----------------
moving:
  wlog x, y
return

' -----------------
mid:
  if firstTime then
    firstTime = 0
    return
  endif 
  if pin(mid) = 0 then return
  x = xC : y = yC
return
 
If my choice of GPIOs sounds strange to you, please note that I use a Wemos D1 ESP32, which has all those pins in-line. But they can use the ones they want, taking into account the limitations of the ESP32 in terms of usable GPIOs.

I tried to find, both in the old forum and in this current one, examples on which to base myself, but I did not find anything.
Greetings to all.
You do not have the required permissions to view the files attached to this post.
Post Reply