MATLAB Cookbook – Code Examples for the Most Common Tasks

In this post, I will write example code for the most common things you’ll do in MATLAB. MATLAB is a software package used for numerical computation and visualization.

My goal is to write bare-bones, skeleton recipes that can be easily modified and adapted to your own projects.

Prerequisites

  • You have MATLAB installed on your computer. I’m using MATLAB Release 2020a.

Select a Current Directory

Open MATLAB.

In the command window, select your desired Current Folder (i.e. working directory). The syntax is:

cd 'path_to_folder'

For example., in the Command Window, you would type the following command and press Enter in your keyboard:

cd 'C:\Program Files\My_Documents'

Create New Scripts

To create a new script (i.e. the most basic Matlab file with the ‘.m’ extension), run the following command in the Command window.

edit matlab_cookbook_1.m

If this is your first time creating a file in MATLAB, you might see a prompt that asks you “Do you want to create it?”

Highlight “Do not show this prompt again,” and click Yes.

Accept User Input

Write the following code inside matlab_cookbook_1.m.

% Get rid of blank lines in the output
format compact

% Accept a string as input
% Semicolon prevents every variable and output from appearing
% in the command window
name = input("What's your first name : ", "s");

% Check if the user entered something as input
if ~isempty(name)
    fprintf("Hi %s\n", name) 
end

Save the code.

Click Run to run the code.

Type in your name into the Command Window.

Press Enter.

Here is the output:

2-user-input-output

To stop a script from running at any time, you can type CTRL+C.

Now, let’s create a new file named matlab_cookbook_2.m.

edit matlab_cookbook_2.m

Add the following code:

% Get rid of blank lines in the output
format compact

% Accept vector input
vector_input = input("Enter a vector : ");

% Display the vector to the Command Window
disp(vector_input)

Click Run.

Enter your vector. For example, you can enter:

[1 2 3]

Here is the output:

3-enter-your-vector

Declare and Initialize Variables and Data Types

Let’s work with variables and data types (i.e. classes).

Create a new script.

edit matlab_cookbook_3.m

Type the following code.

format compact

% Initialize a character variable
char_1 = 'A'

% Determine the class of a character
class(char_1)

% Initialize a string variable
str_1 = "This is a string"

% Determine the class
class(str_1)

% Evaluate a boolean expression
5 > 2

% Initialize a boolean varable to true
bool_1 = true

% Initialize a boolean variable to false
bool_2 = false

% Check out the maximum and minimum values that can be 
% stored in a data type
intmin('int8')
intmax('int8')

% See the largest double value that can be stored
realmax

% See the largest integer that can be stored
realmax('single')

Run it.

Here is the output:

4-matlab-cookbook3-output1
4-matlab-cookbook3-output2

How do you create an expression that spans more than one line?

Open a new script.

edit matlab_cookbook_4.m
format compact

% An expression that spans more than one line
var_1 = 5 + 5 + 1 ...
      + 1

Save and then run the code. 

5-matlab-cookbook4-output

Casting Variables to Different Data Types

Let’s explore how to cast variables to different data types.

Create a new script.

edit matlab_cookbook_5.m

Type the following code.

format compact

% Create a double (double is the default)
var_1 = 9

% Output the data type
class(var_1)

% Caste the double to an int8 data type
var_2 = int8(var_1)

% Check that the variable was properly converted
class(var_2)

% Convert a character to a double
var_3 = double('A')

% Convert a double to a character 
var_4 = char(64)

Run it.

Here is the output:

6-matlab-cookbook5-output

Formatting Data into a String

Let’s explore how to format data into a string.

Create a new script.

edit matlab_cookbook_6.m

Type the following code.

format compact

% Format output into a string.
% Sum should be a signed integer - %d
sprintf('9 + 2 = %d\n', 9 + 2)

% Format output into a string.
% Sum should be a float with two decimal places
sprintf('9 + 2 = %.2f\n', 9 + 2)

Run it.

Here is the output:

7-matlab-cookbook6-output

Basic Mathematical Operations

Let’s explore how to do basic mathematical operations in MATLAB.

Create a new script.

edit matlab_cookbook_7.m

Type the following code.

% Supress the display of blank lines
format compact 

% Display formatted text
% Addition
fprintf('9 + 2 = %d\n', 9 + 2)

% Subtraction
fprintf('9 - 2 = %d\n', 9 - 2)

% Multiplication
fprintf('9 * 2 = %d\n', 9 * 2)

% Display float with two decimal places
fprintf('9 * 2 = %0.2f\n', 9 / 2)

% Exponentiation
fprintf('5^2 = %d\n', 5^2)

% Modulus
fprintf('5%%2 = %d\n', mod(5,2))

% Generate a random number between 50 and 100
randi([50,100]) 

Run it.

Here is the output:

8-matlab-cookbook7-output

Basic Mathematical Functions

Let’s take a look at some basic mathematical functions in MATLAB.

Create a new script.

edit matlab_cookbook_8.m

Type the following code.

format compact

% This code has some basics mathematical functions
% in MATLAB

% Absolute Value
fprintf('abs(-7) = %d\n', abs(-7))

% Floor
fprintf('floor(3.23) = %d\n', floor(3.23))

% Ceiling
fprintf('ceil(3.23) = %d\n', ceil(3.23))

% Rounding
fprintf('round(3.23) = %d\n', round(3.23))

% Exponential (e^x)
fprintf('exp(1) = %f\n', exp(1)) 

% Logarithms
fprintf('log(100) = %f\n', log(100))
fprintf('log10(100) = %f\n', log10(100))
fprintf('log2(100) = %f\n', log2(100))

% Square root
fprintf('sqrt(144) = %f\n', sqrt(144))

% Convert from degrees to radians
fprintf('90 Deg to Radians = %f\n', deg2rad(90))

% Convert from radians to degrees
fprintf('pi/2 Radians to Degrees = %f\n', rad2deg(pi/2))

%%%% Trigonometric functions%%%
% Sine of argument in radians
fprintf('Sine of pi/2 = %f\n', sin(pi/2))

% Cosine of argument in radians
fprintf('Cosine of pi/2 = %f\n', cos(pi/2))

% Tangent of argument in radians
fprintf('Tangent of -pi/4 = %f\n', tan(-pi/4))

Run it.

Here is the output:

9-matlab-cookbook8-output

To see a big list of the built-in mathematical functions, you can type the following command:

help elfun

Relational and Logical Operators

Create a new script.

edit matlab_cookbook_9.m

Type the following code.

format compact

%{ 
Relational Operators: 
  -- Greater than >
  -- Less than < 
  -- Greater than or equal to >=
  -- Less than or equal to <=
  -- Equal to ==
  -- Not equal to ~=

Logical Operators: 
  -- OR || 
  -- AND &&
  -- NOT ~
%} 

% Example
age = 19

if age < 18
    disp("You are not in college yet")
elseif age >= 18 && age <= 22
    disp("You are a college student")
else
    disp("You have graduated from college")
end   

Run it.

Here is the output:

10-matlab-cookbook9-output

Now, let’s work with switch statements.

edit matlab_cookbook_10.m

Here is the output:

format compact

size = 12

switch size
    case 2
        disp("Too small")
    case num2cell(3:10) % If number is between 3 and 10, inclusive
        disp("Just right")
    case {11, 12, 13, 14} % If number is any of these numbers
        disp("A bit large")
    otherwise
        disp("Too big")
end  

Vectors

edit matlab_cookbook_11.m

Here is the output:

format compact

% Create a vector
vector_1 = [6 9 1 3 8]

% Calculate the length of the vector
vector_1_length = length(vector_1)

% Sort a vector in ascending order
vector_1 = sort(vector_1)

% Sort a vector in descending order
vector_1 = sort(vector_1, 'descend')

% Create a vector that has the numbers 3 through 9
vector_2 = 3:9

% Create a vector of numbers from 10 through 15 in steps of 0.5
vector_3 = 10:0.5:15

% Concatenate vectors
vector_4 = [vector_2 vector_3] 

% Get the first item in the vector above. Indices start at 1.
vector_4(1)
edit matlab_cookbook_12.m
format compact

% Create a vector
vector_1 = [6 9 1 3 8]

% Get the last value in a vector
last_val_in_vector = vector_1(end)

% Change the first value in a vector
vector_1(1) = 7

% Append values to end of vector
vector_1(6) = 99

% Get the first 3 values of a vector
vector_1(1:3)

% Get the first and second value of a vector
vector_1([1 2])

% Create a column vector
col_vector_1 = [6;9;1;3;8]

% Multiply a column vector and a row vector
vector_mult = col_vector_1 * vector_1

% Take the dot product of two vectors
% 2 * 5 + 3 * 9 + 4 * 7 = 65
vector_2 = [2 3 4]
vector_3 = [5 9 7]
dot_product_val = dot(vector_2, vector_3)

Here is the output:

13-matlab-cookbook12-output

Matrix Basics

edit matlab_cookbook_13.m
format compact

% Initialize a matrix
matrix_1 = [4 6 2; 6 3 2]

% Get the number of values in a row
num_in_a_row = length(matrix_1)

% Get the total number of values in a matrix
num_of_vals = numel(matrix_1)

% Size of matrix (num rows   num cols)
matrix_size = size(matrix_1)

[num_of_rows, num_of_cols] = size(matrix_1)

% Generate a random matrix with values between 20 and 30
% Matrix has two rows.
matrix_2 = randi([20,30],2)

% Modify a value inside a matrix (row 1, column 2)
% Remember matrices start at 1
matrix_2(1, 2) = 33

% Modify all row values in the first row
matrix_2(1,:) = 26

% Modify all column values in the first column
matrix_2(:,1) = 95

% Get the first value in the last row
first_val_last_row = matrix_2(end, 1)

% Get the second value in the last column
second_val_last_col = matrix_2(2, end)

% Delete the second column
matrix_2(:,2) = [];

Loops

For loops

edit matlab_cookbook_14.m
format compact

% Loop from 1 through 5
for i = 1:5
    disp(i) % Display
end

% Add a space
disp(' ')

% Decrement from 5 to 0 in steps of 1
for i = 5:-1:0
    disp(i)
end

% Add a space
disp(' ')

% Loop from 1 through 3
for i = [1 2 3]
    disp(i)
end

% Add a space
disp(' ')

% Create a matrix
matrix_1 = [1 4 5; 6 2 7];

% Nested for loop to run through all values in a matrix
for row = 1:2
    for col = 1:3
        disp(matrix_1(row, col))
    end
end

% Go through an entire vector
vector_1 = [2 8 3 5]
for i = 1:length(vector_1)
    disp(vector_1(i))
end

Output:

14-matlab-cookbook14-output

While loops

edit matlab_cookbook_15.m
format compact

% Create a while loop
i = 1
while i < 25
    % If the number is divisible by 5
    if(mod(i,5)) == 0
        disp(i)
        i = i + 1;
        continue
    end
    % Else
    i = i + 1;
    if i >= 14
        % Prematurely leave the while loop
        break
    end
end

Output:

15-matlabcookbook15-output

Matrix Operations

edit matlab_cookbook_16.m

Here is the first part of the output.

format compact

% Initialize a 3x3 matrix
matrix_1 = [4 6 2; 3 6 14; 5 2 9]

matrix_2 = [2:4; 7:9]
matrix_3 = [5:7; 9:11]
matrix_4 = [1:2; 3:4; 2:3]

% Add two matrices together
matrix_2 + matrix_3

% Multiply corresponding elements of two matrices together
matrix_2 .* matrix_3

% Multiply two matrices together
matrix_2 * matrix_4

% Perform the square root on every value in a matrix
sqrt(matrix_1)

% Double everything in a matrix
matrix_2 = matrix_2 * 2

% Sum everything in each column
sum(matrix_2)

% Convert a matrix to a boolean array
% Any value greater than 5 is 1
greater_than_five = matrix_1 > 5

Cell Arrays

edit matlab_cookbook_17.m
format compact

% Create a cell array
cell_array_1 = {'Automatic Addison', 25, [6 32 54]}

% Preallocate a cell array to which we will later assign data
cell_array_2 = cell(3)

% Get the first value in the cell array
cell_array_1{1}

% Add more information 
cell_array_1{4} = 'John Doe'

% Get the length of the cell array
length(cell_array_1)

% Display the values in a cell array
for i = 1:length(cell_array_1)
    disp(cell_array_1{i})
end

Here is the output:

17-matlabcookbook17-output

Strings

edit matlab_cookbook_18.m

format compact

% Initialize a string
my_string_1 = 'Automatic Addison'

% Get the length of the string
length(my_string_1)

% Get the second value in the string
my_string_1(2)

% Get the first three letters of the string
my_string_1(1:3)

% Concatenate
longer_string = strcat(my_string_1, ' We''re longer now')

% Replace a value in a string
strrep(longer_string, 'now', 'immediately')

% Split a string based on space delimiter
string_array = strsplit(longer_string, ' ')

% Convert an integer to a string
num_string = int2str(33)

% Convert a float to a string
float_string = num2str(2.4928)

Here is the output:

18-matlabcookbook18-outputJPG

Structures

Here is how to create your own custom data type using structures. Structures consist of key-value pairs (like a dictionary).

edit matlab_cookbook_19.m
format compact

automatic_addison = struct('name', 'Automatic Addison', ...
    'age', 35, 'item_purchased', [65 23])

% Get his age
disp(automatic_addison.age)

% Add a field
automatic_addison.favorite_food = 'Oatmeal'

% Remove a field
automatic_addison = rmfield(automatic_addison, 'favorite_food')

% Store a structure in a vector
clients(1) = automatic_addison

Here is the output:

19-matlabcookbook19-output

Tables

edit matlab_cookbook_20.m
format compact

name = {'Sam'; 'Bill'; 'John'};
age = [32; 52; 19];
salary = [45000; 90000; 15000]
id = {'1', '2', '3'}

% The name of each row will be the id
employees = table(name, age, salary, ...
    'RowName', id)

% Get the average salary
avg_salary = mean(employees.salary)

% 'help table' command helps you find what you can do with tables

% Add a new field
employees.vacation_days = [10; 20; 15]

Here is the output:

20-matlabcookbook20-output

File Input/Output

edit matlab_cookbook_21.m
format compact

% Generate a random 8x8 matrix
random_matrix = randi([1,5],8)

% Save the matrix as a text file
save sample_data_1.txt random_matrix -ascii

% Load the text file
load sample_data_1.txt

disp sample_data_1 

type sample_data_1.txt

Here is the output:

21-matlabcookbook21-output

Functions

edit matlab_cookbook_22.m
format compact

% Input vector
values = [9.7, 63.5, 25.2, 72.9, 1.1];

% Calculate the average and store it
mean = average(values)

% Define a function named average.m that 
% accepts an input vector and returns the average
function ave = average(x)
    % Take the sum of all elements in x and divide 
    % by the number of elements
    ave = sum(x(:))/numel(x); 
end

Here is the output:

22-matlabcookbook22-output

Creating a Plot

edit basic_plot.m
% Graph a parabola
x = [-100:5:100];
y = x.^2;
plot(x, y)

Here is the output:

23-basic-plotJPG

How to Build a DIY Aluminium 6-DOF Robotic Arm From Scratch

In this tutorial, we will build a robotic arm with six degrees of freedom from scratch. A degree of freedom is the number of variables needed to fully describe the position and orientation of a system (e.g. x, y, z, and rotation about each of those axes in the case of our robotic arm).

Our goal is to build an early prototype of a product to make it easier and faster for factories, warehouses, and food processing plants to pick up objects and place them into boxes (i.e. pick and place).

I modeled the robot in a CAD (Computer-aided design) program called Creo Parametric. Here are the STL files.

robotic_arm_6dof_creo_parametric_6_0_cad_2

Real-World Applications

Robotic arm systems have a number of real-world applications. Here are just a few examples: 

  • Warehouses and Logistics
  • Grocery Stores
  • Hospitals and Medical Centers
  • Military
  • Food Processing Plants
  • And more…

Let’s get started!

Prerequisites

  • No prior knowledge necessary. We’ll build everything from the ground up.

You Will Need

This section is the complete list of components you will need for this project.

Directions

Let’s assemble the robotic arm. Follow the steps carefully, and take your time to make sure everything is set up properly. It took me almost a week to assemble the arm. Go slowly.

The instructions for assembling the arm come inside the package, but let’s walk through the process anyways.

Unpack the Robotic Arm Kit

Open the robotic arm kit. Lay out all the components on a table. You should have the following pieces of hardware:

2020-05-15-130141
  • 1 x Aluminum Clamp Claw
  • 1 x L-type Servo Bracket
  • 3 x U-type Robot Waist Bracket
  • 4 x Long U-type Servo Bracket
  • 4 x Miniature Ball Radial Bearing
  • 5 x Multi-functional Servo Bracket
  • 6 x MG996R Servo
  • 6 Sets x Aluminum Servo Horns
  • 4 Sets x Round Head M3*10 Screws and M3 Nuts (The 10 means 10mm in length, including the head)
  • 20 Sets x Round Head M3*8 Screws and M3 Nuts 
  • 24 Sets x Fixed Head M4*10 Screws and M4 Nuts (I never used these)
  • 30 Sets x Round Head M3*6 Screws and M3 Nuts
  • *Note: The kit that I have didn’t have labels on the screws, making it tricky to figure out what screws to use at what stage. Just use screws and nuts that can fit into the hole when the time comes. Don’t sweat over the exact type of screw I mention in this tutorial. The end goal is to make sure every part is secure.

Assemble the Base

Grab 6 x M3*8 screws and nuts (these are the screws that are 8mm long from the top of the head to the base of the screw)..

Using a screwdriver (helpful to use needle-nose pliers to hold the nut in place as you screw in the screws and nuts), connect two of the U-type robot waist brackets together using the M3*8 screws and nuts.

2020-05-15-184837
2020-05-16-112416

Grab the third U-type robot bracket, and attach it to one side of the base using six M3*8 screws and nuts.

2020-05-16-135056

Install the First Servo Motor

Grab one M3*10 screw, nut, and a bearing.

Grab one Multi-functional servo bracket.

2020-05-17-133726

Place a screw through the hole. It might have a bit of trouble fitting through the hole, so make sure you apply enough force to snap it through there.

2020-05-17-134051

Insert the bearing over the screw, with the wide end of the bearing touching the Multi-functional servo bracket.

Insert the nut over the screw in order to hold the bearing in place. 

Tighten the screw with a 7/32 inch wrench.

2020-05-17-135137

Now we need to attach the Multi-functional servo bracket to that U-type bracket that was mounted on top of the robot base. Use four M3*6 screws and nuts to do this job.

2020-05-17-142815

Take one of your servo motors outside of its bag.

Mount it over the two arms of the Multi-functional servo bracket. Make sure the motor is mounted just as you see it here. We will call this servo motor the steering servo.

2020-05-18-082351

Get four M3*8 screws and nuts (the fattest screws and nuts in the kit). Use these to secure the steering servo into place. 

I recommend holding the nut in place with one of your fingers or the needle-nose pliers and using a Phillips screwdriver to tighten the screw inside the nut. 

2020-05-18-083951

Here is how your setup should look at this stage.

2020-05-18-085055

Grab one of the plastic rocker arms. It should be inside the bag that had your servo motor.

Insert the rocker arm on top of the steering servo. The grooves of the steering servo should fit nicely with the grooves of the rocker arm.

The rocker arm should be placed perpendicular across the steering servo axis (i.e. that golden, grooved metal circle on top of the steering servo).

2020-05-18-090425

Now take your finger and move the rocker arm to the left and to the right.

Take note of where the rocker stops turning when you twist the rocker arm to the left side with your fingers.

Now take note of where the rocker arm stops turning on the right side.

Reposition the rocker arm so that it is perpendicular across the steering servo when the underlying steering servo axis is exactly at the halfway point between the left and right stopping points that you just marked.

2020-05-18-091312

After you have adjusted the angle of the steering servo axis using the rocker arm, grab the servo horn.

Carefully remove the rocker arm by pulling it straight up off the steering servo axis. You want to be careful not to move the steering servo axis.

Fit the servo horn on top of the steering servo axis so that it looks like this. One of the holes of the servo horn should point straight forward.

2020-05-18-092712

Twist the servo horn from right to left. The rotation range should be 0-225°.

Once you are sure that the servo horn is positioned properly over the steering servo axis, secure it into place by placing a screw in the center.

2020-05-18-092717

Grab one of the long U-type brackets.

Slip the hole of the U-type bracket over the bearing underneath the servo motor.

2020-05-18-100142

Slip the other end of the U-type bracket over the top of the servo motor. The big hole of the U-type bracket should be over the screw.

2020-05-18-100338

Grab a small screw.

Place the screw in one of the small holes of the long U-type bracket. Don’t tighten too hard at this stage.

2020-05-18-100359

Move the U-type bracket from left to right. Make sure it can touch each side of that third U-type robot waist bracket.

Now, remove the screw you just put in.

2020-05-18-102150

Install the Second Servo Motor

Grab a bearing, a long screw, and a nut.

Grab a Multi-functional servo bracket.

2020-05-19-112304

Secure the bearing on the Multi-functional servo bracket using the screw and the nut.

2020-05-19-113447

Grab four M3*6 screws.

Use the screws to secure the Multi-functional servo bracket on top of the long U-type servo bracket.

2020-05-19-114506

Grab another servo. This servo will be called the arm servo since it is responsible for raising and lowering the robotic arm.

2020-05-19-114731

Place it into the Multi-functional servo bracket.

Secure the servo into place with four fat screws (M3*8) and nuts. I recommend using needle-nose pliers to hold the nut steady while you use a Phillips screwdriver to tighten the screw.

2020-05-19-115625

Grab one of the plastic rocker arms. It should be inside the bag that had your servo motor.

Insert the rocker arm on top of the steering servo. The grooves of the steering servo should fit nicely with the grooves of the rocker arm. 

The rocker arm should be placed perpendicular across the steering servo axis (i.e. that golden, grooved metal circle on top of the steering servo).

Now take your finger and move the rocker arm to the left and to the right. 

Take note of where the rocker stops turning when you twist the rocker arm to the left side with your fingers.

Now take note of where the rocker arm stops turning on the right side.

Reposition the rocker arm so that it is perpendicular across the steering servo when the underlying steering servo axis is exactly at the halfway point between the left and right stopping points that you just marked.

After you have adjusted the angle of the steering servo axis using the rocker arm, grab the servo horn.

2020-05-19-120733

Carefully remove the rocker arm by pulling it straight up off the steering servo axis. You want to be careful not to move the steering servo axis.

Fit the servo horn on top of the steering servo axis so that it looks like this. One of the holes of the servo horn should point straight forward.

Twist the servo horn from right to left. The rotation range should be 0-225°.

Once you are sure that the servo horn is positioned properly over the steering servo axis, secure it into place by placing a screw in the center.

2020-05-19-121511

Grab one of the long U-type brackets.

Slip the hole of the U-type bracket over the bearing on one side of the Multi-functional bracket.

Slip the other end of the U-type bracket over the top of the servo motor. The big hole of the U-type bracket should be over the screw.

2020-05-19-121620

Grab four M3*6 screws.

Place the four screws over the small holes of the long U-type bracket.

Move the U-type bracket from left to right. Make sure it has a full range of motion. It should hit the first U-type bracket when you twist it to the right. That is fine.

2020-05-19-122446

Now, we are going to attach a long U-type servo bracket to the U-type bracket you just secured.

Grab a long U-type servo bracket and four M3*6 screws and nuts.

Your robotic arm should have a full range of motion, backward and forwards.

2020-05-20-145630

Install the Elbow

Now, we need to install the elbow.

Grab the L-type servo bracket, a Mult-functional servo bracket, a bearing, an M3*10 screw, and a nut.

2020-05-20-150252

Attach the bearing to the Multi-functional servo bracket using the M3*10 screw and nut.

2020-05-20-150749

Grab two M3*6 screws and nuts. If you’ve run out of M3*6 screws, just use screws and nuts in the kit that are able to fit through the holes. Sometimes the kits don’t have all the screws you need, and it doesn’t help that the kit that I received came with unlabeled screws.

Attach the L-type servo bracket to the Mult-functional servo bracket as shown in the image below. Use the two screws and nuts.

2020-05-20-152217

Grab the last long U-type bracket.

2020-05-21-114542

Use two M3*6 screws and nuts to secure the U-type bracket to the L-type bracket.

2020-05-21-115308

Grab a servo motor.

Place the servo motor into the Mult-functional servo bracket.

Secure the servo motor into the Multi-functional servo bracket with four M3*8 screws and nuts. Again, don’t worry if you don’t have enough M3*8 screws and nuts. The goal is to use screws and nuts to secure the servo motor into the holder.

2020-05-21-120040

Grab one of the plastic rocker arms. It should be inside the bag that had your servo motor.

Insert the rocker arm on top of the steering servo. The grooves of the steering servo should fit nicely with the grooves of the rocker arm. 

2020-05-21-120132

Now take note of where the rocker arm stops turning on the right side.

Reposition the rocker arm so that it is perpendicular across the steering servo when the underlying steering servo axis is exactly at the halfway point between the left and right stopping points that you just marked.

After you have adjusted the angle of the steering servo axis using the rocker arm, grab the servo horn.

Carefully remove the rocker arm by pulling it straight up off the steering servo axis. You want to be careful not to move the steering servo axis.

Fit the servo horn on top of the steering servo axis so that it looks like this. 

Twist the servo horn from right to left. The rotation range should be 0-225°.

Once you are sure that the servo horn is positioned properly over the steering servo axis, secure it into place by placing a screw in the center.

2020-05-21-120458

Place the Multi-functional servo bracket (with attached servo motor) inside the top U-bracket.

Secure it into place with four screws.

2020-05-21-120853

Install the Wrist

Grab two Multi-functional brackets.

Get a bearing, a screw, and a nut. Attach them to one of the Multi-functional brackets.

2020-05-21-153906

Grab two M3*6 screws and nuts. Use these screws and nuts to connect the Multi-functional brackets together.

2020-05-21-155644

Grab a servo motor, and place it into one of the Multi-functional brackets.

2020-05-21-160651

Grab four M3*8 screws and secure the servo motor into place.

2020-05-21-161152

Grab the arm rudder and place it over the servo axis.

As we have done with other servo motors, the arm rudder should be straight up and down at the halfway point of the motion of the servo (when you twist to the left and right).

Once you are happy with the angle, take the arm rudder off, and replace it with a servo horn.

Stick a screw in the middle of the servo horn to tighten it.

2020-05-21-161528

Place the Mult-functional bracket in the U-type bracket.

Use the servo horn screws to secure the servo horn into place.

Install the Hand Servo

Grab another servo motor.

Place the servo motor into the Multi-functional bracket up top.

Secure the servo motor into the Multi-functional bracket using four screws and nuts.

Add the arm rudder on top of the servo axis, and do the same routing we have done before to find the halfway point. You want the arm rudder to be up and down across the servo motor at the halfway point.

2020-05-21-171153

Attach the Claw

Grab a screw and place it in the center of the hand servo horn.

Grab two screws and secure the claw to the hand servo horn.

Grab the last servo and four M3*6 screws.

Attach the last servo to the claw using the screws. If you run out of screws, feel free to pull some screws from the base of the robot.

2020-05-21-172349

Grab the arm rudder and place it on top of the servo axis.

Find the halfway point of the servo axis. When you find the halfway point place the arm rudder on top of the axis so that it points straight up and down.

Carefully take the arm rudder off.

Push the servo horn over the servo axis.

Use a small screw to secure the servo horn on the servo axis. The screw that you should use is the one with something that looks like a disk or a washer around the neck near the head. Don’t tighten it too tight.

Arrange the claw in the open position.

Grab two small black screws. 

Secure the loose piece of the claw to the servo horn using the two black screws.

Check that you’re able to open and close the claw. The claw should close completely.

That’s it. If you’ve gotten this far, you have assembled the body of your robotic arm.

Move the Robotic Arm

Your robotic arm has six motors (six degrees of freedom). To move your robotic arm, you can buy a six-channel digital servo tester (you can find them on eBay or AliExpress) and move them like I explain on this post.

All you need to do is connect your digital servo tester to a power source (i.e. 6V…which can be a 4xAA battery pack), and also connect your servos to the tester. You’ll be up and running in just a few minutes.

2-Way Communication Between Raspberry Pi and Arduino

In this tutorial, I’ll show you how to set up two-way communication between your Raspberry Pi and your Arduino. I’ve done something similar in the past, but let’s take a look at a simpler example.

Here is our end goal:

  • We will send a block of integers from the Raspberry Pi to the Arduino. 
  • We will then have the Arduino repeat those integers back to the Raspberry Pi. 
  • The Raspberry Pi will then print the integers it received from the Arduino.

A real-world application of two-way communication between Raspberry Pi and Arduino is when you have a robotic arm that needs to pick up an object from a conveyor belt in a warehouse (or factory) and place that object inside a bin. This task is commonly known as pick and place

A camera is mounted above the robotic arm. You want to have the Raspberry Pi detect and recognize objects via the camera (using computer vision software like OpenCV), do some calculations, and then send servo angle values to the Arduino. The Arduino will then move the servo motors accordingly so the robotic arm can pick up the object.

Prerequisites

  • You have the Arduino IDE (Integrated Development Environment) installed either on your personal computer or on your Raspberry Pi. I’m using Arduino Uno.
  • You have Raspberry Pi set up. (Raspberry Pi 3B, 3B+, 4, etc…doesn’t matter which one)

Directions

Send a String From Arduino to Raspberry Pi

Let’s get started by sending a string of text (“Hello World”) from your Arduino to your Raspberry Pi.

Write the following program and upload it to your Arduino. Save it as send_string_to_raspberrypi.ino

/*
Program: Send Strings to Raspberry Pi
File: send_string_to_raspberrypi.ino
Description: Send strings from Arduino to a Raspberry Pi
Author: Addison Sears-Collins
Website: https://automaticaddison.com
Date: July 5, 2020
*/

void setup(){
  
  // Set the baud rate  
  Serial.begin(9600);
  
}

void loop(){
  
  // Print "Hello World" every second
  // We do println to add a new line character '\n' at the end
  // of the string.
  Serial.println("Hello! My name is Arduino.");
  delay(1000);
}

Before you connect the Arduino to your Raspberry Pi, you need to set up the Raspberry Pi so that it can receive data from the Arduino. We first need to figure out the port that connects the Arduino and the Raspberry Pi.

Turn on your Raspberry Pi, and open a new terminal window.

Update the list of packages on your system:

sudo apt-get update

Upgrade any outdated packages (optional):

sudo apt-get upgrade

Install the PySerial package.

python3 -m pip install pyserial
1-install-pyserialJPG

If you get an error, you need to install pip first. After you run the command below, then try installing PySerial again.

sudo apt install python3-pip

Open a new terminal window, and type the following command to get a list of all the ports that begin with the prefix tty.

ls /dev/tty*

Here is what you should see:

2-ls-dev-ttyJPG

Now, plug the USB (Universal Serial Bus) cable into your Arduino and connect that to the USB port of your Raspberry Pi.

Reboot your computer.

sudo reboot

Once you’ve rebooted the computer, type the command again in the terminal window on your Raspberry Pi:

ls /dev/tty*

You see the new port? You should see a new port with a name like /dev/ttyACM0. That is your Arduino.

3-ls-dev-tty-afterJPG

Another way to see all the USB devices connected to your Raspberry Pi is to use this command:

lsusb

Set the baud rate of that port (i.e. the speed of data communication over that port/channel). Let’s use 9600. 9600 isn’t set in stone. For other projects you could use 38400, 57600, 115200, etc.

stty -F /dev/ttyACM0 9600

Let’s check the baud rate to see if it is set properly.

stty -F /dev/ttyACM0
4-check-the-baud-rateJPG

Now, create a new folder that will store the code we are going to write.

cd Documents
mkdir pi_arduino_communication

Move inside that folder.

cd pi_arduino_communication

Install gedit, my favorite text editor.

sudo apt-get install gedit

Create a new Python program.

gedit receive_string_from_arduino.py

Write the following code and save it.

#!/usr/bin/env python3

###############################################################################
# Program: Receive Strings From an Arduino
# File: receive_string_from_arduino.py
# Description: This program runs on a Raspberry Pi. It receives a string from 
#  Arduino and prints that string to the screen.
# Author: Addison Sears-Collins
# Website: https://automaticaddison.com
# Date: July 5, 2020
###############################################################################

import serial # Module needed for serial communication

# Set the port name and the baud rate. This baud rate should match the
# baud rate set on the Arduino.
# Timeout parameter makes sure that program doesn't get stuck if data isn't
# being received. After 1 second, the function will return with whatever data
# it has. The readline() function will only wait 1 second for a complete line 
# of input.
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)

# Get rid of garbage/incomplete data
ser.flush()

# Infinite loop
while (1):

  # If there is data available
  if(ser.in_waiting > 0):
  
    # Read everything until the new line character
    # Convert the data from a byte into a string of type 'utf-8'
    # You could also use 'ascii'
    # rstrip() function removes trailing characters like
    # the new line character '\n'
    line = ser.readline().decode('utf-8').rstrip()
	
    # Print the data received from the Arduino
    print(line)

Make it executable.

chmod +x receive_string_from_arduino.py

Now run the program.

./receive_string_from_arduino.py

You should see this print out to your screen.

5-receive-string-from-arduinoJPG

When you’re ready, press CTRL+C to stop the Python script.

Send a String From Raspberry Pi to Arduino

In this section, we will:

  1. Create a Python program that sends a string from the Raspberry Pi to the Arduino
  2. The Arduino will respond back to the Raspberry Pi with the string it has received.
  3. The Raspberry Pi will print out the string it received from the Arduino.

Let’s start by creating the program for the Arduino.

Create the following sketch, and upload it to your Arduino. Save it as receive_string_from_raspberrypi.ino.

/*
Program: Receive Strings From Raspberry Pi
File: receive_string_from_raspberrypi.ino
Description: Receive strings from a Raspberry Pi
Author: Addison Sears-Collins
Website: https://automaticaddison.com
Date: July 5, 2020
*/

void setup(){
  
  // Set the baud rate  
  Serial.begin(9600);
  
}

void loop(){

  if(Serial.available() > 0) {
    String data = Serial.readStringUntil('\n');
    Serial.print("Hi Raspberry Pi! You sent me: ");
    Serial.println(data);
  }
}

Now go over to your Raspberry Pi, and open a new Python file.

Open a new terminal window, and type the following commands:

cd Documents/pi_arduino_communication
gedit send_strings_to_arduino.py

Write the following code and save it.

#!/usr/bin/env python3

###############################################################################
# Program: Send Strings to an Arduino From a Raspberry Pi
# File: send_strings_to_arduino.py
# Description: This program runs on a Raspberry Pi. It sends strings
#   to Arduino. It also receives the  string it sent
#   and prints it to the screen. This provides bi-directional (2-way) communication
#   between Arduino and Raspberry Pi.
# Author: Addison Sears-Collins
# Website: https://automaticaddison.com
# Date: July 5, 2020
###############################################################################

import serial # Module needed for serial communication
import time # Module needed to add delays in the code

# Set the port name and the baud rate. This baud rate should match the
# baud rate set on the Arduino.
# Timeout parameter makes sure that program doesn't get stuck if data isn't
# being received. After 1 second, the function will return with whatever data
# it has. The readline() function will only wait 1 second for a complete line 
# of input.
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)

# Get rid of garbage/incomplete data
ser.flush()

# Infinite loop
while (1):

  send_string = ("My name is Raspberry Pi\n")
  
  # Send the string. Make sure you encode it before you send it to the Arduino.
  ser.write(send_string.encode('utf-8'))
  
  # Do nothing for 500 milliseconds (0.5 seconds)
  time.sleep(0.5)

  # Receive data from the Arduino
  receive_string = ser.readline().decode('utf-8').rstrip()

  # Print the data received from Arduino to the terminal
  print(receive_string)

Make it executable.

chmod +x send_strings_to_arduino.py

Plug your Arduino into your Raspberry Pi using the USB cable.

Now run the Python program.

./send_strings_to_arduino.py

You should see this print out to your screen.

6-send-strings-to-arduinoJPG

Press CTRL+C when you’re done.

Send Integers From Arduino to Raspberry Pi

Let’s create programs to send integers from Arduino to Raspberry Pi.

Upload the following code to your Arduino. Save the file as send_ints_to_raspberrypi.ino.

/*
Program: Send Integers to Raspberry Pi
File: send_ints_to_raspberrypi.ino
Description: Send integers from Arduino to a Raspberry Pi
Author: Addison Sears-Collins
Website: https://automaticaddison.com
Date: July 5, 2020
*/

// Initialize the variables with some randomly-chosen integers
// that could represent servo motor angles, for example.
int servo_0_angle = 90;
int servo_1_angle = 7;
int servo_2_angle = 63;
int servo_3_angle = 85;
int servo_4_angle = 162;
int servo_5_angle = 45;

void setup(){
  
  // Set the baud rate  
  Serial.begin(9600);
  
}

void loop(){
  
  // Print integers every 500 milliseconds
  // We do println to add a new line character '\n' at the end
  // of the comma-separated stream of integers
  Serial.print(servo_0_angle); Serial.print(",");
  Serial.print(servo_1_angle); Serial.print(",");
  Serial.print(servo_2_angle); Serial.print(",");
  Serial.print(servo_3_angle); Serial.print(",");
  Serial.print(servo_4_angle); Serial.print(",");
  Serial.println(servo_5_angle); 
  delay(500);
}

Now go over to your Raspberry Pi. 

Open a new terminal and go to your folder.

cd Documents/pi_arduino_communication

Create a new Python program.

gedit receive_ints_from_arduino.py

Write the following code and save it.

#!/usr/bin/env python3

###############################################################################
# Program: Receive Integers From an Arduino
# File: receive_ints_from_arduino.py
# Description: This program runs on a Raspberry Pi. It receives comma-separated 
#  integers from Arduino and prints them to the screen.
# Author: Addison Sears-Collins
# Website: https://automaticaddison.com
# Date: July 5, 2020
###############################################################################

import serial # Module needed for serial communication

# Set the port name and the baud rate. This baud rate should match the
# baud rate set on the Arduino.
# Timeout parameter makes sure that program doesn't get stuck if data isn't
# being received. After 1 second, the function will return with whatever data
# it has. The readline() function will only wait 1 second for a complete line 
# of input.
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)

# Initialize 6 integers
servo_0_angle = 90
servo_1_angle = 90
servo_2_angle = 90
servo_3_angle = 90
servo_4_angle = 90
servo_5_angle = 90

# Infinite loop
while (1):

  # Read everything until the new line character
  # Convert the data from a byte into a string of type 'utf-8'
  # You could also use 'ascii'
  line = ser.readline().decode('utf-8')

  # Take out the commas. Parse the string into a list.
  parsed = line.split(',')
	
  # rstrip() function removes trailing characters like
  # the new line character '\n' and '/r'. Also removes
  # white space.
  parsed = [x.rstrip() for x in parsed]
	
  # We know we need to receive 6 integers. This code helps with any loss
  # of data that might happen as data is transferred between Arduino
  # and the Raspberry Pi.
  if(len(parsed) > 5):
    print(parsed)
	  
    # We add the '0' character to the end of each item in the 
    # parsed list. This makes sure that there are no empty
    # strings in the list. Adding 0 makes sure that we have
    # at least 6 string values we can convert into integers.
    # Dividing by 10 removes the trailing 0 but it makes the integer a float.
    # We then have to convert the float to an integer.
    servo_0_angle = int(int(parsed[0]+'0')/10)
    servo_1_angle = int(int(parsed[1]+'0')/10)
    servo_2_angle = int(int(parsed[2]+'0')/10)
    servo_3_angle = int(int(parsed[3]+'0')/10)
    servo_4_angle = int(int(parsed[4]+'0')/10)
    servo_5_angle = int(int(parsed[5]+'0')/10)
  print("Servo 0 Angle: " + str(servo_0_angle))
  print("Servo 1 Angle: " + str(servo_1_angle))
  print("Servo 2 Angle: " + str(servo_2_angle))
  print("Servo 3 Angle: " + str(servo_3_angle))
  print("Servo 4 Angle: " + str(servo_4_angle))
  print("Servo 5 Angle: " + str(servo_5_angle))
	
  # This line proves that we have successfully converted the strings
  # to integers.
  print("Sum of Servos 0 and 1: " + str(servo_0_angle + servo_1_angle))

Make it executable.

chmod +x receive_ints_from_arduino.py

Plug your Arduino into your Raspberry Pi using the USB cable.

Now run the Python program.

./receive_ints_from_arduino.py

You should see this print out to your screen.

7-receive-ints-from-arduinoJPG

Send Integers From Raspberry Pi to Arduino

Let’s put it all together. We will:

  1. Create a Python program that sends integers from the Raspberry Pi to the Arduino.
  2. The Arduino will respond back to the Raspberry Pi with the integers it has received.
  3. The Raspberry Pi will print out the integers it received from the Arduino.

Let’s start by creating the program for the Arduino.

Create the following sketch, and upload it to your Arduino. Save it as receive_ints_from_raspberrypi.ino.

/*
Program: Receive Integers From Raspberry Pi
File: receive_ints_from_raspberrypi.ino
Description: Receive integers from a Raspberry Pi
Author: Addison Sears-Collins
Website: https://automaticaddison.com
Date: July 5, 2020
*/

// Initialize the integer variables
int servo_0_angle = 90;
int servo_1_angle = 90;
int servo_2_angle = 90;
int servo_3_angle = 90;
int servo_4_angle = 90;
int servo_5_angle = 90;

int sum = 0;

void setup(){
  
  // Set the baud rate  
  Serial.begin(9600);
  
}

void loop(){

  if(Serial.available() > 0) {
    servo_0_angle = Serial.parseInt();
    servo_1_angle = Serial.parseInt();
    servo_2_angle = Serial.parseInt();
    servo_3_angle = Serial.parseInt();
    servo_4_angle = Serial.parseInt();
    servo_5_angle = Serial.parseInt(); 

    // Compute a sum to prove we have integers
    sum = servo_0_angle + servo_1_angle;

    // We do println to add a new line character '\n' at the end
    // of the comma-separated stream of integers
    Serial.print(servo_0_angle); Serial.print(",");
    Serial.print(servo_1_angle); Serial.print(",");
    Serial.print(servo_2_angle); Serial.print(",");
    Serial.print(servo_3_angle); Serial.print(",");
    Serial.print(servo_4_angle); Serial.print(",");
    Serial.print(servo_5_angle); Serial.print(",");
    Serial.println(sum); 
  }
}

Now go over to your Raspberry Pi, and open a new Python file.

gedit send_ints_to_arduino.py

Write the following code and save it.

#!/usr/bin/env python3

###############################################################################
# Program: Send Integers to an Arduino From a Raspberry Pi
# File: send_ints_to_arduino.py
# Description: This program runs on a Raspberry Pi. It sends integers
#   to Arduino in comma-separated format. It also receives the integers it sent
#   and prints them to the screen. This provides bi-directional (2-way) communication
#   between Arduino and Raspberry Pi.
# Author: Addison Sears-Collins
# Website: https://automaticaddison.com
# Date: July 5, 2020
###############################################################################

import serial # Module needed for serial communication
import time # Module needed to add delays in the code

# Set the port name and the baud rate. This baud rate should match the
# baud rate set on the Arduino.
# Timeout parameter makes sure that program doesn't get stuck if data isn't
# being received. After 1 second, the function will return with whatever data
# it has. The readline() function will only wait 1 second for a complete line 
# of input.
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)

# Intialize the integer values we'll send to Arduino
servo_0_angle = 90
servo_1_angle = 7
servo_2_angle = 63
servo_3_angle = 85
servo_4_angle = 162
servo_5_angle = 45

# Get rid of garbage/incomplete data
ser.flush()

# Infinite loop
while (1):

  # Convert the integers to a comma-separated string
  angle_value_list = [str(servo_0_angle),str(servo_1_angle),str(
    servo_2_angle),str(servo_3_angle),str(servo_4_angle),str(servo_5_angle)]	
  send_string = ','.join(angle_value_list)
  send_string += "\n"

  # Send the string. Make sure you encode it before you send it to the Arduino.
  ser.write(send_string.encode('utf-8'))

  # Receive data from the Arduino
  receive_string = ser.readline().decode('utf-8', 'replace').rstrip()

  # Print the data received from Arduino to the terminal
  print(receive_string)

Make it executable.

chmod +x send_ints_to_arduino.py

Plug your Arduino into your Raspberry Pi using the USB cable.

Now run the Python program.

./send_ints_to_arduino.py

You should see this print out to your screen.

8-send_ints_to_arduinoJPG

Note that instead of receive_ints_from_raspberrypi.ino, you can use this code (receive_ints_from_raspberrypi_strings.ino). It is a bit more complicated (and takes up almost double the amount of memory), but the output is exactly the same. This is to show you that there are many ways to skin the cat:

/*
Program: Receive Integers From Raspberry Pi
File: receive_ints_from_raspberrypi_strings.ino
Description: Receive integers from a Raspberry Pi
Author: Addison Sears-Collins
Website: https://automaticaddison.com
Date: July 5, 2020
*/

// Initialize the integer variables
int servo_0_angle = 90;
int servo_1_angle = 90;
int servo_2_angle = 90;
int servo_3_angle = 90;
int servo_4_angle = 90;
int servo_5_angle = 90;

// Initialize the String variables
String servo_0_angle_str = "";
String servo_1_angle_str = "";
String servo_2_angle_str = "";
String servo_3_angle_str = "";
String servo_4_angle_str = "";
String servo_5_angle_str = "";

int sum = 0;

// Get ready to accept comma-separated values
int comma_position;

void setup(){
  
  // Set the baud rate  
  Serial.begin(9600);
  
}

void loop(){

  if(Serial.available() > 0) {

    // Read string until the new line character
    String data = Serial.readStringUntil('\n');

    // There are 6 integers we will be receiving from the
    // Raspberry Pi

    // Integer 0
    comma_position = data.indexOf(',');   
    servo_0_angle_str = data.substring(0,comma_position);
    servo_0_angle = servo_0_angle_str.toInt();
    data = data.substring(comma_position+1, data.length());

    // Integer 1
    comma_position = data.indexOf(',');   
    servo_1_angle_str = data.substring(0,comma_position);
    servo_1_angle = servo_1_angle_str.toInt();
    data = data.substring(comma_position+1, data.length());

    // Integer 2
    comma_position = data.indexOf(',');   
    servo_2_angle_str = data.substring(0,comma_position);
    servo_2_angle = servo_2_angle_str.toInt();
    data = data.substring(comma_position+1, data.length());

    // Integer 3
    comma_position = data.indexOf(',');   
    servo_3_angle_str = data.substring(0,comma_position);
    servo_3_angle = servo_3_angle_str.toInt();
    data = data.substring(comma_position+1, data.length());

    // Integer 4
    comma_position = data.indexOf(',');   
    servo_4_angle_str = data.substring(0,comma_position);
    servo_4_angle = servo_4_angle_str.toInt();
    data = data.substring(comma_position+1, data.length());

    // Integer 5
    comma_position = data.indexOf(',');   
    servo_5_angle_str = data.substring(0,comma_position);
    servo_5_angle = servo_5_angle_str.toInt();
    data = data.substring(comma_position+1, data.length());

    // Compute a sum to prove we have integers
    sum = servo_0_angle + servo_1_angle;

    // We do println to add a new line character '\n' at the end
    // of the comma-separated stream of integers
    // The stuff below is ready by the Raspberry Pi
    Serial.print(servo_0_angle); Serial.print(",");
    Serial.print(servo_1_angle); Serial.print(",");
    Serial.print(servo_2_angle); Serial.print(",");
    Serial.print(servo_3_angle); Serial.print(",");
    Serial.print(servo_4_angle); Serial.print(",");
    Serial.print(servo_5_angle); Serial.print(",");
    Serial.println(sum); 
  }
}

That’s it for this tutorial. Keep building!