[ros]callback can not run

asked 2021-12-08 20:55:29 -0500

ZMNQAQ gravatar image

hello,this is a ros starter. I got some problem with the follow code that is the callback function can not work

#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/LaserScan.h"
float x_pillar=1.0,y_pillar=1.0,alpha_pillar=0.0;
void call_back(const sensor_msgs::LaserScan::ConstPtr& scan_msg){
//ROS_INFO("call back");
int arr_size = floor((scan_msg->angle_max-scan_msg->angle_min)/scan_msg->angle_increment);
float smallest_distance=10000;
for (int i=0 ; i< arr_size ;i++){
    if (scan_msg->ranges[i] < smallest_distance){
        smallest_distance = scan_msg->ranges[i];
        alpha_pillar = (scan_msg->angle_min + i*scan_msg->angle_increment);
    }
}
//Pillar Husky offset pose
x_pillar = smallest_distance*cos(alpha_pillar);
y_pillar = smallest_distance*sin(alpha_pillar);

ROS_INFO("Pillar offset angle(rad):%lf", alpha_pillar);
ROS_INFO("pillar x distance(m):%lf", x_pillar);
ROS_INFO("pillar y distance(m):%lf", y_pillar);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "controller");
ros::NodeHandle nh;
ros::Subscriber scan_sub = nh.subscribe<sensor_msgs::LaserScan>("/scan", 10, call_back);
ros::Publisher vel_pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
ros::Rate loop_rate(10);
int count = 0;
while (ros::ok()) {
    geometry_msgs::Twist vel_msg;
    float p_gain_vel = 0.1;
    float p_gain_ang = 0.4;
    if(x_pillar>0.2){
        if (x_pillar <= 0.4 ){
            vel_msg.linear.x = 0;
            vel_msg.angular.z = 0;

        }
        else{
            vel_msg.linear.x = x_pillar * p_gain_vel  ;
            vel_msg.angular.z = -(y_pillar * p_gain_ang) ;

        }
    }
    else{
        vel_msg.linear.x = 0;
        vel_msg.angular.z = 0;
    }
    vel_pub.publish(vel_msg);
    ros::spinOnce();
    loop_rate.sleep();
    ++count;
}
return 0;

}

edit retag flag offensive close merge delete