Ask Your Question

python example of a motor hardware interface

asked 2022-05-30 15:51:25 -0500

niklongstone gravatar image

updated 2022-05-30 15:51:33 -0500

Hi all,

I have a 4WD robot that uses PWM motor controls. I am looking for a good ROS2 python example to convert Twist signal in PWM.


edit retag flag offensive close merge delete


What model of controllers do you have for these PWM motors? This package simple_drive and this AutomaticAddison blog post describe similar things you can try to achieve here

ljaniec gravatar image ljaniec  ( 2022-05-31 05:44:55 -0500 )edit

thanks, I've written very similar code. I was looking for something which included odom for a bot without encoders.

niklongstone gravatar image niklongstone  ( 2022-06-05 16:46:52 -0500 )edit

How would it work exactly?

ljaniec gravatar image ljaniec  ( 2022-06-06 01:39:20 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2022-06-06 06:43:58 -0500

niklongstone gravatar image

updated 2022-06-06 11:17:49 -0500

To convert Twist message to PWM that's what I've done

  1. I've created a test script that sends PWM duty cycle signal from the lowest to highest at specific time intervals (e.g. 1sec, 2sec and son on).
  2. For each event (e.g. PWM 50 for 2sec) I've measured the distance covered by the robot.
  3. With distances (x) and duty cycles (y) I've calculated the slope(m) and y-intercept(b) values of a linear equation y = mx + b
  4. With the linear function I can calculate the duty cycle needed. So, for instance from the Twist linear.x velocity message value, defined as meters/second, I can derive the duty cycle. Note that when the robot goes from a stop state to a moving state some initial friction needs to be considered.


def calc_vel(self, x, z): # x and z are coming from Twist 
    t = self.track #distance between wheels

    r_vel = x + ((z * t) /2)
    l_vel = x - ((z * t) /2)

    dc_r = calc_duty_cycle(r_vel)
    dc_l = calc_duty_cycle(dc_l)

    return dc_r, dc_l

def calc_duty_cycle(self, vel):
    # linear equation variables defined by experimentation
    M_SLOPE = 50

    return M_SLOPE * vel + Y_INTERCEPT
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2022-05-30 15:51:25 -0500

Seen: 106 times

Last updated: Jun 06