ROS学习——控制小车前进给定距离

	现在提出了一个小小的需求,就是要求控制小车前进五米。那么这个需求可以转化为一个问题,就是如何控制小车前进给定的距离,于是我编写了下面这个程序,向小车发布指令,然后使小车前进。
#include<ros/ros.h>
#include<string>
#include<iostream>
#include<geometry_msgs/Pose.h>
#include<nav_msgs/Odometry.h>
#include<geometry_msgs/Twist.h>
#include<time.h>

double r_dis_long;
double ix, iy, px, py;//initation & pose x,y

double dis_long;//the distance need to move
double robot_v;//the linear_velocity with the robot
//double robot_w;//the angular_velcity eith the robot

//ros::Time last_time, current_time;



void poseCallback(const nav_msgs::Odometry &p_msg){
    px = p_msg.pose.pose.position.x;
    py = p_msg.pose.pose.position.y;
    ROS_INFO("Robot walked %.2f m",px);
}

int main(int argc,char** argv){
    ros::init(argc, argv, "command_publisher");
    ros::NodeHandle nh;
    ros::Publisher command_pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
    // ros::Publisher  init_data_pub = nh.advertise<nav_msgs::Odometry>("/odom", 10);
    ros::Subscriber pose_sub = nh.subscribe("/odom", 10, poseCallback);
    
    std::cout << "Please Input distance(m) :"<< std::endl;
    std::cin >> dis_long;
    std::cout << "Please Input velocity(m/s) :"<< std::endl;
    std::cin >> robot_v;
    // std::cout << "Please Input radius(rad/s) :"<< std::endl;
    // std::cin >> robot_w;

    
    bool is_start = true;
    
    double count = 0;
    while(ros::ok()){
        ros::spinOnce();
        if(is_start)
        {
            ix = px;
            is_start =false;
        }

        if(count < dis_long){
            ros::spinOnce();

            geometry_msgs::Twist com_msg;
            if(count < dis_long / 5 || count > dis_long * 4 / 5){
                com_msg.linear.x = robot_v / 3;
            }
            else{
                com_msg.linear.x = robot_v;
            }
            ROS_INFO("Publish turtle velocity command[%.2f m/s,%.2f rad/s] distance: %.2f", com_msg.linear.x, com_msg.angular.z, count);
            command_pub.publish(com_msg);
            count = px - ix;
        }
        if(count >= dis_long)break;
        
    }

    return 0;
}   
该程序只需要输入需要小车前进的距离(m)和小车前进的速度(m/s)即可。
  • 10
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值