Electrical Drives & Control

Chapter 10
Digital Implementation, Estimation, and Embedded Control

Bachelors Program in Electrical Engineering
Electrical Drives & Control   •   Bachelor

Digital Implementation, Estimation, and Embedded Control

Introduction

Modern electrical drives are controlled by digital processors rather than by continuous analogue circuits alone. A microcontroller, digital signal processor (DSP), or field-programmable gate array (FPGA) samples currents, voltages, speed, and position; calculates control actions; and updates a power converter at prescribed instants. This implementation provides flexibility, diagnostics, communication, and sophisticated algorithms, but it also introduces sampling, computation delay, quantization, scheduling, and sensor-interface effects.

A mathematically correct continuous-time controller can therefore perform poorly when translated directly into software. The engineer must design the complete sampled-data loop: sensors, conditioning circuits, analogue-to-digital conversion, timing, algorithm execution, pulse-width modulation (PWM), actuators, and protection functions.

Learning Objectives

After studying this chapter, the reader should be able to:

  1. Explain sampling, discretization, computational delay, quantization, and their effects on drive stability.
  2. Convert common continuous-time controllers into implementable discrete algorithms.
  3. Design practical anti-windup and real-time scheduling strategies.
  4. Interface encoders, resolvers, Hall sensors, and current sensors with a controller.
  5. Explain observers, phase-locked loops (PLLs), and parameter-estimation methods.
  6. Select implementation practices that improve reliability, safety, and maintainability.

1. The Sampled-Data Drive System

A typical digital drive contains a reference generator, outer speed or position loop, inner current loop, PWM modulator, inverter, motor, sensors, and embedded processor. The current loop usually operates fastest, the speed loop more slowly, and supervisory functions more slowly still.

At sampling instant k, a controller receives measured data y[k], compares it with reference r[k], calculates an error e[k] = r[k] − y[k], and produces a command u[k]. The command is held, usually by a zero-order hold, until the next update.

The sampling frequency is f_s = 1/T_s, where T_s is the sampling period in seconds. Sampling must be sufficiently fast relative to the closed-loop bandwidth and must be synchronized with PWM switching. A common engineering practice is to choose the current-loop bandwidth well below the sampling frequency, often by a factor of 5 to 20, depending on delay, noise, and hardware capability. This is a design guideline rather than a universal law.

If a signal contains frequency components above f_s/2, aliasing can occur. The Nyquist frequency is f_s/2. An anti-aliasing filter must attenuate unwanted components before conversion; software cannot reliably reconstruct information that has already aliased.

2. Discretizing Controllers

2.1 Discrete integration

For a continuous integrator,

x(t) = ∫ e(t) dt

where e is the input and x is the integrator state. Forward Euler integration gives

x[k+1] = x[k] + Ts e[k]

This method is simple but introduces approximation error. It is acceptable when T_s is small relative to the relevant system time constants.

The backward Euler form is

x[k] = x[k−1] + Ts e[k]

It is more numerically damped and is useful when robustness is more important than exact frequency matching. The trapezoidal, or Tustin, form is

x[k] = x[k−1] + (Ts/2)(e[k] + e[k−1])

Tustin generally gives better frequency-domain correspondence near the design frequency, but it can require more computation and careful treatment of saturation.

2.2 A discrete PI controller

A continuous PI controller is

u(t) = Kp e(t) + Ki ∫ e(t)dt

where K_p is proportional gain and K_i is integral gain. With forward Euler integration, an implementation is

I[k] = I[k−1] + Ki Ts e[k]
u^*[k] = Kp e[k] + I[k]

Here I is the integral contribution and u* is the unsaturated command. If the actuator limits are u_min and u_max, the applied command is

u[k] = min(max(u^*[k], umin), umax)

The gains have units determined by the input and output variables. For a speed controller producing torque command, K_p has units of torque per speed and K_i has units of torque per speed-second.

An alternative incremental PI equation is

u[k] = u[k−1] + Kp(e[k] − e[k−1]) + Ki Ts e[k]

The positional form is often easier to combine with anti-windup and diagnostics; the incremental form can be convenient when the previous output is naturally available.

2.3 Mapping a first-order plant

For a continuous first-order model

τ dx/dt + x = K u

where τ is the time constant and K is the steady-state gain, exact zero-order-hold discretization gives

x[k+1] = a x[k] + b u[k]

with

a = e^(−Ts/τ), b = K(1 − e^(−Ts/τ))

This result assumes that u remains constant during each sampling interval. It is useful for digital simulation and controller design.

3. Delays, PWM, and Quantization

Digital control includes measurement delay, computation time, PWM update delay, and zero-order-hold behavior. A delay of one sample contributes the factor z^−1 in the discrete transfer function. Even a fraction of a sampling period can reduce phase margin, especially in a high-bandwidth current loop.

In center-aligned PWM, the effective instant at which a newly calculated duty ratio affects the average voltage depends on the timer update mechanism. The designer must consult the processor and inverter timing rather than assume an ideal instantaneous actuator.

Quantization maps a continuous measurement to a finite code. For an ideal N-bit ADC with input span V_span, the approximate voltage resolution is

ΔV = Vspan / 2N

The exact endpoint convention depends on the converter. If quantization error is modeled as uniformly distributed between −ΔV/2 and +ΔV/2, its variance is ΔV²/12; this statistical model is useful only when the signal spans many codes and is not correlated with the sampling process. At low speed, encoder quantization and ADC offsets may instead produce deterministic ripple.

Sensor offsets, gain errors, common-mode limits, amplifier saturation, and PWM common-mode voltage can be more important than nominal ADC resolution. Calibration should therefore measure zero offset, gain, polarity, and phase alignment.

4. Real-Time Scheduling and Software Architecture

A drive controller is a real-time system: correctness depends on both numerical results and execution time. A missed deadline can be equivalent to a faulty control law.

A practical task hierarchy is:

TaskTypical rateMain functions
PWM/current interruptSwitching rateADC capture, current control, duty update, protection
Speed loopLower than current loopSpeed control and torque reference
Position loopApplication dependentPosition control and trajectory generation
CommunicationVariableCommands, diagnostics, firmware interface
BackgroundSlowLogging, calibration, health monitoring

Interrupt service routines should be short and deterministic. Floating-point operations may be suitable on a DSP but costly on a small microcontroller. Fixed-point arithmetic can be efficient, but scaling, overflow, rounding, and saturation must be explicitly designed.

Worst-case execution time should be less than the available interval, including interrupt latency and safety checks. Shared variables require atomic access or a defined buffering strategy. A double-buffered data structure can prevent a communication task from reading a half-updated control record.

A useful implementation sequence is: acquire synchronized samples; validate sensor status; transform and filter measurements; execute the inner controller; apply limits and protection; update PWM registers; then execute slower tasks when permitted. Hardware overcurrent trips should not depend solely on software timing.

5. Anti-Windup and Practical Limits

Integrator windup occurs when the controller demands more actuator output than the inverter, voltage bus, current limit, or mechanical system can provide. The error remains nonzero, so the integrator continues accumulating. When the command becomes feasible again, the stored integral causes overshoot and slow recovery.

5.1 Conditional integration

A simple method disables integration when the output is saturated in the direction that would increase saturation. For positive saturation, integration is allowed only when e < 0; for negative saturation, it is allowed only when e > 0. This method is easy to implement but can produce discontinuities and is less effective during complex multivariable limiting.

5.2 Back-calculation

Let u* be the unconstrained output and u the limited output. Back-calculation modifies the integrator as

I[k+1] = I[k] + Ts[Ki e[k] + Kaw(u[k] − u^*[k])]

where K_aw is the anti-windup gain. The difference u − u* drives the integrator toward a value consistent with the achievable actuator command. The units of K_aw must make the second term an integrator-rate contribution. A common tuning choice is to select an anti-windup time constant T_aw and set K_aw = 1/T_aw, provided the controller structure and units are defined consistently.

Limits should be applied at every relevant level: current, voltage vector, modulation index, acceleration, and thermal capacity. In vector control, independently limiting d- and q-axis commands can distort the voltage vector; a circular or priority-based limiter may be more appropriate.

6. Sensor Interfaces

6.1 Incremental encoders

An incremental encoder supplies pulses, often with quadrature channels A and B, and sometimes an index channel Z. Quadrature decoding determines direction and provides four counts per mechanical cycle when all edges are used. If the encoder has P line cycles per revolution and four-edge decoding is used, counts per revolution are 4P.

Position can be estimated from the count n as

θm = 2πn/Ncpr

where N_cpr is counts per mechanical revolution and θ_m is mechanical angle in radians. Speed from count difference is

ωm[k] = (θm[k] − θm[k−1]) / Ts

This estimate becomes noisy at low speed because the count difference may remain zero for several samples. Period measurement or a combined position-speed estimator can improve low-speed behavior. Electrical angle for a motor with p pole pairs is

θe = p θm + θoffset

where θ_offset accounts for sensor alignment and should be calibrated.

6.2 Hall sensors and resolvers

Three Hall sensors provide six valid commutation states in a typical six-step drive. Their angular resolution is coarse, so interpolation or an observer is required for smooth sinusoidal control. A resolver provides sine and cosine signals whose ratio represents rotor angle. A resolver-to-digital converter or software tracking loop is needed, and excitation, phase shift, amplitude mismatch, and noise must be considered.

6.3 Current sensing

Shunt resistors, Hall-effect sensors, and fluxgate sensors are common. A shunt gives a voltage

Vsh = I Rsh

where I is current and R_sh is shunt resistance. An amplifier produces a measurable signal, but its common-mode range, bandwidth, offset, and propagation delay must be checked. Shunt losses are P_sh = I²R_sh, so thermal design is required.

Two- and three-shunt inverter measurements may have intervals in which one or more phase currents cannot be directly reconstructed because of PWM switching states. The software must identify valid sampling windows and use the current-sum relation i_a + i_b + i_c = 0 only when the system is a three-wire motor without a neutral current path and measurement errors are acceptable.

7. Observers and State Estimation

A sensorless drive estimates unmeasured states such as rotor position, speed, or back electromotive force from measured voltages and currents. A discrete state model is

x[k+1] = A x[k] + B u[k] + w[k]
y[k] = C x[k] + D u[k] + v[k]

where x is the state vector, u the input, y the measured output, A–D model matrices, and w and v process and measurement disturbances.

A Luenberger observer uses

x̂[k+1] = A x̂[k] + B u[k] + L(y[k] − Cx̂[k] − Du[k])

where x̂ is the estimated state and L is the observer-gain matrix. The estimation error dynamics are governed by A − LC. The gain must be selected so that the observer is sufficiently fast but not so fast that it amplifies noise or becomes sensitive to model errors.

The extended Kalman filter (EKF) handles nonlinear motor models by linearizing them around the current estimate and propagating state and covariance. It can estimate speed, position, resistance, or load torque, but requires credible noise covariances, sufficient computational capacity, and careful initialization. An EKF is not automatically superior to a well-designed simpler observer.

8. Phase-Locked Loops

A PLL estimates the phase of a periodic signal by driving a phase error toward zero. In a rotating-frame implementation, the measured signal is transformed using an estimated angle θ̂. A phase detector produces an error e_θ, a loop filter processes it, and an integrator generates the angle.

A basic angle-tracking structure is

ω̂[k] = ω̂[k−1] + Ki Ts e_θ[k]
θ̂[k+1] = θ̂[k] + Ts(ω̂[k] + Kp e_θ[k])

where K_p and K_i are PLL gains. The angle should be wrapped to a chosen interval, such as 0 to 2π. The PLL bandwidth must balance tracking speed against noise rejection. Grid-connected converters commonly use synchronous-reference-frame PLLs; motor drives may use PLLs to track back-EMF or encoder-derived position.

At very low speed, back-EMF amplitude becomes small, reducing observability. A PLL cannot recover reliable position from information that is physically absent; high gain merely increases noise sensitivity.

9. Parameter Estimation and Adaptation

Motor parameters vary with temperature, saturation, frequency, and operating point. Important parameters include stator resistance, inductance, rotor time constant, friction, and load torque.

For a scalar regression model

y[k] = φᵀ[k]θ + ε[k]

where φ is a known regressor, θ is an unknown parameter vector, and ε is error, recursive least squares (RLS) updates an estimate θ̂ using

K[k] = P[k−1]φ[k] / (λ + φᵀ[k]P[k−1]φ[k])
θ̂[k] = θ̂[k−1] + K[k](y[k] − φᵀ[k]θ̂[k−1])
P[k] = [P[k−1] − K[k]φᵀ[k]P[k−1]]/λ

Here P is the covariance or adaptation matrix and λ is the forgetting factor, normally 0 < λ ≤ 1. Persistent excitation is required: the input must contain enough independent variation to identify the parameters. A constant-speed, constant-load condition may not identify all motor parameters.

Adaptation must be bounded. Estimated resistance should not become negative, and parameter updates should be frozen when sensors are invalid, the model is unobservable, or the drive is in a transient outside the model assumptions.

10. Worked Example: Digital PI Current Control

Consider a current controller with K_p = 2 V/A, K_i = 400 V/(A·s), sampling period T_s = 100 μs, previous integral contribution I[k−1] = 8 V, and measured error e[k] = 3 A. The unconstrained command is

I[k] = 8 + (400)(0.0001)(3) = 8.12 V

The proportional contribution is K_p e = 6 V, so

u*[k] = 6 + 8.12 = 14.12 V

If the available voltage command is limited to ±12 V, the applied command is u[k] = 12 V. Without anti-windup, the integrator would continue increasing on subsequent samples while the command remained saturated. Back-calculation or conditional integration should therefore be enabled.

The calculation assumes that the error is constant over the integration interval, the gains use the stated units, and the voltage limiter represents the actual available actuator range.

11. Illustrative Case: Sensorless PMSM Drive

Background

An illustrative industrial pump drive uses a permanent-magnet synchronous motor (PMSM), an inverter, a DC-link voltage sensor, two phase-current shunts, and no mechanical encoder. The pump must operate efficiently over a wide speed range.

Problem

At medium and high speed, back-EMF provides useful position information. During starting and low-speed operation, back-EMF is weak. Direct use of a high-gain PLL causes noisy angle estimates, torque pulsation, and occasional loss of synchronism.

Analysis

The engineering team identifies three operating regions. At standstill, position is obtained from an initial alignment procedure. At low speed, an open-loop ramp with current limiting moves the rotor into an observable region. At medium and high speed, a back-EMF observer and PLL estimate electrical angle. The transition must be bumpless: the estimated angle and speed are initialized from the open-loop trajectory rather than abruptly reset.

Approach and solution

The current loop runs synchronously with center-aligned PWM. ADC conversions occur at a quiet midpoint of the PWM interval. Measured currents are offset-corrected, transformed into rotating coordinates, and controlled by d–q PI regulators with voltage-vector limiting and back-calculation anti-windup. The PLL bandwidth is reduced at low signal amplitude and increased only when a confidence measure indicates adequate back-EMF. A watchdog, hardware overcurrent trip, invalid-sensor detection, and safe PWM shutdown are implemented independently of the high-level estimator.

Outcome

The drive starts reliably, avoids excessive low-speed noise, and transitions smoothly to sensorless operation. Efficiency improves because the controller maintains appropriate electrical angle at operating speed. The case also demonstrates that an observer is part of a complete operating strategy, not a substitute for startup logic, protection, and validation.

Learning points

  1. Observability changes with speed and operating condition.
  2. Estimator confidence should influence control mode selection.
  3. Sampling synchronization can be as important as the control equation.
  4. Safety functions must remain effective when estimation fails.

12. Limitations, Safety, and Contemporary Practice

Digital implementation is limited by finite resolution, processor capacity, timing jitter, sensor bandwidth, model uncertainty, and electromagnetic interference. Numerical overflow can create catastrophic commands; therefore every intermediate quantity should have a known range. Unit consistency and polarity tests should be automated.

Embedded drives are cyber-physical systems. Communication commands must be authenticated or physically controlled where risk warrants it. Firmware should use version identification, fault logs, controlled updates, and traceable parameter changes. Functional-safety designs commonly separate safety-related shutdown paths from ordinary control software and follow applicable industrial standards and organizational risk assessments.

Hardware-in-the-loop simulation, processor-in-the-loop testing, automatic code testing, fault injection, and recorded-data replay reduce commissioning risk. Contemporary controllers increasingly use model-based design, automatic calibration, and machine-learning diagnostics. Machine learning may classify bearing or inverter faults, but it should not replace deterministic protection or an explainable safety mechanism. Any data-driven estimator must be validated over temperature, load, sensor faults, and production variation.

Best-Practice Checklist

  • Synchronize ADC sampling, computation, and PWM updates.
  • Design anti-aliasing and verify sensor bandwidth.
  • Account explicitly for computation and PWM delay.
  • Use saturation and anti-windup at every actuator constraint.
  • Calibrate sensor offset, gain, polarity, and angle alignment.
  • Bound all estimator parameters and handle loss of observability.
  • Measure worst-case execution time, not only average execution time.
  • Provide hardware-based overcurrent and emergency shutdown.
  • Test startup, reversal, saturation, sensor failure, and communication loss.
  • Record units, scaling, software versions, and calibration data.

Chapter Summary

Digital electrical drives are sampled-data systems whose behavior depends on sampling frequency, discretization, delay, quantization, PWM timing, and real-time execution. Continuous PI controllers can be converted into positional or incremental discrete forms, but actuator limits require anti-windup. Encoder, Hall, resolver, and current-sensor interfaces must account for resolution, timing, noise, offsets, and physical operating limits. Observers estimate unavailable states using motor models; PLLs track phase; and RLS or related methods estimate changing parameters when sufficient excitation exists. Reliable embedded control combines mathematical design with deterministic scheduling, protection, calibration, verification, and safe handling of estimator uncertainty.

Key Terms

Sampling period: Time between successive control samples.

Aliasing: Distortion caused when sampled data cannot represent signal frequency content correctly.

Zero-order hold: Assumption that a digital command remains constant between updates.

Quantization: Mapping of a continuous-valued signal to discrete numerical codes.

Computational delay: Time between measurement acquisition and application of a control result.

PWM: Pulse-width modulation used to control average converter voltage.

PI controller: Controller containing proportional and integral actions.

Windup: Excessive integrator accumulation during actuator saturation.

Back-calculation: Anti-windup method that feeds saturation error to the integrator.

Incremental encoder: Position sensor producing pulse transitions related to motion.

Quadrature: Two phase-shifted encoder signals used to determine direction.

Electrical angle: Rotor angle multiplied by pole-pair number and adjusted for alignment.

Observer: Algorithm that estimates unmeasured states from a model and measurements.

PLL: Feedback system that tracks the phase of a periodic or rotating signal.

Persistent excitation: Input variation sufficient to identify unknown parameters.

RLS: Recursive least-squares parameter-estimation algorithm.

Jitter: Variation in the timing of a nominally periodic task.

Worst-case execution time: Maximum execution duration considered in real-time scheduling.

Observability: Property describing whether internal states can be inferred from available inputs and outputs.

Review Questions

Short Answer Questions

  1. What is aliasing, and why is an anti-aliasing filter used?
  2. State the forward-Euler discrete integrator equation.
  3. Why does integrator windup occur?
  4. What information is obtained from encoder quadrature channels?
  5. Why can a back-EMF observer become unreliable at low speed?

Long Answer Questions

  1. Explain the complete signal and timing path from current measurement to PWM update in a digital drive.
  2. Compare forward Euler, backward Euler, and Tustin discretization for a PI controller.
  3. Explain back-calculation anti-windup and discuss the meaning of its tuning gain.
  4. Describe the architecture and timing requirements of a real-time embedded drive controller.
  5. Compare a Luenberger observer, an EKF, and a PLL in terms of purpose and limitations.

Analytical / Application Questions

  1. A PI controller has K_p = 1.5 V/A, K_i = 300 V/(A·s), T_s = 200 μs, I[k−1] = 4 V, and e[k] = 2 A. Calculate the new integral contribution and unconstrained output if the previous error is irrelevant to the positional form.
  2. An encoder has 2,500 line cycles per mechanical revolution and four-edge decoding. Determine counts per revolution and the mechanical angle represented by 1,000 counts.
  3. Design a startup and transition strategy for a sensorless PMSM drive whose back-EMF observer is unreliable below 10% rated speed. Identify the required control modes, transition conditions, protections, and validation tests.

Multiple Choice Questions with Answers

Question 1

What is the main purpose of an anti-aliasing filter before an ADC?

A. To increase PWM frequency

B. To attenuate frequency components that could alias

C. To eliminate actuator saturation

D. To calculate rotor position

Correct Answer: B. To attenuate frequency components that could alias

Question 2

For forward-Euler integration, which equation is correct?

A. x[k+1] = x[k] − T_s e[k]

B. x[k+1] = x[k] + T_s e[k]

C. x[k+1] = x[k]/T_s + e[k]

D. x[k+1] = T_s x[k] + e[k]

Correct Answer: B. x[k+1] = x[k] + T_s e[k]

Question 3

A 12-bit ADC has an ideal input span of 4.096 V. Its approximate voltage resolution is:

A. 1 mV

B. 4 mV

C. 12 mV

D. 16 mV

Correct Answer: A. 1 mV

Question 4

What causes integrator windup?

A. The actuator saturates while the integrator continues accumulating error

B. The sampling frequency is exactly twice the signal frequency

C. The encoder has quadrature channels

D. The PLL angle is wrapped

Correct Answer: A. The actuator saturates while the integrator continues accumulating error

Question 5

With four-edge decoding, an encoder with 2,000 line cycles per revolution provides:

A. 500 counts per revolution

B. 2,000 counts per revolution

C. 4,000 counts per revolution

D. 8,000 counts per revolution

Correct Answer: D. 8,000 counts per revolution

Question 6

In a Luenberger observer, the term L(y − Cx̂ − Du) primarily:

A. Limits the PWM duty ratio

B. Corrects the model estimate using measurement residual

C. Calculates ADC resolution

D. Sets the motor pole-pair number

Correct Answer: B. Corrects the model estimate using measurement residual

Question 7

What is required for reliable identification of multiple motor parameters using RLS?

A. A completely constant input

B. Persistent excitation and valid measurements

C. Removal of all feedback

D. An infinitely high forgetting factor

Correct Answer: B. Persistent excitation and valid measurements

Question 8

Why is a PLL based on back-EMF difficult to use at standstill?

A. Back-EMF amplitude is very small or absent

B. The ADC has too many bits

C. PWM cannot be synchronized

D. The motor has no electrical angle

Correct Answer: A. Back-EMF amplitude is very small or absent

Question 9

For a motor with p pole pairs, the electrical angle is generally related to mechanical angle by:

A. θ_e = θ_m/p only

B. θ_e = pθ_m + θ_offset

C. θ_e = θ_m − p

D. θ_e = p/θ_m

Correct Answer: B. θ_e = pθ_m + θ_offset

Question 10

Which scheduling property is most important for a current-control interrupt?

A. Large random timing variation

B. Deterministic completion before the required update deadline

C. Execution only after background logging

D. Unlimited computation time

Correct Answer: B. Deterministic completion before the required update deadline

Electrical Drives & Control
Chapter 10 of 14