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

Publisher/subscriber in one python script

asked 2013-12-05 07:35:17 -0500

updated 2014-01-28 17:18:44 -0500

ngrennan gravatar image

Hello everybody,

I would like to get some help from you. I want to use a Dynamixel servo but I do not want to have many different files just for listening the positions and setting new goals, so I created the following Python node:

#!/usr/bin/env python

import rospy
from math import fabs
from dynamixel_msgs.msg import JointState
from std_msgs.msg import Float64

goal_pos = 0;
pub = rospy.Publisher('/tilt_controller/command', Float64)

def transform_callback(data):
    global goal_pos
    rospy.loginfo(rospy.get_name() + ': Current motor angle {0}'.format(data.current_pos))

    # If the motor has reached its limit, publish a new command.
    if fabs(goal_pos-data.current_pos) < 0.01:
        if goal_pos == 0:
            goal_pos = 3.141592
        else:
            goal_pos = 0

        str = "Time: {0} Moving motor to {1}" .format(rospy.get_time(), goal_pos)
        rospy.loginfo(str)
        pub.publish(Float64(goal_pos))


def dxl_control():
    rospy.init_node('dxl_control', anonymous=True)
    rospy.Subscriber('/tilt_controller/state', JointState, transform_callback).
    # Initial movement.
    pub.publish(Float64(goal_pos))
    rospy.spin()


if __name__ == '__main__':
    try:
        dxl_control()
    except rospy.ROSInterruptException:
        pass

The code is just a union of the simple publisher and listener tutorials adapted to my application. As I do not have too much experiences programming with ROS (neither Python) I would like to know what do you think about having the publisher and the goal_pos as global variables and also the publisher and the listener in the same node and file.

The plan is that transform_callback will also publish a tf message. Is it ok as it is or would you do it in separate files and nodes?

Thank you!

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
13

answered 2015-06-26 01:43:19 -0500

After some experience with ROS, and with no other answers, I can say this is perfectly OK and common among ROS nodes.

edit flag offensive delete link more

Comments

is it possible to give rospy.spin a rate?

jester gravatar image jester  ( 2020-07-23 05:22:01 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2013-12-05 07:35:17 -0500

Seen: 19,635 times

Last updated: Jun 26 '15