• UFRJ Nautilus

PID Control With Arduino

Updated: Jun 26

How can we command a robot so that it maintains a position and orientation under water? In this post we will see how a PID controller can be used to solve this and other problems in robotics.


There are different control algorithms that can be used in our systems, but the most common closed control algorithm is probably the PID. To understand it in an intuitive way, we first need to understand what a closed control is. Let’s think of the case of a driver in tortuous terrain. The driver wishes to keep his vehicle in the speed limit. This is the wish of the controller, and we will call it “setpoint”. The driver controls the acceleration of the car, which we will call “plant”, through the gas and brake pedals. He can also observe the changes in the car’s speed by looking at the speed meter.


This is probably the simplest and most daily example we have of a closed control system, where the driver uses the observation of the car to control it using the gas and brake pedals. The diagram for this system would be:



Now that we know what a closed control system is, also called a feedback control system, we can talk about the PID, an acronym for Proportional, Integral, Derivative. This controller will use the current error (Proportional), its integral (Integral) and its derivative (Derivative) to generate an output we will use to act in our system. Its diagram would look like the following:



The equation that describes the output for this diagram as a function of time is the following:

We will implement this controller with the objective of controlling the speed of a DC motor using an arduino.


In order to do so, we will use the discrete version of the equation above, substituting the integral by a summation and rewriting the error variation in a discrete way.



Our circuit consists of a motor we wish to control, with an encoder, a sensor capable of measuring the speed of the motor, and a potentiometer we can use to choose the speed of the motor.


Implementation of the controller:

// Hardware Mapping
#define PWM_OUT       3
#define ENCODER_A 2
#define POT_IN A0

int output;           // defines the PWM output
int speed;            // motor speed
int lastError = 0;    // declares the last error
int setpoint;         // declares the setpoint
int error = 0;        // current error
int I_error = 0;