ROS学习——控制小车转向

给定一个旋转的角度,让小车进行顺时针或逆时针旋转。
#include<iostream>
#include<string>
#include<ros/ros.h>
#include<geometry_msgs/Twist.h>
#include<geometry_msgs/Quaternion.h>
#include<nav_msgs/Odometry.h>
#include<tf/tf.h>

#define UNIT_ANGLE 180 / 3.1149

double rotation_angle, rotation_vel = 0.5;
geometry_msgs::Vector3 rpy;
tf::Quaternion q_msg;
double roll, pitch, yaw, i_yaw, m_yaw=0;

void poseCallback(const nav_msgs::Odometry &odom){
    tf::quaternionMsgToTF(odom.pose.pose.orientation, q_msg);
    tf::Matrix3x3(q_msg).getRPY(roll, pitch, yaw);
}

double T_angle(double a){
    a = fmod(a, 360);
    if(a > 180)a = a - 360;
    else if(a < -180)a = a + 360;
    return a;
}

int main(int argc, char **argv){
    ros::init(argc, argv, "rotation_publisher");
    ros::NodeHandle nh;
    ros::Publisher rotation_pub = nh.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
    ros::Subscriber pose_sub = nh.subscribe("/odom", 10, poseCallback);

    std::cout << "Please Input the rotation_angle: " << std::endl;
    std::cin >> rotation_angle ;
    // std::cout << "Please Input the rotation_vel: " << std::endl;
    // std::cin >> rotation_vel ;

    rotation_angle = T_angle(rotation_angle);

    double angle = 0;
    
    double abs_rotation_angle = abs(rotation_angle);

    bool start = true;
    double count = 0;
    while(ros::ok()){
        ros::spinOnce();
        if(start){
            i_yaw = yaw;
            start = false;
        }
        if(angle * UNIT_ANGLE < abs_rotation_angle){
            ros::spinOnce();
            geometry_msgs::Twist r_vel_msgs;
            
            if(rotation_angle < 0){
                angle = i_yaw - yaw;
                r_vel_msgs.angular.z = -rotation_vel;

                rotation_pub.publish(r_vel_msgs);
            }
            else{
                angle = yaw - i_yaw;
                r_vel_msgs.angular.z = rotation_vel;

                rotation_pub.publish(r_vel_msgs);
            }
            
            // if(yaw > m_yaw)m_yaw = yaw;
            std::cout << "yaw: %.5f" << yaw << "Angle: %.2f " << angle * UNIT_ANGLE << std::endl;
        }
        if(angle *UNIT_ANGLE >= abs_rotation_angle)break;
        
    }

    return 0;

}

该程序只需给定一个旋转角度,例:90:表示逆时针旋转90度;-90:表示顺时针旋转90度。

  • 2
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值