Robotics Programming (90+ New Hacks 2019)

Robotics Programming

Robotics Programming with 90+ New Hacks 2019

The next important requirement for working with a robot is to learn a few programming languages. By using these languages, we can program the robot for a different application. Some of the popular programming languages used for creating robotic applications are C++ and Python.

 

This doesn’t mean that we won’t use other languages. Programming languages like Java and C# are also used in robotics, but the most common languages are C++ and Python. This Tutorial explains the 90+ New Hacks for Robotics Programming that used in 2019. Also discusses the C++ and Python for creating robotic applications.

 

 

This post discusses some fundamental concepts of C++ and its compilation process. These concepts will definitely help you when you start working with ROS. The fundamentals include mainly object-­ oriented programming (OOP) concepts and compiling code using Make and CMake tools.

 

This post assumes that you have some fundamental understanding of C programming languages. So let’s get started with C++ fundamental.

 

C++ for Robotics Programming

Robotics Programming 2018

 

We can define C++ as a superset of the C programming language, or we can say “C with classes.” The C++ programming language project, initially called C with Classes, was started in 1979 by computer programmer Bjarne Stroustrup.

 

His main work was adding object-oriented programming into the C language by maintaining its portability without sacrificing speed or low-level functionality. Like C, C++ is a compiled language. It needs a compiler to convert the source code into executable code.

 

Timeline The C++ Language

In 1983, the C with Classes project changed to C++. The ++ operator is used for incrementing a variable, so C++ means it is the C language with new features. In 1990, Borland’s Turbo C++ compiler released as a commercial product.

 

In 1998, C++ standards were published as C++ ISO/ IEC 14882:1992 or C++98. In 2005, the C++ standards committee released a report of new features added to the latest C++ standard. In 2011, the new C++ standards were completed.

 

The Boost libraries (Boost C++ Libraries) made a considerable impact on the new standards. Boost C++ Libraries is a set of libraries for the C++ programming that provides support for tasks and structures, such as linear algebra, multithreading, image processing, regular expressions, and unit testing.

 

C/C++ in Ubuntu Linux

Ubuntu Linux comes with an in-built C/C++ compiler called GCC/G++. GCC stands for GNU Compiler Collection. It includes compilers for C, C++, Objective-C, Fortran, Ada, and Go, as well as libraries for these languages. GCC was written for the GNU Project by Richard Stallman.

 

Installing C/C++ Compiler

First, you may need to update the list of Ubuntu packages from the repository with the following command.

$ sudo apt-get update

Now install the packages for getting the compilers.

$ sudo apt-get install build-essential manpages-dev

The build-essential package is associated with numerous packages for developing software in Ubuntu Linux.

 

Verifying Installation

After installing the preceding package, you can verify whether the installation is correct by using the following commands.

$ whereis gcc
$ whereis g++

 

These commands locate the path of the gcc/g++ command and the manual page of the same command.

The following commands print the GCC compiler that we are going to use and display the path of the command.

$ which gcc

$ which g++

 

The following commands print the current version of GCC that we are going to use.

$ gcc version

$ g++ version

 

gcc

Introduction to GNU Project Debugger (GDB)

Let’s have a look at debugger tools for C/C++. So, what is a debugger? A debugger is a program that runs and controls another program, examining each line of code to detect problems or bugs.

 

The Ubuntu Linux comes with a debugger called GNU Debugger, which is also called GDB (GDB: The GNU Project Debugger). It is one of the popular C and C++ program debuggers for the Linux system.

 

Installing GDB in Ubuntu Linux

Here is the command to install GDB in Ubuntu. It’s already installed on the latest version of Ubuntu. If you are using other versions, you can use the following command to install it. $ SUDO apt-get install gdb

 

Verifying Installation

To check whether GDB is installed properly on your PC, use the following command. Once you type gdb in your terminal. $ gdb

 

You can verify the gdb version by using the following command.$ gdb version

The version also shows when you enter the gdb command. In the next section, we are going to write our first C++ code on Ubuntu. We will compile it and debug it to find bugs in the code.

 

Writing Your First Code

Let’s start writing the first program in Ubuntu Linux. To write the code, you can use a text editor in Ubuntu. You can choose either the gedit or nano terminal text editor. gedit is a popular GUI text editor in Ubuntu.

 

We already worked with nano in the first post, so now let’s check out gedit. In Ubuntu, search for gedit and select from the search results.

 

This editor is very similar to Notepad or WordPad in Windows. You can write your first C++ code in this text editor. the first C++ code that we are going to compile in the Linux. Write the code in the text editor and save it as hello_world.cpp.

 

Gedit

 

Explaining Code

The hello_world.cpp code is going to print the message, “Hello Ubuntu Linux”. #include <iostream> is a C++ header file for input/output functions, such as taking input from a keyboard or printing a message.

 

In this program, we are only using the print function to print messages, so iostream will be enough. The next line is using namespace std.

Explaining Code

The namespace is a special feature in C++ to group a set of entities. The std namespace is used in the iostream library. When we using namespace std, we can access the functions or other entities included in the std namespace, such as functions like cout and cin.

 

If we are not using this line of code, you have to mention std:: for accessing functions inside that namespace; for example, std::cout is a function to print a message.

 

After discussing the header file and other lines code, we can discuss what is included in the main function. We are using cout<<"Hello Ubuntu Linux"<<endl to print that message. The endl adds a new line after printing the message. After printing the message, the function returns 0 and exits the program.

 

Compiling Your Code

After saving your code, the next step is to compile the code. The following procedure will help you to compile the code. You can take a new terminal and switch the terminal path to the folder where the code is saved.

 

In this case, we have saved the code to /home//Desktop folder. To change the terminal path to the Desktop folder, you have to use the 'cd' command like shown below.

$ cd Desktop

If you have saved your code in the home directory, you don’t need to run this command. After switching to the Desktop folder, type ls to list the files in it.

$ ls

If your code is in the folder, you can do the compilation by using the following command.

$ g++ hello_world.cpp

The G++ compiler checks the code, and if there is no error, it creates an executable named a.out. You can execute this file by using the following command.

$ ./a.out

It shows the output as

 

Hello Ubuntu Linux

 

Hello Ubuntu Linux

 

Congratulations! You have successfully compiled and executed your first C++ code. Now let’s check some of the g++ options. This will be useful in the upcoming sections.

 

If you want to create an executable with a particular name, you can use the following command.

$ g++ hello_world.cpp -o hello_world

The -o argument points out the output executable name. So, the preceding command creates an executable named hello_world. You can execute it by using the following command.

$./hello_world

 

 

hello

Debugging Your Code

Using the debugger tool, we can go through each line of code and inspect the values of each variable. Figure 2-10 shows C++ code to compute the sum of two variables. Let’s save this code as sum.cpp.

 

To debug/inspect each line of code, you have to compile the sum.cpp using g++ with the -g option. This builds the code with debugging symbols and enables it to work with GDB.

 

The following command helps to compile the code with debug symbols.

$ g++ -g sum.cpp -o sum

After compiling, you can execute it by running the following command.

$. /sum

 

For debugging, use GDB. The output of the preceding set of commands is shown in Figure.

After creating the executable, you can debug the executable by using following the command.

$ gdb sum

the sum is the name of the executable. After entering the command, you have to use the GDB commands to proceed with debugging. The following are important GDB commands that you need to remember.

b line_numer: Creates a breakpoint in the given line number. While debugging, the debugger stops at this breakpoint.
n: Executes the next line of code.
r: Runs the program until the breakpoint.
p variable_name: Prints the value of a variable.
q: Exits the debugger.

 

debugger

Learning OOP Concepts from Examples

If you already know C structures, then learning about OOP concepts will not take much time. In C structures, we can group different data types— such as integer, float, and string—into a single, user-defined data type.

 

Similar to structures, C++ has an enhanced version of structs that have 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 concepts. The main OOP concepts are explained with C++ code next.

 

The Differences Between Classes and Structs

Before going through the OOP concepts, let’s look at the basic differences between a struct and a class.

 

Example Code to Demonstrate C++ Class and Struct

#include <iostream>
#include <string>
using namespace std;
struct Robot_Struct
{
int id;
int no_wheels;
string robot_name;
};
class Robot_Class
{
public:
int id;
int no_wheels;
string robot_name;
void move_robot();
void stop_robot();
};
void Robot_Class::move_robot()
{
cout<<"Moving Robot"<<endl;
}
void Robot_Class::stop_robot()
{
cout<<"Stopping Robot"<<endl;
}
int main()
{
Robot_Struct robot_1;
Robot_Class robot_2;
robot_1.id = 2;
robot_1.robot_name = "Mobile robot";
robot_2.id = 3;
robot_2.robot_name = "Humanoid robot";
cout<<"ID="<<robot_1.id<<"\t"<<"Robot Name"<<robot_1. robot_name<<endl;
cout<<"ID="<<robot_2.id<<"\t"<<"Robot Name"<<robot_2. robot_name<<endl;
robot_2.move_robot();
robot_2.stop_robot();
return 0;
}

 

This code defines a struct and a class. The struct name is Robot_Struct and the class name is Robot_Class.

It defines a struct with variables such as id, name, and the number of wheels. As you know, a struct has a name, and the declaration of all the variables are inside it. Let’s check the definition of a class.

 

So, what is the difference between the two? A struct can only define a different variable, but a class can define different variables and declare functions too. The class shown in Figure declares two functions along with the variables.

 

So where is the definition of each function? We can either define the function inside the class or outside the class. The standard practice is to keep the definition external to the class definition to keep the class definition short.

 

In the function definition, the first term is the return data type, followed by the class name, and then the function name followed by ::, which states that the function is inside the class.

 

Inside the function definition, we can add our code. This particular code prints a message. You have seen the function definition inside a class. The next step is to learn how to read/write to variables and functions.

 

C++ Classes and Objects

This section explains how to read/write to structs and classes. Similar to the struct instance, we can create an instance of a class and that is called an object.

 

Let’s look at Robot_Class robot_2; here, robot_2 is an object and robot_1 is an instance of the structure. Using this instance or object, we can access each variable and function.

 

We can use the . operator to access each variable. The struct and class variables are accessed by using the. operator. If you use struct or class pointers, you have to use the -> operator to access each variable.

 

Creating a C++ Object and Accessing Object by Reference

Robot_Class *robot_2;
robot_2 = new Robot_Class;
robot_2->id - 2;
robot_2->name = "Humanoid Robot";

 

The new operator allocates memory for the C++ object. We can access the functions inside the class and print all values by using them . operator. 

 

C++ Classes and Objects

We can save the code as class_struct.cpp, and compile it by using the following command.

$ g++ class_struct.cpp -o class_struct $. /class_struct

 

Class Access Modifier

Inside the class, you may have seen a keyword called public:. It is called an access modifier. This feature is also called data hiding. By setting the access modifier, we can limit the usage of functions defined inside it. There are three types of access modifiers in a class.

public: A public member can access from anywhere outside the class within a program. We can directly access the public variable without even writing functions.

 

private: Variables or functions cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members.

 

protected: Access is very similar to private members, but the difference is the child class can access the members. The concepts of child class/ derived class are discussed in the upcoming section.

Access modifiers help you group variables, which you can keep visible or hidden in the class.

 

[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]

 

C++ Inheritance

C++ Inheritance

Inheritance is another important concept in OOP. If you have two or more classes, and you want to have the functions inside those classes in a new class, you can use the inheritance property.

 

By using the inheritance property, you can reuse the function inside the existing classes in a new class. The new class that is going to inherit an existing class is called a derived class. The existing class is called a base class.

 

A class can be inherited through public, protected, or private inheritance. The following explains each type of inheritance.

Public inheritance: When we derive a class from a public base class, the public members of the base class become public members of the derived class, and protected members of the base class become protected members of the derived class.

 

The private members of the base class can never be accessed in the derived class. It can access through calls to the public and protected members of the base class.

 

Protected inheritance: When we inherit using the protected base class, the public and protected members of the base class become protected members of the derived class.

 

Private inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived class.

#include <iostream>
#include <string>
using namespace std;
class Robot_Class
{
public:
int id;
int no_wheels;
string robot_name;
void move_robot();
void stop_robot();
};
class Robot_Class_Derived: public Robot_Class {
public:
void turn_left();
void turn_right();
};
void Robot_Class::move_robot()
{
cout<<"Moving Robot"<<endl;
}
void Robot_Class::stop_robot()
{
cout<<"Stopping Robot"<<endl;
}
void Robot_Class_Derived::turn_left()
{
cout<<"Robot Turn left"<<endl;
}
void Robot_Class_Derived::turn_right()
{
cout<<"Robot Turn Right"<<endl;
}
int main()
{
Robot_Class_Derived robot;
robot.id = 2;
robot.robot_name = "Mobile robot";
cout<<"Robot ID="<<robot.id<<endl; cout<<"Robot Name="<<robot.robot_name<<endl;
robot.move_robot();
robot.stop_robot();
robot.turn_left();
robot.turn_right();
return 0;
}

So in this example, we are creating a new class called Robot_Class_ Derived, which is derived from a base class called Robot_Class. The public inheritance is done using a public keyword followed by the base class name. There should be a : after the derived class name, followed by a public keyword and a base class name.

 

If you chose public inheritance, you can access the public and protected variables and functions of the base class; in this case, ­Robot_Class. We are using the same class that we used in the first example.

 

Here we are creating an object of 'Robo_Class_Derived' called 'robot'. If you go through the code, you can understand that we didn’t declare id and robot_name variables in the Robo_Class_Derived, but it was defined in the Robo_Class. Using inheritance property, we can access the variable of Robo_Class inside its derived class.

 

Let’s look at the output of the code. We can save this code as class_ inherit.cpp and compile it by using the following command.

$ g++ class_inherit.cpp -o class_inherit ./class_inherit

 

 

output

We have covered some important OOP concepts.

 

C++ Files and Streams

Let’s discuss file operation in C++ and how to read/write data to a file. We have already discussed the iostream header for doing file operations. We need another standard C++ library called fstream. The following three data types are inside fstream.

ofstream: Stands for the output file stream. It is used to create a file and to write data into it.

ifstream: Represents an input file stream. It is used to read data from files.

fstream: Has both read and write capabilities.

 

Example C++ Code to Read/Write from a File

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream out_file;
string data = "Robot_ID=0"; cout<<"Write data:"<<data<<endl; out_file.open("Config.txt"); out_file <<data<<endl; out_file.close(); ifstream in_file; in_file.open("Config.txt"); in_file>> data;
cout<<"Read data:"<<data<<endl;
in_file.close();
return 0;
}

We have to include the fstream header to get the read/write data type in C++. We have created an ofstream class object, and in that object, there is a function called open () to open a file. After opening the file, we can write to it by using the << operator. After writing the data, we close the file for a reading operation.

 

For reading, we are using the ifstream class object in C++ and opening the file with the open("file_name") function inside the ifstream class. After opening the file, we can read from the file by using the >> operator.

 

After reading, it is printed on the terminal. The file name that we are going to write is Config.txt and the data is a robot parameter. You can see that Config.txt has been created in the Desktop folder.

 

Namespaces in C++

The namespace concept was mentioned earlier with the Hello World code. In this section, you learn how to create, where to use, and how to access a namespace. provides an example of creating and using two namespaces.

 

Example Code for C++ Namespaces

#include <iostream>
using namespace std;
namespace robot {
void process(void)
{
cout<<"Processing by Robot"<<endl;
}
}
namespace machine {
void process(void)
{
cout<<"Processing by Machine"<<endl;
}
}
int main()
{
robot::process();
machine::process();
}

 

To create a namespace, use the namespace keyword followed by name of the namespace. In Listing, we are defining two namespaces. If you go through the code, you see that the same function is defined inside each namespace. The namespaces are used to group a set of functions or classes that perform a unique action.

 

We can access the members inside the namespace using the name of the namespace followed by: and the function name. In this code, we are calling two functions inside the namespace, called robot and machine.

 

The code is saved as namespace.cpp.

 

 

namespace

 

C++ Exception Handling

Exception handling in C++ is a new method for handling circumstances in which there is an unexpected output in response to user input. The exception can happen during runtime. 

 

Example of C++ Exception Handling

#include <iostream>

using namespace std;
int main()
{
try
{
int no_1 = 1;
int no_2 = 0;
if(no_2 == 0)
{
throw no_1;
}
}
catch(int e)
{
cout<<"Exception found:"<<e<<endl;
}
}

exception

 

To handle an exception, we mainly use three keywords.

 

try: Inside the try block, we can write our code, which may raise an exception.

catch: If the try block raises an exception, the catch block catches the exception. We can decide what to do with that exception.

throw: We can throw an exception from the try block when the problem starts to show. If the throw statement is executed, it raises an exception and is caught by the catch block.

 

General Structure for Exception Handling

try
{
//Our code snippets
}
catch (Exception name)
{
//Exception handling block
}

 

The code is checking whether num_2 is 0. If num_2 is 0, an exception is raised by using the throw keyword with num_1, so the catch block can receive the num_1 value for inspecting. Inside the catch block, we print the exception value (i.e., the value of num_1, which is 1). Exception handling is widely using for easily debugging a program.

 

C++ Standard Template Libraries

If you want to work with data structures such as list, stacks, arrays, and so forth, it is best to look at the Standard Template Library (STL). STL provides the implementation of various standard algorithms in computer science, such as sorting and searching, and data structures like vectors, lists, and queue. This is an advanced C++concept.

 

Building a C++ Project

Now that you’ve learned some important OOP concepts, let’s have a look at how to build a C++ project. Just imagine, you have hundreds or thousands of lines of source code, and you need to compile and link it.

 

How do you do that? This section discusses that. If you are working with more than one source code, it is a good idea to review and use the following tools to compile and build your project.

 

Creating a Linux Makefile

A Linux makefile is a tool to compile one or more sources in a single command and build the executable. Let’s discuss a simple project to demonstrate the makefile capabilities.

 

We are going to write code for adding two numbers. For the addition, we first create a class. While working with the C++ classes, we write the declaration and definition of the class in the main source code.

 

Another approach is to declare and define the class in a header and .cpp file, and then include this header in the main code for getting that class. This approach is helpful in modularizing the entire project. So, our project has three files.

  • main.cpp: The main code that we are going to build.
  • add.h: The header file of the add class. It has a declaration of the class.
  • add.cpp: This file has the entire definition of the add class.

 

It is a good idea to use the class name as the name of the header and .cpp file. Here we create the add class so that the name of the header is added .h and add.cpp.

add.h
#include <iostream>
class add
{
public:
int compute(int no_1,int no_2);
};
add.cpp
#include "add.h"
int add::compute(int a, int b)
{
return(a+b);
}
main.cpp
#include "add.h"
using namespace std;
int main()
{
add obj;
int result = obj.compute(43,34); cout<<"The Result:="<<result<<endl; return 0;
}

 

make file

In the main.cpp we include the add.h header file to access the add class. We create an object of the add class, pass two numbers to the compute function and print the result.

 

We can compile and execute the code in Listing using the following command.

$ g++ add.cpp main.cpp -o main

$ ./main

 

The g++ command is easy to use for compiling a single source code, but if we want to compile several source codes, the g++ command is inconvenient. A Linux makefile is one way to compile multiple source codes in a single command. Listing 2-10 shows how to write a makefile for compiling the code.

 

A Linux Makefile

CC = g++
CFLAGS = -c
SOURCES = main.cpp add.cpp OBJECTS = $(SOURCES:.cpp=.o) EXECUTABLE = main
all: $(OBJECTS) $(EXECUTABLE)
$(EXECUTABLE) : $(OBJECTS)
$(CC) $(OBJECTS) -o $@
.cpp.o: *.h
$(CC) $(CFLAGS) $< -o $@
clean :
-rm -f $(OBJECTS) $(EXECUTABLE)
.PHONY: all clean


After saving the code in Listing as a makefile, you have to execute the following command to build it. $ make

After building using the make command, you can execute the program by using the following command. $. /main

 

Creating a CMake File

CMake (cmake.org) is another approach to building a C++ project. CMake stands for cross-platform makefile. It is an open source tool to build, test, and package software across multiple OS platforms.

 

Install CMake by using the following command.

$ sudo apt-get install cmake
After installing, you can save Listing as CMakeLists.txt.
Listing The CMakeLists.txt File
cmake_minimum_required(VERSION 3.0)
set(CMAKE_BUILD_TYPE Release)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
project(main)
add_executable(
main
add.cpp
main.cpp
)

The code is self-explanatory. It basically sets the C++ flags and creates an executable named main from the source code: add.cpp and main.cpp. The list of CMake commands is available at Documentation | CMake.

 

After saving the preceding commands as CMakeLists.txt, we have to create a folder for building the project. You can choose any name for the folder. Here, we use to build for that folder.

$ mkdir build

After building the folder, switch to the build folder and open the terminal from the build folder. Execute the following command from the build folder path.

$ cmake ..

 

This command parses CMakeLists.txt in the project path. The cmake command can convert CMakeLists.txt to a makefile, and we can build the makefile after that. Basically, it automates the process of making the Linux makefile. 

 

If everything is successful after executing the cmake .. command. 

After this, you can make the project by entering the make command ($ make).

 

If successful, you can execute the project executable ($. /main).

 

 

cmake

Python for Robotics Programming

Python for Robotics Programming

The last post discussed the fundamental concepts of C++ and the object-oriented programming concepts used to program robots. In this post, we look at the basics of the Python programming language, which can be used to program robots.

 

C++ and Python are the common languages used in robotics programming. If your preference is performance, then you should use C++, but if the priority is easiness in programming, you should go with Python.

 

For example, if you are planning to work with a robotic vision application, C++ is a good choice because it can execute the application faster by using less computing resources.

 

At the same time, that application can quickly prototype using Python, but it may take more computing resources. Basically, choosing a programming language for the robotics application is a trade-off between performance and development time.

 

Getting Started with Python

The Python programming language is a commonly used, general-purpose, high-level, object-oriented programming language popular for writing scripts. When compared with C++, Python is an interpreted language that executes code by line by line.

 

Python was created by Guido van Rossum who started development from 1989, and first internal release was in 1990. It is an open source software managed by the non-profit Python Software Foundation.

 

The main design philosophy of Python is the readability of code and syntax, which allows programmers to express their concepts in much fewer lines of code.

In robotics applications, Python is commonly preferred where less computation is required, such as writing data to a device using serial communication protocols, logging data from a sensor, creating a user interface, and so forth.

 

Timeline The Python Language

Here are the major milestones in the Python programming language:

  • The project started in 1989.
  • The first version was released in 1994.
  • The second version was released in 2000.
  • A popular version of Python, 2.7, was released in 2010.
  • The third version was released in 2008.
  • The latest version of Python, 3.6, was released in 2016.

 

Python in Ubuntu Linux

Let’s start programming Python in Ubuntu Linux. Like the GNU C/C++ compiler, Python interpreter is preinstalled in Ubuntu. The command shown in Figure opens the default Python version interpreter.

 

Python version interpreter

$ python

The default Python version is 2.7.12. You get a list of the installed Python version by pressing the Tab key twice after entering the Python command.

 

Here you see a list of Python commands for two different versions of Python: 2.7.12 and 3.5.2. The python, python2, and python2.7 commands launch version 2.7.12, and the remaining commands launch version 3.5.2. python3m and python3.5m are versions with pymalloc enabled, which performs better for memory allocation than the default memory allocation using malloc.

 

Installing Python on Ubuntu 16.04 LTS

As discussed, Python is preinstalled on Ubuntu, but the following command installs Python manually.

$ sudo apt-get install python python3

 

Verifying Python Installation

This section shows how to check the Python executable path and version. The following checks the current path of the python and python3 commands.

$ which python

$ which python3

 

If you want to see the location of Python binaries, sources, and documentation, use the following command.

$ whereis python
$ whereis python3.5

 

Writing Your First Code

Our first program will be printing a Hello World message. Let’s see how we can achieve it using Python. Before going into the programming, let’s look at the two ways in which we can program in Python.

  • Programming directly inside Python interpreter
  • Writing Python scripts and running using an interpreter

 

These two methods work in the same way. The first method executes line by line inside the interpreter. The scripting method writes all the code in a file and executes using the same interpreter.

 

The standard practice is to use Python scripting. We may use the Python interpreter shell for testing a few commands.

Let’s print a Hello World message in a Python interpreter shell, Simply use the print statement along with your message, and press Enter.

>>> print 'Hello World'

 

If you are doing the Hello World program in Python version >= 3.0, there are some changes in the Python statement. The main differences are found at https://wiki.python.org/moin/ Python2orPython3. Instead of the print statement used in Python2.x, the following statement is used in Python3.x for printing a message.

>>> 'print('Hello World')

 

Let’s start scripting using Python. With scripting, we write the code into a file with a .py extension.

hello

 

The standard way to write Python code is explained at ­PEP 8 -- Style Guide for Python Code. We are going to create a file called hello_world.py and write the code in the file. You can use the gedit editor or any text editor for this.

 

You may be wondering about the purpose of the extra lines in the script when compared to a print statement. There are certain standards to keep in the Python script in order to make it more readable, maintainable, and have all the information about the software that we made.

 

The first line (#!/usr/bin/env) in Python is called Shebang. If we execute the Python code, the program loader parses this line and executes the rest of the code using that environment. Here we are setting Python as the environment, so the rest of the code will execute in the Python interpreter.

 

There are coding styles suggested by Google at GitHub Pages.

Let’s look at how to execute the preceding code.

 

Running Python Code

You can save the hello_world.py in your home folder or in your Desktop folder. If you are in Desktop, you have to switch the path to Desktop.

The figure shows the execution of the hello_world.py code.

 

Currently, the code is in the Desktop folder, and you can execute the code by using the following command.

$ python hello_world.py

If your code does not have any errors

There is another way to execute the Python file. Use the following command.

$ chmod a+x hello_world.py

By using the chmod command, you are giving executable permission to the given Python code.

com/unix_commands/chmod.htm.

 

And after giving permission, you can simply execute the Python code using the following command.

$ ./hello_world.py

So you have seen how to write a Python script and execute it. Next, we discuss the basics of Python. This is actually a big topic, but we can discuss each aspect of Python by using examples to accelerate learning.

 

Understanding Python Basics

The popularity of the Python language is mainly due to its easiness in getting started. The code is short, and we can prototype an algorithm more quickly in Python than in other languages. Because of its popularity, there are a vast number of Python tutorials online. There are active communities to support you.

 

There are extensive libraries to implement your application. The availability of the Python library is one reason to choose this language over others. With a library, you can reduce development time by using existing functions.

 

Python is a cross-platform language that is widely used in research, networks, graphics, games, machine learning, data science, and robotics. Many companies use this language for automating tasks, so it is relatively easy to get a job in Python.

 

So how difficult is to learn this language? If you can write pseudocode for a task, then you can code in Python, because it is very similar to pseudo code.

 

What’s New in Python

If you know C++, it is easy to learn Python, but you have to be aware of a few things while writing Python code.

 

Static and Dynamic Typing

Python is a dynamic typing language, which means that we don’t need to provide the data type of a variable during programming; it takes each variable as an object. We can assign any kind of data type to a name. In C++, we have to first assign a variable with a data type, and then we can only assign that type of data to that variable.

 

C++ is a static typing language; for example, in C++, we can assign like this:

int number;
number = 10; //This will work
number = "10" // This will not work
But in Python, we can assign like this:
#No need mention the datatype
number = 10 #This will work
number = "10" #This will also work
So currently, the value of number is "10".

 

Code Indentation

Indentation is simply the tab or white space prior to a line of code. In C++, we may use indentation to group a block of code, but it is not mandatory. The C++ code compiles even if we are not keeping any indentation, but it is different in Python.

 

We should keep the block of code in the same indent; otherwise, it shows an indentation error. When indentation is mandatory, the code looks neat and readable.

 

Semicolons

In C/C++, semicolons at the end of each statement are mandatory, but in Python, they are not. You can use a semicolon in Python as a separator but not as a terminator; for example, if you want to write a set of code in a line, you can write it by separating semicolons. This can be done in C++ too.

 

Python Variables

You have already seen how Python handles variables. The figure shows assigning and printing primitive data types, such as int, float, and string. These examples are tested in Python version 2.7.12.

 

tuples

 

Similar to an array in C/C++, Python provides lists and tuples. The values inside a list can be accessed through a list index using square brackets ([]); for example, the first element in a list can be accessed by a [0] subscript, which is similar to an array in C/C++.

 

Tuples work similarly to lists, but a tuple is enclosed in parenthesis (()) and a list is enclosed in square brackets ([]). A tuple is a read-only list because its value can’t update once it is initialized, but in a list, we can update the value.

 

The next inbuilt data type Python provides is a dictionary. Similar to an actual dictionary, there is a key and a value associated with it. For example, in our dictionary, there is a word and the corresponding meaning of it. The word here is the key, and value is its meaning.

Python Variables

 

If we give the key in the dictionary, it returns the value associated with the key. In the next section, we look at the Python condition statement.

 

Python Input and Conditional statement

Similar to C++, Python also has if/else statements to check a condition. In the following example, you see how Python handles user input and makes a decision based on it.

 

The logic of the program is simple. The program asks the user to enter a command to move a robot. If the user enters a valid command, such as move_ left, move_right, move_forward, or move_backward, the program prints that it is moving; otherwise, it prints Invalid command.

 

To take input from a user in Python, we can use either the raw_input() function or the input() function. The raw_input() function accepts any kind of data type, but the input() function only accepts integer types. Here is the syntax of the raw_input() and the input() functions.

var = raw_input("Input message")

var = input("Input message")
raw_input() stores the user input in variable called var as a string. After storing the user input, we compare the input to a list of
commands. Here is the syntax for the if/else statement.
if expression1:
statement(s1)
elif expression2:
statement(s2)
else:
statement(s3)

 

Python Input and Conditional statement

 

A colon ends each expression, after which you have to use indentation for writing the statement. If you don’t use indentation, you will get an error.

 

Python Loops

Python has a while and for loops, but not do while loops, by default. Figure showcases the usage of the while loop and the for loop in Python. In this example, the robot position in the x and y-direction is incremented, and if it is reached in a particular position, the program terminates after printing a message.

 

The following shows the syntax of a while loop.

  • while expression:
  • statement(s)

 

In the preceding example, the expression is (robot_x < 2 and robot_y < 2).

There are two conditions inside the expression. We are performing AND logic between two conditions. In Python, 'and', 'or' are logic AND and logic OR. If the condition is true, the inside statements are executed.

 

As discussed earlier, we have to use proper indents on this block. When the expression is false, it quits the loop and prints the message 'Destination is reached'.

 

We can implement the same application using the for loop in Python.

In the preceding code, the for loop executes 0 to 100, increments robot_x and robot_y, and checks if the robot’s position is within limits. If the limit is exceeded, it prints the message and breaks them for a loop.

 

python loop

 

The following shows for loop syntax in Python.

for iterating_var in sequence:

statements(s)

 

Python Functions

As you know, if you want to repeat a block of code with different data, you can write it as a function. Most programming languages have a feature to define a function.

The following is the format to define a function in Python.

def function_name(parameter):

"function_docstring"

function_code_block

return [expression]

 

The order of a function definition in Python is important. The function call should be after the function definition. The docstring function is basically a comment with a description of the function and an example of the function’s usage. Comments in Python use # on a single line, but if the comment is in a block of code or a docstring, use the following style.

'''

<Block of code>

'''

you can see how to define a function in Python and how to call it. You may be confused with the usage of if __name__ == "__main__". It’s basically a common practice, like using int main() in C++. The program also works without this line.

 

If you enter any of the commands, it calls the appropriate function. The functions are defined at the top of the code. Also note the indentation in each block of code. The function defined in Figure does not have any arguments, but you can pass an argument to a function if you want.

 

Python Functions

Python Handling Exception

An exception is an event that disrupts the normal flow of a program’s instruction. When Python encounters a problem, it raises an exception. If we caught an exception, it means the program encountered an error.

 

If the code raises an exception, it can either handle the exception or terminate the program. In this section, we see how to handle an exception in Python.

 

A simple example of a try-except statement is pision by zero. Whenever the user input is zero, an exception is raised due to pision by zero, and that exception is handling statements inside except.

 

Python Handling Exception

 

Python Classes

This section shows how to write a class in Python. As discussed, Python is an object-oriented programming language like C++. The OOP concepts are the same in both languages. The following is the syntax for a class definition.

class ClassName:
'Optional class documentation string' class_suite

Here the docstring is an optional component and class_suite has the class members, data attributes, and functions. Class in Python is a vast concept.

 

The program simply prints a message; it does not actually move a robot. Let’s analyze each part of the program.

The following code is the constructor of the Python class. Whenever we create an object of this class, it executes first. self refers to the current object.

def __init__(self):
print "Started Robot"

 

The following function is the destructor of the class. Whenever an object is destroyed, the destructor is called.

def __del__(self):

print "Robot stopped"

 

We can define methods inside the class, which is how we define it. In all methods, the first argument should be self, which makes the function inside the class. We can pass arguments in a function; in the following example, distance is the argument.

def move_forward(self,distance):
print "Robot moving forward: "+str(distance)+"m"

 

In this function, there are functions to move back, right, and left. Now let’s see how to create an object of the class. The following line creates the object. When an object is created, the constructor of the class is called.

obj = Robot()

After initializing, we can call each function inside the class by using the following method.
obj.move_forward(2)
obj.move_backward(2)
obj.move_left(2)
obj.move_right(2)

 

When the program terminates, the object calls the destructor.

python class

 

In the next section, we learn how to handle files in Python.

 

Python Files

Writing and reading from a file is important in a robotics application. You may have to log data from a sensor or write a configuration file. This section provides an example program to write and read the text to a file. When we run the code, it asks to enter text. The text data save to a file, and later it reads and prints on the screen. The explanation of Python code is given below.

 

The following command creates the file handler in reading and writing mode. Like C/C++, there are several file operation modes, such as reading, writing, and appending. In this case, we are using w+ mode, in which we can read/write to a file. If there is an existing file, it is overwritten.

file_obj = open("test.txt","w+")
To write to a file, we can use the following command. It writes text into the file.
file_obj.write(text)
To close the file, we can use following statement.
file_obj.close()
To read the file again, we can use 'r' mode, like in the following statement.
file_obj = open("test.txt",'r')
To read a line from a file, we can use readline() function.
text = file_obj.readline()

 

 

python file

 

 

 

Python Modules

C++ uses header files to include a new class or a set of classes. In Python, instead of header files, we use modules. A module may contain a class, a function, or variables. We can include the module in our code using the import command. The following is the syntax of the import statement. import <module_name>

 

Example: import os; import sys

These are the standard modules in Python. If there is a list of classes in a module, and we want only a specific class, we can use the following line of code. from <module_name> import <class_name> Example: from os import system

 

A module is Python code, but we can create our own modules too. The figure shows a test module, which can be imported into our code and execute the function inside it. The http://test.py file has a function called execute() that prints the text passing as a function argument.

 

A line of code in Python interpreter shows how to use the test module. It should be noted that the http://test.py file should be in the same path as the program or in the Python shell; for example, if http://test.py is in the Desktop folder, the current path of the shell should also be in the same folder.

 

When testing, we import the test module by using the import statement.

We create an object called obj by using the following statement.

obj = test.Test()

 

This accesses the Test() class inside the test module. After creating the object, we can access the execute() function.

Python Modules

Python Handling Serial Ports

When we build robots, we may have to interface various sensors or microcontroller boards to a laptop or to single board computers such as the Raspberry Pi. Most of the interfacing is through USB or UART communication.

 

Using Python, we can read/write to a serial port on the PC. This helps with reading data from sensors/actuators and writing control commands to the actuators.

 

Python has a module called PySerial to communicate with the serial port/com port on a PC. This module is very easy to use. Let’s look at how to read/write to a serial port in Ubuntu using Python.

 

Installing PySerial in Ubuntu 16.04

Installing PySerial is a very easy task in Ubuntu. Just follow these commands to install it:

  • $ sudo apt-get update
  • $ sudo apt-get install python-serial

 

After installing the module, plug in your serial device; it can be a USB-to-serial device or an actual serial device. The USB-to-serial device converts the USB protocol to the UART protocol. The following are the two most popular USB-to-serial chips available on the market.

FTDI: www.ftdichip.com

Prolific: www.prolific.com.tw/US/company.aspx?id=1

 

When you plug in the devices with these chips in the Linux based system, it automatically loads the device driver and creates a serial device. The FTDI and Prolific device drivers are available in the Linux kernel. You get the serial device name by executing the dmesg command. This command shows the kernel message.

 

$ dmesg

When you plug the serial device to the PC and execute dmesg, you see the serial device name. In this case, it is /dev/ttyUSB0.

To communicate with the device, you may have to change the device permission. You can either use chmod to change the permission or you can add the current user to the dialout group, which gives access to the serial port.

 

Change the permission of the serial device.

$ sudo chmod 777 /dev/ttyUSB0

Add a user to the dialout group.

$ sudo adduser $USER dialout

 

In the preceding code, you can see the importing serial module by using the following code.

import serial

The following is the command to open the serial port with the given baud rate.

ser = serial.Serial('/dev/ttyUSB0',9600)

The following is the command to write to the serial port.ser.write('Hello')

The following is how to read from the serial port. text = ser.readline()

You could also use the following command.

text = ser.read() #This will read 1 byte of data text = ser.read(10) # read 10 bytes of serial data

The preceding code can interact with Arduino, Raspberry Pi, and other serial sensor devices. 

 

Python Scientific Computing and Visualization

In this section, you learn about some of the popular Python libraries for scientific computing and visualization.

Numpy (NumPy - NumPy): The fundamental package for scientific computing.

Scipy (SciPy.org - SciPy.org): An open-source software for mathematics, science, and engineering.

Matplotlib (Python plotting - Matplotlib 2.2.3 documentation): A Python 2D plotting library that produces publication-quality figures.

 

Python Machine Learning and Deep Learning

Python is very famous for implementing machine learning and deep learning. The following are the popular libraries in Python.

 

TensorFlow (www.tensorflow.org): An open source library for numerical computation using data flow graphs.

Keras (Keras Documentation): A high-level, neural networks API that is capable of using TensorFlow, Theano as a back end.

Caffe (Caffe | Deep Learning Framework): A deep learning framework developed by Berkeley AI Research and community contributors.

 

Theano (http://deeplearning.net/software/ theano/): A Python library that allows you to efficiently define, optimize, and evaluate mathematical expressions involving multi-dimensional arrays.

 

Scikit-learn (scikit-learn: machine learning in Python): A simple machine learning library in Python.

 

Python Computer Vision

There are two popular computer vision libraries compatible with Python.

 

OpenCV (OpenCV library): Open Source Computer Vision is free for academic and commercial use. It has C++, C, Python, and Java interfaces and supports Windows, Linux, Mac OS, iOS, and Android.

 

PIL (Python Imaging Library (PIL)): Python Imaging Library adds image processing capabilities to your Python interpreter.

 

Python Robotics

Python has a good interface for robotics programming using ROS. You can explore more about the capabilities of Python using ROS at ­http://wiki. ros.org/rospy.

 

Python IDEs

There are some popular IDEs (integrated development environments) that make development and debugging faster. The following are three common IDEs.

PyCharm: www.jetbrains.com/pycharm/
Geany: www.geany.org
Spyder: Spyder IDE

 

Summary

This post discussed the fundamentals of Python programming in Ubuntu Linux. Knowledge of Python programming is a prerequisite for working with ROS. We started with the Python interpreter in Ubuntu and saw how to work with it. After working with the interpreter, we saw how to create a Python script and run it on Ubuntu.

 

Then we discussed the fundamentals of Python, such as handling input, output, Python loops, functions, and class operations. After these topics, we saw how to communicate with a serial device using a Python module.

 

At the end of the post, we covered Python libraries for scientific computing, machine learning, deep learning, and robotics.

Recommend