Note: This tutorial assumes that you have completed the previous tutorials: ROS tutorials. |
![]() |
How to Write a Generic Teleoperation Node
Description: This tutorial goes over generic teleoperation code that is used as an example in many of the teleoperation tutorials.Tutorial Level: BEGINNER
Contents
The Code
1 #include <ros/ros.h>
2 #include <turtlesim/Velocity.h>
3 #include <joy/Joy.h>
4
5 class TeleopTurtle
6 {
7 public:
8 TeleopTurtle();
9
10 private:
11 void joyCallback(const joy::Joy::ConstPtr& joy);
12
13 ros::NodeHandle nh_;
14
15 int linear_, angular_;
16 double l_scale_, a_scale_;
17 ros::Publisher vel_pub_;
18 ros::Subscriber joy_sub_;
19
20 };
21
22 TeleopTurtle::TeleopTurtle():
23 linear_(1),
24 angular_(2),
25 l_scale_(50.0),
26 a_scale_(2.0)
27 {
28
29 nh_.param("axis_linear", linear_, linear_);
30 nh_.param("axis_angular", angular_, angular_);
31 nh_.param("scale_angular", a_scale_, a_scale_);
32 nh_.param("scale_linear", l_scale_, l_scale_);
33
34
35 vel_pub_ = nh_.advertise<turtlesim::Velocity>("turtle1/command_velocity", 1);
36 joy_sub_ = nh_.subscribe<joy::Joy>("joy", 10, &TeleopTurtle::joyCallback, this);
37 }
38
39 void TeleopTurtle::joyCallback(const joy::Joy::ConstPtr& joy)
40 {
41 turtlesim::Velocity vel;
42 vel.angular = a_scale_*joy->axes[angular_];
43 vel.linear = l_scale_*joy->axes[linear_];
44 vel_pub_.publish(vel);
45 }
46
47 int main(int argc, char** argv)
48 {
49 ros::init(argc, argv, "teleop_turtle");
50 TeleopTurtle teleop_turtle;
51
52 ros::spin();
53 }
The Code Explained
Now, let's break down the code piece by piece.
Error: No code_block found
- turtlesim/Velocity.h includes the turtle velocity msg, so that we can publish velocity commands to the turtle
- joy/Joy.h includes the joystick msg, so that we can listen to the joy topic
Error: No code_block found Here we create the TeleopTurtle class and the define the joyCallback function that will take a joy msg. We also create a node handle, publisher, and subscriber for later use.
Error: No code_block found Here we initialize some parameters, the linear_ and angular_ variables are use to define which axes of the joystick will control out turtle. We also check the parameter server for new scalar values for driving the turtle.
Error: No code_block found Here we create a publisher that will advertise on the command_velocity topic of the turtle.
Error: No code_block found Here we subscribe to the joystick topic for the input to drive the turtle, we are buffering 10 messages joystick topic.
Error: No code_block found Here we take the data from the joystick and manipulate it, scaling it and using independent axes for controlling the linear and angular velocity of the turtle.
Error: No code_block found Lastly we initialize our ros node, create a teleop_turtle, and spin our node until we get a Crtl-C.