PID Control with Raspberry Pi

PID control with Raspberry Pi

PID Control with Raspberry Pi: Where Should Linux Sit in the Control Loop?

Writing a PID equation on a Raspberry Pi is easy. Building a control system that still behaves correctly when the network is busy, a sensor cable fails or Linux pauses a task for longer than expected is a different job.

That distinction matters because a Raspberry Pi is a small computer, not simply a faster PLC or a large microcontroller. It is excellent at networking, data logging, user interfaces and running complex software. Those strengths make it useful in control projects, but they do not automatically make every PID loop a good candidate for direct execution under Linux.

The first question should therefore not be “Can Raspberry Pi run PID?”

The useful question is: how fast does this process need to be controlled, and how much timing variation can it tolerate?

The basic principles of the controller itself are covered in What is PID?. Here we concentrate on what changes when Linux and Raspberry Pi hardware are placed around that algorithm.

Three very different ways to use a Raspberry Pi

A useful way to approach the problem is to separate three architectures.

1. Raspberry Pi runs the complete PID loop. This can work well for relatively slow processes such as laboratory heating, environmental chambers, room ventilation or other applications where small timing variations are not critical.

2. Raspberry Pi supervises another controller. A PLC, microcontroller, VFD or temperature controller performs the time-sensitive PID calculation while the Pi handles recipes, data storage, web pages, reports or remote access.

3. Raspberry Pi calculates higher-level commands while a dedicated device closes the fast loop. For example, the Pi may generate a target speed or position while a servo drive handles the rapid motor-current and velocity loops internally.

These three systems can all be described casually as “Raspberry Pi PID”, but technically they are quite different.

The GPIO header is digital I/O, not an industrial analog input card

A regular Raspberry Pi computer provides digital GPIO pins and interfaces such as SPI, I2C and serial communication. A typical industrial transmitter, however, may produce 4–20 mA or 0–10 V.

Those signals should not be connected directly to a GPIO pin.

A practical analog-input chain may require:

• signal conversion,
• an ADC,
• input protection,
• filtering,
• electrical isolation where required,
• correct grounding and shielding.

This is where a bench experiment and an industrial installation start to separate.

Connecting a small potentiometer through an ADC module is one thing. Reading a 4–20 mA transmitter from a cable running through a plant beside motors and contactors is another.

The electrical fundamentals are discussed in industrial analog signals.

Example: reading a pressure transmitter

Suppose a pressure transmitter measures 0–10 bar and produces:

4 mA = 0 bar
20 mA = 10 bar

The software does not magically receive “6.2 bar”. It first receives a digital representation from the measurement interface. That raw value has to be converted into the correct engineering unit.

If the conversion is wrong, the PID controller operates on the wrong process value.

Imagine that the real line pressure is 6 bar but incorrect scaling tells the program it is only 5 bar. The controller will increase its output even though the physical process is already at the required pressure.

No amount of PID tuning can correct a measurement chain that lies to the controller.

Before changing gains, verify the field instrument, electrical signal, ADC conversion and engineering scaling.

The Raspberry Pi GPIO pin is not a motor driver

The controller output presents another common mistake.

A GPIO output can provide a logic signal. It should not be expected to directly operate a motor, solenoid, contactor coil or other significant load.

The final interface may require a transistor stage, MOSFET, relay interface, H-bridge, isolated digital output, DAC, industrial I/O module or a dedicated motor controller.

For an AC pump or fan, a better architecture may be:

Raspberry Pi → command/reference → VFD → motor

rather than trying to create a power stage around the Raspberry Pi itself.

In fact, if the drive already includes a process PID controller, the simplest design may be to leave pressure or flow regulation inside the drive and use the Pi for supervisory functions. See PID control with a VFD.

The control interval matters more than CPU speed

A digital PID controller does not operate continuously in the mathematical sense. It repeatedly:

reads the measurement → calculates the error → calculates a new output → waits for the next cycle.

The time between those calculations is part of the controller.

If the controller is designed around a 100 ms sampling interval but sometimes runs after 100 ms, sometimes after 140 ms and occasionally after 300 ms, the integral and derivative behaviour may no longer match the intended tuning.

This variation in execution timing is commonly described as jitter.

For a large thermal process, a few milliseconds of jitter may be irrelevant. For fast motion or vibration control, the same timing variation may be unacceptable.

This is why time delay and process dynamics have to be considered before choosing the control platform.

Linux is doing more than your PID program

A normal Raspberry Pi Linux system may also be handling networking, storage, USB devices, display tasks, background services and other applications.

Your Python or C program therefore does not own the processor in the same way that a small bare-metal microcontroller may control its execution environment.

For slow processes this may not matter at all.

For time-sensitive control it needs to be measured rather than assumed.

Real-time PID control is therefore a more appropriate comparison than simply comparing processor clock frequencies.

PREEMPT_RT can improve timing, but it is not a magic checkbox

A real-time Linux configuration can significantly reduce scheduling latency and provide much more predictable execution than an ordinary desktop-style configuration.

That can make Linux suitable for control applications that would otherwise be difficult.

But installing or enabling real-time preemption does not automatically guarantee that every part of the system is deterministic.

The control path may still involve:

• USB devices,
• SPI or I2C transactions,
• network communication,
• device drivers,
• storage operations,
• user-space scheduling,
• other CPU workloads.

If timing is important, the system should be tested under realistic load and the worst observed latency should be examined, not only the average loop time.

Python is useful — but write the loop as a control program

Python is a practical choice for learning PID control, laboratory equipment, test stands and slower process systems. Its plotting, networking and data-processing ecosystem is also extremely useful during development.

A sensible software loop normally has more responsibilities than simply evaluating the textbook PID equation.

For example:

1. Acquire the process value.
2. Validate the measurement.
3. Convert it to engineering units.
4. Measure the actual elapsed time.
5. Calculate the control error.
6. Calculate P, I and D contributions.
7. Apply output limits.
8. Handle integral windup.
9. Send the command to the output interface.
10. Record important diagnostic values.
11. Detect missed or excessively late control cycles.

The underlying actions of P, I and D are explained separately in the components of a PID algorithm.

Use the actual elapsed time

A common software mistake is to assume that every loop took exactly the requested delay.

For example, a program may request a 100 ms sleep and then perform its PID calculation as though exactly 100 ms has passed.

On a multitasking system that assumption may not always be true.

The controller should normally use an appropriate monotonic time source to determine the actual elapsed interval used by the discrete integral and derivative calculations.

This does not remove timing jitter, but it prevents the software from pretending that late execution happened on time.

Derivative action and noisy measurements do not get along well

Real sensors are not perfectly quiet.

An analog pressure value may move slightly because of electrical noise, pump pulsation or ADC resolution. Temperature readings can also fluctuate. Encoder measurements contain their own quantization and timing effects.

Derivative action reacts strongly to rapid change, so measurement noise can produce an unnecessarily noisy D contribution.

Filtering may help, but filtering also introduces delay.

This is one reason PID design must be based on the actual process and measurement quality rather than on the assumption that all three terms should always be used.

Output saturation needs to be handled deliberately

Suppose a heater is already operating at 100% power but the temperature is still 15 °C below the setpoint.

The software cannot produce 140% heater power.

If the integral term continues accumulating error while the output is physically saturated, a large stored integral contribution may remain when the process finally approaches the setpoint. The result can be severe overshoot.

This is integral windup.

A practical Raspberry Pi controller should therefore have defined output limits and a suitable anti-windup strategy.

The same concept appears in industrial PID tuning and gain adjustment.

A sensor failure must not become a maximum-output command

This is where a classroom PID example can become dangerous in a real process.

Imagine a temperature sensor disconnects and the software interprets the failed reading as an extremely low temperature.

A naive PID loop may respond by commanding maximum heater output.

The software should distinguish between:

• a valid low process value,
• an impossible measurement,
• a communication timeout,
• stale data that has not changed for too long,
• a sensor-interface error.

Invalid measurements should trigger a defined fault response rather than simply being fed into the PID calculation.

Example: a temperature chamber is a reasonable Raspberry Pi PID project

Consider a small test chamber that needs to remain at 45 °C.

A suitable temperature sensor provides the process measurement. The Raspberry Pi receives this value through the appropriate electrical interface and calculates heater demand.

The process is relatively slow. Temperature does not normally jump from 30 °C to 45 °C in a few milliseconds.

This gives the controller time to measure, calculate, log and update the output without requiring an extremely fast loop.

The Pi can simultaneously:

• run the PID calculation,
• record temperature history,
• provide a web interface,
• change recipes,
• send alarms,
• export test data.

For this type of application, the computer-like features of Raspberry Pi can be an advantage rather than a problem.

The alternative dedicated-controller approach is covered in PID with a temperature controller.

Example: pressure control may be better left inside the VFD or PLC

Now consider a booster pump maintaining constant water pressure.

A pressure transmitter provides 4–20 mA feedback. The motor is already controlled by a modern VFD with a built-in PID function.

In that case there may be little value in sending the pressure to Linux, calculating PID in user space and sending a new speed command back to the drive every cycle.

A simpler architecture may be:

Pressure transmitter → VFD PID → Pump

while Raspberry Pi:

reads operating data → records trends → changes approved setpoints → provides remote monitoring.

Alternatively a PLC may execute the PID loop when multiple pumps, valves, permissives and machine sequences need to be coordinated.

The software platform should be selected around the process, not around a desire to make Raspberry Pi perform every available task.

Fast servo loops belong somewhere else in most projects

A servo drive may contain current, velocity and position loops operating at much higher rates than a typical slow process PID controller.

Replacing those internal loops with a normal Linux Python task is generally not a sensible starting architecture.

Raspberry Pi can still play a useful role. It may calculate a trajectory, generate higher-level targets, provide machine vision results or send position commands to a dedicated motion controller.

The fast feedback control remains in the hardware designed for it.

The distinction between these loops is discussed in PID control with servo motors.

Raspberry Pi and a microcontroller can make a good team

Using a microcontroller does not mean the Raspberry Pi has failed as the control platform.

It may simply be good engineering to divide the jobs.

For example:

Microcontroller: samples the sensor at a precise interval, executes the fast PID loop and updates PWM.

Raspberry Pi: supplies the setpoint, displays graphs, logs measurements, provides network connectivity and manages the user interface.

If Linux pauses briefly, the microcontroller continues controlling the process locally.

This type of architecture combines deterministic low-level control with the computing and networking advantages of Linux.

Compare this with PID control with microcontrollers.

Raspberry Pi and Raspberry Pi Pico should not be treated as the same controller

The shared name causes unnecessary confusion.

A Raspberry Pi computer normally runs an operating system and behaves like a compact Linux computer.

Raspberry Pi Pico products are microcontroller boards based on RP-series microcontrollers. Their software execution and peripheral architecture are fundamentally different from Linux-based Raspberry Pi computers.

Therefore a project described online as “Raspberry Pi PID” should be checked carefully before copying its circuit or timing assumptions.

A Pico example and a Raspberry Pi computer example may solve the same mathematical PID problem through completely different hardware architectures.

What happens after a reboot?

This question matters more in production than the elegance of the PID equation.

If power disappears and comes back:

• Does the control program restart automatically?
• Is the previous setpoint restored?
• Should the actuator remain off until the sensor is validated?
• What happens while network services are still starting?
• Is the integral term restored or reset?
• Could the output change unexpectedly during startup?

A real control system needs a defined startup state.

Starting a web server automatically is not the same problem as safely restarting a heater, valve or motor.

A watchdog helps, but it is not the safety system

A watchdog can detect that software has stopped responding and force a restart or another predefined action.

That is useful for availability.

It should not be confused with an independent safety function.

If uncontrolled heater operation can create a fire hazard, for example, the protection should not depend solely on the same Raspberry Pi and the same application software that performs the normal temperature control.

Likewise, emergency-stop and personnel-protection functions should be implemented using the required safety architecture for the machine.

PID control regulates normal operation. It is not a substitute for machine safety.

Industrial electrical noise changes the project

A Raspberry Pi running beside a keyboard on a workbench sees a friendly electrical environment.

Inside an industrial cabinet there may be VFDs, contactors, brake coils, motors and long analog cables switching around it.

Noise problems may appear as:

• unstable ADC measurements,
• communication errors,
• unexpected resets,
• corrupted readings,
• ground-loop problems.

Power supply quality, separation of signal and power wiring, shielding, grounding and isolation may therefore determine whether a prototype becomes a reliable machine.

Raspberry Pi, PLC or Industrial PC?

These platforms overlap, but they are not interchangeable.

Raspberry Pi is attractive for flexible software, networking, dashboards, data collection, laboratory systems and low-cost custom applications.

PLC is designed around industrial I/O, predictable machine operation, long-term maintenance and control engineering workflows.

Industrial PC provides computer-class processing while being available with hardware, interfaces and environmental characteristics intended for industrial installations.

A useful architecture may use more than one:

PLC closes the process loop → Raspberry Pi performs analytics or visualization.

Or:

Microcontroller closes a fast loop → Raspberry Pi manages the experiment.

Or:

Industrial PC runs the real-time application → remote SCADA handles supervision.

See PID control with industrial PCs for the computer-based industrial approach.

When Raspberry Pi is a good PID platform

Good candidates can include:

• laboratory temperature systems
• educational control experiments
• environmental chambers
• greenhouse or ventilation control
• slow pressure or level experiments
• test rigs with heavy data logging
• network-connected monitoring and control
• supervisory control above a PLC or microcontroller

Applications requiring much more careful engineering include:

• high-bandwidth servo loops
• current regulation
• vibration control
• tightly synchronized multi-axis motion
• very small and tightly bounded cycle times
• safety-related control functions

The difference is not whether Raspberry Pi has enough CPU power. The important quantities are required loop rate, acceptable jitter, I/O behaviour and the consequence of a missed deadline.

Before tuning Kp, Ki and Kd, check the complete loop

If a Raspberry Pi PID system performs poorly, use the signal path rather than immediately changing gains:

1. Is the sensor measuring the physical process correctly?
2. Is its electrical interface suitable for the Raspberry Pi system?
3. Is the raw value converted to the correct engineering unit?
4. Is the loop executing at the intended rate?
5. How much timing jitter occurs under realistic CPU and network load?
6. Are output limits correctly defined?
7. Does the actuator really follow the requested output?
8. Is the process physically capable of reaching the setpoint?
9. What happens when the sensor fails?
10. What happens when Linux, the application or the whole board restarts?

Only after this chain is known to be healthy does PID gain tuning become the logical next step.

Related Raspberry Pi and PID Topics

PID fundamentals: PID Control FAQ · What is PID? · P, I and D Components · PID Tuning

Control platforms: PID with Arduino · PID with Microcontrollers · PID with PLCs · PID with Industrial PCs

Measurement and field signals: Analog Signals · 0–10 V and 4–20 mA · Pressure Sensors · Temperature Sensors

Timing and real applications: Real-Time PID Control · Time Delay and Process Dynamics · PID with VFDs · PID with Temperature Controllers

Raspberry Pi boards, operating systems and I/O arrangements vary. Before using a Raspberry Pi in a control application, verify the actual sampling interval, worst-case latency, electrical interface, output behaviour and fault response under realistic operating conditions.