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

adding std_msgs Int16 and int ?

asked 2018-09-06 00:39:03 -0600

mohamed ahmed gravatar image

i made a simple publisher which publish a Int16. the problem is in the subscriber i try to receive the int16 and add a constant number to it for example 2 the publisher code:

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import Int16
import random
def ty():
    pub = rospy.Publisher('to', Int16, queue_size=10)
    rospy.init_node('talker1')
    r = rospy.Rate(1) # 1hz
    while not rospy.is_shutdown():

        value=random.randint(0, 100)
        print(value)
        pub.publish(value)
        r.sleep()
if __name__ == '__main__':
    try:
        ty()
    except rospy.ROSInterruptException:
        pass

the subscriber code:

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import Int16

def cb(x):
    rospy.loginfo(x+2)
def listener():


    # In ROS, nodes are uniquely named. If two nodes with the same
    # node are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("to", Int16, cb)
    rospy.spin()

if __name__ == '__main__':
    listener()

i got this error :

TypeError: unsupported operand type(s) for +: 'Int16' and 'int'

how can i solve this problem

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2018-09-06 01:21:20 -0600

gvdhoorn gravatar image

updated 2018-09-06 02:23:12 -0600

The problem is that std_msgs/Int16 is not a simple int type but a Python class.

It contains a single field data that contains the actual int.

So for your code to work you should write:

rospy.loginfo(x.data + 2)

See std_msgs/Int16 for the documentation of the message type, and see wiki/msg - Message Description Specification - Field Types for how those fields map to Python types.

edit flag offensive delete link more

Comments

thank you very much, it is my first time asking on ROS answers, i didn't expect such a fast response thank you again it works for me

mohamed ahmed gravatar image mohamed ahmed  ( 2018-09-07 04:04:04 -0600 )edit

Question Tools

Stats

Asked: 2018-09-06 00:39:03 -0600

Seen: 9,520 times

Last updated: Sep 06 '18