PID Control with Microcontrollers

PID control with microcontrollers ADC PWM timer interrupts and real-time control

PID Control with Microcontrollers: From Sensor Sampling to PWM Output

PID control with a microcontroller means implementing the feedback calculation in embedded software while the hardware reads a real sensor and drives a real actuator.

A typical control path is:

Sensor → ADC or digital interface → PID calculation → PWM / DAC / digital output → Actuator → Process

The basic PID equation may appear simple, but a reliable embedded controller requires much more than:

error = setpoint - processValue

and:

output = Kp × error + Ki × integral + Kd × derivative

Actual performance also depends on:

sample time,

ADC behaviour,

timer accuracy,

interrupt jitter,

numeric precision,

output saturation,

sensor filtering,

PWM timing,

fault handling.

An embedded PID loop is a real-time system, not just a formula written in C. Timing, scaling, numeric limits and the sensor/actuator chain are part of the controller.

For the control fundamentals, see What Is PID? and P, I and D Components.

Microcontroller or Microprocessor?

The terms are sometimes used loosely, but they are not identical.

A microprocessor - MPU mainly refers to the processing core and commonly depends on external memory and peripheral devices.

A microcontroller - MCU usually integrates the CPU with:

flash memory,

RAM,

ADCs,

timers,

PWM modules,

UART,

SPI,

I2C

on one device.

That makes microcontrollers particularly convenient for compact real-time control hardware.

MPU-based systems can also run PID, especially where a richer operating system, user interface or networking stack is required.

PID can run on either an MCU or MPU, but integrated timers, ADCs and PWM peripherals make MCUs especially practical for direct embedded control.

What Happens During One PID Cycle?

A practical embedded loop may perform the following sequence:

1. Acquire the sensor value.

2. Convert the raw measurement into engineering units.

3. Calculate SP - PV error.

4. Calculate proportional, integral and optional derivative terms.

5. Apply output minimum and maximum limits.

6. Apply anti-windup logic.

7. Convert controller output into PWM, DAC or another actuator command.

8. Execute the next cycle at the correct fixed interval.

The last point is critical.

A controller designed for a 1 ms or 10 ms sample time should not execute at an arbitrary interval simply because the main program loop happens to be available.

Main Loop or Timer Interrupt?

A simple educational controller may calculate PID inside:

while(1)

or another endless program loop.

But a real application may also be:

updating a display,

handling serial communication,

writing memory,

processing diagnostics.

If these tasks change execution time, PID timing also changes.

A common embedded architecture is therefore:

hardware timer → periodic interrupt → control-loop execution

This gives much more predictable timing.

If the controller is designed for a 10 ms sample period, one calculation at 8 ms, the next at 25 ms and the next at 11 ms can directly distort integral and derivative behaviour.

This is a central issue in Real-Time PID Control.

What Is Sample Time?

A digital PID controller calculates at discrete intervals.

This interval is commonly written as:

Ts - sample time.

A simple discrete integral can be written as:

I[k] = I[k-1] + Ki × e[k] × Ts

and a simple derivative as:

D[k] = Kd × (e[k] - e[k-1]) / Ts

Ts is therefore part of the mathematics, not just a software scheduling detail.

The relationship between execution timing and plant behaviour is discussed further in Time Delay and System Dynamics.

How Fast Should the PID Loop Run?

There is no universal correct sample rate.

It depends on the physical system.

Temperature control can be relatively slow.

Pressure and flow control may require faster execution.

Motor current control can run hundreds or thousands of times faster than a thermal loop.

Running PID unnecessarily fast does not automatically improve control. Running it too slowly can miss important plant dynamics.

What Is Timing Jitter?

Jitter means the control-loop execution interval is not perfectly constant.

A nominal 1 ms loop might actually execute at:

1.00 ms,

1.01 ms,

0.99 ms.

Small variation may be acceptable.

But large unpredictable variation can become a control problem.

Sources of jitter include:

long interrupt service routines,

interrupt priority conflicts,

blocking communication,

RTOS task scheduling,

slow peripheral operations.

Should Everything Run Inside the Control Interrupt?

Usually not.

The control ISR should normally remain:

short,

deterministic,

predictable.

Operations such as:

long printf calls,

blocking UART waits,

file handling,

display rendering

should generally not be placed inside a high-speed control ISR.

Slower supervisory tasks can run in the main loop or in lower-priority RTOS tasks.

Why the ADC Matters

In an analog-sensor system, the ADC is the entry point between the physical process and the digital controller.

ADC design should not be reduced to:

8 bit,

10 bit,

12 bit,

16 bit.

Also consider:

reference-voltage accuracy,

offset error,

gain error,

sampling rate,

input impedance,

noise.

A high-resolution ADC does not automatically produce a high-accuracy process measurement.

ADC Resolution and Process Resolution

A 12-bit ADC has:

4096 digital codes

in the ideal case.

If a 0-10 bar pressure signal uses the entire ADC range, the theoretical increment is approximately:

10 / 4095 ≈ 0.00244 bar

per code.

Real usable resolution can be worse because of:

sensor noise,

ADC noise,

reference instability.

Bit count is not the same thing as effective measurement accuracy.

How Do You Connect a 4-20 mA Sensor to an MCU?

A microcontroller ADC normally measures voltage, not loop current directly.

A 4-20 mA signal can be converted into voltage using an appropriate shunt resistor and signal-conditioning circuit.

For example:

250 Ω × 4 mA = 1 V

250 Ω × 20 mA = 5 V

But a real industrial input design should also consider:

ADC input limits,

isolation,

surge protection,

resistor power rating,

grounding.

For the instrumentation side, see 0-10 V and 4-20 mA and What Is an Analog Signal?.

Should Raw ADC Counts Be Used Directly?

They can be, but using engineering units often makes the application much easier to maintain.

Instead of controlling:

2478 ADC counts

the program can work with:

6.05 bar.

This allows:

setpoints,

alarm limits,

HMI values,

diagnostics

to use the same physical unit.

An input-scaling error can look exactly like a PID tuning problem.

ADC and PWM Synchronization

In switching power converters and motor drives, sampling at an arbitrary point can produce noisy measurements.

PWM switching edges create:

high dv/dt,

high di/dt,

ground bounce,

switching interference.

An MCU can trigger ADC conversion at a selected point within the PWM cycle where the current or voltage measurement is more reliable.

This is particularly important in fast current-control applications.

In some fast control systems, when the ADC samples can be as important as how many bits the ADC provides.

Can DMA Help?

DMA - Direct Memory Access can move ADC or communication data into memory without requiring the CPU to service every individual transfer.

This can reduce:

CPU loading,

interrupt traffic,

timing jitter.

However, DMA does not remove the need for correct:

buffer management,

sample synchronization,

control timing.

Using PWM as PID Output

Suppose the PID output is normalized to:

0-100%

This can be converted into:

PWM duty cycle,

motor-voltage demand,

heater switching ratio.

For example:

PID output = 65%

might become:

65% PWM duty.

But a heater controlled with a multi-second time-proportioning window is not equivalent to a motor inverter switching at tens of kilohertz.

The output method must match the actuator and process.

Using a DAC for Analog Output

If the MCU includes a DAC, the PID output can be converted into an analog voltage.

An external DAC and suitable signal-conditioning circuit can also generate industrial references such as:

0-10 V,

4-20 mA.

The MCU can then provide a reference to:

a control valve,

VFD,

servo amplifier,

power controller.

Fixed-Point or Floating-Point PID?

Embedded PID can use:

floating-point arithmetic

or:

fixed-point arithmetic.

Floating point simplifies scaling and algorithm development.

It can also execute efficiently on MCUs that include a floating-point unit.

Fixed point can be useful on:

lower-cost devices without an FPU,

applications that need predictable integer arithmetic,

highly optimized control code.

Neither method is automatically better.

What Are Q15 and Q31?

Q15 and Q31 are common fixed-point fractional-number formats.

They represent fractions using integer storage.

This allows efficient integer arithmetic but requires careful management of:

scaling,

overflow,

saturation,

precision.

Fixed-point PID is not simply replacing float variables with integers. Every intermediate value needs a deliberate numeric range and scaling strategy.

How Can Integer Overflow Break a PID Loop?

The integral accumulator can grow continuously.

A signed 16-bit integer only represents approximately:

-32768 to +32767.

If an accumulator exceeds its available numeric range, the result may wrap or saturate depending on the implementation.

A positive integral term can suddenly become a negative value and command the actuator in the wrong direction.

Fixed-point controllers may therefore require:

wider accumulators,

saturating arithmetic,

explicit integral limits.

Preventing Integral Windup in MCU Software

If controller output has reached its maximum and the error is still trying to push it higher, continuing to integrate that error can create windup.

Possible anti-windup approaches include:

integral clamping,

conditional integration,

back-calculation,

output tracking.

For the underlying control behaviour, see PID Troubleshooting.

Derivative Calculation in Embedded Software

A basic digital derivative can be written as:

D = Kd × (error - previousError) / Ts

But measurement noise can become strongly amplified by this difference calculation.

Practical implementations may therefore use:

filtered derivative,

derivative on measurement.

Derivative does not predict the future; it reacts to rate of change.

Using derivative on PV can also reduce derivative kick when the setpoint changes suddenly.

Is Sensor Filtering Always Helpful?

A low-pass filter can reduce noise.

But it also adds phase delay.

A large amount of filtering may be acceptable in a slow thermal process.

The same filter can destabilize or significantly slow a fast pressure, speed or current loop.

A smooth sensor trace is not automatically good feedback. Excessive filtering can make the controller act on old information.

Moving-Average Filtering

A moving-average filter is simple to implement.

It averages the most recent N measurements.

A larger N generally reduces high-frequency variation.

But it also increases effective response delay.

The window length must therefore be selected according to process dynamics rather than only by how smooth the display looks.

Why Use a Setpoint Ramp?

A sudden command such as:

0 → 100

can create a large control demand.

Embedded software can implement:

a setpoint ramp,

a slew-rate limiter.

A motor-speed command could, for example, be limited to:

100 rpm/s.

This becomes especially useful in PID Speed Control.

Output Clamping

The PID equation may mathematically calculate:

132%

output.

But the physical PWM output may only support:

0-100%.

The software therefore applies minimum and maximum limits.

But output clamping alone does not completely solve integral windup.

The internal integrator must also be handled appropriately.

Manual-to-Auto Transfer

Suppose a system is manually operating at 40% output.

If the PID's stored internal state corresponds to an 80% output when Auto is enabled, the actuator can jump suddenly.

Embedded controllers can avoid this with:

integrator initialization,

output tracking,

bumpless transfer.

This is part of the broader requirements described in Stable PID Operation.

Why Is a Watchdog Important?

If embedded software locks up, the actuator may remain at its previous output.

A heater could remain at 100%.

A motor could retain a high command.

A hardware watchdog can reset the MCU if the program stops executing correctly.

But reset behaviour must also be designed carefully.

A watchdog can reset the processor; it does not automatically make the machine safe. Output behaviour during reset and restart must also be defined.

Brown-Out Detection

When supply voltage falls below the range required for reliable MCU operation, the processor should not continue executing unpredictable instructions.

Brown-out detection can force the device into reset.

For motor-control, heater-control and power-converter hardware, the design should define what happens to outputs during:

power loss,

brown-out,

restart.

How Should Sensor Failure Be Handled?

A PID controller trusts its feedback unless the application checks whether the measurement is credible.

Useful fault checks include:

open circuit,

short circuit,

out-of-range measurement,

stuck value,

communication timeout.

For a 4-20 mA input, an abnormally low loop current can be treated as a wiring or transmitter fault if the input standard is designed accordingly.

When a critical sensor fails, the controller may need to:

disable normal PID action,

apply a predefined safe output,

raise an alarm.

NaN, Infinity and Invalid Numbers

Floating-point applications can produce invalid values through:

division by zero,

bad sensor conversions,

NaN,

infinity.

If these values propagate into the actuator command, output behaviour can become unpredictable.

Robust software can use:

range checking,

finite-number checks,

fallback values,

fault states.

PID with an RTOS

In an RTOS-based MCU, a PID loop can run as a high-priority periodic task.

However, scheduling can introduce:

priority inversion,

blocking on mutexes,

communication waits,

wake-up jitter.

A very fast motor-current loop may still be better implemented directly from a hardware timer interrupt.

A slower process controller can often run comfortably as an RTOS task.

There is no single architecture that is best for every loop.

Choosing MCU Processing Power

The processor must usually do more than calculate one PID equation.

Other workload can include:

ADC processing,

filtering,

communication,

display logic,

data logging,

state machines,

fault management.

Do not select an MCU only by clock frequency.

Also consider:

FPU,

DSP instructions,

interrupt latency,

DMA,

timer hardware,

PWM peripherals,

ADC trigger architecture.

Can an 8-Bit MCU Run PID?

Yes.

PID does not automatically require a high-end 32-bit processor.

A slow:

temperature loop,

basic speed loop,

process controller

can often be implemented successfully on an 8-bit MCU with careful numeric design.

High-performance servo or power-converter loops may require a more capable MCU or DSP because of:

higher sample rates,

multiple channels,

complex coordinate transformations.

How Does Arduino Relate to Microcontroller PID?

PID Control with Arduino is fundamentally a microcontroller PID implementation using a convenient hardware and software ecosystem.

Arduino itself is not a control theory.

The MCU on the board still:

reads sensors,

executes the PID calculation,

produces PWM or another output.

Using a PID library does not remove the need to understand:

sample time,

output saturation,

sensor quality,

process dynamics.

How Is This Different from Raspberry Pi?

PID Control with Raspberry Pi usually runs in a much richer Linux-based computing environment.

This provides strong:

networking,

database,

visualization,

high-level software

capabilities.

But standard operating-system scheduling is not as naturally deterministic as a bare-metal MCU timer interrupt.

A practical architecture can therefore use:

Raspberry Pi for supervisory functions,

MCU for fast deterministic control.

How Is FPGA Control Different?

PID Control with FPGA can provide highly parallel and deterministic hardware execution.

This can be useful when an application requires:

extremely high sample rates,

many control loops in parallel,

very low latency.

An MCU is usually easier and more flexible for many general embedded-control applications.

Microcontroller or PLC?

An industrial PLC typically provides ready-made:

isolated I/O,

industrial power supply,

communication interfaces,

programming software,

diagnostics.

An MCU provides greater freedom for custom electronics and high-volume product design.

A PLC PID block may be configured quickly.

On an MCU, the designer may be responsible for everything from:

ADC hardware

to:

watchdog and fault behaviour.

For the PLC approach, see PID Control with PLCs.

Motor PID with a Microcontroller

A basic DC motor system can use an encoder to measure actual motor speed.

The MCU can then perform:

Speed SP → Speed feedback → Speed PI/PID → PWM → Motor

In a more advanced motor drive, the speed loop may sit outside a much faster current loop.

This links directly with PID Speed Control, PID Torque Control and PID with Servo Motors.

Temperature PID with a Microcontroller

A temperature-control system may use:

thermocouple,

Pt100,

NTC,

digital temperature sensor.

The MCU reads the measurement and can control:

SSR time proportioning,

PWM,

analog power reference.

Because thermal dynamics are usually slow, extremely high PID execution rates are normally unnecessary.

Related pages include Temperature Sensors, Pt100 and PID Temperature Control.

Pressure and Flow PID with a Microcontroller

A 4-20 mA transmitter can be connected through an appropriate analog front end.

The MCU can:

measure the signal,

scale it into pressure or flow,

run a PI/PID loop,

generate a valve or pump-drive reference.

Useful related pages are Pressure Sensors, PID Pressure Control and PID Flow Control.

Can One MCU Run Nested Control Loops?

Yes.

A servo or motor-control system may use:

Position loop → Speed loop → Current loop

with different execution rates.

The current loop may be the fastest.

The speed loop may run slower.

The position loop may be slower again.

The inner loop should normally be substantially faster than the outer loop.

This is an important practical example of cascade and other control strategies.

Can PID Parameters Be Stored in Flash or EEPROM?

Yes.

Parameters such as:

Kp,

Ki,

Kd,

setpoint,

calibration values

can be stored in non-volatile memory.

But flash and EEPROM have finite write endurance.

The program should not write tuning values during every PID cycle.

Parameters should normally be saved only when:

the user changes them,

a controlled save command is executed.

Useful protection mechanisms include:

CRC,

configuration version numbers,

default fallback values.

Remote PID Tuning

Tuning parameters can be changed through:

UART,

RS-485,

CAN,

Ethernet,

other communication interfaces.

But remote parameters should always be checked for:

valid range,

authorization,

data integrity.

A communication error that changes Kp from 2 to 2000 can turn a useful control loop into a dangerous one.

PID Is Not a Safety Function

The MCU may correctly command a heater off when temperature rises.

But:

software can lock up,

the sensor can fail,

an output transistor can fail short circuit.

Critical equipment may therefore require independent:

thermal cutoffs,

pressure relief,

hardware overcurrent protection,

STO,

safety relays.

A PID running in firmware is a normal control algorithm. It should not be treated as the only protection against every dangerous failure mode.

Common Microcontroller PID Mistakes

Running PID at an uncontrolled speed in the main loop: sample time becomes variable.

Using delay() as the control scheduler: other tasks can disturb timing.

Ignoring Ts in integral and derivative calculations: tuning loses its intended meaning.

Incorrect ADC scaling: the PID sees the wrong physical process value.

Excessive filtering: feedbac