ros sends and receives array data with std_msgs (python)

1. Problem description

Because it is necessary to publish an array of data to a topic, and then use another topic to receive it.
At first, I used from std_msgs.msg import Float32 to define the data type as Float32, and then when I subscribed to the data, I couldn’t read the data, and the program that sent the data would directly report an error and exit. Then I wonder if this type can only transmit one data, and the array I transmitted has 24 data. Sure enough, if the data is changed to one, there is no problem with this type, and it can be sent and received continuously. It's easy to find the reason.
At first I wanted to define an array of float32[] by myself, but I found it too troublesome. Putting it in my messy package would definitely cause a lot of problems. Thinking that std_msgs must have an array type, it is impossible to only have a single data type. So I checked, there are so many types as follows,
insert image description here
and finally changed the type directly to Float32MultiArray, that is,
from std_msgs.msg import Float32MultiArray, still reported an error, and then checked the specific information of this type

rosmsg show std_msgs/Float32MultiArray 

insert image description here
We only need the data inside, so the following needs to be processed when the data is released, as follows:

data=Float32MultiArray(data=data_list)
pub.publish(data)

Then the topic part of the subscription is still the same, so that the publication and subscription of the data in the array can be realized.

2. Realize the code

release

img0 = cv.imread('/home/whp/my_robot/src/code/script/yolov5_detect/image/image1.png')
data_list=detect(img0)
rospy.init_node('yolov5_detect_data')
 pub = rospy.Publisher('data_list', Float32MultiArray,  queue_size=10)
    while not rospy.is_shutdown():
        print('start')
        data=Float32MultiArray(data=data_list)
        pub.publish(data)
        print('end')

subscription:

import rospy
from std_msgs.msg import Float32MultiArray
def yolov5_grasp():
    rospy.init_node('yolov5_grasp')
    print(2)
    sub=rospy.Subscriber("/data_list", Float32MultiArray, call_back)
    rospy.spin()
def call_back(data):
    print(data)
if __name__ == '__main__':
    yolov5_grasp()

Guess you like

Origin blog.csdn.net/puqian13/article/details/111598012