ROS learning ROS basics

ROS learning (1)

ROS basics

1. Basic operations of workspace

Create workspace

mkdir -p ~/yyj_ws/src
//到src下
cd yyj_ws/src

Initialize the workspace in the src folder and turn it into an attribute of the ROS workspace

catkin_init_workspace

Create function package directive in src

catkin_create_pkg<package_name>[depend1][depend2][depend3][...]

For example:

catkin_create_pkg learning_communication std_msgs rospy roscpp

At this time, the src in the function package contains the core code, and the include contains the header files. CMakelists.txt and package.xml are files that all functional packages must have. The former is to place the compilation options and rules for compiling the function package, using the cmake interface; the latter is to describe the specific information of the function package, such as name, version number, maintainer, declared dependencies, etc. Later addition of dependencies needs to be modified in this file.
Then compile at the workspace level and set the environment variables.

cd ..
catkin_make
source ~/yyj_ws/devel/setup.bash

(Function packages with the same name are not allowed to exist in the same workspace. Function packages with the same name are allowed to exist in different workspaces.)
Check the environment variables of ros and pay attention to ROS_PACKAGE_PATH, which is the order in which ros is compiled and run to find function packages and nodes.

env | grep ros
//或者
echo $ROS_PACKAGE_PATH

When a functional package with the same name exists in different workspaces, the path will be generated after searching first.
Example: (Remember to delete this package after the experiment)

//安装ros功能包例程
sudo apt-get install ros-kinetic-roscpp-tutorials
//查找功能包会在opt/ros/kinetic/share/roscpp_tutotials
rospack find roscpp_tutorials
//复制功能包到工作空间src下
//再次设置环境变量
source ~/yyj_ws/devel/setup.bash
//再次查找即发现查找路径指向工作空间里的功能包了
rospack find roscpp_tutorials

2. ROS communication programming - topic programming

"hello world" routine

1. Create a publisher (talker)

a. Enter /home/frany/yyj_ws/src/learning_communication/src to create talker.cpp
b. Write talker.cpp
programming logic:
(1) Initialize ROS nodes;
(2) Register node information with ROS Master, including published topic names and The type of message in the topic;
(3) Publish messages cyclically at a certain frequency;

/*
该例程将发布chatter话题,消息类型String
*/

#include <sstream>
#include "ros/ros.h"
#include "std_msgs/String.h"

int main(int argc,char **argv)
{
  //ROS节点初始化,“talker“为节点名称,后期可更改
  ros::init(argc,argv,"talker");
  
  //创建节点句柄
  ros::NodeHandle n;
  //创建一个Publisher,发布名为chatter的topic,消息类型为std::msgs::String,1000是发布队列的长度,它的作用是缓冲数据,当队列满了会删除时间戳最早的数据,如发布消息过快可能会导致断帧
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

  //设置循环的频率
  ros::Rate loop_rate(10); 

  int count = 0;
  while (ros::ok())
  {
    //初始化std::msgs::String类型的消息
    std_msgs::String msg;
    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();

    //发布消息
    ROS_INFO("%s", msg.data.c_str()); 
    chatter_pub.publish(msg);
    
    //循环等待回调函数
    ros::spinOnce();

    //按照循环频率延时按循环频率(10hz)休眠即100ms,避免cpu占用过高
    loop_rate.sleep();
    ++count;
  }

  return 0;
}
2. Create a subscriber (listener)

a. Enter /home/frany/yyj_ws/src/learning_communication/src to create listener.cpp
b. Write listener.cpp
programming logic:
(1) Initialize ROS nodes;
(2) Subscribe to required topics;
(3) Loop waiting for topic messages , enter the callback function after receiving the message;
(4) Complete the message processing in the callback function;

/*
该例程将订阅chatter话题,消息类型String
*/
#include "ros/ros.h"
#include "std_msgs/String.h"

//接收到订阅的消息后,会进入消息回调函数
void chatterCallback(const std_msgs::String::ConstPtr& msg)
{
  //将接收到的消息打印出来
  ROS_INFO("I heard: [%s]", msg->data.c_str());
}

int main(int argc, char **argv)
{
  //初始化ROS节点
  ros::init(argc, argv, "listener");

  //创建节点句柄
  ros::NodeHandle n;

  //创建一个Subscriber,订阅名为chatter的topic,注册回调函数chatterCallback
  ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

  //循环等待回调函数
  ros::spin(); 

  return 0;
}

3. Add compilation options

C++ needs to be compiled, but python does not because it is an executable file itself.
Compile the code in the CMakeLists.txt file:
a. Process:
(1) Set the code to be compiled and the generated executable file
(2) Set the link library
(3) Set the dependency
add_executable to generate the executable file, which depends on talker.cpp To generate talker, multiple source code files can be added at the end;
target_link_libraries is to link to third-party libraries, and only the default library is linked here.

add_executable(talker src/talker.cpp) 
target_link_libraries(talker ${catkin_LIBRARIES})

add_executable(listener src/listener.cpp)
target_link_libraries(listener ${catkin_LIBRARIES})

b. Compile:
Generate executable files at the yyj_ws workspace level:

catkin_make
4. Run the executable file

a. Start ROS Master
terminal 1:

roscore

b. Start talker
terminal 2:

rosrun learning_communication talker

c. Start listener
terminal 3:

rosrun learning_communication listener

If you do not write the environment variables directly into .bashrc, you need to add the environment variables every time you open a new terminal.

source ~/yyj_ws/devel/setup.bash

Custom topic message

1. Define msg file

Create the msg directory under learning_communication and create the Person.msg file under the msg directory.

string name
uint8 sex
uint8 age

uint8 unknown = 0
uint8 male    = 1
uint8 female  = 2
2. Add function package dependencies in package.xml
  <build_depend>message_generation</build_depend>
  <exec_depend>message_runtime</exec_depend>
3. Add compilation options to CMakeLists.txt
find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
  )
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES learning_communication
  CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
#  DEPENDS system_lib
)
add_message_files(FILES Person.msg)
generate_messages(DEPENDENCIES std_msgs)

final compile

catkin_make
4. View customized messages

If you do not write the environment variables directly into .bashrc, you need to add the environment variables

source ~/yyj_ws/devel/setup.bash
rosmsg show Person

ROS learning (2)

ROS basics

3. ROS communication programming - service programming

Example: Implement the addition listener to publish two numbers to the talker, and the talker adds them to the listener.

1. Custom service file srv

a. Create the srv directory under learning_communication and create the AddTwoInts.srv file under the srv directory.

int64 a
int64 b
---
int64 sum

b. Add function package dependencies in package.xml

  <build_depend>message_generation</build_depend>
  <exec_depend>message_runtime</exec_depend>

c. Add compilation options to CMakeLists.txt

find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
  )
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES learning_communication
  CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
#  DEPENDS system_lib
)
add_service_files(FILES AddTwoInts.srv)
generate_messages(DEPENDENCIES std_msgs)

d. Compile
and generate executable files at the yyj_ws workspace level:

catkin_make

2. Create a server

Create the server.cpp file under the src of learning_communicatio.
Programming logic:
(1) Initialize ROS nodes
(2) Create Server instances
(3) Loop waiting for service requests, enter the callback function
(4) Complete the processing of the service function in the callback function, and Feedback response data

/*
AddTwoInts Server
*/

#include "ros/ros.h"
#include "learning_communication/AddTwoInts.h"

//service回调函数,输入参数req,输出参数res
bool add(learning_communication::AddTwoInts::Request  &req,
         learning_communication::AddTwoInts::Response &res)
{
  //将输入参数中的请求数据相加,结果放到应答变量中
  res.sum = req.a + req.b;
  ROS_INFO("request: x=%ld, y=%ld", (long int)req.a, (long int)req.b);
  ROS_INFO("sending back response: [%ld]", (long int)res.sum);

  return true;
}

int main(int argc, char **argv)
{
  //ROS节点初始化
  ros::init(argc, argv, "add_two_ints_server");
  
  //创建节点句柄
  ros::NodeHandle n;

  //创建一个名为add_two_ints的server,注册回调函数add()
  ros::ServiceServer service = n.advertiseService("add_two_ints", add);

  //循环等待回调函数
  ROS_INFO("Ready to add two ints.");
  ros::spin();

  return 0;
}

3. Create a client

Create the client.cpp file under the src of learning_communicatio.
Programming logic:
(1) Initialize ROS nodes
(2) Create Client instances
(3) Publish service request data
(4) Wait for the response results processed by the Server

/*
AddTwoInts Client
*/

#include <cstdlib>
#include "ros/ros.h"
#include "learning_communication/AddTwoInts.h"


int main(int argc, char **argv)
{
  //Ros节点初始化
  ros::init(argc, argv, "add_two_ints_client");
  
  //从终端命令行获取两个加数
  if (argc != 3)
  {
    ROS_INFO("usage: add_two_ints_client X Y");
    return 1;
  }

  //创建节点句柄
  ros::NodeHandle n;

  //创建一个client,请求add_two_int service,service消息类型是learning_communication::AddTwoInts
  ros::ServiceClient client = n.serviceClient<learning_communication::AddTwoInts>("add_two_ints");

  //创建learning_communication::AddTwoInts类型的service消息
  learning_communication::AddTwoInts srv;
  srv.request.a = atoll(argv[1]);
  srv.request.b = atoll(argv[2]);

  //发布service请求,等待加法运算的应答结果
  if (client.call(srv))
  {
    ROS_INFO("Sum: %ld", (long int)srv.response.sum);
  }
  else
  {
    ROS_ERROR("Failed to call service add_two_ints");
    return 1;
  }

  return 0;
}

4. Add compilation options

Set the compiled code in the CMakeLists.txt file
a. Process:
(1) Set the code to be compiled and the generated executable file
(2) Set the link library
(3) Set dependencies . Open
the CMakeLists.txt file in the learning_communication function package and add The following code:

add_executable(server src/server.cpp)
target_link_libraries(server ${catkin_LIBRARIES})
add_dependencies(server ${PROJRCT_NAME}_gencpp)

add_executable(client src/client.cpp)
target_link_libraries(client ${catkin_LIBRARIES})
add_dependencies(client ${PROJRCT_NAME}_gencpp)

b. Compile:
Generate executable files at the yyj_ws workspace level:

catkin_make

5. Run the executable file

a. Start ROS Master
terminal 1:

roscore

b. Start server
terminal 2:

rosrun learning_communication server

c. Start client
terminal 3:

rosrun learning_communication client 80 99

If you do not write the environment variables directly into .bashrc, you need to add the environment variables every time you open a new terminal.

source ~/yyj_ws/devel/setup.bash

ROS learning (3)

ROS basics

4. ROS communication programming - action programming

Example: Realize the robot's action of washing dishes, and provide real-time feedback on the action of washing dishes. After the dishes are washed, a successful command will be sent back to the client.

1. Custom action message action file

a. Create the action directory under learning_communication and create the DoDishes.action file under the action directory.

#定义目标信息
uint32 dishwasher_id #Specify which dishwasher we want to use
---
#定义结果信息
uint32 total_dishes_cleaned
---
#定义周期反馈的消息  洗盘子进度
float32 percent_complete

b. Add function package dependencies in package.xml

  <build_depend>actionlib</build_depend>
  <build_depend>actionlib_msgs</build_depend>
  <exec_depend>actionlib</exec_depend>
  <exec_depend>actionlib_msgs</exec_depend>

c. Add compilation options to CMakeLists.txt

find_package(catkin REQUIRED COMPONENTS
...
  actionlib_msgs
  actionlib
)
add_action_files(DIRECTORY action FILES DoDishes.action)
generate_messages(DEPENDENCIES std_msgs actionlib_msgs)

d. Compile
and generate executable files at the yyj_ws workspace level:

catkin_make

2. Create an action server

Create the DoDishes_server.cpp file under the src of learning_communicatio.
Programming logic:
(1) Initialize the ROS node
(2) Create an action server instance
(3) Start the server and wait for the action request
(4) Complete the processing of the action service function in the callback function, and Feedback progress information
(5) The action is completed and the end information is sent

#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include "learning_communication/DoDishesAction.h"

typedef actionlib::SimpleActionServer<learning_communication::DoDishesAction> Server;

// 收到action的goal后调用该回调函数
void execute(const learning_communication::DoDishesGoalConstPtr& goal, Server* as)
{
   ros::Rate r(1);
   learning_communication::DoDishesFeedback feedback;

   ROS_INFO("Dishwasher %d is working.", goal->dishwasher_id);

   // 假设洗盘子的进度,并且按照1hz的频率发布进度feedback
   for(int i=1; i<=10; i++)
   {
       feedback.percent_complete = i * 10;
       as->publishFeedback(feedback);
       r.sleep();
   }

   // 当action完成后,向客户端返回结果
   ROS_INFO("Dishwasher %d finish working.", goal->dishwasher_id);
   as->setSucceeded();
}

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

   // 定义一个服务器
   Server server(n, "do_dishes", boost::bind(&execute, _1, &server), false);
   
   // 服务器开始运行
   server.start();

   ros::spin();

   return 0;
}

3. Create action client

Create the DoDishes_client.cpp file under the src of learning_communicatio.
Programming logic:
(1) Initialize ROS nodes
(2) Create action client instances
(3) Connect to action servers
(4) Send action targets
(5) Process according to different types of server feedback Callback

#include <actionlib/client/simple_action_client.h>
#include "learning_communication/DoDishesAction.h"

typedef actionlib::SimpleActionClient<learning_communication::DoDishesAction> Client;

// 当action完成后会调用该回调函数一次
void doneCb(const actionlib::SimpleClientGoalState& state,
       const learning_communication::DoDishesResultConstPtr& result)
{
   ROS_INFO("Yay! The dishes are now clean");
   ros::shutdown();
}

// 当action激活后会调用该回调函数一次
void activeCb()
{
   ROS_INFO("Goal just went active");
}

// 收到feedback后调用该回调函数
void feedbackCb(const learning_communication::DoDishesFeedbackConstPtr& feedback)
{
   ROS_INFO(" percent_complete : %f ", feedback->percent_complete);
}

int main(int argc, char** argv)
{
   ros::init(argc, argv, "do_dishes_client");

   // 定义一个客户端
   Client client("do_dishes", true);

   // 等待服务器端
   ROS_INFO("Waiting for action server to start.");
   client.waitForServer();
   ROS_INFO("Action server started, sending goal.");

   // 创建一个action的goal
   learning_communication::DoDishesGoal goal;
   goal.dishwasher_id = 1;

   // 发送action的goal给服务器端,并且设置回调函数
   client.sendGoal(goal,  &doneCb, &activeCb, &feedbackCb);

   ros::spin();

   return 0;
}

4. Add compilation options

Set the compiled code in the CMakeLists.txt file
a. Process:
(1) Set the code to be compiled and the generated executable file
(2) Set the link library
(3) Set dependencies . Open
the CMakeLists.txt file in the learning_communication function package and add The following code:

add_executable(DoDishes_client src/DoDishes_client.cpp)
target_link_libraries(DoDishes_client ${catkin_LIBRARIES})
add_dependencies(DoDishes_client ${${PROJECT_NAME}_EXPORTED_TARGETS})

add_executable(DoDishes_server src/DoDishes_server.cpp)
target_link_libraries(DoDishes_server ${catkin_LIBRARIES})
add_dependencies(DoDishes_server ${${PROJECT_NAME}_EXPORTED_TARGETS})

b. Compile:
Generate executable files at the yyj_ws workspace level:

catkin_make

5. Run the executable file

a. Start ROS Master
terminal 1:

roscore

b. Start client
terminal 2:

rosrun learning_communication DoDishes_client

c. Start server
terminal 3:

rosrun learning_communication DoDishes_server

If you do not write the environment variables directly into .bashrc, you need to add the environment variables every time you open a new terminal.

source ~/yyj_ws/devel/setup.bash

ROS learning (4)

ROS basics

5. Distributed communication

ROS is a distributed software framework in which nodes are combined in a loosely coupled manner.

1. Configure IP and environment

Two machines are connected to the same network. Use the command to check their respective IPs. The IP address is after the inet addr of wlan0.

ifconfig

Then check the respective computer names

hostname

Open the /etc/ hosts file and enter the other party’s IP and computer name respectively.

sudo gedit /etc/hosts

My configuration:
(note that the two machines cross-enter each other’s information)

192.168.52.47   frany-PF4WN2F 
192.168.52.83   ltstl308-desktop

After the configuration is completed, ping the two machines to test whether the underlying network communication is successful.

ping frany-PF4WN2F 
ping  ltstl308-desktop

If the network is smooth, the underlying network communication is correct.
Open the .bashrc file in the slave machine to set the other party's ROS_MASTER_URI

sudo gedit ~/.bashrc
export ROS_MASTER_URI=http://ltstl308-desktop:11311

The default port number of ROS Master is 11311.

2. Little turtle test

Run the little turtle emulator on the host machine

roscore
rosrun turtlesim turtlesim_node

View the topic list on the slave machine

rostopic list

You will see:

/rosout
/rosout_agg
/turtle1/cmd_vel
/turtle1/color_sensor
/turtle1/pose

Then publish the little turtle motion control message:

rostopic pub /turtle1/cmd_vel geometry_msgs/Twist -r 1 -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, 1.8]'

You can see the circular motion of the little turtle of the host machine.

ROS learning (5)

ROS basics

5. Key components of ROS

(1) launch file

Multi-node configuration and startup is achieved through XML files (ROS master can be automatically started). The
root element is defined using this tag.
Start node
<node pkg="package-name" type="executable-name" name="node-name"/>
pkg: The name of the function package where the node is located
type: The executable file name
of the node name: The name of the node when it is running
output: Print the output information to the terminal
respawn: Restart if the node fails or fails
required: The node must be present, otherwise the launch fails
ns: Namespace
args: parameter
param:ros global variable
arg: local variable in launch
Insert image description here
Insert image description here

(2)TF transformation

TF manages some position coordinate transformations
by broadcasting TF transformations and monitoring TF transformation relationships.
The little turtle follows the routine.

#安装功能包
sudo apt-get install ros-kinetic-turtle-tf
#启动launch文件
roslaunch turtle_tf turtle_tf_demo.launch
#启动控制节点
rosrun turtlesim turtle_teleop_key
#能够监听当前时刻所有通过ROS广播的tf坐标系,并绘制出树状图表示坐标系之间的连接关系保存到离线文件中,监听5秒后,保存5秒内坐标系之间的关系,会生成一个pdf文件。
rosrun tf view_frames
#使用tf_echo工具可以查看两个广播参考系之间的关系
rosrun tf tf_echo turtle1 turtle2
#通过rvize可视化工具更加形象的看到这三者之间的关系
rosrun rviz rviz -d 'rospack find turtle_tf' /rviz/turtle.rviz

Implemented with code

#创建功能包
catkin_create_pkg learning_tf roscpp rospy tf turtlesim
#再learning_tf/src中创建cpp文件
touch turtle_tf_broadcaster.cpp
touch turtle_tf_listener.cpp

Write in turtle_tf_broadcaster.cpp

#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <turtlesim/Pose.h>

std::string turtle_name;

void poseCallback(const turtlesim::PoseConstPtr& msg)
{
// 创建tf的广播器
static tf::TransformBroadcaster br;

// 初始化tf数据
tf::Transform transform;
transform.setOrigin( tf::Vector3(msg->x, msg->y, 0.0) );
tf::Quaternion q;
q.setRPY(0, 0, msg->theta);
transform.setRotation(q);

// 广播world与海龟坐标系之间的tf数据
br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", turtle_name));
}

int main(int argc, char** argv)
{
    // 初始化ROS节点
ros::init(argc, argv, "my_tf_broadcaster");

// 输入参数作为海龟的名字
if (argc != 2)
{
ROS_ERROR("need turtle name as argument"); 
return -1;
}

turtle_name = argv[1];

// 订阅海龟的位姿话题
ros::NodeHandle node;
ros::Subscriber sub = node.subscribe(turtle_name+"/pose", 10, &poseCallback);

    // 循环等待回调函数
ros::spin();

return 0;
};

Write in turtle_tf_listener.cpp

#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/Twist.h>
#include <turtlesim/Spawn.h>

int main(int argc, char** argv)
{
// 初始化ROS节点
ros::init(argc, argv, "my_tf_listener");

    // 创建节点句柄
ros::NodeHandle node;

// 请求产生turtle2
ros::service::waitForService("/spawn");
ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("/spawn");
turtlesim::Spawn srv;
add_turtle.call(srv);

// 创建发布turtle2速度控制指令的发布者
ros::Publisher turtle_vel = node.advertise<geometry_msgs::Twist>("/turtle2/cmd_vel", 10);

// 创建tf的监听器
tf::TransformListener listener;

ros::Rate rate(10.0);
while (node.ok())
{
// 获取turtle1与turtle2坐标系之间的tf数据
tf::StampedTransform transform;
try
{
listener.waitForTransform("/turtle2", "/turtle1", ros::Time(0), ros::Duration(3.0));
listener.lookupTransform("/turtle2", "/turtle1", ros::Time(0), transform);
}
catch (tf::TransformException &ex) 
{
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
continue;
}

// 根据turtle1与turtle2坐标系之间的位置关系,计算turtle2需要运动的线速度和角速度
// 并发布速度控制指令,使turtle2向turtle1移动
geometry_msgs::Twist vel_msg;
vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),
                        transform.getOrigin().x());
vel_msg.linear.x = 0.5 * sqrt(pow(transform.getOrigin().x(), 2) +
                      pow(transform.getOrigin().y(), 2));
turtle_vel.publish(vel_msg);

rate.sleep();
}
return 0;
};

Add the following code to CMakeLists.txt:

add_executable(turtle_tf_broadcaster src/turtle_tf_broadcaster.cpp)
target_link_libraries(turtle_tf_broadcaster ${catkin_LIBRARIES})

add_executable(turtle_tf_listener src/turtle_tf_listener.cpp)
target_link_libraries(turtle_tf_listener ${catkin_LIBRARIES})

Compile in the workspace root directory

catkin_make

source the following workspace

source devel/setup.bash

Start ROS Master

roscore

Start the turtle emulator

rosrun turtlesim turtlesim_node

Release/turtle1Turtle coordinate system relationship

rosrun learning_tf turtle_tf_broadcaster __name:=turtle1_tf_broadcaster /turtle1

Note: turtle_tf_broadcaster __name:=turtle1_tf_broadcaster rename

Release/turtle2Turtle coordinate system relationship

rosrun learning_tf turtle_tf_broadcaster __name:=turtle2_tf_broadcaster /turtle2

Start a custom node

rosrun learning_tf turtle_tf_listener

Start the turtle control node

rosrun turtlesim turtle_teleop_key

Or create a launch file

#在/learning_tf创建launch文件夹
mkdir launch
#进入launch文件夹创建launch文件
touch start_demo_with_listener.launch

Write in launch file

<launch>

   <!--海龟仿真器-->
   <node pkg="turtlesim" type="turtlesim_node" name="sim"/>
   <!--键盘控制-->
   <node pkg="turtlesim" type="turtle_teleop_key" name="teleop" output="screen"/>
   <!--两只海龟的tf广播-->
   <node pkg="learning_tf" type="turtle_tf_broadcaster"
         args="/turtle1" name="turtle1_tf_broadcaster" />
   <node pkg="learning_tf" type="turtle_tf_broadcaster"
         args="/turtle2" name="turtle2_tf_broadcaster" />
   <!--监听tf广播,并且控制turtle2移动-->
   <node pkg="learning_tf" type="turtle_tf_listener"
         name="listener" />

</launch>

Start the launch file and you can control the turtle with the keyboard

roslaunch learning_tf start_demo_with_listener.launch

(3) QT toolbox

log message

rqt_console

Computational graph visualization tool

rqt_graph

Data plotting tools

rqt_plot

Parameter dynamic configuration tool

rosrun rqt_reconfigure rqt_reconfigure

rqt_Press the tab key to see related tools

(4) rviz visualization platform

Data visualization
plug-in mechanism

(5) gazebo physical simulation environment

Robot simulation, function/algorithm verification
with physically familiar simulation environment, cloud + local
installation

sudo apt-get install ros-kinetic-gazebo-ros-pkgs ros-kinetic-gazebo-ros-control
roslaunch gazebo_ros empty_world.launch

gazebo_ros - used for gazebo interface encapsulation, gazebo server and client startup, URDF model generation, etc.
gazebo_msgs - gazebo's Msg and Srv data structures
gazebo_plugins - general sensor plug-ins for gazebo
gazebo_ros_api_plugins and gazebo_ros_path_plugin. These two gazebo plug-ins implement interfaces to encapsulate
gazebo simulation steps.
Create simulation environment.
Configure robot model.
Start simulation.

ROS learning (6)

Robot system design

View the specific member variables in the pointer

show turtlesim/Pose

The definition and composition of robots

Actuator,
drive system,
sensing system
, control system

Robot system construction

1. Actuator
Chassis, motor, steering gear
2. Drive system
Power supply subsystem
Motor drive subsystem
Sensor interface: ultrasonic, odometer
3. Sensing system
Robot odometer
Inertial measurement unit

Connect camera:

cd catkin_ws/src
git clone https://github.com/bosch-ros-pkg/usb_cam.git
cd ~/catkin_ws
catkin_make
roslaunch usb_cam usb_cam-test.launch
rqt_image_view

Connect kinect :

sudo apt-get install ros-kinect-freenect-*
git clone http://github.com/avin2/SensorKinect.git
cd SensorKinect/Bin
tar xvf SensorKinect093-Bin-Linux-x86-v5.1.2.1.tar.bz2
cd Sensor-Bin-Linux-x86-v5.1.2.1/
sudo ./install.sh

Create a freenect.launch file under src and write it

<launch>


    <!--启动freenect驱动-->
    <include file="$(find freenect_launch)/launch/freenect.launch">
        <arg name="publish_tf"                       value="false"/>
        <arg name="depth_registration"               value="true"/>
        <arg name="rgb_processing"                   value="true"/>
        <arg name="ir_processing"                    value="false"/>
        <arg name="depth_processing"                 value="false"/>
        <arg name="depth_registered_processing"      value="true"/>
        <arg name="disparity_processing"             value="false"/>
        <arg name="disparity_registered_processing"  value="false"/>
        <arg name="sw_registered_processing"         value="false"/>
<arg name="hw_registered_processing"         value="true"/>
    </include>


</launch>

Run freenect.launch in this layer directory

roslaunch freenect.launch 
rosrun rviz rviz

Change the fixed frame under Global options to camera_rgb_optical_frame
, add pointcloud2 and image and subscribe to the topics respectively.
Connect to rplidar:

#在工作空间的src下安装雷达的ros包
git clone https://github.com/Slamtec/rplidar_ros.git
#编译工作空间
catkin_make
#查看雷达串口权限
ls -l /dev |grep ttyUSB
#修改权限
sudo chmod 666 /dev/ttyUSB0
#查看雷达扫描点云图
roscore
roslaunch rplidar_ros view_rplidar.launch
#运行雷达
rosrun rplidar_ros rplidarNode
#在终端查看雷达数据
rosrun rplidar_ros rplidarNodeClient
#或者
echo /scanl

URDF robot modeling

URDF is Unified Robot Description Format, a unified robot description format that
can parse robot models described in XML format in URDF files.
ROS also provides a C++ parser for URDF files.

Describe the appearance and physical properties of a certain rigid body part of the robot; size, color, shape, inertia matrix, collision parameters, etc. Describe the appearance parameters of the link part of the robot. Describe the inertia parameters of the link. Describe the collision attributes of the link. Describe the kinematic properties and dynamics of the robot joints. The physical properties, including the position and speed limits of joint motion, can be divided into six types according to the joint form. Practice: urdf: store the URDF or xacro file of the robot model meshes: place the model rendering file referenced in the URDF launch: save the relevant startup file config: save the rviz configuration file

catkin_create_pkg mbot_description urdf xacro

joint_state_publisher: Publish the status of each joint (except fixed type), and the joint can be controlled through the UI interface
robot_state_publisher: Organize the relationship between the various links and joints of the robot into three-dimensional attitude information in the form of TF and publish it
in the launch file Create display_mbot_base_urdf.launch file and write in

<launch>
<param name="robot_description" textfile="$(find mbot_description)/urdf/mbot_base.urdf" />

<!-- 设置GUI参数,显示关节控制插件 -->
<param name="use_gui" value="true"/>

<!-- 运行joint_state_publisher节点,发布机器人的关节状态  -->
<node name="joint_state_publisher" pkg="joint_state_publisher" type="joint_state_publisher" />

<!-- 运行robot_state_publisher节点,发布tf  -->
<node name="robot_state_publisher" pkg="robot_state_publisher" type="robot_state_publisher" />

<!-- 运行rviz可视化界面 -->
<node name="rviz" pkg="rviz" type="rviz" args="-d $(find mbot_description)/config/mbot_urdf.rviz" required="true" />
</launch>


check the overall architecture of the robot URDF model under the URDF folder

#先将 xacro 文件解析成 urdf 文件
rosrun xacro xacro xxx.xacro > xxx.urdf
urdf_to_graphiz xxxxx.urdf

Guess you like

Origin blog.csdn.net/feichangyanse/article/details/133000927