How do I send a steering wheel/Joystick input to a game from Python?

Viewed 2252

I need to send a series of steering wheel input : (steering wheel, accelerator, brake) that is calculated in Machine learning Model to a game in order to implement self driving. I have already used pynput to send keys and control the car with ['w','a','s','d'] but I want a smoother way to control the car, hence I'm looking for a way to emulate a joystick in python. So, that I can send analogue input for steering wheel and accelerator.

I previously used this type of code to input controls

from pynput.keyboard import Key, Controller
import time

keyboard = Controller()
keyboard.press('w')
time.sleep(1)
keyboard.release('w')
1 Answers

I used Vjoy to emulate a joysick and create a virtual joystick; used FreePie as Feeder Application, and wrote a Python Script to send input values to Vjoy for each axis. My Vjoy Script:- Currently I use motion of my mouse to send value of X-axis and Y-axis, But you can use any way you please.

from System import Int16

if starting:
    system.setThreadTiming(TimingTypes.HighresSystemTimer)
    system.threadExecutionInterval = 5
    x = 0
    y = 0
    max = 1
    min = -max

    
    vjoy = vJoy[0] # controlling Vjoy Device 0
    sensX = 50
    sensY = 50

y -= mouse.deltaY * sensY
x += mouse.deltaX * sensX

if x > max:
    x = max
elif x < min:
    x = min

if y > max:
    y = max
elif y < min:
    y = min

vjoy.x = x
vjoy.y = y
diagnostics.watch(vJoy[0].x)
diagnostics.watch(vJoy[0].y)

For Purpose of self-Driving Car you can write another python script which feeds input values(For x-axis and y-axis) to this script.

Related