ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

Revision history [back]

import rospy
from sensor_msgs.msg import Joy
from ackermann_msgs.msg import AckermannDriveStamped

ack_publisher = None
max_speed = 1 # m/s
max_steering = 1.047198 # radians

def joyCallback(msg):
    for i in range(len(msg.buttons)):
        if msg.buttons[i] == 1:
            print 'WOW! You pressed the ' + str(i) + ' button!'

    ack_msg = AckermannDriveStamped()
    ack_msg.header.stamp = rospy.Time.now()
    ack_msg.header.frame_id = 'your_frame_here'
    ack_msg.drive.steering_angle = msg.axes[0] * max_steering
    ack_msg.drive.speed = msg.axes[1] * max_speed
    ack_publisher.publish(ack_msg)

if __name__ == '__main__':
    rospy.init_node('Ryan_F_example')
    max_speed = rospy.get_param("~max_speed", 1)
    max_steering = rospy.get_param("~max_steering", 1.047198)
    rospy.Subscriber('joy', Joy, joyCallback)
    ack_publisher = rospy.Publisher('your/topic/here', AckermannDriveStamped, queue_size=1)
    while not rospy.is_shutdown():
        rospy.spin()

I have not tested the code, but it should work with some minor corrections. I don't see why you would want to publish joy messages, so in this example I have subscribed to the joy topic, and based on that I am publishing AckermannDriveStamped messages.

A small explanation of the code:

Starting from main, we first initialize our node, get two parameters for max_speed and max_steering, which are based on our robot and can be acquired from a yaml file that is fed to our code using a launch file. We then subscribe to the joy topic, and create a publisher for AckermannDriveStamped messages. The following while ensures that the node will trigger its callback(s) for as long as it is alive.

Continuing with the joyCallback method, we first check if there are any buttons pressed and print a dummy message there. You can remove this code, or use it based on your needs and your robot's capabilities (e.g. X button used as horn and Y button as headlights!). After taking care of the buttons, we come to the interesting part: The axes! In this example I assume that you use the left analog stick to control the robot. axes[0] is left/right in a range of [-1,1] (with left being the positive) and axes[1] is forward/back in a range of [-1,1] (with forward being the positive). Regarding your Header question, you should NEVER touch the seq field of the header, because it is automatically generated. It is also a good practice to fill in the frame_id field.

I think I have covered the basics. Hit me up if you have any more problems! Good luck!