0% found this document useful (0 votes)
6 views37 pages

ROS2 Programming: Python & C++ Basics

Chapter 4 covers programming for ROS2 using Python and C++. It discusses the advantages of both languages, including Python's ease of use and extensive libraries, and C++'s performance and real-time capabilities. The chapter also provides basic programming concepts and comparisons between Python and C++, including syntax, data types, and object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views37 pages

ROS2 Programming: Python & C++ Basics

Chapter 4 covers programming for ROS2 using Python and C++. It discusses the advantages of both languages, including Python's ease of use and extensive libraries, and C++'s performance and real-time capabilities. The chapter also provides basic programming concepts and comparisons between Python and C++, including syntax, data types, and object-oriented programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 4.

Programming for ROS2: Python & C++ 1st part


010243407-68 Robot Operating System Programming
[Link]. Noppadol Pudchuen
Production and Robotics Engineering
King Mongkut’s University of Technology North Bangkok
Topics
• Why both Python & C++?
• Python basics
• First python script
• Variables and basic types
• Input and output
• Condition: if, elif, else
• Loop: for and while
• C++ basics
• What is difference from C?
• How to build (compile) C++?
Why both Python & C++? – Why Python for ROS2
• Why Python for ROS2?
• Easy to learn & write
• Lots of libraries:
• Mathematics, Linear algebra, Algorithm: NumPy, SciPy
• Machine Learning, Neural Networks: Scikit-learn, TensorFlow, PyTorch
• Perception, Computer Vision: OpenCV, Open3D
• Graphic User Interface: PyQt, Tkinter
• Webserver: Django, Flask
• Tools: Matplotlib (Visualization), Pandas (Data Analytics), Jupyter (Coding)
• ROS2 supports rclpy (Python client library) (This course mainly focus on python
Why both Python & C++? – Why Python for ROS2
• Why C++ for ROS2?
• ROS2 core and many high-performance packages are written in C++.
• C++ is used when we need: Speed, Real-Time behavior, Typed (well defined)
• Modern professional libraries:
• Mathematics, Linear algebra: Eigen
• Machine Learning & Algorithm: dlib
• Perception, Computer Vision: OpenCV, Open3D, CGAL
• 3D Graphic: OpenGL
• Graphic User Interface: Qt
• Neural Networks: TensorFlow, PyTorch(C++)
• ROS2 supports rclcpp (C++ client library)
Python
Most popular Programming Language
How Python Works?
First Python Script!
• Create and open file: “[Link]”.
• Type the following code:
print("Hello, ROS2 world")
• Execute/Run “[Link]” via the Terminal then type:
python3 [Link]
Python basics, with C comparison –
Variables & Types
• Python is dynamically typed, no need for int, float in declarations.
C
int a = 10;
float b = 3.5f;
char *name = "robot";
Python
a = 10 # int
b = 3.5 # float
name = "robot" # str
Python basics, with C comparison –
Print, Input
• Python have two method for string formatting.
C
int battery = 0;
printf("Enter battery level%%");
scanf("%d", &battery);
printf("Battery: %d%%\n", battery);
Python
battery = input("Enter battery level%")
print(f"Battery: {battery}%")
print("Battery: {}".format(battery))
Python basics, with C comparison –
Condition
• Python uses indentation for scoping code.
!!(Don’t mix between spacebar and tab for indentation)
C Python
if (battery > 50) { if battery > 50:
printf("Battery OK\n"); print("Battery OK")
} else if (battery > 20) { elif battery > 20:
printf("Battery medium\n"); print("Battery medium")
} else { else:
printf("Battery low\n"); print("Battery low")
}
Python basics, with C comparison –
Loop
• Python uses indentation for scoping code.
!!(Don’t mix between spacebar and tab for indentation)
C Python
for (int i = 0; i < 5; i++) { for i in range(5):
printf("Step %d\n", i); print("Step", i)
}
int count = 0 count = 0
while (count < 3){ while count < 3:
printf("Loop: %d\n", count) print("Loop", count)
count += 1; count += 1
}
Python basics, with C comparison –
Collections
• Python has three types of collections: tuple(immutable),
list(mutable), dictionaries, and all of them have dynamic size
C Python

float distances[3] = {0.5f, 0.8f, distances = (0.5, 0.8, 1.2)


1.2f}; print(distances[0])
printf("Distance: %f\n", distances[0]);
//C doesn’t have a built-in dynamic size distances = [0.5, 1.2, 0.8]
collection.// print(distances[0]) # 0.5
[Link](1.0) # [0.5, 1.2, 0.8, 1.0]
Python basics, with C comparison –
Collections
• Python has three types of collections: tuple(immutable),
list(mutable), dictionaries, and all of them have dynamic size
C Python

//C doesn’t have a built-in key access robot = {


collection.// "name": "turtlebot3",
"battery": 80,
"mode": "AUTO"
}

print(robot["name"])
robot["battery"] = 75
Python basics, with C comparison –
Functions
• Python uses def keyword for function declaration. User doesn’t
have to specify the types of arguments and types of outputs.
C Python

float distances[3] = {0.5f, 0.8f, 1.2f}; distances = [0.5, 1.2, 0.8]

float average(float array[], int size){ def average(array) :


float sum = 0.0f; sum = 0
if(size == 0) return sum; if len(array) == 0 :
for(int i = 0; i < size; i++){ return sum
sum +=array[i]; for num in array :
} sum += num
return sum/size; return sum/len(array)
}
Python basics, with C comparison –
Modules, Libraries
• In Python, a user can create and save each .py file as a module.
The module allows users to import functions from another file.
C Python

// utils #utils

void greet(char name[]){ def greet(name):


printf(“Hello: %s\n", str); print("Hello: {}".format(name))
}
#include "utils.h" import utils

int main(int argc, char** argv){ name = "ROS2"


char name[] = "ROS2"; [Link](name)
greet(name);
}
C++
Old, Complex, Fast, Efficient, Risky!
How C++ works?
C/C++ in Ubuntu Linux
• Ubuntu Linux comes with built-in C/C++ compiler called
GCC/G++ stands for GNU Compiler Collection.
• GCC is a compiler for C, and the G++ is a compiler for C++.
• Install C/C++ Compiler:
• $ sudo apt update
• $ sudo apt install build-essential
• Verify installation:
• $ whereis gcc, $whereis g++
• $ which gcc, which g++
• $ gcc --version, g++ --version
First C++ Program!
• Create and open file: “[Link]”.
• Write the following code below, then save.
#include <iostream>

int main(int argc, char **argv){


std::cout << "Hello, world" << std::endl;
return 0;
}
• Compiling your code:
• $ g++ [Link]
• Execute your executable named [Link]
• $ ./[Link]
First C++ Program!
• Create and open file: “[Link]”.
• Write the following code below, then save.
#include <iostream>

int main(int argc, char **argv){


std::cout << "Hello, world" << std::endl;
return 0;
}
• Compiling your code with a particular name:
• $ g++ [Link] –o hello
• Execute your executable named hello
• $ ./hello
C++ basics vs C – Hello world
• <iostream> instead of <stdio.h>
• std::cout + << operators instead of printf.
C C++

#include <stdio.h> #include <iostream>

int main(int argc, char **argv){ int main(int argc, char **argv){
printf("Hello, world\n"); std::cout << "Hello, world" << std::endl;
return 0; return 0;
} }
C++ basics vs C – Types & std::string
• std::string is easier than char[] / char* from C.
• Use std::string in real code.
#include <iostream>
#include <string>

int main() {
int count = 0;
double speed = 0.5;
bool moving = true;
std::string name = "turtlebot";
std::cout << "Robot " << name << " speed: " << speed << std::endl;
return 0;
}
Object Oriented Programming (OOP)
C++ basics – OOP
• C++ has an enhanced version of structs
that has a provision to define functions.
This enhanced struct version is called
the C++ class. Each instance of the C++
Class is called an object. An object is
simply a copy of the actual class. There
are several properties associated with
objects, which are called object-
oriented programming (OOP) concepts.
C++ basics – Class
• What is class ? And What differences between Class and Struct?.

struct Robot_struct{ A compound variable to


int id; group up any related
int no_wheels;
std::string robot_name; “variables” together
}; based on their context.
C++ basics – Class
• What is class ? And What differences between Class and Struct?.
class Robot{
public:
Robot(); // contructor A compound variable
~Robot(); // destructor
void move_forward(int distance); and function to group up
void move_backward(int distance);
void move_left(int distance); any related “variables”
void move_right(int distance);
and “functions "together
private:
int id;
based on their context
int no_wheels; with access modifier.
std::string robot_name;
};
[Link]

C++ basics – Class


#include "robot.h"

Robot::Robot(){
std::cout<<"Start Robot\n";
}

• How to declare and define the class ? Robot::~Robot(){


std::cout<<"Robot stopped\n";
}

robot.h void Robot::move_forward(int distance){


class Robot{ std::cout<<"Robot moving forward: "<< distance << "\n";
public: }
Robot(); // contructor
~Robot(); // destructor void Robot::move_backward(int distance){
void move_forward(int distance); std::cout<<"Robot moving backward: "<< distance << "\n";
void move_backward(int distance); }
void move_left(int distance);
void move_right(int distance); void Robot::move_left(int distance){
std::cout<<"Robot moving left: "<< distance << "\n";
private: }
int id;
int no_wheels; void Robot::move_right(int distance){
std::string robot_name; std::cout<<"Robot moving right: "<< distance << "\n";
}; }

Class declaration: Your class structure Class definition: Your class structure in details.
C++ basics – Class, Anatomy of class
• Anatomy of class function definition:
• First term: the return data type
• Second term: Class name
• Third term: function name after the :: symbol.

1 2 3

void Robot::move_forward(int distance){


std::cout<<"Robot moving forward: "<< distance << "\n";
}
C++ basics – Class, Object
• User can use a class by declaring a new variable as an instance
(object).
• To use any classes type, user must include their header files.
[Link] • User can use “.” operator to access
#include "robot.h" into class variable or call its function
int main(int argc, char **argv){
as show on the left.
Robot obj; • When we create a new object, the
obj.move_forward(3);
obj.move_backward(4); new object owns its own variables
obj.move_left(5); and doesn't share with another
obj.move_right(6);
object.
return 0;
}
C++ basics – Class, Pointer of class
• User can use a class by declaring a new variable as an instance
(object).
• To use any classes type, user must include their header files.
[Link] • In addition, user can populate a new
#include "robot.h" class object and pointer as shown on
the left.
int main(int argc, char **argv){
Robot *robot_2; • The new operator allocates a new
robot_2 = new Robot(); memory for the object in RAM.
robot_2->move_forward(3);
robot_2->move_backward(4); • Different from the normal variable, to
return 0; access a variable or a function in a
} pointer, the user must use “->”
symbol instead.
C++ basics – Class, Access Modifier
• Class Access Modifier: Permission/Accessibility to access into
class member(variables, functions).
• public: The public class members can be accessed by another
class or user from anywhere outside.
• private: The private class members can’t be accessed by another
class or user from anywhere outside a class. Only the class and
friend functions are allowed to access private class members.
• protected: The protected class members can’t be accessed by
another similar to the private member, but the difference from
private member is the childe class can access the members.
C++ basics – Multiple source files compilation
cmake, [Link]
• To compile several source codes, the direct g++ command is not
convenient anymore.
• cmake is another approach for building the C++ project. It’s
stands for cross-platform make file.
• Install by using the following command;
• $ sudo apt install cmake
C++ basics – Multiple source files compilation
cmake, [Link]
• Create a [Link] file and locate it inside your project.

cmake_minimum_required(VERSION 3.0)
project(robot)

add_executable(
robot
[Link]
robot.h
[Link]
)
C++ basics – Multiple source files compilation
cmake, [Link]
• After finish the preceding commands as [Link], we must
create a new folder for building the project. You can choose any
name you want.
• $ mkdir build
• After creating the build folder, move yourself into the build folder,
then type the following command to generate the project-related
configuration file:
• $ cmake ..
C++ basics – Multiple source files compilation
cmake, [Link]
• After running the cmake.. command, if everything is fine, you
should receive the message shown in figure
C++ basics – Multiple source files compilation
cmake, [Link]
• The last step, after received cmake configuration from command
cmake next, you can build your entire project with the command
• $ make
• If everything work, you can execute the project such as:
• $ ./robot

You might also like