I have complete the task from section 2 which is to find the nearest wall and rotate the robot until the front of the robot facing the wall. The code is below:
#include “ros/node_handle.h”
#include “ros/publisher.h”
#include “ros/subscriber.h”
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/LaserScan.h>
#include <unistd.h>
#include <services_quiz/FindWall.h>ros::Publisher pub;
geometry_msgs::Twist vel;
using namespace std;void counterCallback (const sensor_msgs::LaserScan::ConstPtr& msg)
{float min_range = std::numeric_limits<float>::infinity(); float min_angle = 0.0; for (int i = 0; i < msg->ranges.size(); ++i) { if (msg->ranges[i] < min_range) { min_range = msg->ranges[i]; } } ROS_INFO("min_range %f", min_range); if (msg->ranges[360] > min_range + 0.05) { vel.linear.x = 0.0; vel.angular.z = 0.2; pub.publish(vel); } else { vel.linear.x = 0.0; vel.angular.z = 0.0; pub.publish(vel); }
bool my_callback(services_quiz::FindWall::Request &req,
services_quiz::FindWall::Response &res)
{
ROS_INFO(“The Service move_bb8_in_square_custom has been called”);res.wallfound = true;
return true;
}int main (int argc, char** argv)
{
ros::init(argc, argv, “services_quiz_node”);
ros::NodeHandle nh;
ros::ServiceServer my_service = nh.advertiseService(“/find_wall”, my_callback);
ros::Subscriber sub = nh.subscribe (“scan”, 1000, counterCallback);
pub = nh.advertise<geometry_msgs::Twist>(“cmd_vel”, 1000);
ros::spin();return 0;
}
For section 1, the code is below:
#include “ros/node_handle.h”
#include “ros/publisher.h”
#include “ros/subscriber.h”
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/LaserScan.h>ros::Publisher pub;
void counterCallback (const sensor_msgs::LaserScan::ConstPtr& msg)
{
ROS_INFO(“360 %f”, msg->ranges[360]);
ROS_INFO(“270 %f”, msg->ranges[270]);
ROS_INFO(“450 %f”, msg->ranges[450]);geometry_msgs::Twist vel; if (msg->ranges[360] > 0.3 && msg->ranges[270] > 0.3 && msg->ranges[450] > 0.3) // 0.3 is distance in meter & ranges[NUMBER] identify the robot view angle { vel.linear.x = 0.2; //Adjust the robot speed vel.angular.z = 0; //Adjust the robot angle view pub.publish(vel); //Execute command to robot } else if (msg->ranges[360] <= 0.3 || msg->ranges[450] <= 0.3) { vel.angular.z = -0.2; vel.linear.x = 0.0; pub.publish(vel); } else if (msg->ranges[270] <= 0.3) { vel.angular.z = 0.2; vel.linear.x = 0.0; pub.publish(vel); }
}
int main (int argc, char** argv)
{
ros::init(argc, argv, “topics_quiz_node”);
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe (“scan”, 1000, counterCallback);
pub = nh.advertise<geometry_msgs::Twist>(“cmd_vel”, 1000);
ros::spin();return 0;
}
How can I combine this code by using services? I am a beginner in c++ and ROS.