Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# Differential Steering Joystick Algorithm
# ========================================
# by Calvin Hass
# https://www.impulseadventure.com/elec/
# translated to Python by Laurin Neff
#
# Converts a single dual-axis joystick into a differential
# drive motor control, with support for both drive, turn
# and pivot operations.
#
# INPUTS
nJoyX = 123
nJoyY = 74
# CONFIG
# - fPivYLimit : The threshold at which the pivot action starts
# This threshold is measured in units on the Y-axis
# away from the X-axis (Y=0). A greater value will assign
# more of the joystick's range to pivot actions.
# Allowable range: (0..+127)
fPivYLimit = 32.0
# TEMP VARIABLES
nMotPremixL = 0 # Motor (left) premixed output (-128..+127)
nMotPremixR = 0 # Motor (right) premixed output (-128..+127)
nPivSpeed = 0 # Pivot Speed (-128..+127)
fPivScale = 0.0 # Balance scale b/w drive and pivot ( 0..1 )
# Calculate Drive Turn output due to Joystick X input
if(nJoyY>=0):
# Forward
nMotPremixL = 127.0 if nJoyX>=0 else 127.0 + nJoyX
nMotPremixR = 127.0 - nJoyX if nJoyX>=0 else 127.0
else:
# Reverse
nMotPremixL = 127.0 - nJoyX if nJoyX>=0 else 127.0
nMotPremixR = 127.0 if nJoyX>=0 else 127.0 + nJoyX
# Scale Drive output due to Joystick Y input (throttle)
nMotPremixL = nMotPremixL * nJoyY/128.0
nMotPremixR = nMotPremixR * nJoyY/128.0
# Now calculate pivot amount
# - Strength of pivot (nPivSpeed) based on Joystick X input
# - Blending of pivot vs drive (fPivScale) based on Joystick Y input
nPivSpeed = nJoyX
fPivScale = 0.0 if abs(nJoyY)>fPivYLimit else 1.0-abs(nJoyY)/fPivYLimit
# Calculate final mix of Drive and Pivot
nMotMixL = int((1.0-fPivScale)*nMotPremixL + fPivScale*( nPivSpeed)) # Motor (left) mixed output (-128..+127)
nMotMixR = int((1.0-fPivScale)*nMotPremixR + fPivScale*(-nPivSpeed)) # Motor (right) mixed output (-128..+127)
@ImpulseAdventure

This comment has been minimized.

Copy link

commented Sep 6, 2019

Thanks for sharing the translation, Laurin! -Cal

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.