Skip to main content
emobility.academy
M.TechMotor controlAdvanced About 8 weeksKit + add-ons

Relay-Feedback PID Auto-Tuning for an EV Motor Speed Loop

Build an auto-tuner that finds PID gains for a DC motor speed loop by running a relay-feedback experiment on the STM32. You compare the auto-tuned gains with manual and step-response tuning on overshoot, settling time and integrated error.

Uses: PWM · GPIO · UART

The problem

Motor controllers in vehicles must be tuned for each motor and load, and manual tuning is slow and depends on the engineer. Relay-feedback auto-tuning finds the ultimate gain and period from a short, controlled oscillation, which a controller can do on its own in the field.

Objectives

  • Implement a relay with hysteresis around a speed set-point and detect the limit cycle
  • Compute ultimate gain and period and derive PID gains with several tuning rules
  • Compare auto-tuned, step-response and manual gains on quantified metrics
  • Study sensitivity to relay amplitude, hysteresis and load

What you need

From the EV Embedded Development Kit

  • STM32F103C8T6 microcontroller unit (Arm Cortex-M3)
  • Motor driver for PWM motor-control experiments
  • Analog potentiometer input
  • 4×3 matrix keypad
  • Serial UART interface
  • 16×2 LCD

Software

  • STM32CubeIDE with HAL TIM (PWM, encoder) and UART
  • Embedded C
  • Python with NumPy, SciPy, pandas and matplotlib
  • MATLAB (optional) for frequency-response checks

Extra parts

  • A small brushed DC gear motor with a quadrature encoder, within the motor driver's rating — The kit has no motor and no speed sensor; the encoder provides speed feedback.

Key concepts

Relay feedback
Replacing the controller with an on/off relay around the set-point makes most plants oscillate at the frequency where their phase lag is 180 degrees.
Ultimate gain
From the describing function, Ku is 4d divided by pi times a, where d is relay amplitude and a is output oscillation amplitude; the period Pu is measured directly.
Tuning rules
Ziegler–Nichols, Tyreus–Luyben and similar rules turn Ku and Pu into PID gains, with different trade-offs between speed and robustness.
Hysteresis
A small dead zone in the relay stops measurement noise from causing chattering, at the cost of a small, correctable bias in the estimate.

Step-by-step guide

  1. 1

    Plan the experiment

    Write the test method before touching the hardware: a relay around a mid-range speed set-point with bias duty d0, amplitude d and hysteresis h, run until several stable oscillation cycles are seen. Choose the metrics you will use to judge every gain set: overshoot, settling time, integral of absolute error and control effort, measured on a standard set-point step and a standard load step. List the tuning rules to compare and the number of repeats for each test.

    Checkpoint: A test plan with set-points, relay parameters and metrics.

  2. 2

    Board and encoder setup

    Use the DIP switches to enable the motor driver, keypad and LCD. Configure the 72 MHz clock, a 20 kHz PWM channel, a timer in encoder mode on the encoder pins, a 100 Hz control timer and a UART at 115200 baud for logging. Compute speed every 10 ms from the signed difference of encoder counts. Check the reading at a fixed duty against a timed count of shaft revolutions before using it for any tuning.

    Checkpoint: Speed reading is steady at a fixed duty and matches a timed revolution count.

  3. 3

    Identify the plant as a baseline

    Run open-loop duty steps around the operating point you will tune at and log speed. In Python, fit a first-order-plus-dead-time model with SciPy's least-squares tools and check the fit by overlaying the simulated response on the measured one. Use the model to compute PID gains with a step-response rule such as SIMC. These gains are one of your baselines, and the model lets you check the relay results independently.

    Checkpoint: A fitted model whose simulated step response overlays the measured one.

  4. 4

    Implement the relay

    Replace the controller with a relay in the 100 Hz interrupt: set duty to the bias d0 plus amplitude d when speed is below the set-point minus hysteresis h, and to d0 minus d when it is above the set-point plus h. Choose d0 so the motor runs near the set-point on average and d small enough to stay within limits. Record speed and the time of each relay switch, and watch the motor settle into a steady oscillation.

    Checkpoint: The motor speed oscillates in a steady limit cycle around the set-point.

  5. 5

    Detect the limit cycle

    Track the peaks and troughs of speed and the period between relay switches. Declare the cycle stable when the last three periods and amplitudes agree within 5%, then average them. Add safety aborts: stop the test if speed leaves a safe band, if no oscillation appears within a time limit, or if the test runs too long. Report the estimated ultimate gain Ku and period Pu, and repeat the test several times to check repeatability.

    Checkpoint: The tuner reports Ku and Pu, and repeated runs agree within a few per cent.

  6. 6

    Compute gains

    Correct the measured amplitude for the relay hysteresis, then compute Ku as 4d divided by pi times the amplitude, and read Pu from the averaged period. Compute PID gains with Ziegler–Nichols, Tyreus–Luyben and one more rule of your choice. Convert the gains to the fixed-point format used by the controller and show the selected set on the LCD. Recompute the same gains on the PC from the logged data to check the firmware arithmetic.

    Checkpoint: Computed gains match a PC recalculation from the same logged data.

  7. 7

    Switch to PID control

    After the tune, switch to a PID with anti-windup using the selected gains. Make the changeover bumpless by initialising the integrator so the first PID output equals the last relay bias duty. Use keypad keys to start a new tune and to choose which tuning rule's gains are active. Check that the speed settles at the set-point after changeover without a visible jump, and that a new tune can be started safely while running.

    Checkpoint: The motor settles at set-point with the new gains without a jump at changeover.

  8. 8

    Quantified comparison

    For each gain set, namely manual, step-response, and each relay-based rule, run five set-point steps and five load steps under the same conditions. In Python compute overshoot, settling time, integral of absolute error and control effort for every run. Present the mean and spread in a comparison table and overlay representative responses. Say which gains you would ship and why, using the metrics rather than visual impressions.

    Checkpoint: A comparison table with means and spread for every gain set.

  9. 9

    Sensitivity study

    Repeat the auto-tune while varying one setting at a time: relay amplitude, hysteresis width, set-point speed and an added mechanical load. Plot the estimated Ku and Pu against each setting, and run the closed-loop tests again with the resulting gains. This shows how robust the method is in practice and which settings matter. Recommend relay settings for this class of motor based on the results, with the evidence alongside.

    Checkpoint: Plots of estimated Ku and Pu against each parameter.

  10. 10

    Report

    Write up the theory of relay feedback and the describing-function result, the firmware implementation and its safety aborts, the comparison against manual and model-based tuning, and the sensitivity results. Present clear tables and figures, and discuss sources of error such as friction, encoder quantisation at low speed and the first-harmonic approximation. Finish with recommendations for using the auto-tuner on a different motor.

    Checkpoint: A report with tables and figures suitable for review.

Testing & validation

  • Repeatability of Ku and Pu over repeated tuning runs
  • Gains checked against PC recomputation
  • Closed-loop metrics for every gain set, five repeats each
  • Sensitivity of results to relay amplitude, hysteresis and load

Expected results

An on-board PID auto-tuner that finds gains from a short relay test, with quantified evidence of how its gains compare with manual and model-based tuning and how robust the method is to its settings.

Research angle for your M.Tech thesis

Research questions: how accurate are relay-based estimates of Ku and Pu on a geared DC motor with friction and quantised encoder speed, and which tuning rule gives the best robustness–performance trade-off? Metrics: IAE, overshoot, settling time, control effort, gain and phase margins computed from the identified model. Baselines: manual tuning and SIMC from a step-response model. Publishable work could propose a correction for friction or quantisation bias and show measured improvement over standard rules.

Take it further

  • Add gain scheduling with a separate tune at several operating points
  • Use a two-relay test to estimate a second frequency point
  • Run the tuner as a FreeRTOS task alongside other vehicle functions

Viva and review questions

Why does a relay produce an oscillation at the ultimate frequency?

The relay's describing function has zero phase, so the loop oscillates where the plant's phase lag reaches 180 degrees, which is the ultimate frequency.

How do you compute Ku?

Ku is 4d divided by pi times a, with d the relay amplitude and a the measured output amplitude.

Why add hysteresis?

Without it, encoder noise near the set-point makes the relay chatter; hysteresis gives clean switching, and its bias can be corrected.

Why compare several tuning rules?

Ziegler–Nichols is aggressive with large overshoot, while rules like Tyreus–Luyben are more conservative, so the best choice depends on the application.

Related EV projects

All 100 EV projects