I have connected an analog joystick to my Raspberry Pi 3B, and I'm trying to get the up down left right movement to map to W A S D. The code looks like this:
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import ADC0834
import time
from pynput.keyboard import Key, Controller
BtnPin = 22
def setup():
# Set the GPIO modes to BCM Numbering
GPIO.setmode(GPIO.BCM)
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
ADC0834.setup()
def destroy():
# Release resource
GPIO.cleanup()
def loop():
keyboard = Controller()
while True:
x_val = ADC0834.getResult(0)
y_val = ADC0834.getResult(1)
Btn_val = GPIO.input(BtnPin)
# Map joystick input to keyboard keys
if y_val < 127:
keyboard.press(Key.W)
keyboard.release(Key.W)
elif y_val > 127:
keyboard.press(Key.S)
keyboard.release(Key.S)
if x_val < 131:
keyboard.press(Key.A)
keyboard.release(Key.A)
elif x_val > 131:
keyboard.press(Key.D)
keyboard.release(Key.D)
time.sleep(0.2)
if __name__ == '__main__':
setup()
try:
loop()
except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the program destroy() will be executed.
destroy()
When the code runs from terminal, I get this error message:
Traceback (most recent call last):
File "/home/pi/Joystick.py", line 46, in <module>
loop()
File "/home/pi/Joystick.py", line 31, in loop
keyboard.press(Key.S)
File "/usr/lib/python3.9/enum.py", line 405, in __getattr__
raise AttributeError(name) from None
AttributeError: S
I have downloaded the library pynput through sudo pip3 install pynput
, and I have also tried to change between upper and lowercase of W A S D in the code. The analog output works as well. I just can't figure out how to map to W A S D properly. Any help is apperciated.
The Key
object does not have attributes for plain letters such as S
.
If you want to press a plain letter key, use this:
keyboard.press('S')
keyboard.release('S')