Using RS232 communication protocol. Read multiarray Serial

asked 2020-06-27 16:32:51 -0600

ricfed gravatar image

updated 2020-06-28 01:01:43 -0600

gvdhoorn gravatar image

I don't know how to use the serial::Serial:read and publish the coming data in a ROS Message. I have to control a motor-driver, and i have to write 4 bytes like "02 00 C4 C6". If the host computer send it correctly in this format, the driver immediately returns the two addresses of the command to the host computer, indicating that the driver has successfully received the command. Thank you very much for your help!!

This is the code:

#include <ros/ros.h>
#include <serial/serial.h>
#include <std_msgs/String.h>
#include <std_msgs/Empty.h>
#include <iostream>
#include <string>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/UInt8MultiArray.h"
#include "std_msgs/Int32.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/Odometry.h"
#include "std_msgs/Float64.h"
#include <sstream> 

serial::Serial ser;
uint8_t buff;
std_msgs::UInt8MultiArray buf;
void write_callback(const std_msgs::UInt8MultiArray::ConstPtr& msg){
    //ROS_INFO_STREAM("Writing to serial port" << msg->data);
    ser.write(msg->data);
}

int main (int argc, char** argv){
    ros::init(argc, argv, "serial_example_node");
    ros::NodeHandle nh;

    ros::Subscriber write_sub = nh.subscribe("write", 1000, write_callback);
    ros::Publisher read_pub = nh.advertise<std_msgs::UInt8MultiArray>("read", 1000);

    try
    {
        ser.setPort("/dev/ttyUSB0");
        ser.setBaudrate(9600);
        serial::Timeout to = serial::Timeout::simpleTimeout(1000);
        ser.setTimeout(to);
        ser.open();
    }
    catch (serial::IOException& e)
    {
        ROS_ERROR_STREAM("Unable to open port ");
        return -1;
    }

    if(ser.isOpen()){
        ROS_INFO_STREAM("Serial Port initialized");
    }else{
        return -1;
    }

    ros::Rate loop_rate(5);
    while(ros::ok()){

        ros::spinOnce();

        if(ser.available()){
            ROS_INFO_STREAM("Reading from serial port");
            std_msgs::UInt8MultiArray result;
            //result.data = ser.read(ser.available());
            result.data=ser.read(4);
            //ROS_INFO_STREAM("Read: " << result.data);
            read_pub.publish(result);
        }
        loop_rate.sleep();

    }
}
edit retag flag offensive close merge delete