PID Control with Arduino

Hello dear colleagues,
PID control with Arduino is not simply a matter of installing a library, entering three tuning values and calling Compute(). Sensor scaling, sampling time, actuator limits, PWM behaviour, control direction and the dynamics of the physical system all determine whether the loop actually works.
Arduino is an excellent platform for learning the practical side of PID control. It allows the complete feedback loop to be observed at low cost: a sensor measures the process, the controller calculates an error, the PID algorithm produces a correction, and an actuator changes the physical system.
That makes Arduino useful for temperature experiments, DC motor speed control, small positioning systems, line-following robots, balancing platforms and laboratory projects. However, an Arduino development board running PID software should not automatically be treated as an industrial process controller. Industrial control also requires consideration of electrical isolation, EMC, protected I/O, watchdog behaviour, fail-safe outputs, wiring practices and long-term hardware reliability.
What Does the Complete Arduino PID Loop Look Like?
A PID controller does not control anything by itself. It needs a measurable process variable and an actuator capable of influencing that variable.
For a temperature system, the sensor might measure degrees Celsius and the actuator might be an electrical heater. For a motor-speed loop, the feedback may come from an encoder while the actuator is a motor driver. For a line-following robot, the process variable can be the lateral position of the line and the actuator command becomes the difference between left and right motor speeds.
The complete feedback path can be represented as:
Setpoint → Error → PID calculation → Driver / power stage → Physical process → Sensor → Arduino → Error again
The Arduino normally handles measurement, calculation and low-power command signals. A motor, heater, solenoid or other significant load should not be powered directly from an Arduino I/O pin. The microcontroller provides the command; an appropriate driver stage supplies the power.
What Do P, I and D Actually Do?
The proportional, integral and derivative terms perform the same basic functions on Arduino as they do in a PLC, drive or dedicated process controller.
Proportional – P: Produces a correction related to the present control error. A larger error results in a stronger proportional response.
Integral – I: Accumulates error over time. It is particularly useful when proportional control leaves a persistent offset between the setpoint and the measured value.
Derivative – D: Responds to the rate of change of the measured behaviour and can add damping to suitable systems. It is also highly sensitive to measurement noise and is not automatically useful in every application.
Imagine a DC motor requested to run at 1500 rpm. With proportional control alone, the motor might stabilize at 1430 rpm because some error is required to generate enough output to overcome the load. Integral action can gradually remove that residual error. Too much integral action, however, can drive the controller beyond the required output and produce repeated overshoot.
This is why Kp, Ki and Kd should never be copied blindly from another Arduino project. The correct values depend on the motor, load, sensor, sampling period, mechanical inertia and many other properties of the actual system.
Use Meaningful Engineering Units
A surprisingly common Arduino PID mistake is to compare values expressed in different units.
Suppose the desired temperature is entered as 60 °C, but the PID input is the raw ADC value 427. The controller is now subtracting two numbers that do not represent the same physical quantity. The calculated error has no useful engineering meaning.
For most real projects it is better to convert the sensor reading into the actual engineering unit first:
- Temperature in °C,
- Pressure in bar or kPa,
- Motor speed in rpm,
- Position in mm or degrees,
- Flow in L/min or m³/h.
The setpoint and the process variable then use the same scale. The program becomes easier to tune, trend and troubleshoot.
What Does analogRead() Really Return?
`analogRead()` does not inherently return temperature, pressure or speed. It returns the result of the board's analog-to-digital conversion.
The program must convert that value according to the sensor interface and the ADC characteristics of the selected Arduino board.
For example, a pressure transmitter may first be converted into a voltage suitable for the microcontroller input. The ADC reading is then translated into voltage and finally into pressure according to the transmitter range.
Industrial 0–10 V and 4–20 mA signals should not simply be connected to an Arduino analog input without appropriate signal conditioning. Voltage scaling, current-to-voltage conversion, filtering, input protection and, where required, galvanic isolation must be considered.
analogWrite() Usually Does Not Mean Analog Voltage
The name `analogWrite()` is one of the most confusing parts of basic Arduino control projects.
On many common Arduino boards and pins, `analogWrite()` produces PWM – Pulse Width Modulation, not a continuously variable analog voltage.
For example:
analogWrite(pwmPin, 0); // 0% duty
analogWrite(pwmPin, 128); // approximately 50% duty
analogWrite(pwmPin, 255); // 100% duty
The pin rapidly switches between its low and high states. The average energy delivered to a suitable load is controlled by changing the duty cycle.
Some Arduino families provide true DAC output on specific pins, so the exact behaviour depends on the board. The important point is that the function name alone does not guarantee a true analog voltage output.
Do Not Drive the Motor Directly from the Arduino Pin
A microcontroller output is a logic-level command, not a motor power supply.
A DC motor generally requires a MOSFET stage, H-bridge or dedicated motor driver. The motor current flows through the power stage while the Arduino controls the driver's enable, PWM and direction inputs.
A proper closed-loop speed system also requires actual speed feedback. An encoder, Hall sensor or optical sensor can provide pulses from which rpm is calculated.
Without feedback, changing PWM duty cycle is simply open-loop motor command. It is not PID speed control.
Sampling Time Is Part of the Controller
A digital PID controller does not calculate continuously. It measures and updates at discrete intervals.
The appropriate interval depends on the physical process.
A heating system may change slowly over several seconds. A motor-speed loop may need updates much more frequently. A balancing robot may require an even faster and more consistent cycle.
If the sampling period is much too long, additional effective delay is introduced into the loop. If it is unnecessarily short, the program may process mostly measurement noise without gaining useful control performance.
Sampling should therefore be selected with the process dynamics and time delays in mind.
Why delay(100) Is a Poor PID Scheduler
A beginner example often looks like this:
input = analogRead(sensorPin);
myPID.Compute();
analogWrite(actuatorPin, output);
delay(100);
The code may appear to work, but `delay(100)` blocks the whole main program for 100 ms.
During that period the application cannot conveniently perform other time-sensitive tasks such as checking switches, processing serial communication, updating alarms or servicing additional software logic.
The commonly used PID_v1 library already has its own sample-time mechanism. `Compute()` can be called repeatedly from `loop()`, while the library decides whether enough time has passed to calculate a new PID output.
The control period can be defined explicitly:
myPID.SetSampleTime(100); // 100 ms
This means the main program can continue doing useful work instead of being intentionally frozen between PID calculations.
A Cleaner PID_v1 Example
The following code demonstrates the software structure. It intentionally uses the ADC value directly to keep the example generic. A real temperature, pressure or speed controller should convert the measurement into suitable engineering units before feeding it into the PID block.
#include <PID_v1.h>
const byte sensorPin = A0;
const byte pwmPin = 9;
double Setpoint;
double Input;
double Output;
/*
Example values only.
These are NOT universal PID settings.
*/
double Kp = 1.2;
double Ki = 0.4;
double Kd = 0.0;
PID myPID(&Input,
&Output,
&Setpoint,
Kp, Ki, Kd,
DIRECT);
void setup()
{
pinMode(pwmPin, OUTPUT);
// Example target in raw ADC units
Setpoint = 600;
// Match the output to an 8-bit PWM command
myPID.SetOutputLimits(0, 255);
// PID calculation interval
myPID.SetSampleTime(100);
myPID.SetMode(AUTOMATIC);
}
void loop()
{
Input = analogRead(sensorPin);
if (myPID.Compute())
{
analogWrite(pwmPin, (int)Output);
}
/*
Other non-blocking program tasks can continue here.
No delay() is required for PID timing.
*/
}
The Kp, Ki and Kd values above only demonstrate how the library is configured. They are not recommended settings for any real motor, heater or machine.
DIRECT and REVERSE Control
The controller must also know which direction of output produces the required process response.
DIRECT: Increasing controller output causes the measured process variable to increase.
A heater is a straightforward example: increasing heater power normally increases temperature.
REVERSE: Increasing controller output causes the measured variable to decrease.
This may be required, for example, when the controller output represents cooling power.
If control direction is selected incorrectly, the loop behaves like positive feedback. When the measurement moves away from the setpoint, the controller drives it even farther away instead of correcting the error.
Why SetOutputLimits() Matters
Physical actuators have limits.
An 8-bit PWM command may use 0–255. A valve may use 0–100%. A drive may accept another numerical range. The PID output should represent the range that the actuator can actually use.
For example:
myPID.SetOutputLimits(0, 255);
The PID_v1 implementation constrains both the calculated output and its accumulated internal output term to the defined limits. This is useful in reducing uncontrolled integral accumulation inside the algorithm.
However, software limits must still correspond to the real actuator. If software believes the output can move between 0 and 255 while the actual motor driver does not respond below 70, that dead zone remains part of the physical system.
Integral Windup Is a Physical Problem Too
Suppose the controller demands maximum heater power but the process is still far below the setpoint. The error remains large and the integral term tends to accumulate.
When the process finally approaches the target, excessive stored integral action may keep the output high for too long and produce overshoot.
Output limiting inside the PID algorithm helps, but the complete design should also consider actual actuator saturation, minimum usable output, manual mode and startup conditions.
Heater Control Is Different from Motor PWM
A DC motor driver and a mains heater should not automatically use the same output technique.
Motor power electronics commonly accept relatively fast PWM. A mechanical relay controlling a heater should obviously not be switched hundreds of times per second.
For slow thermal systems, a PID output can instead be converted into time-proportional control.
Imagine a 5-second control window. If the PID output corresponds to 40%, the heater can be energized for approximately 2 seconds and turned off for approximately 3 seconds during that window.
With a suitable SSR, a shorter switching window may be practical. The correct method depends on the load, switching device and manufacturer requirements.
This is why PID temperature control should not be reduced to “calculate PID, then call analogWrite().”
Motor-Speed Feedback: Count Pulses or Measure Period?
For motor-speed control, the PID input should represent measured speed rather than the PWM command itself.
An encoder or Hall sensor can be used in several ways.
Pulse counting: Count how many pulses arrive during a fixed measurement window and convert that number into rpm.
Period measurement: Measure the time between successive pulses and calculate speed from the pulse period.
Neither method is universally better.
At low encoder resolution, a very short counting window may produce only a few pulses, causing the calculated speed to jump between discrete values. A long counting window improves resolution but adds delay.
Period measurement can provide better low-speed resolution but becomes sensitive to timing accuracy and missing pulses.
Sensor resolution, speed range and PID sample time should therefore be designed together.
Line-Following Robot: A PID Loop Without a Conventional Process Sensor
A line-following robot is one of the best demonstrations of PID control in robotics.
The controlled variable is not temperature or pressure. An optical sensor array estimates how far the robot is from the desired line position.
For example:
Error = required line center − measured line position
The PID output can then be used as a steering correction:
leftMotor = baseSpeed + correction;
rightMotor = baseSpeed - correction;
If proportional action is too weak, the robot reacts too slowly in bends. If it is too strong, the vehicle may repeatedly cross the line and produce a zigzag motion.
Derivative action can help damp rapid steering changes. Integral action is often small or unnecessary in simple line-following applications because accumulated steering error can create undesirable behaviour after sharp turns.
Why a Self-Balancing Robot Is Much Harder
A two-wheel balancing robot looks like a small hobby project, but from a control perspective it is considerably more demanding than a heater or fan controller.
The mechanical system is naturally unstable. Once the robot starts falling, waiting too long before applying motor torque makes the error grow rapidly.
Successful control therefore depends on much more than PID gains:
- Reliable IMU measurement,
- Angle estimation or sensor fusion,
- Consistent sampling interval,
- Fast motor response,
- Suitable center of gravity,
- Minimum software blocking,
- Sufficient battery voltage and motor torque.
This is a good example of why a `delay()`-driven sketch can become a serious limitation. The loop should keep running predictably while sensor acquisition, communications and other tasks are handled without unnecessary blocking.
Why the Derivative Term Can Become Noisy
Derivative action responds strongly to rapid changes.
Suppose a nearly constant sensor produces the sequence:
500, 503, 499, 502, 500...
The physical process may hardly be changing, but the numerical derivative sees repeated movement. A large Kd can therefore cause the control output to jump unnecessarily.
Possible sources include electrical noise, ADC quantization, poor grounding, unstable reference voltage, mechanical vibration or genuinely noisy process measurement.
Applying a very heavy software filter is not automatically the answer because filtering also introduces delay. The correct solution begins by determining where the noise originates and whether derivative action is actually useful for that process.
Setpoint Changes Can Be Part of the Problem
A PID loop may be perfectly stable while still producing aggressive behaviour after a large setpoint step.
For example, changing motor demand instantly from 0 to 2000 rpm may command maximum output and create a large mechanical and electrical transient.
In some applications it is better to ramp the setpoint gradually:
0 → 100 → 200 → 300 → ... → 2000 rpm
Setpoint ramping is not a substitute for correct PID tuning, but it can reduce shock, current peaks and unnecessary overshoot.
Arduino Timers and PWM Conflicts
As an Arduino project grows, timing resources become important.
PWM generation, `millis()`, Servo libraries, tone generation, frequency measurement and third-party libraries may depend on hardware timers.
Using two functions on the same timer can change PWM frequency, disable a feature or create unexpected behaviour depending on the board and libraries involved.
For simple projects this may never become visible. For motor control, balancing systems and multi-channel projects, the timer allocation of the selected board should be checked rather than assuming every PWM pin is completely independent.
What About millis() Overflow?
`millis()` eventually rolls over because it is stored in a finite-width unsigned value.
The usual safe pattern is to work with elapsed time:
if (millis() - previousTime >= interval)
{
previousTime = millis();
// task
}
Unsigned subtraction allows this pattern to continue working across the normal rollover point when implemented correctly.
In most ordinary PID_v1 use, the library's own time-difference logic already follows this type of approach.
How Should Arduino PID Gains Be Tuned?
A poor Arduino tutorial often gives three numbers such as:
Kp = 2, Ki = 5, Kd = 1
with no explanation of where they came from.
Those numbers are almost meaningless without the process.
A useful experimental approach is to begin with integral and derivative action removed or kept very small and observe proportional behaviour first. Once the process responds sensibly, integral action can be introduced if persistent offset remains.
Derivative action should be added only where the process dynamics justify it and the sensor signal is clean enough to make it useful.
Even this approach is not a universal tuning law. Integrating, highly delayed and naturally oscillatory processes require different strategies. The behaviour described in PID tuning for different process types still applies when the controller happens to be an Arduino.
Trend the Loop Instead of Tuning by Eye
One of the most valuable things Arduino gives us is easy access to controller data.
Setpoint, process input and controller output can be sent over the serial interface:
Serial.print(Setpoint);
Serial.print(",");
Serial.print(Input);
Serial.print(",");
Serial.println(Output);
When these values are plotted together, PID behaviour becomes much easier to understand.
A trend can answer questions such as:
- How quickly does the process approach the setpoint?
- How much overshoot occurs?
- Does the output remain saturated at 255?
- Is the process cycling repeatedly?
- Is the sensor noisy?
- Is integral action producing a long-period oscillation?
- Is the actuator constantly moving despite a stable process?
Good tuning is much easier when setpoint, measurement and output are viewed together rather than judging the system from a single display value.
MANUAL and AUTOMATIC Modes
A practical control system often needs both manual and automatic operation.
During commissioning, manual mode allows the engineer to apply a known output and observe the natural process response before closing the PID loop.
This is useful for discovering:
- Whether the process responds in the expected direction,
- Approximate process gain,
- Response speed,
- Significant time delay,
- Dead zones or actuator problems.
PID_v1 supports `MANUAL` and `AUTOMATIC` modes and initializes its internal state when automatic operation is enabled.
For an actual machine, the transition should still be engineered carefully so that manual-to-auto transfer does not create an unsafe output jump.
Startup and Reset Behaviour
What happens when the Arduino resets?
This question matters greatly when the actuator adds energy to the process.
After reset, program variables and PID internal state are initialized again. The I/O pins also pass through their startup conditions before the application reaches normal operation.
A safe design should not rely on software alone to guarantee that a heater or motor remains harmless during startup.
A useful sequence may be:
1- Start with actuator command disabled.
2- Initialize hardware and communications.
3- Obtain a valid sensor measurement.
4- Confirm that the measurement is within a reasonable range.
5- Initialize the PID controller.
6- Enable automatic control only when the system is ready.
For a heater, motor or other potentially hazardous load, the external power stage should also have a known safe state if the Arduino is disconnected, held in reset or loses power.
What If the Sensor Fails?
A feedback controller cannot make a safe decision from a measurement that is physically impossible.
Suppose a temperature sensor becomes disconnected and the program interprets the resulting ADC value as an extremely low temperature. A naive PID loop may react by commanding maximum heater power exactly when the measurement system has failed.
The application should therefore validate the feedback signal before using it.
Depending on the system, checks may include:
- Minimum and maximum credible sensor values,
- Rate-of-change limits,
- Communication timeout,
- Open-wire detection,
- Redundant sensor comparison.
A sensor fault should lead to a defined control response rather than allowing the PID algorithm to continue blindly.
Where Arduino PID Is a Good Choice
Education: It allows proportional, integral and derivative behaviour to be observed on a real physical system rather than only in simulation.
Laboratory projects: Small motors, fans, heaters, lamps and experimental mechanisms can be controlled inexpensively.
Robotics: Speed, steering, line tracking and small balancing projects provide excellent feedback-control exercises.
Prototype development: A control concept can be evaluated before it is transferred to a PLC, custom embedded controller or production electronics.
Hobby systems: Incubators, soldering stations, fan controllers and small positioning projects can make good PID experiments when appropriate electrical precautions are taken.
Where Arduino Is Not Automatically a PLC
The fact that an Arduino can execute a PID algorithm does not make a standard d