Top 100 Mechatronics Engineer Interview Questions and Answers
The questions most likely to come up in your Mechatronics Engineer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed: —
Q&A-1Walk me through the PID loop on a servo axis: what does each term do to the step response, and how would you tune it on real hardware?
The 90-second answer
A servo axis closes position error with a PID controller that turns error into a torque or current command. On a small industrial axis I would run the position loop at 4 kHz, estimate velocity from the encoder at the same rate, and leave the current loop in the drive at 16 kHz or faster. The PID output is clamped to the drive current limit, and the integral term is not updated while that clamp is active and the error would push it further into saturation.
The controller I would write is:
// Position PID, called every 250 us (4 kHz). Gains are in SI units.
float error = setpoint - position;
float velocity = -(position - prev_position) / dt; // derivative on measurement
deriv_filt += alpha * (velocity - deriv_filt);
float p = kp * error;
float d = kd * deriv_filt;
float i_candidate = integral + error * dt;
float raw = p + ki * i_candidate + d + feedforward;
float out = clamp(raw, -i_limit, i_limit);
// Conditional integration: freeze the integrator while saturated
// in the direction the error is pushing.
bool saturated = (out != raw);
if (!saturated || (error * out < 0.0f)) {
integral = i_candidate;
}
prev_position = position;
return out;Derivative on measurement matters here. Differentiating error gives a kick when the setpoint steps, which saturates the drive for one cycle and excites the coupling. The filtered derivative term above still damps motion, without that kick. For the filter, I set alpha = dt / (tau + dt) and choose the time constant tau so the filter corner sits well below encoder noise and well above the mechanical bandwidth I am trying to damp. I verify that choice by watching standstill current, not by trusting a default.
What each term does to a step
| Term | Step response effect | What goes wrong if overdone |
|---|---|---|
| --- | --- | --- |
| P | Raises stiffness and speed. Rise time falls, steady state error remains under gravity or friction. | Overshoot, then sustained oscillation if the loop phase margin collapses. |
| I | Removes steady state error by building torque while error persists. | Windup during saturation, long overshoot and a slow tail after the move. |
| D | Adds damping based on velocity. Overshoot falls and ringing settles faster. | Amplifies encoder quantisation and velocity noise into current chatter. |
Feedforward carries most of the torque for a known move profile, so the PID only corrects model error and disturbances. Without it, the integral term has to do that work on every move and tuning becomes a compromise between tracking and stability.
Tuning on real hardware
I start with the axis mechanically sound. Backlash, a loose coupling, or a resonance in the mount will look like a tuning problem and no gain fixes it. I check that with a small manual jog and by looking at the velocity spectrum at rest.
Then, with the axis unloaded or lightly loaded and travel limits set in software:
- Set I and D to zero. Raise P until the step shows about 10 to 20 percent overshoot or the velocity trace starts to ring. Back off 30 percent. That gives a usable proportional gain.
- Add D until overshoot drops without audible noise or visible current ripple at standstill. If standstill current rises, the derivative filter corner is too high or the encoder resolution is too coarse for that gain.
- Add I slowly, watching a small step and a held position against a disturbance such as a cable pull. The integral should remove offset in a few hundred milliseconds. If the axis hunts around the target, I is too high or friction is causing stick slip.
- Test the full move at increasing speed and payload. Gains that work unloaded often oscillate with a heavier tool because inertia rises and the resonance frequency falls. I retune at worst case payload and accept slower response unloaded.
- Verify saturation behaviour. Command a large step, confirm the output sits at the current limit briefly, then comes off cleanly with no integral tail. That test catches windup faster than any small signal test.
Two failure modes show up in production. First, a resonance that only appears at certain positions, common with a long arm or a belt drive. The fix is a notch filter in the drive or a lower bandwidth, not more D gain. Second, limit cycling at rest from integral action plus static friction. The axis creeps, sticks, then jumps. A small deadband on the integral term, or friction feedforward, stops it without giving up accuracy on larger moves.
I would close by logging position, velocity, error and output for the tuning steps. A candidate gain set that looks good on a scope trace but leaves a 200 ms settling tail in the log is not tuned.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2An intermittent machine fault could be mechanical, electrical, or firmware. What is the first check you would make before tearing the machine down?
The 90-second answer
I would check the fault log and reproduce the fault with logging running before I touched any hardware. That is the rule for an intermittent fault: capture evidence first, because opening the machine, reseating a connector, or swapping a part often clears the symptom and destroys the only clue you had.
In practice that means making the machine safe, noting the exact symptom, and pulling the drive fault code, controller event log, and any timestamps for the last few occurrences. Then I run the same cycle that triggers it while logging position, current, supply voltage, and controller status on one time base. If the fault repeats, the log usually tells me which layer to open next. If it does not repeat, I have at least a baseline and I have not disturbed the machine.
Why this comes first
A mechanical, electrical, and firmware fault can look the same from outside. The axis stops, the cycle aborts, the operator resets it, and it runs again. The log separates them. A drive undervoltage code points to supply or load. A following error at a fixed position points to encoder, belt, or obstruction. A watchdog reset with no drive code points to firmware or controller timing. Without that record I am guessing, and guessing usually means swapping parts until the fault happens to clear.
| Log finding | Likely layer | Next check |
|---|---|---|
| Drive reports undervoltage during acceleration | Electrical | Measure the rail at the drive terminals under load |
| Following error at the same position every time | Mechanical or encoder | Inspect belt, guide, and encoder signal at that position |
| Watchdog reset, drive still powered, no fault code | Firmware | Check task timing, stack use, and recent code changes |
| No code logged, fault only when a cable flexes | Electrical connection | Flex the cable through full travel while watching the signal |
A concrete trace
Suppose the log shows the same drive code, UV, at 14:03:12 and 14:41:55, both during acceleration. That pattern alone saves a teardown. I would measure the 24 V rail at the drive while repeating that acceleration. If the rail dips there but is steady at the supply, the fault is between the supply and the drive: a loose connector, a damaged cable, or a load drawing too much current. If the rail is steady at the drive too, I move on to the load that acceleration is asking for, such as a binding axis or a brake that is not releasing.
The common mistake is to start with the most visible part. Reseating a connector or swapping a motor can make an intermittent fault vanish for weeks, and then nobody knows whether the part was faulty or the connector was simply disturbed. Logging first keeps the diagnosis honest. I change one thing at a time after that, and I only call it fixed when the original cycle, at the original load, runs clean for a defined number of repetitions.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Walk me through how you would select a sensor to measure 0 to 50 mm displacement on a moving stage at 200 Hz, given you need 1 µm repeatability in a noisy factory environment?
The 90-second answer
I start from the measurement, not the catalogue. For a 0 to 50 mm stage needing 1 µm repeatability at 200 Hz in a factory, I write down five numbers first: range with overtravel, resolution I must resolve, accuracy I must guarantee after calibration, bandwidth of the real motion, and the environment. Resolution, accuracy and repeatability are different. A sensor can resolve 0.1 µm and still be 20 µm wrong because of linearity error, thermal drift or mounting. I only shortlist a technology after those five numbers rule most of them out.
For linear displacement the credible shortlist is LVDT, capacitive probe and optical encoder or interferometer. The table shows why the choice turns on the environment and the mounting, not on the headline resolution.
| Technology | Strength | Limit that matters here |
|---|---|---|
| LVDT | Tolerates vibration, dirt and misalignment, contactless | Bandwidth and resolution fall with stroke, needs AC excitation and demodulation |
| Capacitive probe | Sub-micrometre resolution, high bandwidth, no contact | Gap must be held stable, sensitive to contamination, tilt and cable movement |
| Optical encoder / interferometer | Direct digital counts, excellent repeatability, high bandwidth | Needs clean scale or reflector, alignment and thermal expansion of the structure dominate |
On a dirty, vibrating stage with a 50 mm stroke I would default to an LVDT or a sealed encoder and prove the error budget. On a clean metrology frame where I can control the gap I would consider capacitive. I would not pick a strain gauge or a potentiometer here. The potentiometer wears and its resolution is set by wiper contact, and a strain gauge measures strain, so displacement would need a flexure and a bridge calculation that adds compliance.
Worked numbers
Range 50 mm for 1 µm repeatability is 50,000 distinguishable steps. That is log2(50,000) = 15.6 bits before noise. A 16 bit ADC over a 0 to 10 V span gives an LSB of 10 / 65,536 = 153 µV, or 50 mm / 65,536 = 0.76 µm per count. That looks sufficient on paper and fails in practice if the front end noise is 4 LSB rms, because the effective number of bits drops to about 12 and the noise floor becomes roughly 12 µm peak to peak. I therefore budget noise, not bits: I want the conditioned signal noise below 0.3 µm rms at the ADC input, I use differential signalling, and I check the sensor datasheet for noise density in µm per sqrt(Hz) over the bandwidth I actually use.
Bandwidth sets sampling and filtering. Motion at 200 Hz needs sampling well above 400 Hz, the Nyquist limit, and in a control loop I would sample at 2 to 5 kHz so the loop sees the measurement with low delay. The anti-alias filter goes before the ADC, typically a low pass at 500 Hz to 1 kHz for a 2 kHz sample rate, with the sensor bandwidth at least 5 times the signal bandwidth so its phase lag does not eat phase margin. If the sensor is an LVDT with a 5 kHz carrier, I demodulate and filter after demodulation, and I keep the carrier away from drive PWM frequencies.
Accuracy is closed by calibration and temperature. I calibrate at 0, 10, 25 and 50 mm against a reference, fit the linearity error, and record drift over the expected temperature range. A steel structure expands about 12 µm per metre per degree C, so a 0.5 m frame moves 6 µm per degree. That alone can consume the whole budget, which is why the sensor choice includes where it is mounted and what it measures against.
# Python 3.11, illustrative budget for the stage above
range_mm = 50.0
target_um = 1.0
steps = range_mm * 1000 / target_um
import math
print(f"steps={steps:.0f}, bits={math.log2(steps):.1f}")
print(f"16-bit LSB = {range_mm/65536*1000:.2f} um")
# 4 LSB rms noise -> effective resolution
print(f"noise floor at 4 LSB rms = {4*range_mm/65536*1000:.1f} um rms")Signal conditioning and failure modes
The chain is sensor, excitation or supply, amplifier, filter, ADC, and only then digital filtering. Each stage has a job. An LVDT needs a stable AC excitation and a synchronous demodulator. A bridge sensor needs a ratiometric reference so supply drift cancels. A capacitive probe needs a guarded, short, fixed cable because cable capacitance is part of the measurement. In all cases I use a differential pair into the ADC, a single point ground at the controller, shielded twisted pair, and I route sensor cables away from motor power and PWM. Grounding the shield at both ends is a common cause of hum in a cabinet with variable frequency drives.
The failure modes I test for are saturation on overtravel, aliasing of vibration above the sample rate, thermal drift during warm up, and Abbe error from measuring off the axis of motion. Saturation is detected by a raw count rail check and by sizing the range 20 percent beyond the working stroke. Aliasing shows up as a false low frequency component, so I run a swept vibration test with the loop open. Thermal drift shows in a soak test at fixed position. Abbe error shows when the reading changes with lateral load, which points to moving the sensor onto the measurement axis rather than buying a higher resolution part.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Walk me through how you would size a motor and actuator for a 10 kg linear stage that must accelerate at 2 m/s² to 0.5 m/s with a 5 mm lead screw, including torque, speed and duty cycle?
The 90-second answer
I start from the load at the actuator shaft, work backwards through the transmission, then check speed, peak torque and RMS torque against the motor datasheet. I state the assumptions first because they change the answer: horizontal or vertical axis, friction, move profile and dwell. A motor that meets peak torque but overheats on RMS torque, or that cannot reach the required speed, is the wrong motor.
Take a concrete case. A 10 kg horizontal stage, linear guides, 5 mm pitch ball screw, efficiency 0.85, must reach 0.5 m/s at 2 m/s². Assume 15 N of guide and seal friction, labelled as an assumption to measure on the real rig.
Force during acceleration:
F = m*a + F_friction = 10*2 + 15 = 35 NScrew torque:
T = F * pitch / (2*pi*eta) = 35 * 0.005 / (2*pi*0.85) = 0.033 N*mAdd screw and coupling inertia, roughly 20 percent here, giving about 0.040 N*m peak. Screw speed is the problem:
rev/s = v / pitch = 0.5 / 0.005 = 100 rev/s = 6000 rpmThat is high for a small screw. Critical speed and buckling become real limits, so I would either increase pitch to 10 mm, which halves speed to 3000 rpm and doubles torque to about 0.066 N*m, or switch to a belt drive. That trade is the core of sizing: pitch trades speed against torque.
Mechanical power at top speed is F*v = 17.5 W, so a 50 to 100 W servo class motor is plausible after drive losses, but power alone does not select it. Torque and speed curves do.
Duty cycle and RMS torque
Peak torque tells you if the motor can accelerate. RMS torque over the full cycle tells you if it survives thermally. Suppose the cycle is 0.25 s acceleration, 1 s cruise, 0.25 s deceleration, 2 s dwell, repeated.
During cruise, force is friction only, 15 N, so torque is about 0.014 N*m. During dwell on a horizontal axis, torque is near zero. RMS torque:
T_rms = sqrt((0.040^2*0.5 + 0.014^2*1.0 + 0^2*2.0) / 3.5) = 0.017 N*mI would select a motor with continuous torque above 0.017 Nm at 6000 rpm, peak torque above 0.060 Nm after a 1.5 margin, and a rated speed comfortably above 6000 rpm. I would also check the torque at speed on the datasheet curve, because continuous torque at stall and at 6000 rpm are different numbers.
A short Python check keeps the arithmetic honest when pitch or mass changes:
import math
def size(m=10, a=2, f_fric=15, pitch=0.005, eta=0.85, v=0.5):
F = m*a + f_fric
T_peak = F * pitch / (2*math.pi*eta) * 1.2 # inertia allowance
rpm = v / pitch * 60
return F, T_peak, rpm
print(size()) # (35, 0.039, 6000.0)Choosing the actuator type
| Type | Strength | Limit that decides it |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| BLDC servo with encoder | High speed, torque at speed, closed loop following error | Cost, drive tuning, needs brake on vertical axis |
| Stepper, open loop | Simple, holds position at standstill, cheap | Torque falls sharply with speed, missed steps are silent, heating at low speed |
| Pneumatic cylinder | Simple force, tolerant of overload | Poor stiffness and position control, needs external encoder and servo valve for precision |
For this stage I would pick a BLDC servo. A stepper at 6000 rpm has little torque left and no feedback to detect a lost step. Pneumatics would struggle to hold 2 m/s² smoothly with a 10 kg load.
Failure modes I check before ordering
Vertical axis changes everything. Gravity adds mg = 98 N, roughly 0.092 Nm of holding torque on this screw, so the motor needs a brake and the drive needs a safe stop on power loss. Backdriving is possible with a ball screw, unlike a worm gear.
Thermal failure shows up as rising winding resistance and current for the same move, then a thermal trip. I detect it by logging RMS current per cycle and winding temperature on the first article, not by waiting for the trip.
Inertia mismatch causes oscillation and following error even when torque looks adequate. Reflected load inertia should stay within roughly three times the rotor inertia for a stiff servo loop, and I verify that with a step response and a measured following error at top speed.
Finally, I validate on the rig: commanded versus encoder position, peak and RMS current, and temperature after 30 minutes at the worst duty cycle. If RMS current is within 80 percent of the continuous limit, I upsize the frame or reduce dwell time in the cycle rather than relying on the drive limit.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Walk me through how closed-loop feedback controls a motorised stage, and how you would read overshoot, settling time and steady-state error from its step response?
The 90-second answer
Closed-loop control measures what the plant actually did, compares it with the setpoint, and drives the error toward zero. For a motorised stage: setpoint minus encoder position gives error, the controller turns that error into drive voltage or current, the motor and load move, and the encoder reports the new position. Open loop would apply a fixed voltage and hope friction, load and supply variation do not matter. Closed loop corrects them, at the cost of possible instability if gain or phase lag is wrong.
Read the step response, a sudden setpoint change with everything else held constant, against four numbers. Overshoot is how far past the setpoint the first peak goes. Settling time is when it enters and stays inside a band, usually plus or minus 2 percent of the step. Steady-state error is the offset left after it settles. Stability is whether those oscillations decay at all.
Worked step response
Hypothetical but typical numbers for a 10 mm step on a small linear stage, sampled from an encoder at 1 kHz:
| Time (ms) | Position (mm) | Note |
|---|---|---|
| 0 | 0.0 | step applied |
| 100 | 4.2 | rising |
| 200 | 8.1 | rising |
| 300 | 11.8 | crossed setpoint |
| 392 | 12.54 | first peak |
| 500 | 10.9 | decaying oscillation |
| 650 | 9.85 | inside 9.8 to 10.2 band |
| 800 | 10.02 | settled |
Overshoot: (12.54 - 10.0) / 10.0 = 25.4 percent. Settling time: about 650 ms, the last entry into the plus or minus 2 percent band (9.8 to 10.2 mm). Steady-state error: 10.0 - 10.02, effectively zero in this run because integral action removed the offset. With proportional control only, the same stage settled at 9.6 mm, giving 0.4 mm or 4 percent steady-state error, which integral action exists to remove.
Those numbers map to the standard second-order model. Damping ratio zeta sets overshoot: percent overshoot = 100 x exp(-pi zeta / sqrt(1 - zeta squared)). Zeta of 0.4 gives exp(-1.37) = 25 percent, matching the trace. Natural frequency wn sets speed: settling time is roughly 4 / (zeta wn). With wn = 20 rad/s and zeta = 0.4, that predicts 0.5 s, close to the measured 0.65 s once sampling delay and current-loop lag are included. Raise zeta toward 0.7 and overshoot falls to about 5 percent, but rise time lengthens. Push zeta above 1 and the response is sluggish with no overshoot at all.
Stability and failure modes
Stability means the poles of the closed-loop transfer function sit in the left half plane, so transients decay. In practice you watch gain margin and phase margin on the loop transfer function. Phase margin below about 30 degrees usually shows up as ringing that grows with gain. Common mechatronics causes: encoder quantisation feeding a derivative term, which produces jitter and limit cycling around the setpoint; a flexible coupling or belt resonance that the controller excites, visible as a sustained oscillation at a fixed frequency regardless of step size; and integral windup, where the integrator saturates during a large move and the stage overshoots badly on arrival because the accumulated term has to unwind.
# Python 3.11, metrics from a sampled step response
def step_metrics(t_ms, pos_mm, setpoint=10.0, band_pct=2.0):
peak = max(pos_mm)
overshoot_pct = 100.0 * (peak - setpoint) / setpoint
lo, hi = setpoint * (1 - band_pct / 100), setpoint * (1 + band_pct / 100)
settling_ms = None
for i in range(len(pos_mm) - 1, -1, -1):
if not (lo <= pos_mm[i] <= hi):
settling_ms = t_ms[i + 1] if i + 1 < len(t_ms) else None
break
steady_state_error = setpoint - pos_mm[-1]
return overshoot_pct, settling_ms, steady_state_errorTuning in the field, I would start with proportional gain low enough to stay stable with the heaviest payload, add derivative on measurement rather than on error to avoid a kick when the setpoint changes, then add integral slowly and clamp it. If overshoot persists while steady-state error is already zero, the problem is damping or a resonance, not integral gain, and more integral will make it worse.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6If a sensor on a moving stage goes quiet when you stop the stage but leave the drive and sensor powered, does that point to electrical noise or mechanical vibration?
The 90-second answer
Mechanical vibration. Stopping the stage removes the motion while leaving the sensor, cabling, and drive electronics powered. Electrical noise from the sensor, acquisition input, or wiring does not need motion to exist, so it would still be there. Noise that disappears when motion stops is being generated by the moving system and coupled into the measurement.
That is the first split I would make on the bench. I would not start by adding a filter, because a filter would quiet both cases and leave the cause in place.
| Condition | Sensor still noisy | Sensor goes quiet |
|---|---|---|
| Stage stopped, drive and sensor powered | Points to electrical noise | Points to mechanical vibration |
| Stage stopped, drive switched off | Ambiguous, PWM noise also stops | Ambiguous, both sources stop |
| Sensor on a rigid block, same cables | Points to electrical noise | Points to vibration from the stage |
The middle row is the trap. Switching the drive off removes vibration and also removes switching noise from the motor drive. Keeping the drive enabled while the stage is held still keeps the electrical environment unchanged and changes only the mechanics.
Worked check
I would log RMS noise in the two powered states, using the same sensor and sample rate. The figures below are a typical bench example, labelled as such.
| State | RMS noise | Reading |
|---|---|---|
| Moving at 200 mm/s | 8.0 µm | Baseline for the test |
| Stopped, drive enabled | 1.1 µm | Noise followed the motion |
| Stopped, drive disabled | 1.0 µm | Confirms the powered stopped state |
A short calculation makes the comparison explicit rather than visual:
import numpy as np
def rms(x):
return float(np.sqrt(np.mean(np.asarray(x, dtype=float) ** 2)))
moving = rms(moving_samples)
stopped_powered = rms(stopped_powered_samples)
print(moving, stopped_powered, moving / stopped_powered)A ratio near 7, as in the table, is a clear mechanical result. A ratio near 1 would send me to the electrical side: check shield termination, cable routing away from motor leads, and grounding between drive cabinet and controller.
Once the split is made, the follow-up differs completely. For vibration I would compare the sensor spectrum with an accelerometer on the stage and look for matching peaks at belt, screw, or bearing frequencies. For electrical noise I would look for 50 or 60 Hz pickup, harmonics, or spikes at the drive PWM frequency, then fix routing and shield termination before filtering. Filtering comes last in both cases, since it adds phase lag and can mask a loose mount or a ground loop that will fail again under load.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Your motor controller must read a 1 MHz encoder and two I2C sensors over a 2 m cable at 400 kHz while a 20 A PWM driver switches nearby, and the bus intermittently returns no data: how do you allocate SPI, I2C and UART, size the I2C pull-ups, and isolate the fault?
The 90-second answer
I would not put any of those three buses over a 2 m cable at full speed next to a 20 A PWM stage and expect it to work. The allocation has to start with physics, then pin count, then protocol.
Put the fast and noise sensitive link local. An encoder that needs 1 MHz signalling belongs on SPI on the same PCB as the controller, or it gets a differential pair such as RS-422 or LVDS if it must leave the board. SPI over 2 m of single ended cable is a transmission line problem, not a protocol problem. Reflections and ground bounce from the driver will corrupt edges long before the clock rate matters.
Keep I2C on the board for the two slow sensors. If those sensors are also at the far end of the cable, I2C at 400 kHz is not viable, and the numbers prove it. Move the sensors, add an I2C buffer or repeater at the board edge, drop to 100 kHz, or switch that link to UART or RS-485 with a differential transceiver. Use UART for the host and debug console, point to point, where I can tolerate a cable and re-sync on a start bit.
Sizing the I2C pull-ups, and why 400 kHz fails here
Bus capacitance is the sum of cable, traces and every device pin. A typical twisted pair is about 80 to 100 pF per metre, so 2 m alone is roughly 200 pF. Add 30 pF per device and PCB traces and a realistic total is 300 to 400 pF, which is the standard mode limit.
Rise time on an open drain bus is approximately tr = 0.8473 x Rp x Cb. At 400 kHz the rise time budget is 300 ns. With Cb = 400 pF:
Rp(max) = 300 ns / (0.8473 x 400 pF) = 885 ohms
The minimum pull-up is set by sink current. For a 3.3 V bus, VOL = 0.4 V and a conservative IOL = 3 mA:
Rp(min) = (3.3 - 0.4) / 0.003 = 967 ohms
Rp(min) is greater than Rp(max). No resistor satisfies both. That is the point where I stop tuning and change the topology. At 100 kHz the rise budget is 1000 ns, Rp(max) becomes about 2950 ohms, and a 2.2 kΩ pull-up works with margin. I would verify the actual Cb with a scope on SDA, measuring the 30% to 70% rise, rather than trusting the estimate.
| Link | Placement | Why |
|---|---|---|
| SPI to encoder | Same PCB, short traces, solid ground plane | Push-pull, no arbitration, 16 bits in microseconds at 5 MHz, but single ended and unterminated over distance |
| I2C to two sensors | Same PCB, 100 kHz if Cb is high | Two wires, addressing, ACK, but open drain and capacitance limited |
| UART to host | Cable acceptable | Asynchronous, tolerates clock difference, no addressing, no ACK in basic form |
| Differential for remote encoder | RS-422 or LVDS over the 2 m run | Common mode rejection against PWM noise, controlled impedance |
Diagnosing intermittent no data
Intermittent points to signal integrity or a stuck bus, not to a wrong register address. I capture with a scope on SCL, SDA, power and ground at the sensor pins, triggered on the failure, and I log what the master saw.
// Recover a bus locked by a slave holding SDA low, then rescan
void i2c_recover(void) {
gpio_set_mode(SDA_PIN, GPIO_MODE_OUTPUT);
gpio_set_mode(SCL_PIN, GPIO_MODE_OUTPUT);
gpio_write(SDA_PIN, 1);
for (int i = 0; i < 9; i++) { // clock SCL until slave releases SDA
gpio_write(SCL_PIN, 1); delay_us(5);
gpio_write(SCL_PIN, 0); delay_us(5);
}
gpio_write(SCL_PIN, 1);
gpio_write(SDA_PIN, 0); delay_us(5); // STOP
gpio_write(SCL_PIN, 1);
gpio_write(SDA_PIN, 1);
gpio_set_mode(SDA_PIN, GPIO_MODE_OPEN_DRAIN);
gpio_set_mode(SCL_PIN, GPIO_MODE_OPEN_DRAIN);
}| Capture | Interpretation | Action |
|---|---|---|
| SDA low at idle, SCL toggling does nothing | Slave crashed mid byte or lost power | Power cycle the slave, check its supply under load, then run recovery above |
| START and address present, NACK on every address | Wrong 7-bit address, device in reset, or SDA/SCL swapped | Scan 0x08 to 0x77, check reset and enable pins, check pull-ups are fitted |
| ACKs present, data correct on bench, corrupt when motor runs | Noise coupling or ground shift from PWM stage | Scope ground at the sensor, not at the controller, check cable routing away from phase leads, add common mode choke or differential link |
| SPI clock and CS present, MISO fixed at 0x00 or 0xFF | Wrong CPOL/CPHA mode, device unpowered, or two CS lines low at once | Compare mode with datasheet, confirm exactly one CS is low, check MISO pull state |
| UART framing errors at one baud only | Clock tolerance exceeded, UART allows roughly 2% total mismatch over 10 bits | Measure the TX bit period, 9600 baud is 104 microseconds, and check the actual oscillator frequency |
Two subtle faults recur. First, a slave that loses power while SDA is low locks I2C for every other device, and a master reset alone does not clear it. The nine clock recovery above does. Second, SPI has no ACK and no CRC in most encoder protocols, so a corrupted frame looks like valid data. I add a sequence counter or CRC in the encoder read and reject frames that fail, rather than trusting the first plausible value.
I change one variable at a time. A known good sensor on the same bus, or the same sensor on a short bench cable, separates wiring and noise from firmware configuration. If it passes on the bench and fails in the enclosure, I treat it as an installation fault until the scope at the far end proves otherwise.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8For a 1 kHz velocity loop on a servo axis, would you run it as a bare-metal timer ISR or as an RTOS task, and how would you check sample rate, jitter and worst-case execution time either way?
The 90-second answer
For a 1 kHz velocity loop I would default to a bare-metal timer ISR on a dedicated microcontroller, and only move to an RTOS task if the same processor also has to run a fieldbus stack, logging and a user interface that cannot be split off. The reason is not speed. Both can meet a 1 ms deadline. The ISR gives me one scheduling decision to reason about, so jitter and worst-case execution time are easier to bound and to measure. An RTOS task adds priority inversion, tick granularity and lock contention as extra sources of variation that I then have to prove away.
I would size the loop from the plant first. If the stage needs 20 Hz closed-loop bandwidth, 1 kHz is 50 times that, which is more than the usual 10 to 20 times rule, so phase lag from sampling is small. If the first structural resonance were at 180 Hz, 1 kHz also keeps the discrete controller well clear of it. If the resonance were at 400 Hz, I would not trust 1 kHz and would either stiffen the mount or raise the rate. Sample rate is therefore a check against bandwidth and resonance, not a round number.
Checking WCET and jitter in practice
WCET is the longest time the loop code can take on this board, with this compiler, under worst-case interrupt nesting and DMA activity. I measure it, I do not calculate it from instruction counts. I toggle a GPIO on ISR entry and exit, run the loop with the fieldbus, logger and diagnostics all active, and record the maximum over a long soak, for example 10 million cycles. I also add a cycle counter check inside the ISR.
Suppose the measured worst case is 180 µs against a 1000 µs period. That is 18% utilisation, which leaves margin for a fault handler or a cache miss burst. I would start worrying above roughly 50%, because one extra long interrupt could then push a cycle over the deadline. The budget I would write down looks like this:
| Work in one 1 kHz cycle | Worst case (µs) |
|---|---|
| ISR entry and encoder latch | 10 |
| ADC and encoder read, scaling | 25 |
| Velocity filter and PID | 35 |
| PWM or DAC update, double buffered | 15 |
| Deadline check and fault counter | 5 |
| Background logging flushed outside ISR | 0 in ISR |
| Total | 90 to 180 depending on nesting |
Jitter is the variation in start time from tick to tick. A timer compare interrupt that is the highest priority source, with the encoder latched by hardware at the compare moment, typically gives jitter of a few microseconds on a Cortex-M class part. I confirm it on a scope by measuring the GPIO pulse spacing. If jitter grew to, say, 80 µs, the effective sample interval would vary by 8%, and I would expect torque ripple and a limit cycle that no PID retune removes. The usual causes are a lower priority interrupt with interrupts disabled for too long, a shared SPI bus transfer blocking the ISR, or, in the RTOS version, a mutex held by a logging task.
// C17, bare-metal 1 kHz tick, jitter and deadline check
volatile uint32_t overruns = 0;
volatile uint32_t max_cycles = 0;
void control_isr(void) {
uint32_t start = DWT_CYCCNT;
int32_t pos = encoder_latched_by_timer();
float vel = velocity_filter(pos);
float torque = pid_step(vel, setpoint_vel);
pwm_set_double_buffered(torque);
uint32_t used = DWT_CYCCNT - start;
if (used > max_cycles) max_cycles = used;
if (used > PERIOD_CYCLES) {
overruns++;
pwm_set_double_buffered(0.0f); // safe torque, do not apply stale command
}
}ISR versus RTOS task, and what changes
| Aspect | Bare-metal timer ISR | RTOS fixed-priority task |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Start jitter | Interrupt latency only, typically 1 to 5 µs | Tick plus scheduler latency, often 10 to 50 µs unless tickless and pinned |
| WCET reasoning | One code path, no locks in the loop | Must bound lock hold times, use priority inheritance, avoid queues in the loop |
| Adding other work | Separate lower priority interrupts or a main loop, easy to starve by accident | Natural place for fieldbus, logging and UI at lower priorities |
| Failure handling | Overrun counter and watchdog in the ISR itself | Watchdog task plus deadline monitoring, more moving parts to test |
The RTOS version is not wrong. If I need a CAN or EtherCAT stack on the same core, I would use it, pin the control task to the highest priority, give it no mutexes, pass setpoints through a lock-free single-producer queue, and measure the same GPIO spacing. If jitter then exceeds my budget, for example 10 µs for this axis, I would split the design: keep the 1 kHz loop on the microcontroller and let the RTOS processor send trajectory setpoints at 100 Hz. That split is common in semiconductor and packaging equipment, where the motion controller is deliberately not the computer running the application.
Either way, a missed deadline must not produce a late torque command. I freeze the integrator, apply holding or zero torque, increment a fault counter the host can read, and let a watchdog reset the axis if overruns repeat. Average timing looking fine is not evidence. The maximum over a soak with all peripherals active is the number I would defend in a design review.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Walk me through how you would choose between incremental, absolute, magnetic and optical encoders, and how you would decode quadrature to get position and velocity with its quantization error?
The 90-second answer
An encoder turns shaft rotation into a countable signal. I choose the type from what the axis must survive and what it must know at power-up, then I decode quadrature for position and derive velocity from count timing, with quantization setting the floor on both.
| Type | Output | When I use it | Main risk |
|---|---|---|---|
| Incremental optical | Pulses per rev plus index | High resolution, clean lab or enclosed machine, homing acceptable | Position lost on power cycle or missed counts, needs homing routine |
| Absolute optical | Unique code per angle, multiturn counter | Must know position immediately after power loss, semiconductor stage | Cost, alignment sensitivity, multiturn battery or gearing for absolute across many turns |
| Magnetic incremental or absolute | Hall array reading pole pattern | Dirty, vibrating, high temperature, sealed motor, larger air gap tolerated | Lower resolution than optical, temperature drift, stray fields |
| Capacitive | Absolute or incremental pattern | Compact, low power, good shock tolerance | Resolution and accuracy depend on disc eccentricity and contamination |
| Resolver | Sine and cosine analog | Harsh temperature, radiation, high shock, safety critical feedback | Needs resolver-to-digital conversion, lower resolution, more wiring |
For a servo axis inside a motor I usually accept incremental and home on an index pulse or a hard stop with current limit. For a stage that must recover position after an e-stop without moving, I pay for absolute.
Quadrature decoding
Incremental encoders output channels A and B, 90 electrical degrees apart, plus often Z for one pulse per rev. Counting both edges of both channels gives 4x decoding. Direction comes from which channel leads.
// STM32G4, TIM2 is the 32-bit timer, encoder mode TI1FP1 + TI2FP2
// Checked against STM32G4 reference manual, TIM2 CCMR1/SMCR
TIM2->CCMR1 |= (1 << 0) | (1 << 8); // CC1S=01 (TI1FP1), CC2S=01 (TI2FP2)
TIM2->CCMR1 |= (4 << 4) | (4 << 12); // IC1F=4, IC2F=4 input filter
TIM2->SMCR = 3; // SMS=011, count on both TI1FP1 and TI2FP2 edges
TIM2->ARR = 0xFFFFFFFF; // free running 32-bit counter
TIM2->CNT = 0;
TIM2->CR1 |= 1; // CEN
int32_t counts = (int32_t)TIM2->CNT; // signed wrap gives directionOn a microcontroller without a timer encoder mode I use pin interrupts on both edges, read the A/B state, and add or subtract one. Each valid step changes only one channel, so a single missed edge loses one count rather than reversing direction.
Position and quantization error
Take a 2048 pulse per rev optical encoder. With 4x decoding:
counts per rev = 4 x 2048 = 8192
angle per count = 360 / 8192 = 0.0439 degrees
linear on 5 mm lead screw = 5 mm / 8192 = 0.61 micrometres per countPosition is known only to plus or minus one count, so plus or minus 0.61 micrometres on that screw, before eccentricity, interpolation error and mounting runout. That is quantization error. It does not average away in a single reading. Averaging helps velocity, and a higher resolution encoder or interpolation in the readhead reduces the step size.
Velocity: M method versus T method
M method counts pulses in a fixed window, for example every 10 ms, and divides by time. At 3000 rpm this encoder gives 8192 x 50 = 409600 counts per second, or 4096 counts per 10 ms window. One count error is 1/4096, about 0.024 percent. At 10 rpm it gives 1365 counts per second, 13.6 per window, and one count is 7 percent error. M method suits high speed.
T method measures time between pulses with a timer clock. At low speed the period is long and timing resolution is fine. At high speed the period shrinks and a fixed timer tick becomes a large fraction. T method suits low speed and standstill detection.
In practice I use M method above a crossover speed and T method below it, or a combined method that counts pulses and timestamps the first and last pulse in the window. That gives a velocity update every window without the staircase you get from differentiating position at the control rate.
Failure modes I check on hardware: missed counts from cable noise or excessive speed above the encoder bandwidth, which shows as position drift against a known index; wrong direction from swapped A and B wiring, which shows as positive feedback and runaway on first enable; and index misalignment, which makes homing repeatable to one count but offset from true zero. I verify with a slow manual rotation, count one full rev against the datasheet counts per rev, and compare velocity from the encoder against a tachometer or a known motor speed before closing the loop.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10What does anti-windup prevent when a PID controller's actuator saturates?
The 90-second answer
Anti-windup prevents integral windup. When the actuator saturates, the error stays large for a while. A plain PID keeps integrating that error, so the integral term grows far beyond what the actuator can deliver. When the stage finally reaches the setpoint, that stored integral keeps driving the output hard in the same direction and the stage overshoots, sometimes for seconds, until the integral unwinds.
The rule is simple: do not let the integral accumulate while the output is saturated and the error would push it further into saturation.
What happens without it
Take a stage moving to a target 20 mm away, with a current limit that caps torque at 60% of what the PID asks for on the initial error. The position trace looks like this in a worked example with hypothetical figures:
| Time (s) | Position (mm) | Error (mm) | Integral term, no anti-windup | Integral term, with anti-windup |
|---|---|---|---|---|
| 0.0 | 0 | 20 | 0 | 0 |
| 0.2 | 3 | 17 | 340 | 120 |
| 0.4 | 8 | 12 | 620 | 180 |
| 0.6 | 14 | 6 | 780 | 210 |
| 0.8 | 20 | 0 | 860 | 215 |
| 1.0 | 24 | -4 | 800 | 190 |
| 1.4 | 23 | -3 | 520 | 150 |
Without anti-windup the integral reaches 860 units while the actuator can only deliver the equivalent of about 200. That excess is why position overshoots to 24 mm. With anti-windup the integral stays near 215, close to what the saturated actuator can actually use, and overshoot is small.
How it is implemented
Two common forms do the same job. Conditional integration freezes the integral while the output is saturated and the error has the same sign as the output. Back-calculation feeds the gap between the saturated and unsaturated output back into the integral, which pulls the integral back toward the value the actuator can deliver.
// dt in seconds, u_max set by the drive current limit
float e = setpoint - position;
float p = Kp * e;
float d_term = Kd * (e - e_prev) / dt;
float u_unsat = p + integral + d_term;
float u = clamp(u_unsat, -u_max, u_max);
// Back-calculation: Kt is the tracking gain, often started at 1/Ti
integral += Ki * e * dt + Kt * (u - u_unsat) * dt;
e_prev = e;When u equals u_unsat, the second term is zero and the controller behaves as a normal PID. When the output saturates, u - u_unsat is negative for a positive saturation, and that term cancels part of the normal integration. The integral therefore stops growing instead of winding up.
How you check it on hardware
Command a move large enough to saturate the drive, then a small move that does not. With working anti-windup, overshoot on the large move stays close to overshoot on the small move, and the logged integral term stays bounded during saturation. Without it, overshoot grows with move size. That size dependence is the signature of windup, and it separates windup from a plain gain problem, where overshoot is roughly the same fraction at any step size.
Anti-windup does not fix a badly tuned PID. It only stops the integral from storing energy the actuator never delivered. If the stage still oscillates after saturation ends, the gains themselves need work, for example by backing off the Ziegler-Nichols values that relay autotuning produced.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Walk me through forward and inverse kinematics for a two-link arm, and how calibration errors in link length and joint zero would move the tool point?
The 90-second answer
Take a planar two-link arm, link lengths L1 and L2, joint angles measured from the x-axis with the second angle relative to the first link. Forward kinematics is direct substitution. Inverse kinematics inverts that with the law of cosines, and it has two solutions except at full extension. Calibration errors do not stay in the parameter that caused them. A joint zero offset rotates everything downstream of that joint, so its tool-point effect grows with reach, while a link length error moves the tool point along that link by exactly the length error.
Forward kinematics
import math
def forward(theta1_deg, theta2_deg, L1=300.0, L2=250.0):
t1 = math.radians(theta1_deg)
t12 = math.radians(theta1_deg + theta2_deg)
x = L1 * math.cos(t1) + L2 * math.cos(t12)
y = L1 * math.sin(t1) + L2 * math.sin(t12)
return x, y
print(forward(30, -50)) # (494.7, 64.5) mmWorked trace for L1 = 300 mm, L2 = 250 mm, theta1 = 30 degrees, theta2 = -50 degrees, so the second link sits at -20 degrees:
| Quantity | Calculation | Result |
|---|---|---|
| Elbow position | (300 cos 30, 300 sin 30) | (259.8, 150.0) mm |
| Tool x | 259.8 + 250 cos(-20) | 494.7 mm |
| Tool y | 150.0 + 250 sin(-20) | 64.5 mm |
Inverse kinematics
For a target (x, y), let r squared = x squared + y squared. The elbow angle comes from the triangle formed by the two links and the target:
cos(theta2) = (r^2 - L1^2 - L2^2) / (2 L1 L2) theta1 = atan2(y, x) - atan2(L2 sin(theta2), L1 + L2 cos(theta2))
The plus or minus sign on theta2 gives elbow-up and elbow-down branches. Both reach the same point with different joint configurations, and the controller must pick one consistently or the arm will flip through a singularity mid-move. No solution exists when r exceeds L1 + L2 or falls below |L1 - L2|. Near full extension the Jacobian loses rank: small radial target changes demand large joint changes, and positioning accuracy in that direction collapses. That is why pick-and-place cells keep the working envelope inside about 85 percent of maximum reach.
How calibration errors propagate
The Jacobian maps joint errors to tool errors. At the pose above:
| Sensitivity | dx/d(theta) | dy/d(theta) | Effect of 0.1 degree error |
|---|---|---|---|
| theta1 (shoulder) | -64.5 mm/rad | 494.7 mm/rad | (-0.11, +0.86) mm |
| theta2 (elbow) | +85.5 mm/rad | 234.9 mm/rad | (+0.15, +0.41) mm |
A 0.1 degree zero offset at the shoulder, which is 1.75 mrad, moves the tool point almost 0.9 mm at this reach. The same offset at the elbow moves it about 0.44 mm because only the second link rotates. Link length errors behave differently. A 0.5 mm error in L1 shifts the tool by 0.5 mm along the first link direction, here (0.43, 0.25) mm. A 0.5 mm error in L2 shifts it along the second link, here (0.47, -0.17) mm. Length errors do not grow with reach, but they also cannot be absorbed by re-zeroing a joint.
In practice the error budget splits into geometric and non-geometric parts. Geometric errors are link lengths, joint zero offsets, encoder scale factors, and base frame misalignment. They are stable and fit well with a least-squares calibration: command a set of poses spread across the workspace, measure the true tool position with a CMM, tracker, or a known fixture, then solve for the parameter corrections that minimise residuals. Non-geometric errors are backlash, gear eccentricity, and deflection under payload or gravity. Those show up as residuals that depend on direction of approach or load, and no DH parameter set will fit them. A candidate who reports a calibration residual of 0.02 mm on a bench test with no payload has measured the model, not the machine.
Two checks separate a good calibration from a lucky one. First, hold out poses not used in the fit and confirm the error stays within tolerance there. Second, repeat measurements approaching each pose from both directions. A split between the two directions quantifies backlash directly, and it tells you whether to fix the model or fix the hardware.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Your 12-bit ADC samples a pressure sensor at 1 kHz and the signal is clean below 50 Hz. Why put an analogue low-pass filter before the ADC instead of filtering in software, and where would you set its cutoff?
The 90-second answer
Sampling at 1 kHz means the ADC can represent frequencies up to 500 Hz, the Nyquist frequency. Any signal content above 500 Hz does not disappear. It folds back into the 0 to 500 Hz band and looks like a lower frequency that was really there. A digital filter applied after sampling cannot tell the folded component from a genuine one, because both are now in band. The analogue filter has to remove the high frequency content before the sample is taken.
For a pressure signal that only changes below 50 Hz, I would set the analogue cutoff around 100 to 200 Hz. That passes the signal with little phase lag, and attenuates content near and above 500 Hz before it can alias. A single-pole RC at 159 Hz is a common starting point. If the noise above 500 Hz is strong, a second-order filter at a similar cutoff gives more attenuation where it matters.
What aliasing looks like in practice
Take a pump vibration at 620 Hz on the pressure line. Sampled at 1 kHz, it aliases to |620 - 1000| = 380 Hz. The controller sees a 380 Hz pressure ripple that is not in the process. A 1.2 kHz component aliases to 200 Hz. A 2.7 kHz component aliases to 300 Hz. All three land inside the band the controller trusts.
| True frequency | Sample rate | Aliased frequency seen by firmware |
|---|---|---|
| 120 Hz | 1 kHz | 120 Hz, genuine |
| 620 Hz | 1 kHz | 380 Hz |
| 1.2 kHz | 1 kHz | 200 Hz |
| 2.7 kHz | 1 kHz | 300 Hz |
A software low-pass filter at 50 Hz would remove the 380 Hz alias, but only because it also removes everything above 50 Hz. If the real pressure had a genuine 80 Hz transient, the same filter would hide it. Worse, a 480 Hz component aliases to 480 Hz, and a 520 Hz component aliases to 480 Hz as well. No post-sampling filter separates them.
Choosing the cutoff
The cutoff needs to sit above the signal band and below Nyquist, with enough margin for the filter roll-off. With a signal band of 50 Hz and Nyquist at 500 Hz, a cutoff of 100 to 200 Hz leaves a decade between signal and Nyquist for the filter to work in.
For a first-order RC, fc = 1 / (2πRC). With R = 10 kΩ and C = 100 nF:
// C11, first-order RC anti-alias filter
#include <math.h>
#define PI 3.14159265f
float rc_cutoff_hz(float r_ohms, float c_farads)
{
return 1.0f / (2.0f * PI * r_ohms * c_farads);
}
// R = 10e3, C = 100e-9 gives fc = 159 HzAt 159 Hz, a single pole attenuates by about 10 dB at 500 Hz and about 16 dB at 1 kHz. That helps, but it is not a wall. A second-order Sallen-Key at 200 Hz attenuates roughly twice as fast per octave, about 28 dB at 1 kHz, at the cost of an op-amp, two resistor pairs, and more sensitivity to component tolerance. I would start with the RC if the sensor output is already quiet, and move to the second-order stage if a spectrum check shows energy above 500 Hz.
Two practical points decide whether the filter works on the board. Place the RC at the ADC pin, not at the sensor, so the long cable does not pick up noise after the filter. Keep the source impedance low enough that the ADC sampling capacitor settles within its acquisition window. A 10 kΩ source with a small sampling capacitor usually settles in a few microseconds, which fits a 1 kHz sample period. If the source impedance is higher, buffer the filter with a voltage follower.
The trade-off to state in the interview
Analogue filtering costs phase lag and component count, and it cannot be retuned in firmware. Digital filtering is flexible and free in hardware, but it only works on content that survived sampling without folding. For this signal, the analogue stage is not optional polish. It is what makes the 1 kHz samples mean what the firmware thinks they mean.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Walk me through how interrupts and ISRs work on a motion controller, what belongs in an ISR, and how you avoid blocking and race conditions?
The 90-second answer
An interrupt is a hardware signal that suspends whatever the CPU is doing and vectors it to a handler, the ISR. The ISR runs with the current context saved, services that one source, acknowledges it so it does not fire again immediately, and returns. On a motion controller the sources that matter are a timer tick for the control loop, an encoder capture or index pulse, a limit switch, and a UART or CAN receive.
What belongs in an ISR is the minimum needed to not lose the event: read or timestamp the hardware register, copy the value into a buffer, set a flag, clear the interrupt source, and exit. Everything else, PID calculation, trajectory planning, logging, bus transactions, belongs in the main loop or a lower priority task that the ISR wakes.
Why the ISR must stay short
While an ISR runs, lower priority interrupts are usually masked and the main loop is stopped. A long ISR therefore adds jitter to every other loop and can cause missed edges. Put numbers on it. A 1 kHz velocity loop has a 1000 µs period. An ISR that captures an encoder count in 6 µs consumes 0.6% of the CPU and leaves the loop timing intact. The same ISR, if it also reads an I2C sensor at 400 kHz, can take 1 to 2 ms for a short transaction. That overruns the next two control ticks, the encoder delta is computed from a stale count, and the axis sees a velocity spike that looks like a mechanical fault.
The same rule bans blocking calls inside an ISR: no delay(), no waiting on a mutex, no printf, no dynamic allocation, and no polling a bus until a device answers. Each of those waits for something outside the ISR, and the wait time is unbounded if the device is busy or disconnected.
// C17, single producer (ISR) to single consumer (main loop)
volatile uint32_t g_encoder_count;
volatile bool g_encoder_ready;
void TIM2_IRQHandler(void) // encoder capture, highest priority
{
g_encoder_count = TIM2->CNT; // snapshot hardware register
g_encoder_ready = true; // flag only, no processing
TIM2->SR &= ~TIM_SR_CC1IF; // acknowledge source
}
int main(void)
{
for (;;) {
uint32_t count;
__disable_irq(); // critical section, a few cycles
count = g_encoder_count;
g_encoder_ready = false;
__enable_irq();
if (count != last_count) {
velocity = (int32_t)(count - last_count) * counts_to_mm;
last_count = count;
run_pid(velocity); // heavy work stays here
}
}
}Race conditions and how to close them
A variable shared between an ISR and the main loop is a race by default. On an 8-bit or 16-bit controller a 32-bit encoder count is read in several instructions, so the ISR can fire halfway through and the main loop assembles a value that never existed. That torn read shows up as a one-off position jump of thousands of counts.
Three defences cover most cases:
| Risk | Defence | When it applies |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Multi-byte variable torn mid-read | volatile plus a short critical section that masks interrupts while copying | Encoder counts, timestamps, 32-bit sensor words |
| Flag set by ISR, cleared by main loop | Clear the flag inside the same critical section, after copying the data | Capture-ready, receive-complete flags |
| ISR writes faster than main loop reads | Single producer, single consumer ring buffer with head and tail indices, drop or count overruns explicitly | UART bytes, encoder events at high rate |
| ISR and task both take the same lock | Never take a lock in an ISR, use the buffer or flag instead | Any shared resource |
volatile alone does not make a read atomic. It stops the compiler caching the value in a register, but the copy still needs the critical section above. Keep that section to the copy only. Masking interrupts for a PID calculation would stall the encoder ISR and defeat the point.
Failure modes I check on hardware
Missed interrupts: toggle a GPIO on ISR entry and measure pulse width and period on a scope. If the period slips past 1000 µs at 1 kHz, the ISR or a higher priority handler is too long. Priority inversion: a low priority ISR that masks interrupts for a long critical section delays the encoder ISR, so keep critical sections to a handful of instructions and assign priorities by deadline, encoder and control tick first, communications last. Nested interrupts: on Cortex-M parts a higher priority ISR can preempt a lower one, which is fine if each ISR is short and they share no buffers. Overrun: keep a counter of ring buffer overruns and expose it in diagnostics. A rising count during a move points to the consumer being too slow, not to the sensor.
The test I trust is worst case execution time, measured with the cycle counter or a GPIO and a scope, with all sources firing at once: encoder at full speed, UART receiving, and the control tick. If that total stays under roughly 10% of the shortest period, the design has margin for the day a sensor starts chattering.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14You halve a servo's proportional gain and the oscillation gets smaller but its frequency stays exactly the same. What does that tell you about the cause?
The 90-second answer
That points to a mechanical resonance, not to tuning. Changing Kp changes the closed loop bandwidth, so a tuning oscillation changes frequency when Kp changes. A structural mode is set by stiffness and inertia of the coupling, shaft, screw, or stage. Its frequency stays put while Kp changes. The amplitude can still fall when Kp falls, because the loop excites the mode less, but the ringing period does not move.
I would confirm it by logging position at the loop rate, halving Kp, and measuring the ringing period in both traces. If the period is unchanged within measurement error, I stop tuning and inspect the mechanics. If the period shifts clearly, I keep tuning.
Worked trace
Labelled example, 10 mm step, position sampled at 1 kHz, ringing measured peak to peak after the first overshoot.
| Case | Kp | Overshoot | Ringing frequency | Reading |
|---|---|---|---|---|
| Baseline | 1.0 | 35% | 22 Hz | Starting trace |
| Kp halved | 0.5 | 12% | 22 Hz | Same frequency, mechanical resonance |
| Kp halved again | 0.25 | 5% | 22 Hz | Amplitude falls, frequency fixed |
| Coupling tightened, Kp restored | 1.0 | 8% | none visible | Resonance removed, tuning was not the fault |
Contrast that with a pure tuning case. There halving Kp typically moves a 22 Hz ringing to about 15 Hz and cuts overshoot at the same time. Frequency movement is the discriminator.
What to check next
With frequency fixed, look for a loose coupling, a long slender shaft, a compliant belt, or a stage mounted on a soft bracket. A quick test is to stiffen or shorten the transmission path, or to add damping, and repeat the same step at the original gains. If the ringing disappears, the loop gains were acceptable and the mechanics were the limit.
One caution. Do not keep lowering Kp to chase the amplitude. That masks the resonance, slows the axis, and leaves the structural problem in place for the next load change to excite again.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Walk me through how you would schedule tasks and assign priorities in an RTOS-based motion controller, and how you would prevent priority inversion from delaying the control loop?
The 90-second answer
I run a preemptive, fixed-priority RTOS, usually FreeRTOS on a Cortex-M7 or similar, and I assign priorities by deadline and consequence, not by which task feels important. The 1 kHz current and velocity loop gets the highest priority because a missed deadline there is a missed torque update. Safety monitoring and the fieldbus stack sit next, then trajectory generation, then diagnostics and logging at the bottom. I check schedulability with rate monotonic analysis, I keep every shared resource under a mutex with priority inheritance, and I measure worst-case execution time on the target rather than trusting estimates.
Fixed priority matters here because it is predictable under load. A logging task that suddenly flushes 4 KB to SD cannot delay the servo loop, provided the loop never blocks on a lock the logger holds. That last clause is where priority inversion enters.
Scheduling and priority assignment
For periodic tasks, rate monotonic scheduling is the starting point: shorter period means higher priority. It is optimal among fixed-priority schemes when deadlines equal periods. If a task has a deadline shorter than its period, deadline monotonic wins, so I use that when a 2 ms fieldbus task must finish within 1 ms.
A typical axis controller looks like this, with hypothetical but realistic figures for a 480 MHz part:
| Task | Period | WCET | Priority | Why there |
|---|---|---|---|---|
| Current / velocity loop | 1 ms | 90 µs | 10, highest | Torque update, jitter directly becomes torque ripple |
| Safety monitor | 5 ms | 60 µs | 9 | Must trip drive disable within one safety cycle |
| Fieldbus / EtherCAT | 2 ms | 250 µs | 8 | Deadline 1 ms, late data means stale setpoint |
| Trajectory generator | 4 ms | 400 µs | 6 | Can slip one cycle without visible motion error |
| Diagnostics, logging | 20 ms | 2 ms | 2, lowest | Best effort, must never block the above |
Utilisation is 0.09 + 0.012 + 0.125 + 0.10 + 0.10 = 0.427, well under the rate monotonic bound for five tasks, about 0.73. That headroom is deliberate. It absorbs interrupt overhead, cache misses and a future task without a redesign. I still run a response time check per task, because utilisation alone does not prove the fieldbus task meets its 1 ms deadline when the safety task preempts it.
Two rules keep the assignment honest. First, no task above the servo loop may block on a queue, a bus or a file. It reads encoder and current samples, computes, writes the PWM compare registers, and returns. Second, anything that can block goes below the loop and communicates through lock-free ring buffers or single-producer queues with a bounded depth.
Priority inversion, with a trace
Priority inversion happens when a high priority task waits on a resource held by a low priority task, while medium priority tasks preempt the low one and run indefinitely. The high task then waits not for the low task's critical section, but for every medium task that arrives.
| Time | Event | Running task |
|---|---|---|
| t0 | Logging task takes the shared CAN mutex to send a fault frame | Logging, priority 2 |
| t1 | Servo loop wakes, tries to read the same bus mailbox, blocks | Trajectory, priority 6 |
| t2 | Trajectory and fieldbus tasks keep arriving every 2 to 4 ms and preempt logging | Fieldbus, priority 8 |
| t3 | Servo loop has missed three 1 ms deadlines, current loop output is stale | Fieldbus / trajectory |
| t4 | Logging finally runs, releases mutex, servo loop resumes 15 ms late | Servo loop |
The Mars Pathfinder reset in 1997 was this pattern on real hardware. A low priority meteorological task held a mutex, medium priority tasks starved it, and the high priority bus task kept timing out and resetting the system.
The fix is priority inheritance. When the servo loop blocks on the mutex, the RTOS temporarily raises the holder to the waiter's priority, so logging runs at priority 10 until it releases the lock. Priority ceiling is the stricter variant: each mutex gets a ceiling equal to the highest priority task that can take it, and taking the mutex immediately raises the holder to that ceiling. Ceiling prevents deadlock as well as inversion, at the cost of more priority boosting than inheritance needs.
In FreeRTOS this is automatic for mutexes and absent for binary semaphores, which is a common trap:
// C, FreeRTOS, checked against FreeRTOS 11.x
static SemaphoreHandle_t busMutex;
busMutex = xSemaphoreCreateMutex(); // priority inheritance built in
// Servo task: never blocks here in practice, mailbox is lock-free
// Fieldbus task:
xSemaphoreTake(busMutex, portMAX_DELAY);
can_send_frame(&frame);
xSemaphoreGive(busMutex);Using xSemaphoreCreateBinary() for mutual exclusion silently removes inheritance. I also keep critical sections short, never call a blocking driver while holding the mutex, and never take two mutexes in opposite orders in different tasks.
How I verify it on hardware
I toggle a GPIO at loop entry and exit and capture it on a logic analyser or oscilloscope. That gives period, jitter and actual execution time under worst case load, with logging, fieldbus and trajectory all active. I then force the inversion case by holding the bus mutex from the logging task and confirm the servo loop still meets its 1 ms period. If jitter exceeds about 20 µs on a 1 kHz loop, I look at interrupt nesting and cache behaviour before touching priorities, because a misconfigured priority grouping in the NVIC will invert priorities at the hardware level regardless of what the RTOS thinks.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Walk me through how you bring up a new peripheral driver from its datasheet, from registers and timing to verification on hardware?
The 90-second answer
I start from the datasheet sections that decide whether the part works at all, not the register table. Supply range and sequencing, absolute maximums, bus mode, clock limits, reset behaviour, and the timing the part needs around chip select and between transactions. Only then do I map registers, write the smallest driver that can read an ID and one measurement, and verify that on a logic analyser before I trust any data the part returns.
Assume a SPI peripheral on a motion controller, for example a sensor or encoder interface running at 5 MHz from a 3.3 V MCU. The sequence is fixed.
1. Extract the electrical and timing contract
From the datasheet I record: VDD range and ramp order, IO voltage tolerance, SPI mode (CPOL/CP), maximum SCLK, CS setup and hold, inter-transaction gap, and whether the first bit is MSB first. I also note what the part does on power-up: does it need a hardware reset pulse, how long until the first valid read, and which registers are reset defaults versus undefined after reset.
For a worked example, suppose the datasheet states mode 3, 10 MHz maximum, 50 ns CS setup, 50 ns CS hold, and 1 us gap before the next transaction. I would run the bus at 5 MHz, half the maximum, to leave margin for cable capacitance and MCU clock tolerance. That decision is written down, because a driver that works at 5 MHz on a bench may fail at 10 MHz over a 2 m cable next to a PWM driver.
2. Build the register map and bring-up sequence
| Register | Access | Reset value | Use in bring-up |
|---|---|---|---|
| WHO_AM_I | read only | 0x3C (example) | First read, proves wiring and mode |
| CTRL | read/write | 0x00 | Start conversion, set output rate |
| STATUS | read only | 0x00 | Data-ready and overrun flags |
| OUT_H / OUT_L | read only | undefined | Measurement, read only after STATUS shows ready |
The driver writes in dependency order: reset if required, read WHO_AM_I, write CTRL with the chosen rate, poll STATUS, then read OUT_H and OUT_L as one transaction if the part supports auto-increment. I never read the output registers on a timer assumption alone. Polling STATUS costs a few extra transactions and removes a whole class of stale-data bugs.
// C, checked against a generic SPI HAL with a 5 MHz bus clock
int sensor_init(spi_bus_t *bus) {
uint8_t id = 0;
if (sensor_read_reg(bus, REG_WHO_AM_I, &id, 1) != 0) return -1;
if (id != EXPECTED_ID) return -2; // wrong part, wrong mode, or no device
uint8_t ctrl = CTRL_RATE_200HZ | CTRL_ENABLE;
if (sensor_write_reg(bus, REG_CTRL, &ctrl, 1) != 0) return -3;
return 0;
}
int sensor_read(spi_bus_t *bus, int16_t *value) {
uint8_t status = 0;
if (sensor_read_reg(bus, REG_STATUS, &status, 1) != 0) return -1;
if (!(status & STATUS_READY)) return -4; // not ready, do not return stale data
uint8_t buf[2] = {0, 0};
if (sensor_read_reg(bus, REG_OUT_H, buf, 2) != 0) return -1;
*value = (int16_t)((buf[0] << 8) | buf[1]);
return 0;
}3. Verify in layers, cheapest first
First, the logic analyser. I decode one WHO_AM_I read and check the trace against the datasheet by hand.
| Event | Expected | What I check |
|---|---|---|
| CS falls | SCLK idle high for mode 3 | CS setup at least 50 ns before first edge |
| 8 SCLK edges | Read command plus address, MSB first | MOSI bits match the register address |
| 8 SCLK edges | Device returns 0x3C on MISO | Data sampled on the correct edge |
| CS rises | Hold at least 50 ns, then 1 us gap | No extra clocks after CS rises |
If the ID is 0x00 or 0xFF, the usual causes are wrong SPI mode, CS not reaching the part, or MISO floating. Changing mode and re-reading the ID separates those cases in minutes.
Next, register readback: write CTRL, read it back, and confirm the value matches. A mismatch points to a write that never landed, a read-only bit I tried to set, or a part that needs a reset after a bus error. Then I compare measurement against a known input. For a displacement or pressure sensor that means a gauge block, a calibrated weight, or a reference encoder position, at three points across the range, not just zero. I record raw counts alongside engineering units so a scaling error in the driver is visible separately from a sensor error.
Finally, fault injection. I hold CS low mid-transaction, disconnect MISO, and run the bus while the motor driver switches at full current. The driver should return an error code, not hang or return the last good value silently. I also check recovery: after a failed transaction, does the next WHO_AM_I read succeed without a power cycle? If not, the init sequence needs an explicit reset step.
The failure modes I watch for are specific. Reading OUT before STATUS is ready gives plausible but stale numbers. Ignoring the inter-transaction gap corrupts the next read on parts with an internal charge pump or ADC. Running SCLK at the datasheet maximum leaves no margin for the cable and level shifters in a real machine. Each one shows up in the trace or the readback before it shows up as a mysterious field fault, which is the point of bringing the part up this way.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Walk me through how PWM duty cycle and switching frequency control a DC motor's speed and torque, and how deadband and current ripple trade off against frequency?
The 90-second answer
PWM switches the bridge fully on and off instead of dissipating power in a linear stage. The winding inductance filters that square wave, so the motor sees roughly the average voltage: Vavg = D x Vbus, where D is duty cycle, the fraction of each period the switch is on. Speed follows back-EMF, so raising D raises average voltage and speed in the linear region. Torque follows average current, which a current loop sets, not D directly.
Frequency sets how coarse that filtering is. During the on interval the current rises with (Vbus - E) x D / (L x f). During the off interval it falls with E x (1 - D) / (L x f). In steady state E = D x Vbus, so both give the same peak-to-peak ripple:
delta_I = Vbus x D x (1 - D) / (L x f)
Higher f cuts ripple, torque ripple and audible noise. It also raises switching loss and gate-drive loss, and makes fixed dead time a larger fraction of the period, so delivered duty diverges from commanded duty near zero.
Worked numbers
Take a 24 V motor, R = 0.4 ohm, L = 200 uH, running at D = 0.5, so E = 12 V in steady state.
| PWM frequency | Ripple delta_I | Consequence |
|---|---|---|
| 4 kHz | 7.5 A peak-to-peak | Torque ripple and extra copper loss, loud whine |
| 20 kHz | 1.5 A peak-to-peak | Above most hearing, manageable ripple for a 10 A rated motor |
| 100 kHz | 0.3 A peak-to-peak | Smooth current, but switching loss and dead-time error dominate |
At 4 kHz the ripple swings about 3.75 A either side of the average. At a light load averaging 1 A, the current therefore crosses zero each cycle and conduction becomes discontinuous, which the current sensor sees as a sawtooth that aliases into the loop. At 100 kHz a 500 ns dead time is 500 ns of a 10 us period, or 5% of the period per switching edge, so the error is no longer negligible.
Deadband
Deadband is the range of commanded duty that produces no motion. Static friction and cogging need a minimum torque before the shaft breaks away. The gate driver and MOSFETs need a minimum on-time to enhance fully. The bridge also inserts dead time, typically 200 ns to 1 us, between high-side and low-side turn-off to prevent shoot-through, where both devices conduct and the supply shorts.
A controller that commands 2% duty may deliver 0% motion, then jump at 6%. Adding a fixed offset, for example forcing a minimum 8% duty when the command is non-zero, restores low-speed response but creates a step in torque. That step shows up as limit cycling in a position loop and as a jerk at start-up. I measure breakaway duty on the real axis, apply the offset only in the direction of motion, and accept that fine velocity control below that threshold needs a current loop with dither or a higher bus voltage, not more duty resolution.
Setting it up in firmware
// Centre-aligned PWM, 170 MHz timer clock, 20 kHz switching
// Period = 170e6 / (2 * 4250) = 20 kHz
htim1.Init.Period = 4250;
htim1.Init.Pulse = 0;
void set_duty(float duty) { // duty in [-1.0, 1.0]
float d = duty < 0 ? -duty : duty;
if (d < 0.08f && d > 0.0f) d = 0.08f; // measured breakaway offset
uint16_t ccr = (uint16_t)(d * 4250.0f);
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, ccr);
// Direction pins select sign; dead time is set in the timer break config
}Current sampling must be blanked for roughly the first 1 to 2 us after each switching edge, while the sense amplifier settles. Without blanking, the sampled current includes switching spikes and the loop chases noise.
Choosing frequency in practice
I default to 16 to 20 kHz for a small industrial axis: inaudible, ripple acceptable, and switching loss still modest. I move to 40 kHz or higher when the motor has low inductance, the current loop bandwidth needs to exceed about 2 kHz, or torque smoothness at low speed matters more than efficiency. I stay at 8 kHz or below only for large, high-inductance motors where the driver is thermally limited and acoustic noise is irrelevant. The check is always the same: measure winding current with a probe at minimum and maximum speed, confirm ripple stays under roughly 20% of rated current, and confirm MOSFET temperature rise at stall, where E = 0 and ripple is worst.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18How do you measure accuracy and repeatability separately on a precision stage, and what do you change first when repeatability is poor?
The 90-second answer
Accuracy and repeatability are different numbers, measured with an independent reference, not the stage's own encoder. Accuracy is how close the mean position lands to the commanded position. Repeatability is how tightly repeated moves cluster around that mean. A stage can be highly repeatable and consistently 20 µm off target. That is good repeatability and poor accuracy. The reverse, a mean near zero with a wide spread, is good accuracy on average and poor repeatability.
Measure both by commanding the same target many times, approaching from the same direction, dwelling until settled, and recording actual position with a laser interferometer or a calibrated glass scale. The stage encoder only tells you what the controller thinks happened. An interferometer such as a Renishaw XL-80 resolves about 10 nm and exposes screw pitch error, scale error and thermal drift that the loop has already closed over.
import statistics
# Actual minus commanded, in um, 30 approaches to +100.000 mm
errors_um = [11.2, 13.1, 10.4, 12.8, 14.0, 11.9, 12.2, 10.8, 13.5, 12.0,
11.6, 13.0, 12.4, 11.1, 12.9, 13.3, 10.9, 12.6, 11.8, 12.2,
13.8, 11.4, 12.7, 10.6, 12.1, 13.2, 11.7, 12.5, 13.6, 12.3]
mean = statistics.mean(errors_um) # accuracy at this target
sd = statistics.stdev(errors_um) # repeatability, 1 sigma
print(f"mean error = {mean:.1f} um, sd = {sd:.1f} um, 3sd = {3*sd:.1f} um")
# mean error = 12.2 um, sd = 1.0 um, 3sd = 3.0 umHere accuracy is 12.2 µm and repeatability is about 1.0 µm (1 sigma), or 3.0 µm as a ±3 sigma band. Report which convention you use. Vendors quote 3 sigma, 6 sigma and bidirectional values interchangeably, so a bare "repeatability: 2 µm" is meaningless without it.
Worked trace
Warm the stage for 30 minutes first, then run 30 moves to each of five targets across the travel, always approaching from the same side. Thermal drift during warm-up otherwise masquerades as random scatter.
| Target (mm) | Mean error (µm) | SD (µm) | Reading |
|---|---|---|---|
| 0 | +2.1 | 0.9 | near zero, tight |
| 25 | +6.4 | 1.0 | systematic offset growing |
| 50 | +12.2 | 1.0 | matches snippet above |
| 75 | +18.9 | 1.1 | error scales with position |
| 100 | +24.8 | 1.0 | about 0.025% of travel |
The pattern decides the fix. Mean error rising with position while SD stays flat points to a scale or screw lead error, roughly 250 ppm here. That is corrected with a compensation table or a scale factor, not with PID tuning. SD rising, or a different mean when you reverse approach direction, points to backlash, hysteresis, cable drag or servo following error. Test that directly: approach the same target from positive and negative directions. A split of, say, 8 µm between the two means is lost motion in the screw, coupling or encoder mounting, and no amount of averaging removes it.
| Symptom | Likely cause | First change |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Mean error varies with position, SD small | Screw pitch, scale graduation, Abbe or cosine error | Map error vs position, apply compensation, check interferometer alignment |
| Mean differs by approach direction | Backlash, hysteresis, cable force | Preload or replace screw and nut, check coupling, dress cables, always approach from one side in the process |
| SD large, no direction split | Servo tuning, vibration, encoder interpolation error, thermal drift | Retune velocity loop, check settling time, isolate vibration, re-warm and re-measure |
| Mean drifts over minutes at a fixed target | Thermal growth of screw or structure | Warm up before measurement, control ambient, shorten the metrology loop |
Failure modes to name in the interview
Measuring with the motor encoder hides the errors you are trying to find, because the loop drives that reading to zero. Measuring too fast, before the stage settles, folds servo ringing into the SD. And quoting repeatability from three moves gives a sample SD you cannot defend. Thirty repeats is the usual minimum for a claim you would put on a datasheet, and the interferometer beam must sit on the measurement axis. Offset it by 50 mm and a small pitch motion of the carriage becomes a false linear error through the Abbe principle.
So the order of work is: independent measurement, separate the mean from the spread, then fix the pattern. Position-dependent mean error gets compensation. Direction-dependent mean gets mechanical preload. Random spread gets servo, vibration and thermal work. That sequence is what separates a stage that is merely precise on a good day from one that holds tolerance in production.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Walk me through how you would condition a 0-10 mV bridge sensor and a 4-20 mA pressure transmitter for a 0-5 V ADC, covering gain, offset, filtering and loop fault detection?
The 90-second answer
Conditioning has one job: deliver a signal the ADC can digitise without losing the information or inventing faults. That means scaling the sensor span to the ADC span, shifting the zero to a known place, removing noise and aliasing before sampling, and preserving a live zero so a broken wire is distinguishable from a real zero.
Take two common cases together. A bridge sensor outputs 0 to 10 mV differential at full scale. A pressure transmitter outputs 4 to 20 mA on a two-wire loop. Both end up as 0.5 to 4.5 V or 1 to 5 V at a 12-bit, 0 to 5 V ADC, but the front ends are completely different.
Gain and offset for the bridge
A single op-amp is the wrong first choice for a differential bridge. Common-mode noise from the stage, cable and supply appears on both legs. An instrumentation amplifier, or a differential amplifier built from a matched op-amp quad, rejects it. Set gain from the span ratio:
# Bridge: 0-10 mV -> 0.5-4.5 V, ADC 0-5 V, 12-bit
v_span = 4.5 - 0.5
gain = v_span / 0.010 # 400
# Non-inverting gain G = 1 + Rf/Rg, Rg = 1.00 kOhm
Rf = (gain - 1) * 1000 # 399 kOhm, use 402 kOhm 0.1% and trim in firmwareOffset is set after gain, not before. A reference at 0.5 V fed to the instrumentation amplifier reference pin puts zero bridge output at 0.5 V, leaving headroom to detect negative overrange and a disconnected bridge. Do not amplify a 0 V zero to the rail. You lose the ability to see drift below zero and you saturate on the first negative transient.
Input offset voltage matters at this gain. A general purpose op-amp with 2 mV offset gives 2 mV x 400 = 0.8 V of output error, 20% of span. Use a zero-drift or chopper amplifier with offset below 10 uV, or a precision instrumentation amplifier below 50 uV. At 25 uV, error is 10 mV at the output, about 8 ADC counts, 0.25% of span. Temperature drift, typically 0.5 uV per degree C for a chopper part, adds another 10 mV over 40 degrees C. Budget it, then calibrate zero and span with a shunt resistor or known load at commissioning.
Filtering before the ADC
Put a first-order RC low-pass at the amplifier output, before the ADC sample-and-hold. Software filtering cannot recover an aliased signal. If you sample at 1 kHz and the stage drive injects 700 Hz noise, it aliases to 300 Hz and looks like real motion.
Set cutoff from the signal bandwidth, not from habit. For a pressure or position signal clean below 50 Hz, sampled at 1 kHz, choose 100 to 150 Hz. That gives roughly a decade between signal and Nyquist while attenuating noise near Nyquist.
import math
fc = 100 # Hz
R = 15.9e3
C = 1 / (2 * math.pi * fc * R) # ~100 nFCheck the side effects. The RC loads the amplifier output, so keep R above 10 kOhm to avoid excessive output current. The ADC input must settle within its acquisition time. With 15.9 kOhm and 100 nF, the source time constant is 1.6 ms, far too slow for a 1 us acquisition. Buffer the filter with a rail-to-rail op-amp follower, or lower R and raise C proportionally and verify the amplifier can drive it. This is the failure mode I see most often: a correct cutoff on paper and a signal that never settles between samples.
The 4 to 20 mA loop
A two-wire transmitter is powered by the loop itself. The receiver measures current, not voltage, so cable resistance and supply variation do not change the reading until compliance is exceeded. The standard receiver is a precision burden resistor to ground.
| Loop current | Voltage across 250 Ohm | Meaning |
|---|---|---|
| 3.6 mA | 0.90 V | Fault, NAMUR NE 43 low alarm |
| 4.0 mA | 1.00 V | Live zero, 0% of span |
| 12.0 mA | 3.00 V | 50% of span |
| 20.0 mA | 5.00 V | 100% of span |
| 20.5 mA | 5.125 V | Overrange |
| 21.0 mA | 5.25 V | High alarm |
Power in the resistor at 20 mA is I squared R, 0.1 W. Use a 0.25 W, 0.1% metal film part, or two 500 Ohm in parallel for lower drift. A 0.1% resistor gives 0.1% span error before the ADC sees it. The ADC at 5 V full scale reads 1 V as about 819 counts on a 12-bit converter, so 1 mA is about 205 counts. Resolution is not the limit. Resistor drift and transmitter accuracy are.
Compliance sets the supply choice. At 20 mA, the burden drops 5 V, cable and barriers drop more, and the transmitter needs typically 10 to 12 V across its own terminals. A 24 V loop supply leaves margin. A 12 V supply often works on the bench and fails at full scale in the panel when a barrier or long cable is added. Measure loop voltage at the transmitter at 20 mA, not at zero current.
Fault detection is the reason for the live zero. Zero current means an open wire. Below 3.8 mA means a fault or a failed transmitter. Above 20.5 mA means overrange or a short. Firmware should flag those bands as invalid data, not clamp them to 0% or 100%. Clamping hides a broken sensor and lets the controller act on a plausible but false value.
Grounding and layout
Keep the bridge front end on a quiet analogue ground, star-connected to the digital ground at one point near the ADC. Route the differential pair twisted, with the filter components at the amplifier, not at the ADC. For the loop, use a single-point ground at the receiver. Multiple grounds on a 4 to 20 mA loop create circulating currents that appear as offset, and no amount of gain or filtering removes them.
In short: scale with a low-offset differential stage, offset to a live zero with headroom, filter in analogue domain below Nyquist and buffer it so the ADC settles, and treat the 4 to 20 mA loop as a current measurement with defined fault bands. Verify each stage with a known input at zero, mid-scale and full scale, and record the counts. If those three points do not match the table, the problem is in the conditioning, not in the control loop.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Your servo stage saturates at ±10 V for 300 ms during a large step and then overshoots badly: how do you detect windup in the loop and stop the integral term from driving that overshoot?
The 90-second answer
Integral windup happens when the actuator is clipped but the integrator keeps adding error. The output can no longer move, so the integral term becomes stored error. When the stage finally approaches the setpoint, that stored term has to unwind through the error first, which produces the long overshoot and slow recovery you saw after the 300 ms saturation.
I handle it in the loop, not as a post-processing limit. I compute the unsaturated output, clip it to the real actuator limit, and feed the difference between clipped and unclipped output back into the integrator. That is back-calculation. I also stop integration when the output is saturated and the error would push it further into saturation. Clamping alone is simpler, but back-calculation pulls the integral back toward the value consistent with the clipped output, so recovery starts as soon as the error changes sign.
// 1 kHz PID, output in volts, actuator limit +/-10 V
float integral = 0.0f;
float prev_meas = 0.0f;
float pid_step(float setpoint, float meas, float dt) {
float error = setpoint - meas;
float deriv = -(meas - prev_meas) / dt; // derivative on measurement
prev_meas = meas;
float p = Kp * error;
float d = Kd * deriv;
float u_unsat = p + integral + d;
float u_sat = clampf(u_unsat, -10.0f, 10.0f);
// Conditional integration: do not integrate deeper into saturation
int pushing_deeper = (u_unsat != u_sat) && ((error > 0.0f) == (u_sat > 0.0f));
if (!pushing_deeper) {
integral += Ki * error * dt;
}
// Back-calculation: bleed the integral toward the clipped output
integral += Kb * (u_sat - u_unsat) * dt;
integral = clampf(integral, -10.0f, 10.0f);
return u_sat;
}Kb is the tracking gain, roughly 1/Tt where Tt is the tracking time constant. A common starting point is Tt = sqrt(Ti * Td) with Ti = Kp/Ki and Td = Kd/Kp, then I tune it on hardware by watching how fast the integral collapses after a saturated step. Too small and windup returns. Too large and the integral fights normal control during brief, harmless clipping.
Worked trace, hypothetical figures
Assume Kp = 2.0 V/mm, Ki = 8.0 V/(mm*s), a 5 mm step, and the same +/-10 V limit. Without anti-windup the integral reaches about 6 V by the end of the saturated interval. With back-calculation it stays near 1.5 V.
| t (ms) | error (mm) | integral, no anti-windup (V) | integral, back-calculation (V) | output (V) |
|---|---|---|---|---|
| 0 | 5.0 | 0.0 | 0.0 | 10.0 clipped |
| 100 | 3.8 | 2.4 | 0.8 | 10.0 clipped |
| 200 | 2.1 | 4.6 | 1.2 | 10.0 clipped |
| 300 | 0.6 | 6.0 | 1.5 | 6.4, leaving saturation |
| 400 | -0.4 | 5.7 | 1.1 | 2.9 |
| 600 | -0.1 | 5.0 | 0.4 | 0.6 |
The point of the table is the state at 300 ms. In the first column the controller still has to burn off roughly 5 V of integral through negative error, so it keeps driving positive while the stage is already past the target. In the second column the integral is already consistent with the clipped output, so the output falls as soon as the error falls.
Detection and limits
In firmware I log three signals together: a saturation flag, the unsaturated output, and the integral contribution. Windup is confirmed when the flag is set for more than a few control cycles, the integral keeps growing in the same sign as the error, and overshoot follows the exit from saturation. A saturation counter that trips a diagnostic after, say, 50 ms at 1 kHz separates a brief current limit from a move the actuator cannot make.
Anti-windup does not fix an undersized axis. If a 10 kg stage needs 2 m/s^2 and the drive clips at 60% of that torque on every move, the right fix is a larger motor, a higher bus voltage, or a slower trajectory with feedforward for friction and inertia. I also ramp the setpoint for large moves so the loop is not asked to close a 20 mm error in one step. That reduces saturation time in the first place, and the anti-windup then handles the residual clipping from friction and load changes.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21For a precision stage needing 1 µm repeatability, high torque at low speed and fast moves, how would you choose between a stepper, a servo and a BLDC motor?
The 90-second answer
First separate the terms, because interviewers test this. A stepper, a servo and a BLDC are not three mutually exclusive motor types. Stepper versus servo describes the control architecture, open loop versus closed loop with position feedback. BLDC describes commutation, electronic rather than brushes. Most modern servos are BLDC motors with an encoder and a current loop drive. A brushed DC motor can also be a servo. Choosing only on the name hides the decision, which is whether you need feedback, torque at speed, and stiffness against disturbances.
For a precision stage I would start from the load, not the catalogue. Calculate required torque across the speed range, inertia reflected to the shaft, duty cycle and the error budget. Then ask whether an undetected position loss is acceptable. If it is not, a pure open loop stepper is out regardless of its holding torque.
| Criterion | Open loop stepper | Closed loop stepper | BLDC servo |
|---|---|---|---|
| Feedback | None, steps are assumed | Encoder on motor shaft | Encoder on motor, sometimes on load |
| Torque behaviour | High at standstill, falls steeply with speed | Same motor curve, drive can boost current | Near constant torque to rated speed, then field weakening |
| Typical example, labelled hypothetical | NEMA 23, 1.9 Nm holding, about 0.4 Nm at 1000 rpm on a 24 V supply | Same motor, stall flagged when following error exceeds a threshold | 400 W servo, 1.27 Nm rated, 3.8 Nm peak, torque constant 0.09 Nm/A |
| Accuracy limit | Step angle, for 1.8 degrees per step that is 200 steps per rev before microstepping. Microstepping smooths motion but does not divide the full step error by the microstep count | Encoder resolution, still limited by coupling and screw errors | Encoder plus loop tuning, load encoder needed for screw pitch and backlash errors |
| Failure mode | Silent missed steps, resonance band roughly 50 to 200 steps per second on many hybrid steppers | Detected stall, but still loses position until rehomed | Following error, oscillation if gains exceed the mechanical resonance, cogging at low speed |
| Cost and complexity | Lowest drive cost, no tuning | Moderate, needs encoder wiring and stall handling | Highest, drive tuning, cable and connector cost, regeneration handling |
Sizing check. Take a 5 kg stage on a 5 mm lead screw, accelerating at 5 m/s squared. Force is 25 N. Screw torque is F times lead divided by 2 pi times efficiency. With efficiency 0.9 that is 25 times 0.005 divided by 5.65, about 0.022 Nm, plus friction and preload which in practice might double it. That looks trivial for any of the three, which is why the static calculation misleads. The deciding numbers are usually peak torque during acceleration with the reflected inertia, torque remaining at top speed, and RMS torque over the duty cycle for heating. A stepper that holds 1.9 Nm at zero speed may deliver under 0.5 Nm at the speed where the move spends most of its time, so the margin disappears exactly when you need it.
When each wins. A stepper suits intermittent moves, low to moderate speed, a well characterised load and a homing routine that can recover position. Add current decay tuning and a ramp that avoids the resonance band, and keep a torque margin rather than running at 90 percent of the pull out curve. Its failure is silent, so on a semiconductor stage I would not accept that without a load side encoder or a periodic reference mark check.
A BLDC servo suits continuous motion, high speed, fast acceleration and loads that change, such as a gripper picking parts of different mass. The current loop gives predictable torque, the velocity loop rejects friction variation, and following error becomes a measurable health signal. The cost is tuning. Raise proportional gain until the axis rings, then back off, and check that the encoder mounting and coupling do not introduce a resonance inside the loop bandwidth. Cogging torque, often a few percent of rated torque on small BLDC motors, also matters at low speed and can be reduced with a higher pole count or a direct drive arrangement.
A closed loop stepper is the middle option when the load is stable and speed is modest but a missed step would scrap a part. It keeps the simple step and direction interface and adds stall detection, yet it cannot match a servo on torque at speed because the winding inductance and drive voltage still limit current rise.
For 1 micrometre repeatability, motor choice is only part of the budget. A ball screw with 5 micrometre pitch error over 300 mm, thermal growth of the structure and backlash will dominate a good encoder. I would put the encoder on the load side if the budget is that tight, or use a linear scale, and treat the motor as the actuator that delivers smooth, controllable torque rather than as the source of accuracy.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22What does a NACK on the ninth clock after the 7-bit I2C address mean, and what is the first thing you check?
The 90-second answer
A NACK on the ninth clock after the address byte means no slave pulled SDA low to acknowledge that address. The master sent the 7-bit address plus the read/write bit, clocked a ninth SCL pulse, and SDA stayed high. That is the whole meaning of the trace.
The first check is whether the addressed device is present and powered. Confirm its supply rail and reset pin, then confirm the address you are sending. Most of these faults are a wrong address, a device in reset, or a device with no power. A logic analyzer shows you the address byte and the NACK. An oscilloscope at the slave pins confirms the address bits are clean and reach the slave, so a wiring or level problem is not masquerading as a NACK.
What the trace looks like
| Clock | Master drives | Slave drives | Meaning |
|---|---|---|---|
| 1 to 8 | Address bits, MSB first, plus R/W | Nothing | Master selects a device |
| 9 | Nothing, SDA released | SDA low for ACK, high for NACK | Slave accepts or rejects the address |
| 10 onward | Data bytes | Data bytes | Only runs after an ACK |
If the ninth clock is high, the transfer stops there. The master should issue a STOP condition, SDA rising while SCL is high, rather than clocking data bytes that no slave has agreed to receive.
Checking the address
Datasheets cause a steady stream of false NACKs here. Many list an 8-bit address with the read/write bit included. The wire carries only the top 7 bits. For example, a datasheet value of 0xA0 means the 7-bit address is 0x50. Sending 0xA0 as a 7-bit address puts a different pattern on the bus and earns a NACK from a healthy device.
Strap pins cause the same result. Devices such as temperature sensors and IO expanders let you set A0 to A2 with resistors. Read the strap state on the board, not the default in the datasheet, and match it in firmware.
A bus scan is the quickest way to see what answers. This C snippet for an STM32 HAL bus walks the 7-bit space and prints every address that ACKs.
// STM32 HAL, 3.3 V bus, 400 kHz
for (uint8_t addr = 0x08; addr < 0x78; addr++) {
uint8_t buf[1] = {0};
if (HAL_I2C_Master_Transmit(&hi2c1, addr << 1, buf, 0, 10) == HAL_OK) {
printf("ACK at 0x%02X\r\n", addr);
}
}The scan starts at 0x08 and ends before 0x78 because the lower and upper ranges are reserved. A zero-length transmit clocks the address and reads the ACK bit without touching a register, so it is safe on most slaves. If the expected address is missing from the list, power and reset move to the top of the list. If a different address answers, the strap pins or a datasheet shift error is the likely cause.
When the scope changes the answer
The analyzer decodes bits. It cannot tell you whether the slave saw them. Put the scope probes at the slave, with a short ground spring, and check three things. Idle SDA and SCL should both sit at the pull-up voltage, usually 3.3 V. The address bits should reach full logic levels without a slow, rounded rise. SDA should not be held low before the transfer starts, which would point to a hung slave rather than a missing one.
A slow rise happens when the pull-up is too large for the bus capacitance, common on a long cable at 400 kHz. The analyzer may still decode the address while the slave rejects it, and the NACK looks like a firmware bug. Fixing the analog layer, usually a smaller pull-up within the sink current limit, clears faults that no amount of driver code will fix.
That order keeps the diagnosis to one step at a time. NACK means no ACK. Power, reset and address explain almost every case, and the scope rules out the bus itself before you rewrite the driver.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-23When does feedforward control actually reduce following error on a servo axis compared with feedback alone, and how would you implement and validate it without masking a tuning problem?
The 90-second answer
Feedforward drives the actuator with the torque or voltage the trajectory is predicted to need, before an error exists. Feedback then only has to correct model error and disturbances. On a servo axis that means following error during motion drops because the loop no longer has to generate the acceleration torque through position error.
For a rotary axis the feedforward term is usually written as:
u_ff = J * a_ref + B * v_ref + tau_g(q_ref) + tau_friction(v_ref)
where J is reflected inertia, B is viscous friction, a_ref and v_ref come from the trajectory, and tau_g covers gravity or a spring load. A velocity feedforward alone, Kv * v_ref, is a special case and is what many drives expose as velocity feedforward gain.
Feedback alone can track a ramp with a constant lag. With proportional position gain Kp in torque per radian, a steady velocity v needs torque B * v, so the loop settles at e = B * v / Kp. Raise Kp and the lag falls, but so does phase margin on a flexible stage. Feedforward supplies B * v directly, so the same Kp gives a much smaller lag without pushing the loop toward resonance.
Worked numbers
Take a hypothetical axis: reflected inertia J = 0.020 kg m^2, viscous coefficient B = 0.15 N m s/rad, Kp = 40 N m/rad. At v = 2 rad/s and a = 10 rad/s^2:
| Term | Calculation | Torque |
|---|---|---|
| Inertia | 0.020 * 10 | 0.20 N m |
| Viscous | 0.15 * 2 | 0.30 N m |
| Total feedforward | 0.20 + 0.30 | 0.50 N m |
| Feedback-only lag at that velocity | 0.30 / 40 | 0.0075 rad |
| Lag with 90% accurate feedforward | 0.03 / 40 | 0.00075 rad |
That tenfold reduction is the claim to test on the machine. If the measured lag does not fall by roughly the model accuracy, the model, the scaling, or the timing is wrong.
// 1 kHz current loop, trajectory already differentiated
float tau_ff = J * a_ref + B * v_ref + tau_gravity(q_ref);
float tau_cmd = tau_ff + Kp * (q_ref - q) + Kd * (v_ref - v);
tau_cmd = clamp(tau_cmd, -tau_max, tau_max);When it helps, and when it does not
It helps most on repeated, known trajectories: pick and place, wafer stage moves, CNC contouring. Acceleration and velocity are known in advance, friction and gravity repeat, and the feedback loop is bandwidth limited by a structural resonance or encoder noise. It also helps at direction reversals only if friction is modelled, including stiction and Coulomb terms, and even then the reversal is where the model is weakest.
It does not fix a poorly tuned loop, a loose coupling, backlash, or a trajectory that changes in response to contact force. If the process force is unknown, as in drilling or polishing, feedforward based on the commanded path can fight the real load. In that case keep the feedforward gain conservative and let feedback and, where fitted, a force loop carry the disturbance.
Implementation details that decide success
Timing matters as much as the equation. The feedforward sample must be aligned with the reference the feedback loop is comparing against. A one sample delay at 1 kHz during a = 10 rad/s^2 with J = 0.020 creates a torque error of J * jerk * dt, and a velocity feedforward delayed by one sample creates a position mismatch of v * dt. Look ahead the trajectory by the known pipeline delay, often one or two control ticks, and verify the alignment by logging q_ref, q, tau_ff and tau_cmd together.
Identify the parameters from the machine, not the datasheet alone. Run constant velocity moves in both directions at several speeds and fit B and Coulomb friction from steady current. Run triangular velocity profiles and fit J from the current during acceleration after subtracting the velocity term. Gravity on a vertical axis comes from slow moves through the travel range. Store the friction table against velocity, because a single Coulomb value will be wrong near zero speed.
Failure modes and checks
Overestimated inertia or friction shows up as error of the opposite sign during acceleration, and as a current spike at the start of a move with no following error. Underestimated values leave a lag that scales with velocity or acceleration. A friction model that is too aggressive near zero causes limit cycling or stick slip, visible as a sawtooth in velocity at low speed. Saturation is the other trap: if tau_ff alone exceeds the current limit, the feedback term has no headroom left and the axis falls behind in a way that looks like a tuning fault.
Validate in stages. First, disable feedback integral action and run the trajectory with feedforward only at reduced speed. The axis should follow roughly, with a small constant offset. Then enable feedback and compare following error with feedforward gain at 0, 0.5 and 1.0. Error should fall and then flatten or rise as the model error dominates. Finally repeat at full speed and check current headroom, RMS error and peak error separately. Peak error often sits at the acceleration corners, RMS error in the constant velocity sections, and they point to different parameters.
A candidate who can show that trace, with the lag shrinking by the predicted factor and current headroom preserved, has demonstrated feedforward. A candidate who only raises a gain until the error looks smaller has demonstrated a faster loop, with the stability cost still to come.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-24Walk me through how you would design the power supply and driver stage for a 24 V, 10 A BLDC motor, including current limiting and thermal sizing?
The 90-second answer
Start from the motor, not the supply. For a 24 V BLDC rated at 10 A continuous, I size the supply for continuous current plus margin, the driver for peak current plus stall, and the heatsink for worst-case losses at high ambient. The supply is a regulated 24 V source with bulk capacitance to absorb PWM ripple and regenerative energy, a fuse and inrush limit on the input, and a current limit in the driver that trips in microseconds, not milliseconds. Thermal sizing then checks that junction temperature stays below about 125 °C at 50 °C ambient with the motor stalled or accelerating, because that is when losses peak.
Power supply stage
Pick a supply rated at 24 V and at least 15 A continuous for a 10 A motor, so it does not fold back during acceleration. Add bulk capacitance at the driver input to hold the rail during current steps. A worked figure: if the rail may droop 2 V while supplying an extra 10 A for 1 ms, C = I·t/ΔV = 10 × 0.001 / 2 = 5000 µF. Use low-ESR electrolytics plus 100 nF ceramics per half-bridge close to the MOSFETs. Add a fuse sized to wiring, an NTC or relay for capacitor inrush, and a TVS on the 24 V rail for regenerative spikes when the motor is braked. If the load can regenerate often, either size the supply to sink that energy or add a braking resistor switched by a chopper at, say, 28 V.
Driver stage and current limit
Use a three-phase bridge with gate drivers that have undervoltage lockout and dead-time control, typically 100 to 200 ns to prevent shoot-through. Set the current limit above the motor's continuous rating but below what the MOSFETs and shunt can survive for more than a few milliseconds. For a 10 A continuous motor, I would set peak limit near 15 A and continuous thermal limit near 10 A.
Current sensing with a 2 mΩ shunt gives 20 mV at 10 A and 30 mV at 15 A. Shunt dissipation at 15 A is I²R = 0.45 W, so use a 1 W part with Kelvin connections. Feed that to a current-sense amplifier with a threshold at 30 mV. On threshold, the gate driver truncates the PWM pulse in the same switching cycle, called cycle-by-cycle limiting. Add a slower I²t or thermal model in firmware that folds the limit back if the motor or driver stays above 10 A for more than a few seconds, because cycle-by-cycle limiting alone does not protect against a stalled motor.
| Item | Value | Reason |
|---|---|---|
| Supply | 24 V, 15 A | 1.5× motor continuous current |
| Bulk capacitance | 5000 µF minimum | Holds rail for 1 ms, 10 A step, 2 V droop |
| Shunt | 2 mΩ, 1 W | 20 mV at 10 A, 0.45 W at 15 A peak |
| Peak current limit | 15 A | Above continuous rating, below device limit |
| Fuse | 20 A slow-blow | Protects wiring, not the motor |
Thermal sizing
Estimate losses per MOSFET from conduction and switching. Conduction loss is approximately I²·Rds(on)·D. With Rds(on) = 5 mΩ, I = 10 A and duty D = 0.8, that is 100 × 0.005 × 0.8 = 0.4 W per conducting device. Add switching loss, roughly 0.5 V × 10 A × 20 kHz × 100 ns = 0.01 W per transition, small at 20 kHz but rising with frequency and gate charge. In practice I budget 1 to 2 W per half-bridge at full current and verify on a bench with a thermocouple, because layout and current sharing change the result.
For the heatsink, total bridge loss at worst case might be 6 W. Allow Tj = 125 °C and ambient = 50 °C. Total allowed thermal resistance is (125 − 50) / 6 = 12.5 K/W. Subtract junction-to-case at 1 K/W and case-to-heatsink at 0.5 K/W, leaving a heatsink at or below 11 K/W. That is a modest extrusion, but only if airflow is guaranteed. In a sealed enclosure with no airflow, I would derate the continuous current to 7 A or move to a larger sink and retest at stall, since stall removes back EMF and keeps current at the limit indefinitely.
# Thermal check, Python 3
Tj_max, Tamb, P_loss = 125, 50, 6.0 # degC, degC, W
Rth_jc, Rth_cs = 1.0, 0.5 # K/W from datasheets
Rth_sa_max = (Tj_max - Tamb) / P_loss - Rth_jc - Rth_cs
print(f"Heatsink must be <= {Rth_sa_max:.1f} K/W")That prints 11.0 K/W. I then run the motor at 10 A for 30 minutes in the worst enclosure and confirm the MOSFET case stays near the predicted temperature. If it runs hot, the usual fixes are lower Rds(on) devices, higher switching frequency only if switching loss allows it, or a lower current limit with a longer acceleration ramp.
Failure modes I check
A shorted phase or a stalled rotor drives current to the limit and holds it there, so the I²t foldback and a hardware overtemperature switch must shut the bridge down. A lost phase connection can cause the controller to raise duty to compensate, so I monitor phase current balance. Supply droop below gate-driver undervoltage lockout can leave MOSFETs half on, so the driver must disable outputs cleanly when the rail falls below about 18 V. Each of those is tested by fault injection on the bench, not just by reading the datasheet.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-25Walk me through derivative kick and measurement noise in a PID loop, and how you filter the derivative action without destabilizing the loop?
The 90-second answer
Derivative kick is the spike you get when the setpoint moves. A textbook PID differentiates error, e = r - y, so a step in r makes de/dt a near impulse. The D term briefly saturates the drive even though the plant has not moved. Measurement noise makes the same term unusable in the other direction: differentiation amplifies high frequency content, so encoder quantization and sensor noise become large, fast output chatter.
I fix both by differentiating the measurement, not the error, and passing that derivative through a first order low pass filter. That removes the setpoint step from the D path entirely and bounds how much high frequency noise reaches the output. The filter is not free. It adds phase lag, so its corner has to sit well above the loop crossover frequency and well below the noise and Nyquist region. If it sits too low, the D term stops providing phase lead where you need it and the loop can go unstable.
Why the kick and the noise happen
For a discrete loop with sample period Ts, the raw derivative is usually (e[k] - e[k-1]) / Ts. Suppose the stage is at rest, the setpoint steps by 10 mm in one sample, and Ts = 1 ms. The error jumps by 10 mm, so the raw derivative is 10 / 0.001 = 10,000 mm/s. With Kd = 0.02 V per (mm/s), the D contribution is 200 V for one sample. The amplifier saturates at, say, 10 V, the axis lurches, and the integral term then has to unwind the damage. The plant never asked for that input. It came from the reference, not from motion.
Noise is the mirror image. Take an encoder with 0.5 um per count sampled at 1 kHz. A single count flicker between samples looks like a velocity of 0.5 um / 1 ms = 0.5 mm/s. Multiply by the same Kd and you get 10 mV of output jitter per count before filtering, and real quantization noise is not a single clean step. It is a train of steps at the sample rate, exactly where the differentiator gain 1/Ts is largest. Raise the sample rate without filtering and the noise term gets worse, not better, because each count is divided by a smaller Ts.
Differentiating the measurement, -dy/dt, instead of de/dt removes the kick because y does not jump when r jumps. It does change the control law slightly: the D term no longer reacts to setpoint changes, which is normally what you want on a motion axis. You lose nothing in regulation, and you keep derivative action on actual motion and disturbances.
Filtered derivative on measurement
In continuous form I use D(s) = Kd * s / (1 + s / N), where N is the filter corner in rad/s. At low frequency this behaves like Kd * s. At high frequency the gain stops growing and flattens at Kd * N, which is what caps the noise amplification. A common starting point is N between 5 and 10 times the loop crossover frequency in rad/s, then I check the result on the hardware.
A discrete version that runs cleanly in a 1 kHz ISR:
// Ts = 0.001 s, fc = 80 Hz filter corner for the derivative
// RC = 1 / (2*pi*fc) = 0.00199 s
// alpha = Ts / (RC + Ts) = 0.001 / 0.00299 = 0.335
float alpha = 0.335f; // precomputed from Ts and fc
float d_raw = -(y - y_prev) / Ts; // derivative on measurement
float d_filt = d_filt + alpha * (d_raw - d_filt);
float u = Kp * e + Ki * integral + Kd * d_filt;
y_prev = y;The same filter applied to the raw error derivative would still spread the kick over a few time constants, about 6 ms to settle for this corner, instead of one sample. That is better than a one sample spike, but derivative on measurement removes it at the source, so I do both.
Worked trace
Hypothetical figures, Ts = 1 ms, setpoint step of 10 mm at sample 2, Kd = 0.02, filter corner 80 Hz. The measurement stays at zero for these samples because the stage has not moved yet.
| Sample | Error (mm) | Raw D on error (V) | D on measurement, filtered (V) |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2 | 10 | 200 | 0 |
| 3 | 10 | 0 | 0 |
| 4 | 10 | 0 | 0 |
The filtered column stays at zero because the measurement never changed. Once the stage starts moving, the filtered term rises with a time constant of about 2 ms, reaching roughly 95 percent in about 6 ms, instead of arriving as a single sample impulse.
The stability cost, in numbers
The filter adds phase lag of arctan(w / N) at frequency w. If the velocity loop crossover is at 20 Hz, that is 126 rad/s. With N at 10 times crossover, 1260 rad/s or about 200 Hz, the lag at crossover is arctan(0.1), roughly 5.7 degrees. That is acceptable. Drop the corner to crossover itself and the lag is 45 degrees, which can eat most of your phase margin and turn a well damped axis into a ringing one. Push the corner up to 2 kHz to recover that phase and the high frequency gain cap Kd * N rises tenfold, so the encoder flicker from earlier produces far more output jitter and the drive starts to buzz.
That trade is the whole design. I set the corner from the crossover, not from the noise, then I look at the D term on a scope or in a log. If it shows a flat floor at the sample rate, the corner is too high or the encoder resolution is too coarse for the sample period, and the fix is a lower corner, a longer velocity estimation window, or a better sensor, in that order. If the step response rings at a frequency near the old crossover after I lowered the corner, the filter is eating phase margin and I raise it or reduce Kd. A second order filter or a notch helps when a structural resonance sits inside the band, but it does not change the basic rule: filter above crossover, below noise, and verify phase margin on the real axis rather than trusting the arithmetic alone.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-26Why are travel limit switches on a multi-axis machine wired normally closed, and what happens if a limit wire breaks?
The 90-second answer
Travel limit switches are wired normally closed so that a broken wire looks the same as a pressed limit. The loop is closed only when the wire is intact and the switch is unpressed. Any open circuit removes drive enable in hardware, without waiting for firmware.
That is the whole safety rule. A normally open switch would fail dangerous: if its wire broke, the controller would read "not pressed" forever and the axis could drive through the end of travel. With normally closed wiring, the failure and the limit demand produce the identical safe state.
How the loop works
Each axis has a negative and a positive limit switch. The two contacts are wired in series, often with the home switch, into the drive hardware inhibit or STO input and into a safety relay. The controller reads the same loop for diagnostics, but it does not create the protection.
| Condition | NC loop | Drive enable | Result |
|---|---|---|---|
| Switch unpressed, wire intact | Closed | Permitted | Axis may move inside its soft limits |
| Switch pressed at end of travel | Open | Removed | Torque drops, fault latches |
| Limit wire broken or connector pulled | Open | Removed | Torque drops, fault latches |
| Switch shorted to supply or ground | Depends on input type | Must be detected | Use monitored input or dual channel where risk requires it |
Because the inhibit is in hardware, a firmware crash, a hung task, or a lost encoder cannot keep the drive powered through a pressed limit. The controller can only re-enable the drive after the loop is closed again and the fault is reset deliberately.
Reading the loop in firmware
Firmware still needs to know which limit opened, so it reads each switch on a separate input as well as the series loop. The series loop protects the machine. The individual inputs explain the fault.
// Pseudocode, checked against typical servo drive STO and digital input behaviour
bool limit_loop_closed(const Axis &a) {
return a.limit_neg_nc && a.limit_pos_nc; // both contacts closed
}
void safety_scan(Axis &a) {
if (!limit_loop_closed(a)) {
a.drive_inhibit = true; // hardware already removed enable
a.fault = Fault::HardLimitOrWireBreak;
a.allow_motion = MotionDir::AwayFromLimitOnly;
}
}Debounce the individual inputs for 5 to 20 ms for a mechanical switch. Do not debounce the hardware inhibit path. That path must react as fast as the drive allows, typically within a few milliseconds, because the axis is still moving while the contact opens.
What happens after a break
The axis stops and the fault latches. The operator cannot jog through the limit to clear it. If the negative limit opened, the controller permits only a slow move in the positive direction, and only while the loop state confirms the axis is moving away from the pressed or broken side. If the loop does not close again within the expected travel, the fault stays latched.
This is also why homing starts with a switch check. If a limit loop is already open at power-up, the machine does not know whether the axis is sitting on a limit or the wire is broken. It must not run a normal homing move. It allows only the creep away from the active side, then checks that the loop closes before it approaches the home switch at reduced speed.
The trade-off is nuisance trips. A loose connector or a vibrating switch will stop the machine, which is the intended behaviour for a fail-safe loop. If nuisance trips become frequent, the fix is better connectors, strain relief, and switch mounting, not rewiring the loop normally open.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-27Walk me through choosing fixed-point versus floating-point for a 1 kHz PID on a Cortex-M0 without an FPU, and how you would scale the gains, error and output so it neither overflows nor loses resolution?
The 90-second answer
On a Cortex-M0 or M3 with no FPU, floating point is emulated in software. A single-precision multiply can cost 50 to 100 cycles and a divide far more, and the compiler may pull in large library routines. That makes worst-case execution time hard to bound at 1 kHz. Fixed point gives deterministic, single-cycle integer multiplies on those cores, at the cost of you owning range and resolution. On a Cortex-M4F or M7 with a single-precision FPU, float is usually the right default for a velocity or position loop. The FPU multiply is one cycle, the code is readable, and the dynamic range removes most scaling work. I would only move that loop to fixed point if profiling showed the FPU path missing the deadline, or if the same firmware must run on a cheaper no-FPU variant.
The scaling work is the real point. You pick formats from the largest values the loop can legally see, not from the values you expect in normal tuning.
Picking the formats
Take a concrete axis. Encoder gives position in counts. Error is setpoint minus position, in counts. Output is a PWM duty or current command, represented as Q15, where 32767 means +100 percent and -32768 means -100 percent. Sample period is 1 ms. Define full-scale error as 32768 counts, so a normalized error of 1.0 corresponds to 32768 counts.
| Quantity | Range to cover | Format | Why |
|---|---|---|---|
| error | plus or minus 200,000 counts on a large step | int32, counts | Counts are already integers |
| normalized error | plus or minus about 6.1 | Q14 in int64 | 1.0 is 16384, covers the large step |
| Kp, Ki, Kd | 0 to about 4.0 | Q14, stored as int32 | 1.0 is 16384, resolution about 0.00006 |
| integral accumulator | many seconds of error | int64, Q14 | Prevents truncation to zero on small errors |
| output | plus or minus 1.0 | Q14 internally, Q15 at the actuator | Matches the actuator limit directly |
Q14 for gains gives headroom above 1.0 and still resolves small gains. If Kp needed to be 0.001 for a soft axis, Q14 would quantize it badly and I would move to Q20 or keep the gain in a wider format. The rule is to check the smallest gain you must represent against 1 divided by 2 to the power of the fractional bits.
A scaled implementation
// Cortex-M0, 1 kHz ISR. Gains in Q14. Error in counts.
// Full-scale error = 32768 counts. Output in Q15.
#define Q14_ONE 16384
#define FS_COUNTS 32768
#define OUT_MAX 32767
#define OUT_MIN (-32768)
static int64_t integral_q14;
static int32_t prev_error;
int16_t pid_step(int32_t setpoint, int32_t position,
int32_t kp_q14, int32_t ki_q14, int32_t kd_q14)
{
int32_t error = setpoint - position;
// Normalized error in Q14: error / FS_COUNTS * Q14_ONE = error / 2
int64_t error_q14 = (int64_t)error * Q14_ONE / FS_COUNTS;
int64_t prev_error_q14 = (int64_t)prev_error * Q14_ONE / FS_COUNTS;
// 64-bit intermediates: error_q14 up to ~100000 times kp_q14
// up to 65536 is ~6.5e9, which overflows int32.
int64_t p_term = (error_q14 * kp_q14) >> 14; // Q14
int64_t d_term = ((error_q14 - prev_error_q14) * kd_q14) >> 14; // Q14
integral_q14 += (error_q14 * ki_q14) >> 14; // ki already includes dt
// Clamp the accumulator before it can wrap. Limits are in Q14.
if (integral_q14 > Q14_ONE) integral_q14 = Q14_ONE;
if (integral_q14 < -Q14_ONE) integral_q14 = -Q14_ONE;
int64_t out_q14 = p_term + integral_q14 + d_term;
if (out_q14 > Q14_ONE) out_q14 = Q14_ONE;
if (out_q14 < -Q14_ONE) out_q14 = -Q14_ONE;
int32_t out_q15 = (int32_t)(out_q14 << 1); // Q14 to Q15: left shift by one
if (out_q15 > OUT_MAX) out_q15 = OUT_MAX;
if (out_q15 < OUT_MIN) out_q15 = OUT_MIN;
prev_error = error;
return (int16_t)out_q15;
}Three details matter here. First, Ki in the code already includes the sample period, so the integral update is just normalized error times Ki. If you store Ki as a per-second gain, multiply by dt as a Q format as well and document it, or the loop gain will change silently if someone changes the ISR rate. Second, the integral accumulator is int64 and clamped in its own units. Clamping only the output lets the accumulator keep growing while saturated, which is windup in fixed point form. Third, the final conversion is a left shift from Q14 to Q15, not a right shift. A right shift would halve the commanded torque.
Worked trace
Suppose Kp is 0.5, so kp_q14 is 8192, Ki and Kd are zero for this trace, and the step is 10,000 counts.
| Sample | Error (counts) | Error Q14 | P term Q14 | Output Q15 | Output percent |
|---|---|---|---|---|---|
| 1 | 10,000 | 5,000 | 2,500 | 5,000 | 15.26 |
| 2 | 4,000 | 2,000 | 1,000 | 2,000 | 6.10 |
| 3 | 100 | 50 | 25 | 50 | 0.15 |
| 4 | 1 | 0 | 0 | 0 | 0.00 |
Sample 4 shows the resolution limit. One count is 0.5 in Q14 after normalization, and 0.5 times Kp 0.5 truncates to zero. That is a 1-count deadband in this scaling. If the axis must hold position to 1 count, I would increase the fractional bits, for example Q20 for the normalized error, or add the integral term, which accumulates that small error over time instead of discarding it each sample.
Failure modes I check for
Overflow wrap is the classic one. In Q15, adding past 32767 wraps to a large negative value if you store the result in int16 before saturating. That can command full reverse torque for one sample. Saturate in the wider type first, as in the code. The second failure is loss of resolution, as in sample 4. Keeping the integral in int64 fixes most of that for steady state error. The third is a limit cycle from truncation in the derivative term. Derivative on error amplifies quantization steps, so I filter the derivative or compute it on measurement, and I test with the encoder stationary to confirm the output does not dither.
On an FPU part I would write the same loop in float, keep the same saturation and anti-windup logic, and measure worst-case execution time with a GPIO toggle and a scope. If the float version meets the deadline with margin, the readability and range win. If it does not, fixed point is a measured optimisation, not a default.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-28Your controller works on the bench but fails on the machine with ground loops, EMI and intermittent connectors: how do you debug it systematically?
The 90-second answer
I treat bench versus machine as a changed environment, and I change one variable at a time while the machine is in its failing state. First I freeze the setup: same firmware, same motion profile, same load, same cable lengths as the bench run. Then I reproduce the fault on the machine and log exactly when it occurs, by axis position, drive current, temperature and time since power-on. Only after that do I split the suspects into grounding, EMI and connectors, because each leaves a different signature and each has a cheap discriminating test.
Grounding. On the bench, the controller, supply and PC often share one outlet and one earth point by accident. On the machine, the drive cabinet, weld frame, coolant pump and controller may bond at several points, so a ground loop drives current through signal returns. I measure AC and DC potential between the controller 0 V, the machine frame and the drive DC bus with a multimeter, then repeat with a scope using a short spring ground, because a long probe lead invents ringing. A few millivolts of difference on a 0 to 10 V input is noise; tens or hundreds of millivolts that move when the drive enables points to a loop.
The fix is deliberate, and it depends on signal type. Power returns and protective earth bond at the drive or supply star point. Signal shields terminate 360 degrees at the cabinet entry, ideally to the same bonded panel, with the far end handled per the cable maker instruction for that shield type. I never lift protective earth to cure a loop. For a single-ended analogue input I check whether a differential input, an isolator, or a single point bond at the sensor end removes the offset. The test that convinces me is boring: enable the drive, run the worst move, and show the offset and noise floor at the ADC input stay inside the error budget.
EMI. Bench runs usually have short leads, no 20 A PWM cable running beside the encoder cable, and no contactor or spindle nearby. On the machine the coupling path changes. I scope the victim signal and the drive PWM output together and look for spikes aligned with switching edges, and I log whether the fault follows drive current, speed or a specific axis position. A fault that tracks PWM edges suggests capacitive or inductive coupling or a shared return. A fault that tracks position suggests a connector, cable bend or encoder mounting issue instead.
Practical checks follow from that trace. Power and signal cables should run in separate trays or at least separated and crossing at right angles where they must cross. Encoder and analogue cables should be twisted pair or screened, with the screen terminated at the drive or controller end as specified, and ferrite cores placed for common-mode noise rather than added randomly. I also check the drive switching frequency and current loop settings against the cable and motor data, because a higher switching frequency can push noise into a band the input filter passes. Software filtering can hide the symptom, so I confirm the raw input at the connector before I touch the filter coefficients.
| Observation on machine | Likely cause | Discriminating test |
|---|---|---|
| Offset appears when drive enables, even at standstill | Ground loop or shared return | Measure frame to controller 0 V with drive on and off |
| Spikes line up with PWM edges | Capacitive or inductive coupling, poor shield termination | Scope victim and PWM together, reroute or reterminate shield |
| Dropouts at one axis position or cable bend | Connector fretting, broken conductor, strain relief | Slow traverse while logging continuity, wiggle test with power safe |
| Fault grows after 20 minutes warm | Thermal expansion, connector contact resistance, solder joint | Heat gun or cold spray on suspect joint while running a repeat move |
| Fault follows a swapped cable to the bench | Cable or connector, and the bench cable was the good one | Swap one cable at a time, keep the machine state fixed |
Connectors. Connectors are the classic bench pass and machine fail. Bench cables sit still, get mated once, and run at room temperature. Machine cables flex, vibrate, see coolant or dust, and get pulled during maintenance. I inspect for bent or recessed pins, incomplete latch engagement, corrosion, and conductors that break at the crimp or solder cup. For intermittents I run the failing move slowly while monitoring the specific pair with a continuity logger or a scope in persistence mode, and I flex the cable along its route rather than yanking the connector. A resistance that jumps from milliohms to open under a small bend is a failed termination, and cleaning rarely fixes a cracked crimp.
I also check mating and strain relief. A connector carrying cable weight will fret its contacts under vibration, which shows as microsecond dropouts that a multimeter in continuity mode misses. The cure is mechanical: clamp the cable within a short distance of the connector, give the loop enough bend radius, use locking or screw types where vibration is present, and replace any connector that has been mated with a bent pin or that shows fretting debris. After any change I rerun the original failing profile, not a gentle jog, and I record the before and after noise and dropout counts so the fix is measured rather than assumed.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-29Walk me through how DMA moves sensor and communication data without the CPU, when you would use it over interrupts, and how you prevent buffer races?
The 90-second answer
DMA is a separate controller that moves data between a peripheral and RAM, or between two peripherals, without the CPU handling each byte or sample. You configure the source address, destination address, length and direction, then the DMA controller arbitrates for the bus, issues the transfers, and raises an interrupt when the block finishes or, in circular mode, at the half-transfer and full-transfer points. The CPU is free for control work in between.
I use it when the data rate or burst size makes per-sample interrupts wasteful or late. A 12-bit ADC scanning four channels at 10 kHz produces 40,000 conversions per second. An interrupt per conversion at 1.5 µs of entry, read and exit costs about 6% of a 100 MHz core, and that is before jitter from a higher priority ISR. With DMA the ADC fills a buffer and the CPU wakes twice per buffer period. The same logic applies to SPI transfers of a few hundred bytes from a sensor or display, and to UART reception where a 64-byte packet would otherwise mean 64 interrupts.
The race is that the CPU and DMA write and read the same buffer at the same time. The fix is ownership: at any moment only one side may touch a given region, and ownership changes only at a defined sync point.
How the transfer works
A DMA channel has a request line from the peripheral, a current source and destination pointer, and a counter. Each request moves one item, which may be a byte, halfword or word, and decrements the counter. When the counter reaches zero the channel stops and flags transfer complete. In circular mode the pointers reload automatically and the channel keeps running, which suits continuous ADC or encoder streams. Bus arbitration matters on a shared MCU bus: a long DMA burst can delay a cache fill or a flash fetch, so I keep burst length short and set the channel priority below the control loop's memory access needs.
/* STM32H7, ADC1 scanning 4 channels, circular DMA, double buffer */
#define N_CH 4
#define N_HALF 64 /* samples per channel per half buffer */
volatile uint16_t dma_buf[2][N_CH * N_HALF];
volatile uint32_t seq[2]; /* set by DMA callbacks when a half is complete */
volatile uint32_t overrun[2]; /* DMA wrapped before CPU consumed the half */
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc)
{
/* First half (index 0) is complete, DMA is now writing index 1. */
if (seq[0] != 0) { overrun[0]++; } else { seq[0]++; }
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
{
/* Second half (index 1) is complete, DMA is now writing index 0. */
if (seq[1] != 0) { overrun[1]++; } else { seq[1]++; }
}
void process_adc(void)
{
for (int h = 0; h < 2; h++) {
if (seq[h] == 0) continue; /* DMA has not finished this half yet */
seq[h] = 0; /* claim it before processing */
/* DMA is writing the other half, so this half is stable to read. */
float v = (float)dma_buf[h][0] * 3.3f / 4095.0f;
(void)v;
}
}Both callbacks are required. The half-transfer callback marks only the first half complete, and the full-transfer callback marks the second half complete. Using one callback and toggling a static index would mark the wrong half on alternate wraps and leave the second half unmarked. The volatile qualifier stops the compiler caching seq in a register. It does not stop DMA writing mid-read, which is why the half buffer is the unit of ownership. On a cache-enabled Cortex-M7 I also place the buffer in a non-cacheable region or clean and invalidate the cache lines for that half before reading, otherwise the CPU may read stale data while DMA updated RAM directly.
Worked trace of the race and the fix
Assume a 128-sample buffer, half = 64 samples, ADC at 1 kHz, so each half fills in 64 ms.
| Time | DMA writes | CPU reads | Result |
|---|---|---|---|
| 0 ms | samples 0 to 63, half 0 | idle | half 0 filling |
| 64 ms | half-transfer callback, starts half 1 | reads half 0 | half 0 stable, no conflict |
| 70 ms | samples 64 to 127, half 1 | still reading half 0 | safe, different memory |
| 128 ms | full-transfer callback, wraps to half 0 | reads half 1 | half 1 stable, half 0 owned by DMA again |
| 130 ms | overwriting half 0 | finished half 1 | CPU must not touch half 0 until next sync |
Without the split, a CPU read starting at 60 ms could span the wrap at 64 ms and return 60 samples from the old scan plus 4 from the new one. That looks like a sensor glitch and is hard to reproduce because it depends on phase. With the split the worst case is a missed half if processing takes longer than 64 ms, which I detect because the callback finds seq still set and increments overrun instead of overwriting it. That is a counted overrun, not silent corruption.
When I would not use DMA
For a single I2C register read of two bytes, or a UART command received once per second, DMA setup costs more code and debug time than an interrupt. DMA also hides timing: a circular buffer that overruns silently drops data unless I count overruns. For a safety related channel, such as a limit switch or a current trip, I keep a direct interrupt path so detection does not wait for a buffer sync. For communication I use DMA for the bulk transfer and keep the framing, CRC check and timeout in the CPU, because those decisions need the whole packet and a failure there should stop the channel rather than let it stream bad frames.
Three checks before I trust a DMA design on hardware: confirm the buffer address is in RAM the DMA can reach, confirm the peripheral data register width matches the DMA item size, and run the sensor at full rate while toggling a GPIO in both callbacks to measure the actual period and jitter on a scope.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-30What does a two-point sensor calibration correct, and what error does it leave behind?
The 90-second answer
A two-point calibration fixes offset and gain, and nothing else. I apply zero input and one known span input, solve for the two unknowns, and apply that straight line in firmware. Offset is the error at zero. Gain is the error in span. Nonlinearity is the bow between those points, so a two-point fit leaves it untouched. If midscale error matters, I need more points and a lookup table, not a better straight line.
Assume the sensor is warmed up, the reference is more accurate than the tolerance I need, and I average each point so noise does not become a coefficient. Temperature is a separate problem. Offset and gain both drift with temperature, so a calibration done at 25 C is only valid near 25 C unless I repeat it across temperature and model that drift.
How the two points work
Take a hypothetical 0 to 10 bar sensor. At 0 bar it reads 8200 counts. At 10 bar it reads 41000 counts. The true value is then:
value = (counts - 8200) * 10 / (41000 - 8200)
That is offset subtraction first, then scaling. In firmware I store the two raw counts, not a slope and intercept rounded to a few digits, so the arithmetic stays exact.
# Python 3.11, no third party libraries
zero_counts = 8200 # raw count at 0 bar
span_counts = 41000 # raw count at 10 bar
span_value = 10.0 # bar
def to_bar(counts):
return (counts - zero_counts) * span_value / (span_counts - zero_counts)| Reference (bar) | Raw counts | Two-point result (bar) | Residual (bar) |
|---|---|---|---|
| 0 | 8200 | 0.00 | 0.00 |
| 5 | 24300 | 4.90 | -0.10 |
| 10 | 41000 | 10.00 | 0.00 |
The endpoints are perfect by construction. The midscale point is off by 0.10 bar because the sensor bows. No adjustment of offset or gain can fix that without breaking an endpoint. That residual is the nonlinearity, and it is the reason I always check a point the fit did not use.
Where temperature enters
Repeat the same two points at other temperatures and the counts move. A typical pattern is offset shifting by tens of counts per degree and gain shifting by around 100 ppm per degree. I measure that shift at, for example, 0, 25 and 50 C after the sensor has soaked to a stable temperature, then correct offset and gain as a function of the temperature measured on the sensor body. A board temperature sensor will not track the sensing element if excitation self-heating or a hot process fluid is involved.
The practical rule I use: if the midscale residual or the temperature drift exceeds the error budget, the two-point model is done. I move to a piecewise linear table with points across the range, and I add a temperature term for offset and gain. If both residuals sit inside the budget, the simple line is the better choice because it is easier to verify and harder to get wrong in the field.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-31Walk me through how cascade control with a position outer loop and velocity or current inner loop improves disturbance rejection and bandwidth on a servo axis, and how you would tune the loop separation?
The 90-second answer
Cascade control nests one loop inside another. The outer loop controls the variable you care about, position, and its output becomes the reference for the inner loop, velocity or current. The inner loop controls that variable and its output becomes torque or current command to the drive.
The inner loop runs faster, typically 5 to 10 times the bandwidth of the outer loop. That separation is the whole design. The inner loop rejects disturbances such as friction changes, cable forces, gravity variation and supply voltage sag while they are still small velocity or current errors. The outer loop then sees a plant that already behaves like a clean, predictable velocity source, so it can be tuned for position accuracy without fighting motor electrical dynamics.
A single position loop can do this in principle, but its gains must compromise between rejecting a torque disturbance and avoiding instability from the motor time constant, inverter delay and encoder noise. Cascade removes that compromise. The current loop, often a PI loop closed at 4 to 16 kHz in the drive, makes torque roughly proportional to command despite back EMF and winding resistance. The velocity loop, often 500 Hz to 2 kHz on the controller, makes velocity follow its reference despite load torque. The position loop, often 50 to 250 Hz, only has to correct the remaining following error.
How I set the rates and gains
I start from the mechanical resonance, not from a desired position bandwidth. If a ball screw stage has its first structural mode at 90 Hz, I keep the position loop below about 20 to 30 Hz and the velocity loop below about 150 to 200 Hz. Pushing the outer loop toward the resonance buys little stiffness and usually excites the mode.
A concrete split for a 24 V BLDC stage I have commissioned:
| Loop | Sample rate | Typical bandwidth | Output limit |
|---|---|---|---|
| Current | 8 kHz in drive | 800 Hz | ±10 A |
| Velocity | 2 kHz | 150 Hz | ±0.8 m/s |
| Position | 500 Hz | 25 Hz | ±0.8 m/s reference |
The position proportional gain then has units of velocity per position error. With a 25 Hz position loop, a 100 µm error produces a velocity correction of roughly 2π × 25 × 0.0001 = 0.016 m/s. That is checkable on the bench: command a 1 mm step, log position, velocity reference and velocity actual, and confirm the velocity reference never hits its limit unless the move is genuinely saturated.
// C, checked against a 500 Hz position / 2 kHz velocity split
// Runs at the slower position rate; velocity loop runs 4x faster.
float pos_err = pos_ref - pos_meas;
float vel_ref = Kp_pos * pos_err; // m/s
vel_ref = clampf(vel_ref, -VEL_MAX, VEL_MAX);
// Anti-windup for the outer integrator: only integrate when
// the inner loop is not saturated.
if (vel_ref == Kp_pos * pos_err) {
pos_int += Ki_pos * pos_err * dt_pos;
vel_ref += pos_int;
}
vel_ref_ramped = ramp_limit(vel_ref, vel_ref_prev, ACCEL_MAX * dt_pos);The ramp matters. An un-ramped velocity reference from a large position step looks like a torque impulse to the inner loop and saturates current. The inner loop then winds up, and the position loop inherits that windup as overshoot.
What cascade buys, in numbers
Take a 10 kg stage accelerating at 2 m/s². Inertial force is 20 N. A cable drag change of 2 N is a 10% torque disturbance. In a single loop tuned for 25 Hz position bandwidth, that disturbance appears first as position error. In cascade, the velocity loop sees velocity sag within one velocity sample, 0.5 ms at 2 kHz, and raises current before position has moved appreciably. In practice I expect following error during a constant velocity move to drop from tens of micrometres to single digit micrometres for the same outer gains, provided the velocity estimate is clean.
That last condition is the main failure mode. Velocity derived from a low resolution encoder is noisy. Differentiating a 17 bit encoder on a 5 mm lead screw gives about 0.04 µm per count, which is fine, but a 12 bit encoder gives 1.2 µm per count and the velocity signal at low speed becomes a staircase. Feeding that into a high gain inner loop amplifies noise into current command, heats the motor and can excite the structure. I check this by logging current command at standstill. If RMS current at zero velocity exceeds about 5% of rated current with no load, I reduce inner gain, add a filtered velocity estimate, or move velocity feedback to a tachometer or observer rather than raw differentiation.
Failure modes I look for
Bandwidth inversion: if the outer loop is tuned faster than the inner loop can follow, the loops fight. Symptom is a limit cycle at the inner loop frequency and position error that grows when outer gain increases. Fix is to slow the outer loop or speed up the inner loop, not to add integral action.
Saturation propagation: when the inner loop saturates, the outer loop must know. I pass a saturated flag back and freeze the position integrator, and I clamp the velocity reference to what the current limit can actually sustain at that speed. Without that, a 300 ms saturation during a large step produces the classic overshoot after the move.
Resonance excitation through the inner loop: a velocity loop with high proportional gain can push energy into a structural mode that the position loop alone would not reach. I sweep the velocity reference with a small sine at standstill and watch for a peak in velocity error. If the peak sits inside the velocity bandwidth, I notch it or lower the gain.
Cascade is not free. It needs a trustworthy inner measurement, more tuning steps and careful limit handling between loops. When the inner variable cannot be measured cleanly, or when the plant is a simple stepper with no current feedback, a well tuned single loop is the better choice. On a servo axis with a real current loop in the drive and a decent encoder, the nested structure is what lets you get stiffness without instability.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-32You are integrating a new SPI absolute encoder from its datasheet. Walk me through how you extract its timing, electrical limits and register sequence before writing the driver?
The 90-second answer
I read a datasheet in the order the hardware will fail, not the order it is printed. First the absolute maximums and recommended operating conditions, because those set supply, level shifting and thermal headroom. Then the timing diagrams and AC characteristics, because those set clock rate, setup and hold times and every delay in the driver. Only then the register map, in sequence, because a register written at the wrong time or with a reserved bit set can lock the part up.
I turn that into three artefacts before coding: a limits table I can check against the schematic, a timing budget for the bus, and a numbered init sequence with the expected readback after each step. If a value is only in a typical column, or only in a graph, I treat it as unguaranteed and design around the minimum or maximum I can defend.
Electrical limits: separate the three columns
Datasheets mix three different things and confusing them is a common bring-up bug.
| Column | What it means | Example, hypothetical SPI encoder | Design check |
|---|---|---|---|
| Absolute maximum | Damage threshold, not operation | VDD abs max 4.0 V, pin voltage -0.3 to VDD + 0.3 V | 3.3 V rail plus tolerance and overshoot stays below 4.0 V |
| Recommended operating | Where specs are guaranteed | VDD 3.0 to 3.6 V, 0 to 70 C, VIH 0.7 x VDD | My 3.3 V rail, level shifter and pull-ups meet this over temperature |
| Typical | One sample at room temperature | Supply current 12 mA typ, 18 mA max | Size the regulator and decoupling for max, not typ |
I also pull the conditions attached to every number. A 10 MHz SCLK rating at VDD = 3.3 V and 25 C with a 15 pF load does not hold at 3.0 V, -20 C and 50 pF on a 2 m cable. Input leakage, output drive, ESD rating and thermal resistance go in the same table. If the encoder sits near a motor driver, I check common mode range and whether the receiver is differential, because a single-ended input that is fine on the bench can fail next to a PWM stage.
Timing: build the budget from the diagram
I extract, in this order: power-on reset time, clock frequency range, CS setup and hold, data setup and hold to SCLK, propagation delay to valid data, inter-frame gap, and any conversion or acquisition time before data is ready. I then compare the sum against my controller.
Suppose the hypothetical part specifies SCLK max 10 MHz, CS setup 50 ns, CS hold 50 ns, and 200 us from CS falling to data ready after a command. At 10 MHz one bit takes 100 ns. A 24-bit read is 2.4 us on the wire, but the 200 us conversion dominates. Polling every 10 us wastes bus time and can starve a 1 kHz control loop. I either schedule the read after a timer event or poll a status bit at a rate that fits the loop budget. That decision comes from the timing table, not from trial and error.
Register sequence: write it as a trace
For each register I note address, width, reset value, access type, reserved bits, and whether the value is read-only status or read-write config. Reserved bits are written as zero unless the datasheet says otherwise, and I never do a blind read-modify-write on a status register where reading clears a flag.
A workable sequence for the hypothetical encoder looks like this:
| Step | Action | Expected result | If it fails |
|---|---|---|---|
| 1 | Wait 10 ms after VDD in range | t_por met | Part not ready, data is garbage |
| 2 | Read ID at 0x00 | 0xA5 | Wiring, CS polarity or level problem |
| 3 | Write config at 0x01, value 0x24, reserved bits zero | Readback 0x24 | Wrong address or write protected bit |
| 4 | Poll status at 0x02 until ready bit set, timeout 1 ms | Ready within 200 us | Clock too fast or conversion not started |
| 5 | Read position at 0x03 to 0x05, check error flag first | Error flag clear | Fault latched, clear per datasheet before reuse |
The driver mirrors that trace, with a timeout on every poll and a readback check after every config write:
// C, checked against the hypothetical datasheet values above
int encoder_init(spi_bus_t *bus) {
delay_ms(10); // t_por
if (spi_read_reg(bus, 0x00) != 0xA5) return -1; // ID
spi_write_reg(bus, 0x01, 0x24); // config, reserved bits = 0
if (spi_read_reg(bus, 0x01) != 0x24) return -2; // readback
for (int i = 0; i < 100; i++) { // 100 x 10 us = 1 ms timeout
if (spi_read_reg(bus, 0x02) & 0x01) return 0; // ready bit
delay_us(10);
}
return -3;
}On hardware I verify with a scope or logic analyser, not just by whether the driver returns zero. I check CS setup and hold at the encoder pins, SCLK period, supply ripple during a read, and the delay from command to ready. Then I run the sequence at minimum and maximum supply and temperature I expect on the machine. A sequence that only works at 3.3 V and room temperature has not been extracted from the datasheet, it has been guessed from one bench setup.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-33A precision stage shows a 30 µm dead zone on reversal and sags 5 µm under a 1 kN process load. How would you explain each effect and choose between mechanical preload and software compensation for the dead zone?
The 90-second answer
The 30 micrometre dead zone on reversal is backlash. The 5 micrometre sag under load is compliance. They look similar on a motor encoder because in both cases the load does not move as far as commanded, but the cause and the fix differ.
Backlash is clearance in the gear mesh or screw nut. When the drive reverses, the motor has to traverse that clearance before the teeth or nut contact the opposite flank and start moving the load. The lost motion is roughly fixed for a given mechanism, so you see a flat segment in load position while motor position changes.
Compliance is elastic deflection. The 1 kN process force bends the screw, coupling, bearing stack or arm structure. The load moves by delta = F / k. With 1000 N producing 5 micrometres, the effective stiffness is 200 N per micrometre. That offset stays as long as the force stays, regardless of travel direction.
Hysteresis is different again. It is a loop between input and output that depends on history and amplitude, common in piezo actuators and in friction in linear guides. It does not give a clean flat dead zone. If you saw a loop whose width changed with travel size, I would suspect hysteresis rather than backlash.
| Test | Backlash | Compliance | Hysteresis |
|---|---|---|---|
| Reverse direction at constant load | Load stays still for about 30 micrometres of motor travel, then follows | No flat segment, load follows immediately | Load follows a different path back than it took out |
| Increase process force from 0 to 1 kN | Dead zone stays about 30 micrometres | Sag grows in proportion to force, about 5 micrometres at 1 kN | Loop width may change, but not in direct proportion to force |
| Hold position and wait | Position stays where it stopped | Position creeps only if the structure or material creeps | Position can drift as friction or piezo material relaxes |
Choosing the fix for the dead zone
| Approach | What it does | Main trade-off | When it fails |
|---|---|---|---|
| Mechanical preload | Split gear, spring loaded gear pair or dual nut screw keeps both flanks in contact | Removes most lost motion at source, but adds friction, wear and drive torque | Preload wears, or process load overcomes the preload and the flank lifts |
| Software backlash compensation | Controller adds a fixed offset when direction reverses, so the motor overtravels by the measured dead zone | No hardware change, quick to implement, easy to adjust after a measurement | Dead zone changes with load, temperature or wear, then the offset overshoots or undershoots |
| Load side encoder with closed loop | Servo closes on the load position instead of motor position | Corrects backlash and compliance in steady state without modelling either | Lower stable bandwidth, because gear flexibility and structural resonance are now inside the loop |
For a production stage I would start with preload if the dead zone is present on every reversal and the load is predictable. It attacks the cause and keeps the servo tuning simple. I would use software compensation only when the mechanism cannot be changed, for example on a bought in axis, and I would validate it at minimum and maximum process load. If the compensation is tuned at no load and then run at 1 kN, the load can hold the gear on one flank and the added offset becomes an error.
For compliance, stiffening the load path comes first. A shorter screw span, larger bearings and a stiffer coupling raise k and reduce the 5 micrometre sag directly. Software can then trim the remainder. If force is measured or estimated from motor current, feedforward deflection of F / k can be added to the command. Raising proportional gain alone is a poor substitute. It raises stiffness only until the first structural resonance limits the loop, and it can excite vibration in the arm or screw.
A load encoder is the diagnostic that separates the two effects. Log motor and load position during a slow reversal at zero load and again at 1 kN. Backlash appears as the flat segment in both runs. Compliance appears as a vertical shift between the runs that scales with force. Without that second sensor, tuning the servo to hide the dead zone usually just moves the error into overshoot on reversal.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-34What sample rate do you pick relative to a control loop's closed-loop bandwidth, and why is twice the bandwidth not enough for control?
The 90-second answer
Pick the sample rate at 10 to 20 times the closed-loop bandwidth. That is the rule of thumb I use for a velocity or position loop, then I check it against the delay budget.
Twice the bandwidth is the Nyquist limit for reconstructing a signal. It is not a usable rate for control. Sampling, the zero-order hold, computation and sensor filtering all add delay, and delay removes phase margin at crossover. At only twice the bandwidth that loss is so large the loop has no margin left, even if the signal itself is not aliased.
A useful approximation for the phase lost to sampling at crossover is:
phase loss = 360 x f_bw / f_s degrees
where f_bw is the crossover or bandwidth frequency and f_s is the sample rate. Total delay from filters, computation and the actuator adds 360 x f_bw x tau degrees on top of that.
Worked example
Take a loop that must cross over at 20 Hz.
| Ratio f_s / f_bw | f_s | Sampling phase loss at 20 Hz |
|---|---|---|
| 2x (Nyquist) | 40 Hz | 180 deg |
| 5x | 100 Hz | 72 deg |
| 10x | 200 Hz | 36 deg |
| 20x | 400 Hz | 18 deg |
At 2x the sampling alone consumes the whole phase margin. At 10x it costs 36 degrees, which is already a large share of a typical 45 degree target. At 20x it costs 18 degrees and leaves room for plant variation, a resonance and filter lag. That is why the rule sits at 10 to 20 times rather than at Nyquist.
# Python 3.11, sampling phase loss at crossover
f_bw = 20.0
for ratio in (2, 5, 10, 20):
f_s = ratio * f_bw
print(ratio, f_s, round(360 * f_bw / f_s, 1))Output: 2 gives 180.0 deg, 5 gives 72.0 deg, 10 gives 36.0 deg, 20 gives 18.0 deg.
How I apply it on an axis
I set each loop from its own bandwidth, not from the processor clock. A current loop crossing at 500 Hz might run at 8 to 16 kHz. A velocity loop crossing at 25 Hz might run at 500 Hz to 1 kHz. A position loop crossing at 10 Hz might run at 200 to 400 Hz. Each step keeps roughly the same 10 to 20 times ratio, and each inner loop stays about a decade faster than the loop outside it.
If the ratio is right but the measured margin is still short, I look for uncounted delay next. A velocity filter, one extra sample of computation delay, or jitter in the timer ISR all subtract phase in the same way. I measure the actual sample period and execution time on the target with a GPIO toggle, then retune. Raising the sample rate only helps if the processor and the sensor can sustain it without jitter, so the check is part of the choice rather than an afterthought.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-35Walk me through how you would design the watchdog, brownout detection and safe recovery so a firmware fault or power dip on industrial equipment cannot leave an actuator energised or restart into motion?
The 90-second answer
I would not let firmware be the only thing that decides whether a motor stays energised. Three layers do the work. An independent hardware watchdog forces a reset if the control loop stops making progress. An external voltage supervisor forces a reset on a brownout before the MCU starts executing out of specification. Hardware defaults, not code, put the actuator in a safe state during that reset, and the reboot path refuses to resume motion until it has re-established position and the operator or a valid cycle start has authorised it.
Assume a 24 V industrial axis, a 3.3 V controller, a 1 kHz current or velocity loop, and a gate driver with a hardware enable. The numbers below are a worked design for that class of machine, not a universal prescription.
Watchdog design
Use the MCU independent watchdog on its own low speed oscillator, or an external supervisor watchdog, rather than a timer in the main clock domain. A window watchdog adds value here: petting too early usually means a loop is spinning without doing the work, petting too late means it has hung. For a 1 kHz loop I would set a window of roughly 50 to 200 ms and pet only from the control task, only after it has checked that the loop counter advanced, the encoder read succeeded, and no latched drive fault is present. A background task must never pet it. That separation is the point. If a lower priority task hangs, the control task still pets and the fault is missed. If the control task hangs, nothing pets and the independent watchdog resets the part even if the scheduler is still running.
The reset must be visible outside the MCU. The supervisor output drives the MCU reset pin and, through a hardware interlock, the gate driver enable and the contactor coil circuit. During reset those outputs are pulled low by resistors, not by firmware initialisation. A normally closed limit chain and a drive fault input wired into the same interlock mean a broken wire also removes enable.
/* Checked against STM32 IWDG semantics, 1 kHz control task */
static uint32_t last_loop_count;
void control_task(void)
{
uint32_t count = loop_counter;
if (count == last_loop_count) return; /* do not pet */
last_loop_count = count;
if (drive_fault_latched() || encoder_error()) return;
if (!window_elapsed_ok()) return;
IWDG->KR = 0xAAAA; /* refresh */
}Brownout handling
The internal brownout detector on many MCUs is too loose to be the primary protection. I would use an external supervisor, for example a TPS3823 class device, with a threshold near 2.93 V for a 3.3 V rail, about 100 mV of hysteresis, and a reset pulse of at least 200 ms. That holds the MCU in reset while the rail recovers instead of letting it boot, fail halfway through peripheral initialisation, and release the drive.
On the 24 V side I monitor the rail with a divider into an ADC channel and also with a comparator threshold for early warning. At about 21 V the controller stops starting new moves, finishes no motion, and writes its state to FRAM. The supervisor handles the final 3.3 V collapse. Hold-up capacitance decides whether that orderly path is real. For a hypothetical 30 W control load that must ride 50 ms from 24 V down to 18 V: C = 2 x P x t / (V1 squared minus V2 squared) = 2 x 30 x 0.05 / (576 minus 324) = 0.0119 F, about 11,900 uF. If the fitted bulk capacitance cannot supply that, the design must assume a hard reset and rely on the hardware safe state, not on a graceful shutdown.
Safe recovery
On every reset the firmware reads the reset cause register and the supervisor status, increments a persistent fault counter in FRAM with a CRC, and records the cause before clearing it. It then runs a fixed sequence: outputs stay disabled, limit switches and encoder are read, the axis is not assumed to be at the last commanded position, and motion is inhibited until a homing move or a validated absolute position check succeeds. Automatic restart into a cycle is the failure I am designing against. A power dip halfway through a press stroke or a gantry move must not resume the stroke on reboot.
| Fault | Detection | Immediate hardware action | Restart condition |
|---|---|---|---|
| Control loop hang | Independent watchdog timeout | Supervisor reset, gate enable low, contactor drops | Reset cause logged, homing or position validation, operator acknowledgement |
| 3.3 V brownout | External supervisor threshold | MCU held in reset for at least 200 ms | Rail stable above threshold plus hysteresis, full POST |
| 24 V dip | ADC and comparator early warning | No new moves, state saved to FRAM | Rail recovered, drive fault cleared, cycle start requested |
| Drive fault or limit open | Drive fault input, normally closed chain | Hardware interlock removes enable | Fault cleared at source, not by a firmware reset alone |
The test I would run before sign-off is fault injection, not a code review alone. Stall the control task, short the 3.3 V rail through a programmable supply, and pull the 24 V rail down at different rates. In each case I would measure gate enable and contactor voltage with a scope and confirm they fall before the MCU can execute, and that the machine never moves on reboot without the recovery sequence completing.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-36Your SPI link to an absolute encoder works at 1 MHz but returns corrupted frames at 20 MHz. How do you debug clock mode, chip select timing, and signal integrity to find the fault?
The 90-second answer
I would not start by lowering the clock and declaring victory. I would split the fault into three layers and test each one in order: protocol timing, chip select framing, then the physical waveform at the encoder pins.
First, confirm the mode the encoder actually expects. CPOL sets the idle level of SCLK and CPHA sets whether data is sampled on the first or second edge. If the mode is wrong, the first bit is shifted or duplicated and every following bit is off by one, even though the bus looks busy and the clock rate is correct. Second, confirm that CS is asserted before the first clock and held until after the last clock, with the setup and hold times from the datasheet. A CS that glitches, deasserts early, or is shared with another device produces truncated frames that look like random corruption. Third, look at the waveform at the far end. At 20 MHz the period is 50 ns and each half period is 25 ns. If the rise time, ringing, or ground bounce eats a large part of that, the encoder samples the wrong level even though the controller side looks clean.
Protocol: mode and framing
| Mode | CPOL | CPHA | Sample edge | Typical use |
|---|---|---|---|---|
| 0 | 0 | 0 | rising | idle low, sample first |
| 1 | 0 | 1 | falling | idle low, sample second |
| 2 | 1 | 0 | falling | idle high, sample first |
| 3 | 1 | 1 | rising | idle high, sample second |
A logic analyser trace makes the error visible. Suppose the encoder expects Mode 3 and returns a 16 bit position. With Mode 0 selected, the trace shows this pattern:
| Time | CS | SCLK edge | MOSI | MISO | Interpretation |
|---|---|---|---|---|---|
| 0 ns | falls | none | command start | high impedance | CS setup starts |
| 25 ns | low | rising | first command bit | first data bit sampled too early | CPHA mismatch |
| 50 ns | low | falling | second bit | shifted data | every bit off by one |
| 800 ns | rises | none | end | last bit never clocked | frame short by one |
The fix is to set CPOL and CPHA from the datasheet timing diagram, not by trial and error, then verify with a known command. I send a fixed MOSI pattern such as 0xA5 and check that MISO returns the expected status or ID register value. If the ID is 0xFF or 0x00 consistently, I suspect mode or CS. If the ID is correct at low speed and wrong only at high speed, I move to signal integrity.
For CS, I check four numbers: setup time from CS falling to first SCLK edge, hold time from last SCLK edge to CS rising, interframe gap, and whether CS stays low for the whole frame. Many absolute encoders need 100 ns to 1 µs of CS setup. A DMA or interrupt driven transfer that toggles CS in software can violate this when the ISR is delayed. I also check for a second device on the same bus. If another peripheral drives MISO while CS is high, the encoder frame is corrupted only when that other device is active.
// STM32H7 style setup, Mode 3, CS handled by GPIO for timing control
spi_handle.Init.CLKPolarity = SPI_POLARITY_HIGH; // CPOL = 1
spi_handle.Init.CLKPhase = SPI_PHASE_2EDGE; // CPHA = 1
spi_handle.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; // tune to target SCLK
spi_handle.Init.FirstBit = SPI_FIRSTBIT_MSB;
HAL_GPIO_WritePin(ENC_CS_GPIO_Port, ENC_CS_Pin, GPIO_PIN_RESET);
__DSB();
for (volatile int i = 0; i < 50; i++) { } // CS setup delay, replace with timer delay
HAL_SPI_TransmitReceive(&spi_handle, tx, rx, 3, 100);
__DSB();
HAL_GPIO_WritePin(ENC_CS_GPIO_Port, ENC_CS_Pin, GPIO_PIN_SET);Signal integrity at speed
At 1 MHz a 2 m cable and a few tens of picofarads of stray capacitance rarely matter. At 20 MHz they do. I measure at the encoder connector with a short ground spring, not a long probe lead, because the probe lead itself adds ringing. I look for overshoot beyond the supply rails, undershoot below ground, a slow rise that crosses the logic threshold late, and ringing that crosses the threshold more than once near the sampling edge.
A quick budget helps. If the driver rise time is 5 ns and the cable adds 100 pF, the RC time constant with a 50 ohm source is about 5 ns, so the edge reaches 90 percent in roughly 11 ns. That is almost half the 25 ns half period. Add a stub, a connector, or a shared return path and the margin disappears. The encoder may sample while the line is still settling.
Fixes I would try, in order of least disruption: reduce the clock to the highest rate that still passes with margin, add a 22 to 47 ohm series resistor at the controller end to damp ringing, route SCLK and MISO with an adjacent ground return and keep them away from PWM motor leads, and remove stubs. If the encoder sits on a moving stage, I check the cable for flex damage and connector fretting, because an intermittent shield or return conductor shows up as speed dependent errors and as errors that change when the axis moves.
I also test with the motor drive running. A clean bench test at 20 MHz can fail on the machine when the PWM driver injects ground bounce through a shared supply. Separating the encoder supply, adding a local decoupling capacitor at the encoder, and keeping the SPI return path out of the motor current path often removes that coupling.
The acceptance test is simple: read the encoder ID and a fixed position register 10,000 times at full speed, with the axis stationary and then moving, and count mismatches. Zero errors in that run, plus a scope capture showing a single clean threshold crossing with at least 30 percent timing margin, is what I would call fixed.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-37Walk me through how you would size a current-sense shunt and amplifier for a 24 V, 10 A BLDC drive, and set overcurrent protection so a short circuit trips before the MOSFETs fail?
The 90-second answer
Assume a 24 V BLDC drive, 10 A continuous, 20 A peak for 2 s, low-side shunt, 12-bit ADC on 0 to 3.3 V, PWM at 20 kHz. I size the shunt from peak current and loss, set gain so peak current fills most of the ADC range without saturating the amplifier, then add a hardware comparator trip that does not depend on firmware. Firmware handles overload by I2t, hardware handles a short circuit in microseconds.
Shunt sizing
Pick the shunt so the voltage drop is large enough to measure cleanly but loss stays manageable. With R = 2 mOhm:
| Current | Vshunt = I x R | Power = I^2 x R |
|---|---|---|
| 10 A continuous | 20 mV | 0.20 W |
| 20 A peak | 40 mV | 0.80 W |
| 25 A trip | 50 mV | 1.25 W |
A 2 mOhm part in a 2512 package rated 2 to 3 W, 1% tolerance, 50 ppm/C or better, gives headroom for the 2 s peak. A 1 mOhm shunt halves the loss but gives only 10 mV at 10 A, where amplifier offset and PCB thermoelectric voltages start to matter. A 5 mOhm shunt gives 50 mV at 10 A but dissipates 0.5 W continuously and 2 W at peak, which heats the board and drifts the value. Use Kelvin connections straight to the shunt pads. A shared copper pour adds milliohms in series and makes the reading depend on layout.
Amplifier gain
Map 20 A peak to about 2.0 V at the ADC. Gain = 2.0 V / 40 mV = 50 V/V. A current-sense amplifier such as INA240A2 (gain 50) or an INA180A2 fits. Output at 10 A is 1.0 V, at 20 A is 2.0 V, at the 25 A trip point is 2.5 V. ADC counts (12-bit, 0 to 3.3 V) are about 1240 at 10 A and 2480 at 20 A, so resolution is roughly 8 mA per count before noise. That is fine for current control. Check the amplifier output swing at the actual supply, its input offset drift over temperature, and its bandwidth at gain 50. You want settling fast enough to sample the current during the PWM on-time, or you sample synchronised to the PWM period and accept the ripple average. Sampling at the centre of the on-time, triggered by the timer, avoids the switching spike that a free-running ADC catches.
If the shunt sits in the high side or in phase with a large common-mode voltage, a plain shunt amplifier will saturate during switching. That is the point where a Hall or isolated sensor, or a shunt amplifier rated for the common-mode range, becomes the better choice despite higher cost and offset.
Overcurrent protection
Two layers, with different speeds:
-
Hardware, cycle by cycle. Feed the amplifier output (or the shunt voltage directly) to a comparator with threshold at 25 A, about 2.5 V after gain 50. Blank the comparator for roughly 0.5 to 1 us after each gate turn-on so ringing does not trip it. On trip, the gate driver disables the MOSFETs and latches the fault until the controller resets it. This must act in under a few microseconds. A MOSFET at 24 V and 25 A dissipates about 600 W while it is on, so waiting for a 1 kHz firmware loop is far too slow.
-
Firmware, for overload. Accumulate I2t above the continuous rating and derate or shut down before the shunt, MOSFETs or motor winding overheat. This catches a stalled motor drawing 14 A for 30 s, which the 25 A hardware trip will never see.
// Called every 100 us from the current loop
float i2t = 0.0f;
void current_protect(float amps) {
float excess = amps - 10.0f; // continuous rating
if (excess > 0.0f) {
i2t += excess * excess * 0.0001f; // integrate I^2 excess
} else {
i2t *= 0.999f; // slow cool-down
}
if (i2t > 400.0f) { // tuned from thermal tests
gate_driver_disable();
fault_latched = 1;
}
}The threshold and time constant come from the MOSFET safe operating area and the motor thermal limit, not from a guess. Log the peak current and the time above threshold so a nuisance trip can be distinguished from a real short.
Failure modes to check on the bench
An open Kelvin sense lead reads zero current while the motor still draws load, so the current loop winds up. Detect it by comparing commanded duty with measured current at start-up. Amplifier saturation during a short looks like a flat top at the supply rail, which the comparator threshold must sit below. Ground bounce between the shunt and the controller ground shifts the reading with switching current, so route the sense ground back to the shunt Kelvin point and measure with a differential probe before trusting the numbers. Finally, verify the trip with a current-limited supply and a deliberate short through a low-value resistor, and confirm the MOSFETs survive repeated trips without the shunt drifting out of tolerance.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-38Walk me through how you would design a trajectory with velocity, acceleration, and jerk limits for a motion axis?
The 90-second answer
Use a 7-segment S-curve (double-S) profile. Jerk is the rate of change of acceleration, so limiting jerk smooths the transitions that a trapezoidal profile makes instant. A trapezoid assumes infinite jerk: acceleration jumps from 0 to a_max in one control tick. That step excites the axis resonance and shows up as following error and vibration. The S-curve ramps acceleration up and down at the jerk limit, so the same v_max and a_max are reached with a finite, controllable onset.
Design in this order: fix the limits from the mechanics, compute the segment times, check whether the move is long enough to reach each limit, then sample the profile at the controller rate.
Worked example. Take a stage move of D = 100 mm, v_max = 200 mm/s, a_max = 1000 mm/s², j_max = 10000 mm/s³. These are illustrative figures for one axis, not a vendor default.
Jerk time: t_j = a_max / j_max = 1000 / 10000 = 0.1 s.
Velocity gained in one jerk phase is ½·j_max·t_j² = 50 mm/s. The full acceleration phase (jerk up, constant acceleration, jerk down) must gain 200 mm/s, so the constant-acceleration segment is t_a = 0.1 s. Acceleration phase duration is 0.3 s.
| Segment | Duration | Velocity change | Distance |
|---|---|---|---|
| Jerk up (+j) | 0.100 s | 0 to 50 mm/s | 1.67 mm |
| Constant a | 0.100 s | 50 to 150 mm/s | 10.00 mm |
| Jerk down (-j) | 0.100 s | 150 to 200 mm/s | 18.33 mm |
| Cruise at v_max | 0.200 s | 200 mm/s | 40.00 mm |
| Deceleration (mirror) | 0.300 s | 200 to 0 mm/s | 30.00 mm |
| Total | 0.800 s | 100.00 mm |
Cruise distance is what is left after both acceleration phases: 100 − 30.00 − 30.00 = 40.00 mm, giving 40.00 / 200 = 0.200 s at v_max. If that remainder came out negative, the move is too short to reach v_max and the peak velocity must be lowered until the profile just touches zero cruise time. The same check applies one level down: if the distance cannot reach a_max, t_a shrinks to zero and the profile becomes jerk-limited only.
Sampling it. At a 1 kHz position loop, evaluate the segment polynomials at each tick and hand the servo velocity and acceleration feedforward alongside position. A short Python check of the segment arithmetic:
# Checked against Python 3.11. Segment timing for the example above.
D, vmax, amax, jmax = 100.0, 200.0, 1000.0, 10000.0 # mm, mm/s, mm/s^2, mm/s^3
tj = amax / jmax # 0.1 s
ta = vmax / amax - tj # 0.1 s of constant acceleration
v1 = 0.5 * jmax * tj**2 # 50 mm/s after jerk up
d1 = jmax * tj**3 / 6 # 1.67 mm
d2 = v1 * ta + 0.5 * amax * ta**2 # 10.00 mm
v2 = v1 + amax * ta # 150 mm/s after constant a
d3 = v2 * tj + 0.5 * amax * tj**2 - jmax * tj**3 / 6 # 18.33 mm
d_acc = d1 + d2 + d3 # 30.00 mm
t_cruise = max(0.0, (D - 2 * d_acc) / vmax) # 0.200 s
t_total = 2 * (2 * tj + ta) + t_cruise # 0.800 s
print(f"tj={tj:.3f}s ta={ta:.3f}s d_acc={d_acc:.2f}mm t_total={t_total:.3f}s")Where it bites in practice. Set j_max from the axis, not from the drive datasheet alone. A stiff ball-screw stage tolerates a higher jerk than a belt axis with a long span, and the first sign of too much jerk is a following-error spike at the acceleration transitions, visible in the error trace before any position overshoot. If the profile is regenerated online for a new target mid-move, recompute from the current velocity and acceleration state, not from rest, or the blend will demand a jerk step at the join. And keep the sampled setpoints ahead of the loop by one tick: a profile computed in the same ISR that consumes it adds a full sample of lag to every move.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-39Walk me through how you would fuse a drifting gyro and accelerometer with GPS or encoder position to estimate orientation, and when would you choose a complementary filter over a Kalman filter?
The 90-second answer
Start with the error each sensor owns. A gyro integrates well over milliseconds but its bias drifts, so integrated angle walks away over seconds. An accelerometer measures gravity plus linear acceleration, so it gives an absolute roll and pitch reference only when the platform is not accelerating much. GPS or an encoder gives absolute position, but at 1 to 10 Hz with latency and, for GPS, jumps. Fusion is deciding, at each sample, how much to trust the fast drifting source versus the slow absolute source, and how that trust changes when the assumptions break.
For a single axis the complementary filter does that with one gain. Predict from the gyro, correct toward the accelerometer angle:
angle = alpha * (angle + gyro * dt) + (1 - alpha) * accel_angle
With dt = 0.01 s and alpha = 0.98, the time constant is roughly dt / (1 - alpha) = 0.5 s. The gyro dominates above about 0.3 Hz and the accelerometer dominates below it. That is the whole design: one crossover frequency, no covariance, about ten lines of code, deterministic timing on a small MCU.
A Kalman filter generalises the same idea. It keeps an estimate plus a covariance P that says how uncertain the estimate is. Prediction grows P by the process noise Q. An update shrinks P by an amount set by the measurement noise R. If Q is large the filter follows the gyro and distrusts its model. If R is large it distrusts GPS or the accelerometer. The gain is computed, not fixed, so it can adapt when a measurement is good or bad, and it can estimate extra states such as gyro bias.
I would ship the complementary filter for a rigid stage or vehicle where the motion is mostly planar, vibration is modest, and the bias is stable enough to calibrate at startup. I would move to a Kalman or error-state Kalman filter when I need bias estimation in flight, yaw from GPS course or magnetometer, asynchronous sensors at different rates, or a defensible way to reject a bad GPS fix. The cost is tuning Q and R, handling nonlinear orientation with quaternions, and testing for divergence.
Worked trace, one axis
Assume the rig sits level and still, so the true angle and the accelerometer angle are both 0 deg. The gyro has a constant bias of 0.2 deg/s and reads 0.2 deg/s. dt = 0.01 s, alpha = 0.98, so the fixed point of the complementary recurrence is alpha * bias * dt / (1 - alpha) = 0.098 deg, reached with a time constant near 0.5 s.
| t (s) | Gyro-only angle (deg) | Complementary angle (deg) | Comment |
|---|---|---|---|
| 0 | 0.00 | 0.00 | Start aligned |
| 1 | 0.20 | 0.085 | Correction already pulling back |
| 5 | 1.00 | 0.098 | Gyro-only has drifted 1 deg from bias |
| 10 | 2.00 | 0.098 | Complementary settled at bias times tau |
The steady error is bias * tau, here 0.2 * 0.49 = 0.098 deg. Shorten tau to 0.1 s and the bias error falls to 0.02 deg, but accelerometer noise and vibration pass through about five times more. That trade is the tuning.
Kalman version in code
A two-state filter, x = [angle, bias], predicted at gyro rate and corrected by the accelerometer angle at a lower rate. F propagates angle with the bias-corrected gyro, Q is diagonal, H picks out angle:
// State: x[0]=angle (deg), x[1]=bias (deg/s). P is 2x2.
// Predict at 100 Hz, dt = 0.01
float F[2][2] = {{1.0f, -dt}, {0.0f, 1.0f}};
x[0] += (gyro - x[1]) * dt;
// P = F * P * F^T + Q, Q = diag(q_angle*dt, q_bias*dt)
float Pn[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
Pn[i][j] = F[i][0]*P[0][j] + F[i][1]*P[1][j];
}
float Pt[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
Pt[i][j] = Pn[i][0]*F[j][0] + Pn[i][1]*F[j][1];
}
Pt[0][0] += q_angle * dt;
Pt[1][1] += q_bias * dt;
P[0][0]=Pt[0][0]; P[0][1]=Pt[0][1]; P[1][0]=Pt[1][0]; P[1][1]=Pt[1][1];
// Update when accel_angle arrives, H = [1 0], R = r_accel
float y = accel_angle - x[0];
float S = P[0][0] + r_accel;
float K[2] = {P[0][0] / S, P[1][0] / S};
x[0] += K[0] * y;
x[1] += K[1] * y;
// P = (I - K*H) * P
float Pnew[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++) {
float ikh = ((i==j)?1.0f:0.0f) - K[i] * ((j==0)?1.0f:0.0f);
Pnew[i][j] = ikh * P[0][j] + ((i==j)?0.0f:0.0f);
// row i of (I-KH) has only column 0 nonzero off the diagonal
Pnew[i][j] = ((i==j)?1.0f:0.0f) * P[i][j] - K[i] * P[0][j];
}
P[0][0]=Pnew[0][0]; P[0][1]=Pnew[0][1]; P[1][0]=Pnew[1][0]; P[1][1]=Pnew[1][1];In production I would use an error-state Kalman filter on quaternions for 3D orientation. The nominal quaternion integrates the gyro, the error state stays small and linear, and bias, GPS position and velocity can be states in the same filter. That avoids the singularities of Euler angles near pitch of 90 degrees.
| Criterion | Complementary filter | Kalman filter |
|---|---|---|
| Tuning | One alpha or time constant per axis | Q and R per state and sensor, plus initial P |
| Bias handling | Fixed or separately calibrated | Estimated as a state if observable |
| Async sensors | Needs interpolation or a fixed schedule | Natural predict and update at each sensor rate |
| Outlier rejection | None built in, add a gate on residual | Residual gating on innovation y against S |
| Failure mode | Wrong crossover passes vibration or lets drift through | Divergence or overconfidence if Q too small or model wrong |
| Compute | A few flops per sample | Matrix ops, still fine at 100 to 1000 Hz on a Cortex-M |
Failure modes I would test for
Accelerometer correction during sustained acceleration. A stage accelerating at 2 m/s squared tilts the apparent gravity by atan(2 / 9.81) = 11.5 deg. A complementary filter with a 0.5 s time constant will swing several degrees during a 1 s move. Fix: gate the accelerometer update by checking | |a| - g | and by using encoder or GPS acceleration to subtract linear acceleration, or shorten trust in the accelerometer while the commanded acceleration is high.
GPS latency and multipath. A 200 ms latency at 0.5 m/s is a 100 mm position error if you fuse it as current. Timestamp the GPS fix, predict the state forward to the fix time, then update. Reject fixes whose innovation exceeds, say, 3 times sqrt(S) for several samples in a row, which catches multipath jumps without rejecting a genuine fast move.
Gyro bias change with temperature or vibration. A bias that moves 0.5 deg/s after a shock will look like a real rotation to a complementary filter until the accelerometer pulls it back. A Kalman filter with a bias state and a Q_bias matched to the thermal drift rate tracks it, provided the accelerometer or GPS makes bias observable. If the platform sits still, bias is observable. If it rotates continuously with no absolute reference, it is not, and no filter invents that information.
Yaw is the trap. Gravity gives no yaw. A complementary filter on roll and pitch alone leaves yaw to integrate the gyro forever. Yaw needs a magnetometer, GPS course over ground while moving, dual antenna GPS heading, or an encoder and a known trajectory. I would state that limit up front in an interview rather than claim the accelerometer fixes heading.
Validation: log raw gyro, accelerometer, GPS and encoder at full rate, replay offline, and compare fused angle against a reference such as a rotary table or motion capture. Sweep alpha or Q and R and plot drift, noise and lag separately. A filter that looks smooth on a bench log often fails on the machine because vibration raises the effective R by an order of magnitude.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-40Walk me through how you would use a logic analyzer, oscilloscope, and debugger to isolate a firmware timing fault on a servo stage that intermittently misses encoder counts?
The 90-second answer
I would use the three instruments to separate three possibilities: the command was never sent, the command was sent but the signal was corrupted, or the command was sent cleanly and the firmware lost track of it. The logic analyzer answers the first question and gives the order of digital events. The oscilloscope answers the second, because it shows edge quality, supply droop, and how long the interrupt actually ran. The debugger answers the third, because it shows priority, pending flags, and what the code was doing when the pulse should have been emitted.
For a servo stage that misses encoder counts only at speed, I would trigger all three on the same step pulse. If the analyzer shows step pulses missing while encoder edges follow the steps that were sent, the encoder and wiring are probably fine and the fault is in step generation. If the analyzer shows every step present and the encoder edges present, but the count in firmware does not move, I look at the counter read and interrupt handling. If the analyzer shows runt pulses or extra edges, I stop and check the scope before changing code.
Worked trace
Assume a 5 mm lead screw, 200 steps per revolution, and a step timer interrupt at 20 kHz. At 0.4 m/s the stage needs 16,000 steps per second, so the step period is 62.5 µs. The 1 kHz velocity loop runs in a separate, higher priority interrupt. The step interrupt toggles a GPIO so I can measure it on the scope.
| Observation | Instrument | Interpretation |
|---|---|---|
| Step pulses present at low speed, 4 pulses dropped in one burst at 0.4 m/s | Logic analyzer on STEP and DIR, 100 MS/s | Command generation, not the encoder, is dropping pulses |
| Encoder A/B edges match the steps that were sent, no extra or reversed edges | Logic analyzer decode | Sensor, cable, and quadrature decoding are consistent |
| STEP edge clean at the drive input, 3.3 V swing, rise time 22 ns, no ringing over 10% | Oscilloscope at the drive pin, short ground spring | Signal integrity is not causing the drive to miss steps |
| Step ISR toggle normally 8 µs wide, 210 µs wide during the dropped burst | Oscilloscope on ISR toggle pin | The step interrupt was preempted for about 210 µs |
| Debugger trace shows the 1 kHz ISR entered first and called a blocking I2C read, step timer flag pending on entry to the step ISR | Debugger with ITM trace, core running | A lower priority step interrupt lost its slot to a blocking routine |
The arithmetic fits. A 210 µs preemption spans more than three 62.5 µs step periods. On this timer setup the compare flag is a single pending bit, not a queue. When the step ISR finally runs it emits one pulse and clears the flag, so the intermediate pulses are gone. The drive then reports fewer encoder counts than the planner commanded, which looks like missed encoder counts even though the encoder counted every step it received.
How I set each one up
Logic analyzer: I probe STEP, DIR, encoder A, encoder B, and the ISR toggle. At 100 MS/s a 62.5 µs period gives roughly 6,250 samples, enough to measure pulse width and count dropped pulses directly. I decode quadrature and compare the encoder count with the step count over the same window. I also check the analyzer sample rate against the shortest pulse in the drive datasheet. At 10 MS/s a 200 ns glitch could vanish, so a clean capture at a low sample rate proves little.
Oscilloscope: I probe at the drive input, not at the controller end of a 2 m cable, and I use a short ground spring. A long ground lead adds ringing that the drive never sees. I measure rise time, overshoot, and the 24 V rail during PWM switching, then I measure the ISR toggle. That toggle gives worst case interrupt time including preemption, which a debugger breakpoint cannot show because halting the core lets pending interrupts settle.
Debugger: I use trace rather than a breakpoint as the first look, because stopping the CPU changes the timing I am trying to observe. ITM or SWO trace logs interrupt entry and exit while the loop runs. I then set a breakpoint on the step ISR and inspect the timer status register, the interrupt priority registers, and the stack. That confirms which interrupt preempted the step handler and whether the code was waiting on the I2C peripheral.
// Before: blocking I2C read inside the 1 kHz ISR, step ISR at lower priority.
// After: I2C moved to DMA with an interrupt on completion, step ISR highest.
void Control_1kHz_IRQHandler(void) {
GPIO_SET(ISR_PIN);
read_encoder_counter();
update_velocity();
i2c_start_dma_read(sensor_regs); // returns immediately
GPIO_CLEAR(ISR_PIN);
}
void StepTimer_IRQHandler(void) {
GPIO_SET(STEP_ISR_PIN);
emit_one_step();
GPIO_CLEAR(STEP_ISR_PIN);
}Fix and verification
I would move the I2C transfer to DMA, raise the step timer interrupt above the control and communication interrupts, and keep the step ISR to a few register writes. If the step rate can rise further, I would switch step generation to a timer PWM or compare output that toggles in hardware, so a delayed ISR cannot drop a pulse. Then I rerun the same trigger at 0.4 m/s and check all three views again: the analyzer shows no dropped steps over 10,000 pulses, the scope shows the step ISR under 10 µs with no 210 µs excursions, and the trace shows no pending step flag on entry. If steps are clean on the analyzer and the scope but counts still disagree, I would revisit the encoder input filter and the counter read for a race between the hardware counter and the software snapshot.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-41Walk me through memory-mapped I/O and clock enables on a microcontroller, and why a register write might have no effect on the hardware?
The 90-second answer
Memory-mapped I/O places peripheral registers at fixed addresses in the CPU address space. A store to that address is decoded by the bus fabric and lands in the peripheral register file, instead of going to RAM or to a separate I/O space. On most Cortex-M parts the peripheral clock is gated by default after reset. The register file exists, so reads and writes complete without a bus fault, but the peripheral logic receives no clock edge and ignores the write. That is the most common reason a write appears to do nothing.
How the mechanism works
Each peripheral has a base address from the memory map. Registers sit at offsets from that base. Firmware accesses them through a volatile pointer cast to a struct, which tells the compiler the value can change outside its view and forces a real load or store each time.
// STM32F4, checked against RM0368. GPIOA base 0x40020000.
#define GPIOA_BASE 0x40020000UL
typedef struct {
volatile uint32_t MODER;
volatile uint32_t OTYPER;
volatile uint32_t OSPEEDR;
volatile uint32_t PUPDR;
volatile uint32_t IDR;
volatile uint32_t ODR;
} GPIO_TypeDef;
#define GPIOA ((GPIO_TypeDef *)GPIOA_BASE)
// 1. Enable the clock first. Without this the write below is lost.
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// 2. Now configure PA5 as push-pull output.
GPIOA->MODER &= ~(3UL << 10);
GPIOA->MODER |= (1UL << 10);
GPIOA->ODR |= (1UL << 5);The clock enable bit lives in a different peripheral, usually RCC on STM32 or CLKCTRL / CMU on other families. Setting it connects the peripheral clock tree to the register file and the logic behind it. Gating the clock when the peripheral is idle saves dynamic power, roughly proportional to clock frequency and switched capacitance, and it also stops the peripheral from reacting to stray bus traffic while unused.
Why a write can have no effect
| Cause | What you observe | Check |
|---|---|---|
| Clock not enabled | Readback returns the written value on many parts, pin never changes | RCC enable bit, scope the peripheral clock test output |
| Peripheral held in reset | Same symptom, status bits stay at reset values | RCC reset register, clear the reset bit after enabling the clock |
| Wrong access semantics | Write appears ignored or clears a different flag | Datasheet: write-1-to-clear, write-1-to-set, read-to-clear, read-only status bits |
| Protected or locked register | Write ignored until a key sequence or enable bit is set | Flash protection, timer lock bits, GPIO lock register |
| Reserved or wrong offset | No fault, no effect, neighbouring register may change | Memory map base address and offset table, read back the intended register |
| Bus fault suppressed | HardFault or a stuck bus if the address is unmapped | Fault status registers, debugger memory view at the target address |
Readback alone does not prove the hardware changed. Many register files are readable even with the clock gated, because the read path is powered by the bus clock. The logic that acts on the value needs the peripheral clock. A scope on the output pin, or on a timer compare output, settles it faster than more code.
On a motion controller this shows up as a timer that never counts, so the PWM for a BLDC stage stays at its reset duty, or a GPIO that never drives a driver enable. The fix order I use is clock enable, reset release, then the register sequence from the datasheet, including any required delay of a few peripheral clock cycles before the first access. If the pin still does not move, I check the pin mux and alternate function routing, because a correct register write to the wrong mux selects a different pad.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-42What happens to velocity quantization noise when you lengthen the time window over which you count encoder pulses?
The 90-second answer
Differentiating position sample by sample turns encoder quantization into velocity spikes. Lengthening the counting window reduces that noise in direct proportion to the window length.
An encoder does not report a continuous angle. It reports integer counts. If the true motion moves 4.1 counts per 1 ms sample, the hardware can only report 4 counts or 5 counts. Dividing that integer difference by the sample time gives a velocity that jumps between two values around the true speed. The derivative term in a PID loop multiplies those jumps, so the output chatters even on a smooth ramp.
Counting over a longer window averages the quantization error. Count pulses for 10 ms instead of 1 ms and the same one count error is spread over ten times as long, so the velocity quantum is ten times smaller. That is the whole rule: velocity resolution improves linearly with window length, at the cost of a slower, more lagged estimate.
Worked trace
Take a 2048 line encoder decoded in quadrature by four, giving 8192 counts per revolution. True speed is 0.5 rev/s. Expected motion is 4096 counts per second.
| Window | Expected counts | Smallest nonzero velocity | Error as % of 0.5 rev/s |
|---|---|---|---|
| 1 ms | 4.096 | 0.122 rev/s (7.3 rpm) | 24% |
| 5 ms | 20.48 | 0.024 rev/s (1.5 rpm) | 5% |
| 10 ms | 40.96 | 0.012 rev/s (0.73 rpm) | 2% |
At 1 ms the raw estimate alternates between 0.488 rev/s for 4 counts and 0.610 rev/s for 5 counts. At 10 ms it alternates between 0.488 rev/s for 40 counts and 0.500 rev/s for 41 counts. Same encoder, same speed, far less jitter.
Implementation
// Count over N samples, then divide by the total elapsed time
#define COUNTS_PER_REV 8192.0f
#define DT 0.001f
#define N 10
static int32_t window_start = 0;
static int sample = 0;
float velocity_rev_s(int32_t count)
{
if (sample == 0) window_start = count;
if (++sample < N) return -1.0f; // window not full yet
float vel = (float)(count - window_start) / (COUNTS_PER_REV * N * DT);
sample = 0;
return vel;
}In a live loop I usually pair the wider window with a light first-order filter on the resulting velocity, with a time constant of a few milliseconds. The window does most of the work. The filter smooths the remaining steps. Both add lag, so I keep the total lag well under the closed loop time constant. If the lag approaches the loop time constant, phase margin falls and the axis can hunt at low speed.
Where this breaks down
At very low speed the window may contain zero counts for several windows in a row, then one count. The estimate is mostly zero with occasional spikes. That is not a tuning fault. It is the quantization floor. The standard remedy is to switch to pulse timing at low speed, measuring the time between encoder edges instead of counting edges in a fixed time. That is the M/T method. For the easy case above, though, the candidate answer is the one rule: longer window, smaller velocity quantum, in direct proportion.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-43Walk me through dead time and shoot-through in an H-bridge, and how you would prevent shoot-through without losing too much duty cycle?
The 90-second answer
An H-bridge leg has a high-side and a low-side MOSFET in series across the supply. Shoot-through is both conducting at once. That puts the supply almost directly across two low resistances, so current is limited mainly by Rds(on), trace inductance and the supply impedance. Even 100 ns of overlap can draw tens of amps on a 24 V bridge.
Dead time is the deliberate gap between turning one device off and turning the other on in the same leg. It exists because the two switching edges are never matched. Turn-off delay, gate discharge time, driver propagation delay and Miller effect differ between devices and drift with temperature, gate voltage and load current. If the incoming device turns on before the outgoing device has fully turned off, you get shoot-through.
What the overlap looks like
Assume a 24 V bridge, 20 kHz PWM, Rds(on) of 5 mΩ per device, and a hypothetical 100 ns overlap. The short-circuit current is roughly 24 V / 10 mΩ = 2,400 A before inductance limits it. Real peaks are lower, often 50 to 200 A for tens of nanoseconds, but the energy is still destructive over time.
Average power from overlap alone is approximately:
P = V x I_peak x t_overlap x f_sw
With 24 V, 100 A peak, 100 ns and 20 kHz, that is 4.8 W per leg, concentrated in the MOSFET die and bond wires. The supply current shows a narrow spike each switching edge, the MOSFETs heat quickly, and in the worst case the devices fail shorted, which then welds the bridge into a permanent supply short.
| Time | High-side gate | Low-side gate | Result |
|---|---|---|---|
| 0 ns | falls | held off | High-side starts turning off |
| 80 ns | near zero | held off | High-side mostly off, still some drain current |
| 120 ns | off | rises | Low-side starts turning on |
| 200 ns | off | fully on | Normal conduction |
| 120 ns, no dead time | falls | rises at 60 ns | Both partly on, shoot-through spike |
How I prevent it
First choice is a gate driver with integrated dead time and interlock, for example a half-bridge driver that takes one PWM input and generates complementary outputs. That removes firmware timing as a single point of failure. I still set the dead time from measured switching, not from the datasheet typical values. On a scope I probe both Vgs signals with matched probes, plus drain voltage, at full bus voltage and at the highest load current, because turn-off slows as current rises.
For a discrete design or a timer generating complementary PWM, I use the timer dead-time register and verify it in hardware. On an STM32 timer at 168 MHz, a 200 ns dead time is about 34 timer counts, subject to the DTG encoding in the reference manual.
// STM32 TIM1 complementary PWM, 20 kHz, approx. 200 ns dead time
TIM_BDTRInitTypeDef bdtr = {0};
bdtr.DeadTime = 34; // DTG value, check encoding for your clock
bdtr.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
bdtr.OSSRState = TIM_OSSRSTATE_ENABLE;
bdtr.OSSIState = TIM_OSSIState_ENABLE;
bdtr.LockLevel = TIM_LOCKLEVEL_OFF;
bdtr.BreakState = TIM_BREAKSTATE_ENABLE;
bdtr.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
bdtr.BreakFilter = 4;
HAL_TIMEx_ConfigBreakDeadTime(&htim1, &bdtr);Second, I match the gate drive paths. Equal gate resistors, a Kelvin source connection for the driver, short gate loops and a low-inductance power layout keep the two edges symmetric. A gate resistor that is too small invites ringing and Miller turn-on, where rising drain voltage couples through Cgd and re-turns on the off device. A resistor that is too large slows switching and increases conduction overlap loss. I start around 4.7 to 10 Ω for a typical 24 V, 10 A bridge and adjust from the scope traces.
Third, I add protection that does not depend on dead time alone. Cycle-by-cycle current limit, desaturation detection on the MOSFETs, undervoltage lockout on the gate supply and a hardware break input that forces both gates off on overcurrent. The break must be wired to the driver fault output, not polled by firmware.
| Method | Strength | Weakness |
|---|---|---|
| Driver integrated dead time | Hard to defeat in firmware, matched delays | Fixed or coarse steps on some parts |
| Timer dead-time register | Adjustable, visible in code | Depends on correct clock setup and pin mapping |
| Firmware delay between GPIO writes | Flexible | Jitter from interrupts, compiler and clock changes |
| RC gate network | Simple | Varies strongly with temperature and gate threshold |
The trade-off
Dead time is not free. During the gap, current freewheels through the body diode or synchronous channel, so effective output voltage drops and low-duty operation distorts. At 20 kHz with 200 ns dead time, you lose about 0.4% of the period per edge, which matters for fine speed control near zero. Too much dead time also raises diode conduction loss and current ripple. Too little risks shoot-through at cold start, when gate thresholds are higher and turn-off is slower.
I validate at the corners: minimum and maximum supply, cold and hot MOSFETs, stall current and direction reversal. If the supply current spike grows at any corner, I increase dead time in small steps and re-check efficiency and low-speed behaviour. A bridge that only works at room temperature on the bench has not been designed yet.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-44Walk me through how you would design for EMI and EMC in a system with a switching power supply and motor drives, from source to victim?
The 90-second answer
I treat EMI as a circuit with a source, a coupling path and a victim, and I design each leg before I touch a filter. The switching supply and the motor drive are the sources. The victims are usually the encoder, the analog sensor front end and the controller supply rail. EMC is the same circuit run in reverse: the box must survive external transients without resetting or driving the actuator into motion.
For a 24 V system with a buck converter at 500 kHz and a BLDC drive switching at 20 kHz, I start with the numbers. A MOSFET switching 24 V in 50 ns gives dv/dt of 480 V per microsecond. Motor cable and winding capacitance to ground is roughly 100 pF per metre, so a 3 m cable presents about 300 pF. Common mode current is C times dv/dt, about 144 mA peak per switching edge. That current returns through the protective earth and the supply, and it is what a near field probe and a LISN will find. If I slow the edge to 200 ns with a larger gate resistor, that peak drops to about 36 mA, at the cost of higher switching loss. That trade, edge rate against loss and heat, is the first decision.
Layout and cabling do most of the work. I keep the high di/dt loop on the drive board physically small: input capacitor, half bridge and shunt in one tight cluster, with the return directly under the forward path. Analog and digital ground join the power ground at one controlled point near the supply entry, not at several places that create a loop. Encoder and sensor cables are shielded twisted pairs, shield terminated 360 degrees at the drive end with a gland, and routed at least 200 mm from motor phase cables or crossing them at 90 degrees. A pigtail shield termination adds inductance and defeats the shield above a few MHz, so I avoid it.
At the power entry I use a two stage filter. A differential mode inductor and X capacitor handle the switching ripple that travels line to line. A common mode choke with Y capacitors to chassis handles the current calculated above. The Y capacitors must be safety rated and their total leakage sets a limit, typically a few nanoseconds of concern in reverse: too much Y capacitance leaks into the earth and can trip a residual device. I place the filter at the enclosure boundary so the noisy side stays inside and the clean side feeds the controller.
| Coupling path | What I see on the bench | Fix I apply first |
|---|---|---|
| Conducted, differential | Ripple on the 24 V rail at 500 kHz, ADC reading moves with load | Input LC plus 100 nF and 10 uF decoupling at the load, shorter sense leads |
| Conducted, common mode | Encoder errors only when the motor runs, scope shows spikes on the cable shield | CM choke, Y caps, 360 degree shield termination, common mode ferrite on the encoder pair |
| Radiated | Failure at a specific frequency in a chamber, near field probe peaks at the cable exit | Bond the enclosure seam, move the cable exit away from the switching node, add a ferrite at the exit |
| Capacitive and inductive near field | Sensor offset changes when the drive accelerates | Separate analog and power routing, guard ring around the sensor input, RC low pass before the ADC |
At the source I reduce generation. Gate resistors set the edge rate. An RC snubber across the half bridge damps ringing from stray inductance, sized from the ringing frequency I measure on the scope rather than guessed. Spread spectrum on the buck converter, if the controller allows it, spreads the peak in the spectrum by a few dB, which helps a conducted emissions margin but does not reduce total energy, so I do not rely on it alone. For the motor, a dv/dt filter or sine filter on a long cable run reduces reflections and bearing current, at a cost in size and loss that I only accept when the cable exceeds about 10 m or the motor insulation is marginal.
For immunity I design for the tests I expect. IEC 61000-4-4 electrical fast transients, 4-5 surge on the supply, 4-6 conducted RF from 150 kHz to 80 MHz and 4-3 radiated RF. That means TVS devices and a surge path on the 24 V input sized for the clamp voltage of the downstream regulator, series resistance or a common mode choke on I/O lines, and firmware that treats a corrupted frame as a rejected sample rather than a command. The watchdog and safe state design matters here: a burst that resets the controller must leave the drive disabled, which I verify by injecting transients while the axis is commanded to hold.
Verification is a loop, not a final test. I measure conducted emissions with a LISN early, with the motor running at worst case current and speed, because a drive at no load can pass and fail at full torque. I probe with a near field probe to find the exit point before it becomes a chamber failure. If a filter change moves the peak but does not shrink it, the coupling path is wrong and I go back to layout and cabling rather than adding more ferrites.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-45Walk me through rate monotonic versus deadline monotonic scheduling for a motion controller, and how you would use utilization and response time analysis to prove the control tasks meet their deadlines?
The 90-second answer
Rate monotonic (RM) and deadline monotonic (DM) are both fixed priority schemes. The scheduler picks the highest priority ready task, and priorities are assigned once, at design time. RM gives the shortest period the highest priority. DM gives the earliest relative deadline the highest priority. For tasks where deadline equals period, the two schemes coincide.
The classic RM utilization bound from Liu and Layland is a sufficient test, not a necessary one:
U = sum(Ci / Ti) <= n * (2^(1/n) - 1)
For many tasks that bound approaches 69%. If utilization is below it, RM is guaranteed schedulable under the model assumptions: independent periodic tasks, preemptive scheduling, no blocking, deadlines equal to periods, and known worst case execution times (WCET). Above the bound the set may still be schedulable, so you run exact response time analysis instead of rejecting it.
DM is optimal among fixed priority schemes when deadlines are at or before periods. Its utilization bound is 100% in that case, but the bound alone does not prove schedulability. You still compute response times.
Worked example on a servo axis
Assume a 1 kHz current loop, a 500 Hz velocity loop, a 100 Hz trajectory planner and a 20 Hz logger. WCET figures are measured worst cases on the target MCU, including ISR entry overhead.
| Task | Period T | WCET C | Deadline D | U = C/T |
|---|---|---|---|---|
| Current loop | 1000 us | 180 us | 1000 us | 0.18 |
| Velocity loop | 2000 us | 300 us | 2000 us | 0.15 |
| Trajectory | 10000 us | 800 us | 10000 us | 0.08 |
| Logger | 50000 us | 2000 us | 50000 us | 0.04 |
| Total | 0.45 |
RM bound for n = 4 is 4 * (2^0.25 - 1) = 0.757. Utilization 0.45 is below it, so RM passes. Exact analysis confirms it. Response time iterates as R = C + sum(ceil(R / Tj) * Cj) over higher priority tasks:
| Task | Iteration | R |
|---|---|---|
| Velocity loop | 300 + ceil(R/1000)*180 | 300 -> 480 -> 480 us |
| Trajectory | 800 + ceil(R/1000)*180 + ceil(R/2000)*300 | 800 -> 1280 -> 1280 us |
| Logger | 2000 + ceil(R/1000)*180 + ceil(R/2000)*300 + ceil(R/10000)*800 | 2000 -> 3280 -> 3280 us |
All response times sit well inside their deadlines. That margin matters because the model ignores jitter, cache effects and interrupt latency, which eat into it on real hardware.
Where DM beats RM
Suppose a fault monitor runs every 10 ms but must finish within 2 ms of release, while a velocity task runs every 5 ms with a 5 ms deadline. RM ranks the velocity task first because its period is shorter. The monitor can then miss its 2 ms deadline even though total utilization is low. DM ranks the monitor first because its deadline is earlier, and both tasks meet their deadlines. This pattern shows up in motion systems whenever a slow but urgent safety or protection task sits beside a faster control task.
| Property | Rate monotonic | Deadline monotonic |
|---|---|---|
| Priority rule | Shortest period first | Earliest deadline first |
| Optimal when | D = T for all tasks | D <= T, arbitrary deadlines |
| Utilization bound | n(2^(1/n)-1), about 69% as n grows | Up to 100% with exact analysis |
| Main weakness | Misses short deadlines on long period tasks | Needs credible deadline values, not guesses |
Failure modes to check before trusting the maths
Blocking breaks the bound. A low priority logger holding a shared bus mutex can block the current loop through priority inversion unless you use priority inheritance or ceiling, and the blocking term B must be added to every response time. WCET underestimation is the other common failure. A task measured at 180 us on a bench with warm caches can run 260 us on the machine with cold caches and bus contention, which pushes the velocity loop response past its deadline at high load. I measure WCET with the drive switching, encoder interrupts firing and the logger active, then add headroom and re-run the analysis. If a task set fails exact analysis, the fixes in order are shortening WCET, moving the offending task to DMA or a hardware timer, or splitting the logger so it never shares a lock with the control path.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-46What does a UART framing error mean, and what is its most common cause?
The 90-second answer
A framing error means the receiver sampled the stop bit as low when it should be high. In an 8N1 frame the line idles high, the start bit pulls it low, eight data bits follow, and the stop bit returns it high for at least one bit time. If the receiver reaches that stop-bit sample and still sees low, it flags FE and usually discards the byte. The most common cause is a baud mismatch. The receiver samples near the middle of each bit, so a clock that is off by more than roughly 2 percent over the frame drifts into the next bit and lands on the wrong level.
That one check separates it from an overrun. An overrun, ORE, means the data arrived correctly but the receive register was not read before the next byte finished. Framing is about the bits on the wire. Overrun is about the software keeping up.
How it shows up on the bench
| Symptom | Points to | What to verify |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| FE on nearly every byte, even a single byte sent slowly | Baud or clock mismatch | Measure the TX bit period on a scope and compare it with the configured baud |
| FE occasionally, most bytes correct | Noise, weak levels, or a marginal baud error | Check the idle level, common ground, and signal swing at the receiver pin |
| FE clear, ORE set, bytes missing in bursts | Receiver serviced too slowly | Check interrupt latency and whether a DMA or ring buffer is used |
Measure the bit period rather than trusting the register value. At 115200 baud one bit lasts 1 / 115200 = 8.68 microseconds, and a full 8N1 byte lasts 86.8 microseconds. If the scope shows about 9.6 microseconds per bit, the sender is near 104 kbaud. That is a wrong clock divider or oscillator selection, not a framing format problem. A logic analyser set to the wrong baud shows the same pattern, a stream of framing errors on otherwise clean edges.
Reading the flags
// STM32-style UART status check, called from the receive ISR
uint32_t sr = USART1->SR;
if (sr & USART_SR_FE) {
framing_count++;
(void)USART1->DR; // reading DR clears FE on this family
}
if (sr & USART_SR_ORE) {
overrun_count++;
(void)USART1->DR; // reading DR clears ORE and restarts reception
}
if (sr & USART_SR_RXNE) {
uint8_t b = (uint8_t)USART1->DR;
ring_push(&rx_ring, b);
}Clearing matters because on many parts ORE stays set until DR is read, and reception stops while it is set. That looks like a dead UART when the real fault was one missed byte. Keep the ISR short. At 115200 baud you have 86.8 microseconds per byte, so a long ISR or a blocked section will cause overruns even with the baud correct. DMA into a circular buffer removes that deadline for sustained throughput.
So the first move on a framing error is not to change the frame format. Confirm both ends use the same baud and the same actual clock, then look at the stop bit on the scope. If the stop bit is high and the period matches, the remaining suspect is noise or levels at the receiver.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-47Walk me through estimating BLDC speed to ±2% and torque to ±5% from phase voltage and current alone from stall to rated speed, given winding heating, PWM ripple and Kt saturation, and where would that estimate fail?
The 90-second answer
In SI units Kt and Ke are numerically equal. Kt is Nm per amp of torque-producing current, Ke is volts per rad/s. Power conservation forces it: electrical power converted, Keωi, equals mechanical power, Ktiω. So Kt = Ke.
That gives two model-based estimates, not measurements. Torque: τ = Kti_q, where i_q is q-axis current. Speed: ω = (V - Ri - L*di/dt)/Ke, using PWM-averaged voltage and current sampled synchronously. Meeting ±2% speed and ±5% torque from stall to rated speed with only V and I is not possible across the whole range. At stall back-EMF is zero, so speed is unobservable. At low speed, resistance error and voltage offsets dominate. At high current, Kt saturation and magnet heating dominate torque. A credible design states the speed band where the estimate holds, and hands over to another method outside it.
Worked numbers and error budget
Hypothetical 24 V BLDC: Kt = Ke = 0.050 Nm/A = 0.050 V·s/rad, R = 0.50 Ω at 20 °C, L = 0.8 mH. Steady state, 18.0 V applied, 4.0 A, di/dt ≈ 0.
| Quantity | Calculation | Result |
|---|---|---|
| Torque | 0.050 * 4.0 | 0.20 Nm |
| Copper loss | i²R | 8.0 W |
| Speed | (18.0 - 0.50*4.0)/0.050 | 320 rad/s, 3056 rpm |
| Power check | 18*4 = 72 W in, 64 W converted + 8 W copper | closes |
Now perturb it the way hardware does. Copper rises 0.39%/K. At 80 °C winding, R = 0.62 Ω. Using the cold value at 4 A overestimates the voltage available for back-EMF by 0.48 V, which is 9.6 rad/s, or 3% at 320 rad/s and 48% at 20 rad/s. A 50 mV voltage offset, typical for a PWM average with dead time error, is 1 rad/s by itself. A 2% current sense error is a 2% torque error before Kt is even considered. NdFeB magnets lose roughly 0.1%/K, so at 80 °C Kt is about 6% low. That alone breaks a ±5% torque budget at temperature unless you correct it.
| Error source | Effect at 320 rad/s, 4 A | Effect at 20 rad/s, 4 A |
|---|---|---|
| R cold vs 80 °C, uncorrected | 3% speed | 48% speed |
| 50 mV V offset | 0.3% speed | 5% speed |
| Kt magnet heating, uncorrected | 6% torque | 6% torque |
| Current sense 2% | 2% torque | 2% torque |
| Ignored L*di/dt at 20 A/ms | 16 V transient, speed spike | same |
The table is the design argument. High speed, moderate current, temperature-corrected R and Kt: ±2% speed and ±5% torque are plausible. Low speed or stall: they are not, regardless of filtering.
How to build the estimator
# Python 3, checked against the worked example
Kt = Ke = 0.050 # Nm/A, V*s/rad, temperature corrected
R = 0.62 # ohm, corrected to measured winding temperature
L = 0.8e-3 # H
V, i, di_dt = 18.0, 4.0, 0.0
omega = (V - R * i - L * di_dt) / Ke
torque = Kt * i
print(f"{omega:.0f} rad/s, {torque:.2f} Nm") # 312 rad/s, 0.20 NmAverage V and i over a full PWM period, triggered from the current sample. Instantaneous PWM voltage is either 0 or the bus, and the L*di/dt term during switching is larger than the back-EMF at low speed. Correct R from a winding temperature estimate, from i²R heating integrated in firmware or a thermistor on the housing with a calibrated offset. Correct Kt for magnet temperature and for saturation using a measured Kt(i) curve, not the single datasheet number. Vendors quote Kt as Nm/A peak, Nm/A rms, or oz·in/A, and Ke as V/kRPM. Mixing peak and rms gives a √2 or √3 error that masquerades as a torque error. Convert everything to SI and name the current convention.
For a three-phase BLDC, transform phase currents to dq and use i_q. Using one phase current or total DC bus current underestimates torque during commutation and adds 6th-harmonic ripple.
Where it fails, and what to do instead
Stall and start: ω = 0 gives V = R*i, so any offset becomes phantom speed. Sensorless drives ramp open-loop, align the rotor with a current pulse, or use phase inductance, then hand over to back-EMF zero-crossing or an observer above roughly 5 to 10% of rated speed. Below handover, report speed as unknown or open-loop commanded, not as a measured value.
Transients: L*di/dt = 16 V at 20 A/ms in this example. Including a raw derivative amplifies switching noise. Blank or down-weight the speed estimate during large current steps, or use an observer that blends the electrical model with back-EMF zero crossings.
Saturation and cogging: average torque follows Kt*i, instantaneous torque does not. Cogging and current ripple mean the estimate is valid for thermal and health monitoring, not for judging following error on a precision axis at one instant.
In practice I use this estimate for sensorless operation above handover, drive health checks, and cross-checking an encoder. If an encoder is fitted, I do not close a precision velocity or position loop on the electrical estimate. The encoder measures the shaft. The electrical estimate measures it through R, L and Kt, all of which drift with temperature and current.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-48Your 1 kHz timer ISR updates a 32-bit encoder count that the main loop reads to compute velocity. How would you share that value safely in C, and when would volatile alone be enough versus needing atomics or a critical section?
The 90-second answer
For a 1 kHz loop I let the timer ISR do only the capture and handoff, and I let the main loop do the maths. The ISR reads the encoder counter once, stores it in a mailbox, and sets a flag. The main loop polls the flag, copies the value out, runs the PID, and writes the PWM register. The question is how that copy stays correct when the ISR can fire at any instruction.
volatile alone is enough only for a single access the hardware makes atomic in practice, such as an aligned 32-bit load on a 32-bit Cortex-M, and even then it gives no ordering guarantee. For anything wider, or for a flag that must order the data write before it, I use C11 atomics or a short critical section. I pick between those two on the size of the copy.
The handoff I use
/* C11, GCC 13, Cortex-M4. Checked against stdatomic.h. */
#include <stdatomic.h>
#include <stdint.h>
static volatile int32_t enc_position; /* written by ISR */
static atomic_bool enc_fresh; /* written by ISR, read by loop */
static int32_t prev_position;
void timer_isr(void)
{
enc_position = (int32_t)ENCODER->CNT; /* one aligned 32-bit store */
atomic_store_explicit(&enc_fresh, true, memory_order_release);
}
void control_step(void)
{
if (!atomic_exchange_explicit(&enc_fresh, false,
memory_order_acq_rel)) {
return;
}
int32_t pos = enc_position; /* single aligned 32-bit load */
int32_t vel = pos - prev_position;
prev_position = pos;
pwm_set_duty(pid_update(pos, vel));
}The release store means the store to enc_position is visible before the flag is. The acquire exchange in the loop means the loop cannot move its read of enc_position above the flag check. That ordering is what volatile does not provide. volatile stops the compiler caching the variable in a register or deleting a load it thinks is redundant. It does not stop the compiler reordering two volatile accesses relative to each other, and it does not make a read-modify-write atomic.
When volatile alone fails: a torn read
On a 16-bit part, or for a 64-bit timestamp on a 32-bit part, a 32-bit or 64-bit read compiles to two half-word loads. Suppose the counter rolls from 0x0000FFFF to 0x00010000 between those two loads. The loop can read the new high half with the old low half and get 0x0001FFFF, which is 65,535 counts ahead of the true value. At a 1 kHz sample rate the loop computes a velocity of 65,535 counts per second for one tick, the PID sees a huge error, and the PWM slams. The same bug appears with volatile int32_t because the compiler is obeying volatile correctly. The access simply is not atomic.
Two fixes cover that case. For a small struct or a 64-bit value, mask interrupts for the copy:
uint32_t primask = __get_PRIMASK();
__disable_irq();
int64_t pos = enc_timestamp;
__set_PRIMASK(primask);That copy takes a few instructions, so the added ISR latency is well under a microsecond at 168 MHz. If the copy grew to a whole telemetry frame, masking interrupts that long would add jitter to every other interrupt, so I would switch to a single-producer ring buffer instead.
Choosing between the approaches
| Approach | What it guarantees | Cost | Use it when |
|---|---|---|---|
volatile only | No caching or deletion by the compiler | Zero runtime cost | A hardware register, or one aligned word on a target where that width is a single bus access |
C11 stdatomic | Atomic access plus explicit ordering | Usually one load or store, sometimes a lock on 8-bit targets | A flag, a counter, or a single word mailbox between ISR and loop |
| Short critical section | No ISR can interleave during the copy | Adds its length to worst case interrupt latency | Copying a struct or a value wider than the bus |
| SPSC ring buffer | Lock free handoff of a stream | Memory for the buffer, overrun counting | Samples arrive faster than the loop consumes them, such as UART bytes |
I check the result on the scope by toggling a GPIO at the top of control_step. If the pulse spacing drifts from 1 ms, the loop is missing ticks, which I also count by checking whether enc_fresh is still set when the ISR fires again. A missed tick count above zero means the loop is late and the PID is running on stale data, and that is a scheduling problem to fix before tuning the gains.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-49Walk me through how you would implement gravity compensation and friction feedforward on a robot arm, and what goes wrong if the model is off?
The 90-second answer
For a robot joint, feedback alone has to discover the torque needed to hold the arm up and to break friction loose. That discovery shows up as lag, steady state error and a limit cycle around zero velocity. Feedforward supplies most of that torque from a model before the error appears, so the PID only corrects the residual.
For joint i, the rigid body model is:
tau_i = M_i(q) qdd_i + C_i(q, qd) + g_i(q) + f_i(qd)
Gravity compensation estimates g_i(q). Friction feedforward estimates f_i(qd). In practice I implement:
tau_cmd = tau_ff + Kp e + Ki integral(e) + Kd de/dt
where tau_ff = g_hat(q) + Fv qd + Fc tanh(qd / v_s)
g_hat(q) comes from link masses and centres of mass. For a planar two link arm, joint 1 gravity torque is roughly g * [ (m1 lc1 + m2 l1) sin(q1) + m2 lc2 sin(q1+q2) ] with sign set by your zero convention. For a general 3D arm I use g(q) = J_v,com^T * m * g_vec summed over links, or a fitted Fourier series in q if link parameters are uncertain. Friction uses viscous Fv qd plus Coulomb Fc smoothed near zero with tanh(qd/v_s), where v_s is about 0.01 to 0.05 rad/s. A hard sign(qd) chatters at rest and fights the integrator.
// 1 kHz joint loop, single joint shown
float q = encoder_angle();
float qd = filtered_velocity();
float e = q_des - q;
float tau_g = gravity_model(q); // Nm, from identified masses
float tau_f = Fv * qd + Fc * tanhf(qd / 0.02f);
float tau_ff = tau_g + tau_f;
float tau_fb = Kp * e + Ki * integral + Kd * (e - e_prev) * dt;
float tau = clamp(tau_ff + tau_fb, -tau_max, tau_max);
current_cmd = tau / Kt; // Kt in Nm/AHow I identify the parameters
Gravity: hold the arm at a grid of static poses across the workspace, with brakes or high gain position hold, and record steady motor current. Fit g_hat(q) to Kt * I at zero velocity, where friction and inertia drop out. Repeat with the heaviest payload expected. If the fit residual exceeds about 5 percent of peak gravity torque, I do not trust a pure physics model and add a learned residual table indexed by q.
Friction: run slow constant velocity sweeps, for example plus and minus 0.05, 0.1, 0.2 and 0.5 rad/s, in both directions at several poses. At constant velocity, acceleration torque is near zero, so Kt * I - g_hat(q) plotted against qd gives viscous slope and Coulomb offset. The gap between positive and negative sweeps at low speed is stiction and hysteresis, not Coulomb friction, and a single Fc will not capture it.
Worked example, hypothetical figures for joint 2 of a small arm, Kt = 0.8 Nm/A:
| q (rad) | qd (rad/s) | g_hat (Nm) | Fv qd (Nm) | Fc tanh term (Nm) | tau_ff (Nm) | Measured Kt I (Nm) | Residual for PID |
|---|---|---|---|---|---|---|---|
| 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0 | 0.05 | 0.05 |
| 0.6 | 0.0 | 3.2 | 0.0 | 0.0 | 3.2 | 3.35 | 0.15 |
| 0.6 | 0.2 | 3.2 | 0.24 | 0.38 | 3.82 | 3.90 | 0.08 |
| 0.6 | -0.2 | 3.2 | -0.24 | -0.38 | 2.58 | 2.70 | 0.12 |
| 1.2 | 0.0 | 5.1 | 0.0 | 0.0 | 5.1 | 5.45 | 0.35 |
The residual at 1.2 rad is larger, which points to a payload or cable torque error rather than friction, because it appears at zero velocity and grows with q.
What goes wrong
Wrong payload is the common failure. A 2 kg tool added to a model tuned for 0.5 kg can add several Nm at full extension. The integrator then winds up to supply it, and when the arm moves to a pose where gravity torque falls, that stored integral causes overshoot. I detect this by logging integral term magnitude during slow moves. If it sits above roughly 20 percent of tau_max for more than a second at near zero velocity, the gravity model is wrong, not the gains.
Sign and frame errors are the second failure. Gravity torque flips sign if joint zero or encoder direction differs from the model convention. The symptom is immediate: the arm sags or drives away from target at rest with feedforward enabled, and improves when it is disabled. I test this on a bench with the arm supported, at low current limit, before enabling full torque.
Friction changes with temperature, load and direction. Gearbox friction on a harmonic or cycloidal drive can rise 30 to 50 percent cold, and Coulomb friction depends on transmitted torque, not just velocity. A fixed Fc then undercompensates on cold start and overcompensates warm. The result is stick slip at low speed: the joint sticks, error builds, feedforward plus integral breaks it loose, and it jumps. Mitigations are a lower Fc with a higher integral rate limited to low speed, dither in some precision axes, or a friction model that includes load torque. I validate by running the same slow trajectory cold and after 20 minutes of operation and comparing following error.
Cable and hose torque, joint elasticity and backlash also masquerade as friction. They vary with q in a way a velocity only model cannot fit, so the residual table from the static pose test matters. If residual shows a repeatable pattern versus q, I add it to g_hat as a position dependent disturbance instead of raising Fc.
Validation is a slow constant velocity move and a static hold at five poses, with feedforward on and off. Good feedforward cuts following error by a factor of three to ten on the slow move and cuts steady state integral to near zero at hold, without increasing current ripple at rest. If it only improves the tuned trajectory and worsens others, the model was overfitted and I refit with payload variation included.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-50What does a step response test tell you about a servo axis, and how do you read overshoot, settling time and steady-state error from it?
The 90-second answer
A step response test commands the axis to jump to a new position and records where it actually goes. From that one trace you read three numbers. Overshoot tells you how far it passes the target. Settling time tells you how long it takes to stay inside the tolerance band. Steady-state error tells you how far it sits from the target once it has stopped moving.
I run it on the assembled axis at rated payload, through the normal controller, and log commanded position, encoder position, velocity and drive current on the same time base. The step size comes from the specification. For a 10 mm move specified to settle within 5 µm, the pass limits are written before the test starts.
| Metric | How to read it | What a bad value usually means |
|---|---|---|
| Overshoot | Peak position minus final position, as a percentage of step size | Proportional gain too high, derivative action too weak, or a lightly damped resonance |
| Settling time | Last time the trace enters and stays inside the tolerance band, for example ±5 µm | Integral action too slow, feedforward missing, or saturation during the move |
| Steady-state error | Mean error over the last 50 ms after settling | Friction, gravity load without feedforward, or encoder offset |
Worked trace
Hypothetical trace for a 10 mm step, sampled from the encoder:
| Time (ms) | Commanded (mm) | Actual (mm) | Error (µm) |
|---|---|---|---|
| 0 | 10.000 | 0.000 | 10000 |
| 50 | 10.000 | 8.200 | 1800 |
| 100 | 10.000 | 10.600 | -600 |
| 150 | 10.000 | 10.950 | -950 |
| 200 | 10.000 | 10.002 | -2 |
Peak position is 10.950 mm, so overshoot is 0.950 mm, or 9.5% of the 10 mm step. The trace last leaves the ±5 µm band at about 200 ms, so settling time is about 200 ms. Mean error over the final 50 ms is about 2 µm, so steady-state error is 2 µm. Against limits of 10% overshoot, 200 ms settling and 5 µm steady-state error, this axis passes, with no margin on settling time.
Reading the trace in code
The same three numbers can be extracted from a logged run instead of read by eye. This Python snippet assumes a 1 kHz log with columns for time, command and position:
import numpy as np
def step_metrics(t_ms, cmd_mm, pos_mm, band_um=5.0):
step = cmd_mm[-1] - cmd_mm[0]
final = np.mean(pos_mm[-50:])
overshoot_pct = (np.max(pos_mm) - final) / step * 100.0
err_um = (cmd_mm - pos_mm) * 1000.0
inside = np.abs(err_um) <= band_um
# last sample outside the band, plus one sample
outside = np.where(~inside)[0]
settling_ms = t_ms[outside[-1]] if len(outside) else t_ms[0]
ss_error_um = np.mean(err_um[-50:])
return overshoot_pct, settling_ms, ss_error_umWhat changes the fix
High overshoot with ringing at a fixed frequency points to gain or damping, so I lower proportional gain or add derivative filtering and retest. Slow settling with no overshoot points to integral action or a current limit reached during the move, so I check drive current and voltage in the log before touching the tuning. A constant offset that does not decay points to friction or gravity, so I check feedforward and the load direction rather than raising integral gain, which would only hide the offset and risk windup on the next large move.
Disturbance and endurance runs build on this trace. Disturbance testing applies a known force and checks peak deviation and recovery against the same band. Endurance testing repeats the step at intervals and watches whether overshoot, settling time or steady-state error drift as the motor heats or the mechanics wear. The step response remains the first check because it separates tuning faults from load and wear faults in a single run.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-51Walk me through how a strain gauge load cell turns force into a voltage, and how you would design and calibrate a Wheatstone bridge for a 0 to 500 N cell with temperature drift?
The 90-second answer
A load cell is a machined elastic element, usually aluminium or steel, with foil strain gauges bonded where the strain is highest and most uniform. Force bends or compresses that element. The gauges change resistance in proportion to strain. A Wheatstone bridge converts that small resistance change into a differential voltage, and an instrumentation amplifier raises it to a level an ADC can use.
The chain is: force to strain, strain to resistance, resistance to bridge voltage, bridge voltage to amplified voltage, amplified voltage to counts, counts to calibrated force. Every error source enters at a specific link in that chain, which is where you fix it.
Strain gauge and gauge factor
For a foil gauge, resistance change follows:
ΔR / R = GF × εGF is the gauge factor, typically 2.0 to 2.2 for constantan foil. ε is strain in m/m. A 500 N single point cell might see 400 to 800 microstrain at full load in the gauged region. Take a worked example, labelled as hypothetical: R = 350 Ω, GF = 2.1, ε = 600 µε at 500 N.
ΔR = 350 × 2.1 × 600e-6 = 0.441 Ω
ΔR / R = 0.00126That is a 0.126% change. You cannot measure it reliably with a simple divider and a single ended ADC. The bridge exists to extract it differentially and reject common changes.
Wheatstone bridge configurations
| Configuration | Gauges active | Approx. output at full strain | Temperature behaviour |
|---|---|---|---|
| Quarter bridge | 1 | Vex × (ΔR/R) / 4 | Poor, gauge tempco appears directly |
| Half bridge | 2, opposite arms | Vex × (ΔR/R) / 2 | Good if gauges are matched and co-located |
| Full bridge | 4, two tension, two compression | Vex × (ΔR/R) | Best, sensitivity doubled again and tempco largely cancels |
With Vex = 5 V and the numbers above, a full bridge gives about 5 × 0.00126 = 6.3 mV differential at 500 N. A quarter bridge gives about 1.6 mV. That is why precision cells use a full bridge and a ratiometric reference: the ADC reference comes from the same excitation, so a drift in excitation cancels in the ratio.
Why the bridge rejects temperature, and where it fails
Temperature changes gauge resistance even with no load. In a full bridge, all four gauges sit on the same element at nearly the same temperature, so all four resistances move together. Opposite arms move in the same direction, adjacent arms move together, and the differential output stays near zero. That is the compensation. It fails when the gauges are not matched, when one gauge is self heated more than the others, or when the element itself expands and changes the mechanical zero. A steel element also changes stiffness with temperature, so span drifts even if zero is compensated. That is a span temperature coefficient, typically 0.01 to 0.03% of full scale per 10 °C for a compensated industrial cell, and worse for an uncompensated one.
Other failure modes are mechanical. Creep in the adhesive or the element makes output drift under sustained load. Hysteresis makes the reading depend on whether you arrived from above or below. Overload past about 150% of rated capacity can yield the element and permanently shift zero. Cable damage matters too: a 3 wire bridge cannot correct lead resistance changes, a 6 wire Kelvin sensed excitation can.
Amplification and calibration
6.3 mV at the bridge becomes 630 mV after a gain of 100, which suits a 0 to 5 V ADC with headroom for overload and zero offset. Gain is not free. An instrumentation amplifier with 100 µV offset drift over temperature will move your zero by a force equivalent you can calculate: 100 µV at the input is about 8 N on this example, since 6.3 mV equals 500 N. That often dominates the gauge error, so amplifier offset and drift set the usable accuracy more than the gauge factor tolerance.
Calibration is a two point fit at minimum, zero and a known load near full scale, repeated at temperature extremes if span drift matters. A shunt calibration resistor across one arm simulates a known resistance change and checks the whole electrical chain without applying force, useful for field checks but it does not verify the mechanical element.
# Python 3, checked against the worked example above
# counts from a 16 bit ADC, ratiometric, 0 to 65535 over 0 to 5 V
def counts_to_newtons(counts, zero_counts, span_counts, span_newtons):
return (counts - zero_counts) * span_newtons / (span_counts - zero_counts)
# Example: zero at 32768 counts, 500 N at 40960 counts
print(counts_to_newtons(40960, 32768, 40960, 500.0)) # 500.0
print(counts_to_newtons(36864, 32768, 40960, 500.0)) # 250.0In firmware I would average over a window matched to the mechanical bandwidth, often 10 to 50 ms for a static weighing cell, and reject samples during impact. I would also log excitation voltage and a temperature sensor on the cell body, then apply a correction table built during thermal calibration rather than a single coefficient, because zero drift and span drift do not track each other.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-52Walk me through how you would choose a microcontroller for a real-time motion application, covering clock, timers, ADC, and peripherals?
The 90-second answer
I start from the control deadline, not the core. For a 1 kHz velocity loop I need a timer that fires every 1,000 microseconds with jitter under about 10 microseconds, PWM at 20 kHz or higher for the drive, encoder capture that does not lose counts at maximum speed, and an ADC that can sample current and voltage synchronously with the PWM. If those four fit with headroom, I then check peripherals, memory and power. A 170 MHz Cortex-M4 with a floating point unit, such as an STM32G4, usually clears that bar. A slower 48 MHz part can also work, but the timer resolution and ADC throughput leave less margin for filtering and diagnostics.
Clock and timers
The clock tree decides timer resolution. On many STM32 parts the timer clock doubles when the APB prescaler is not 1, so I verify the actual timer clock in the reference manual rather than assuming the core clock. PWM resolution follows directly from that clock.
// STM32G4, TIM1 timer clock = 170 MHz, centre-aligned PWM
// f_pwm = f_tim / ((PSC + 1) * 2 * ARR)
uint32_t arr = 170000000UL / (2 * 20000UL); // 4250 counts at 20 kHz
TIM1->PSC = 0;
TIM1->ARR = arr;
TIM1->CCR1 = arr / 2; // 50% dutyAt 20 kHz that gives 4,250 counts, about 12 bits of duty resolution. At 100 kHz the same clock gives only 850 counts, so switching frequency trades directly against duty resolution and current ripple. For the control ISR I use a separate basic timer, for example TIM6 at 1 kHz, and I measure its period and jitter with a GPIO toggle and a logic analyzer. The ISR budget I set on paper is 150 microseconds worst case for PID, filtering and encoder read, leaving the rest of the 1,000 microsecond period for communications and logging. If the measured worst case exceeds that, the part is too slow or the code is doing too much in the ISR.
Encoder handling is a timer choice, not a software polling choice. Quadrature encoder mode on a timer input counts in hardware, and input capture or pulse counting gives velocity without an interrupt per edge. I check the maximum count rate first. A 2,048 line encoder in quadrature gives 8,192 counts per revolution. At 3,000 rpm that is 409,600 counts per second. A timer in encoder mode handles that in hardware. Polling or an interrupt per edge would not.
| Requirement | Worked figure | What it rules in or out |
|---|---|---|
| Control period | 1 kHz = 1,000 us, jitter target under 10 us | Needs a hardware timer ISR, not a loop delay |
| PWM | 170 MHz / (2 x 20 kHz) = 4,250 counts | About 12 bit duty resolution at 20 kHz |
| Encoder | 8,192 counts/rev x 50 rev/s = 409,600 counts/s | Needs hardware quadrature mode |
| ADC | 12 bit over 3.3 V = 0.81 mV per LSB | Check sampling time against source impedance |
ADC and analogue front end
ADC selection is about sampling time and synchronisation. A 12 bit ADC at 3.3 V resolves 0.81 mV per LSB. If a 0 to 10 A current sense is scaled to 0 to 3 V, that is 300 mV per amp, so one LSB corresponds to about 2.7 mA. That resolution is fine for current limiting and torque estimation. The risk is not resolution. It is whether the sample and hold capacitor charges fully through the source resistance before conversion ends. I calculate the acquisition time from the datasheet and the source impedance, and I trigger conversions from the PWM timer so current is sampled at the centre of the on period, away from switching edges. DMA moves the results into a circular buffer so the ISR reads a fresh sample without waiting for conversion. If the signal bandwidth is low, for example a pressure sensor below 50 Hz sampled at 1 kHz, I still keep an analogue low pass before the pin to stop aliasing, and I set its cutoff around 200 to 250 Hz in that case.
Peripherals and the rest of the part
I list the interfaces the machine actually needs before comparing parts. A typical axis needs SPI for an absolute encoder, CAN or CAN FD for the drive network, UART for a debug or host link, I2C for temperature or IO expanders, a DAC or comparator for current limit, and enough DMA channels to run ADC and SPI without the CPU. I also check pin muxing early. A part can have three SPI blocks on paper and still fail if the pins for SPI, CAN and encoder timers land on the same alternate function. Memory matters for trajectory buffers and logs, and a hardware CRC and unique ID help with field diagnostics, but neither rescues a part that misses the timer or ADC requirements.
Two failure modes come up often. First, the timer clock is half what the code assumes because of the APB prescaler, so PWM runs at half frequency and the control loop runs slow. I catch that by measuring the timer output pin. Second, the ADC is triggered asynchronously to the PWM, so current samples land on switching transients and the current loop looks noisy. I catch that by comparing triggered and free running samples on a scope. In both cases the fix is in clock and trigger configuration, not in tuning the PID to hide the symptom.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-53Walk me through how you would set up sampling and anti-aliasing to measure vibration up to 5 kHz without aliasing a 12 kHz bearing tone into your spectrum?
The 90-second answer
Sampling theory sets a hard limit before any software runs. If you sample at fs, any component above fs/2 folds back into the band and looks like a real vibration at f_alias = |f - n*fs|, where n is the integer that puts the result between 0 and fs/2. No digital filter after the ADC can separate that folded tone from a genuine one, because they are identical in the samples. So the order is fixed: condition the sensor, put an analogue low-pass anti-alias filter in front of the ADC, then sample fast enough that the filter has a transition band to work in.
For a 5 kHz vibration band I would not sample at 10 kHz. That puts 5 kHz exactly at Nyquist, where amplitude and phase are unreliable and there is no guard band. I would sample at 51.2 kHz, set the analogue filter cutoff at 5 kHz, and accept that the usable flat band ends a little below cutoff. The frequency that would otherwise fold to 5 kHz is then 46.2 kHz (51.2 kHz minus 5 kHz). A 4th-order Butterworth at 5 kHz gives about 77 dB attenuation at 46.2 kHz, which keeps folded energy near or below the roughly 74 dB ideal SNR of a 12-bit ADC. At 25.6 kHz sampling the same filter would give only about 49 dB at 20.6 kHz, which is not enough for a strong out-of-band tone, so the higher sample rate is what buys the margin.
Worked alias trace
Take fs = 10 kHz as the bad case, with a bearing tone at 12 kHz and a structural mode at 18 kHz:
| True frequency | Alias at fs = 10 kHz | Alias at fs = 51.2 kHz | What you would wrongly report |
|---|---|---|---|
| 2 kHz | 2 kHz | 2 kHz | Correct |
| 12 kHz | 2 kHz | 12 kHz | At 10 kHz, indistinguishable from the 2 kHz mode |
| 18 kHz | 2 kHz | 18 kHz | At 10 kHz, also folds to 2 kHz |
| 8 kHz | 2 kHz | 8 kHz | At 10 kHz, same result |
At fs = 51.2 kHz those tones stay at their true frequencies, outside the 0 to 5 kHz band of interest, and the analogue filter has already attenuated them before sampling.
def alias_freq(f, fs):
# Fold f into 0..fs/2
r = f % fs
return r if r <= fs / 2 else fs - r
for f in (2000, 8000, 12000, 18000):
print(f, alias_freq(f, 10000), alias_freq(f, 51200))Filter choice and its cost
| Approach | Alias protection | Cost |
|---|---|---|
| --- | --- | --- |
| 2nd-order Butterworth, fc = 5 kHz, fs = 51.2 kHz | About 39 dB at 46.2 kHz | Flat to about 4 kHz, but aliasing risk with a 12-bit ADC |
| 4th-order Butterworth, fc = 5 kHz, fs = 51.2 kHz | About 77 dB at 46.2 kHz | Phase lag grows near cutoff, group delay must be accounted for if you compare channels |
| 4th-order Bessel, fc = 5 kHz | Less attenuation per order than Butterworth | Flatter phase and delay, useful when timing between two accelerometers matters |
| Oversampling ADC with internal decimation | Internal filter only helps if the datasheet guarantees it before the modulator | Still needs an external filter for tones above the modulator rate, check the alias table in the datasheet |
The trade-off is phase. A Butterworth 4th-order section at 4 kHz is already rolling off and shifting phase, so a spectrum is fine but a time-domain comparison of force and response will show a lag that is filter, not structure. If I need cross-channel phase, I use matched filter channels on every input, or a Bessel type, and I calibrate the delay out.
Failure modes I check on hardware
First, sensor resonance. A piezoelectric accelerometer with a mounted resonance at 20 kHz will amplify energy near that frequency, so the tone arriving at the filter can be 10 to 20 dB larger than the shaft vibration. The filter calculation must use the amplified level, not the nominal one. Second, filter cutoff drift. An RC filter built with 5% capacitors can move cutoff by several percent, which eats into the guard band, so I verify the actual -3 dB point with a swept sine on the bench rather than trusting the schematic value. Third, sampling jitter. Timing jitter on the ADC clock creates noise that rises with frequency, roughly 20log10(2pift_jitter) dB. At 5 kHz with 10 ns jitter that is about -70 dB, which can dominate a 12-bit converter. I check the clock source on the scope if the noise floor at high frequency looks worse than the ADC datasheet predicts.
If a peak appears in the spectrum, I confirm it is real by changing fs slightly. A true 2 kHz mode stays at 2 kHz. An alias moves by the same amount as fs changes. That one test settles most arguments about whether a line in the FFT is structure or folding.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-54On a Cortex-M microcontroller, what is the first thing you read in a HardFault handler to find the faulting instruction, and why?
The 90-second answer
I read the stacked PC first. On Cortex-M, exception entry pushes the register frame onto the stack, and the PC in that frame is the address of the instruction that faulted, or the next instruction for an imprecise fault. That address, disassembled in the debugger, usually names the line that dereferenced a bad pointer or executed from the wrong address. Resetting before reading it throws away the only direct evidence of where execution went wrong.
Why the stacked PC works
The hardware saves context so the handler can return to the interrupted code. It does not save a copy of PC in a normal register for the handler to read later. The saved copy lives in the stack frame, at a fixed offset from the stack pointer on entry to the handler.
// Cortex-M4/M7, CMSIS 5.x
typedef struct {
uint32_t r0, r1, r2, r3, r12, lr, pc, psr;
} StackedRegs;
void HardFault_Handler(void)
{
StackedRegs *frame = (StackedRegs *)__get_MSP();
volatile uint32_t fault_pc = frame->pc;
volatile uint32_t fault_lr = frame->lr;
(void)fault_pc;
(void)fault_lr;
while (1) {
__DSB();
}
}This version assumes the faulting code was running on MSP, which covers bare-metal code and ISRs. Code running on PSP, as RTOS threads often do, needs the PSP frame instead. The handler still starts with the same idea: get the frame that hardware pushed, then read its PC field.
| Stacked field | What it tells you |
|---|---|
pc | Faulting instruction address for a precise fault, next instruction for an imprecise bus fault |
lr | Return address of the interrupted function, or EXC_RETURN if the fault hit an ISR |
psr | Processor state at the fault, including the active exception number in bits 8:0 |
r0 to r3, r12 | Argument and scratch registers at the fault, useful when the faulting instruction used a register operand |
Reading it in practice
I halt the core in the handler, copy fault_pc and fault_lr to a log buffer or a debugger watch window, and disassemble from fault_pc in the map file. A PC pointing at a load instruction with a register operand sends me to that pointer. A PC pointing into the middle of a function, or a value such as 0xFFFFFFFF, sends me to stack corruption instead, because a corrupted return address becomes the PC on return. A PC in flash at a valid instruction boundary with a fault status register showing an undefined instruction usually means execution jumped into data or a buffer.
That one read separates the common cases quickly. It also tells me whether to chase a pointer, a stack problem, or a bad jump, before I change any code.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-55Walk me through choosing and sizing a Hall, inductive or optical sensor to count a 0.5 mm aluminium flag at 3 mm gap at 5 kHz inside a misted enclosure beside a 20 A BLDC cable, without false-triggering on a steel fixture parked 8 mm away?
The 90-second answer
No off-the-shelf 4 mm inductive sensor meets that specification, and that calculation is the centre of the answer. A 0.5 mm aluminium flag at a 3 mm gap, in mist, beside a high current cable, with a steel fixture 8 mm away, defeats each technology in a different way. The defensible choice is either to change the mechanics so the gap falls, or to put a magnet on the flag and use Hall sensing. Picking a sensor from its headline range without derating for material, thickness and nearby metal is how this fails on the machine.
Hall effect. A bias current in a semiconductor strip is deflected by a magnetic field perpendicular to the strip. The Lorentz force creates a transverse Hall voltage, V_H = I x B / (n q t), where n is carrier density, q is charge and t is strip thickness. Integrated devices add a magnet, amplifier and comparator, often as a latch with hysteresis. The aluminium flag produces no field, so Hall sensing only works if a magnet is bonded to the flag. That makes flag material and thickness irrelevant, mist irrelevant, and response fast enough for 5 kHz counting. The costs are a magnet that can attract steel chips in a machining enclosure, temperature drift in sensitivity and offset, and stray fields. Check the stray field rather than assuming it: for a single 20 A conductor at 20 mm, B = mu0 I / (2 pi r) = 2e-7 x 20 / 0.02 = 0.2 mT. A latch switching at 15 mT on and 8 mT off has more than an order of magnitude margin against that cable. A BLDC rotor magnet parked close is a different problem, because its field can reach millitesla levels at the sensor, so the test is to run the motor through its detent positions with the flag absent and confirm the output never switches.
Inductive. An LC oscillator in the head produces an alternating magnetic field. Eddy currents in a conductive target load the oscillator, the detector sees the amplitude change and switches. Mist, oil and dust on the face do not matter. The limits are conductivity, thickness and nearby metal. Datasheets rate range on a standard mild steel block, often 1 mm thick. Aluminium typically gives 30 to 50 percent of that range, and a target thinner than the standard gives a further reduction. These factors are not optional refinements. They multiply.
Worked example, using typical factors for an M12 sensor rated at 4 mm on steel: aluminium factor 0.4, thin target factor 0.7 for 0.5 mm. Effective range = 4 x 0.4 x 0.7 = 1.12 mm. That is less than half the 3 mm gap, so the sensor will not switch at all, not merely switch late. An M18 sensor rated at 12 mm gives 12 x 0.4 x 0.7 = 3.36 mm, which clears 3 mm on paper but leaves 0.36 mm for bracket tolerance, temperature drift and the steel fixture at 8 mm loading the oscillator. That margin is too thin for production. I would not sign that off without measuring the actual trip point with the real flag, at temperature extremes, with the fixture parked at its closest position. If the flag cannot carry a magnet, the correct move is to reduce the gap to 1.5 mm or less and use the larger head, then verify the fixture at 8 mm does not shift the trip point by more than the remaining margin.
Optical. Photoelectric sensing uses emitted infrared light in diffuse, retroreflective or through-beam mode. It detects any opaque target, gives long range and fast response, and is indifferent to conductivity and magnetism. In a coolant misted enclosure it is the weakest choice. Mist and film on the lens scatter and attenuate the beam, returned intensity falls over a shift, and a diffuse sensor starts missing the flag or, with automatic gain, starts seeing mist itself as a target. Through-beam with an air purge across the lenses can survive, but that adds a purge supply, alignment sensitivity and a failure mode if the purge stops. For a 0.5 mm flag passing at 5 kHz, beam alignment and spot size also matter, because a small flag can pass between pulses of a slow sensor or partially cover the beam.
| Constraint | Hall with magnet on flag | Inductive, no magnet | Optical diffuse |
|---|---|---|---|
| 0.5 mm aluminium at 3 mm | Works, magnet provides field | 4 mm head gives about 1.1 mm effective range, fails | Works optically, mist is the risk |
| Coolant mist | Immune | Immune | Lens fouling, missed triggers |
| 20 A cable at 20 mm | About 0.2 mT stray, below latch threshold | Immune | Immune |
| Steel fixture at 8 mm | No effect unless it shunts the magnet field | Loads oscillator, shifts trip point | No effect if outside beam |
| 5 kHz counting | Suitable, microsecond to tens of microseconds | Check datasheet, often 0.1 to 1 ms, marginal at 5 kHz | Suitable if beam is clean |
| Hidden failure | Magnet collects steel chips, rotor magnet false triggers | Thin aluminium target below derated range | Gradual blinding over a shift |
Decision. If the process allows a magnet on the flag, use a Hall latch, seal the magnet in a non-magnetic cup so chips do not build up on it, set the gap so the magnet field at the sensor is at least twice the on threshold at the worst temperature, and test with the BLDC rotor at every detent and the fixture parked close. If a magnet is not allowed, do not buy a bigger sensor and hope. Move the sensor to a 1.5 mm gap, use a head whose derated range for thin aluminium is at least twice the gap, and measure the trip point with both the flag and the fixture present. Optical sensing only enters the discussion with through-beam geometry, lens air purge and a monitored intensity margin, which is a heavier integration for a counting task that Hall or inductive sensing handles without optics.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-56A horizontal stage must lose motor power when its guard door opens or its E-stop is pressed, even if firmware hangs. How would you wire that chain in hardware, and what must firmware still do?
The 90-second answer
For a horizontal stage, I would put the guard door and the emergency stop in a normally closed hardware chain that removes drive enable and motor power, and I would let firmware read that chain for its state machine. If firmware hangs, the chain still opens. If a wire breaks, the chain still opens. Firmware can add diagnostics and a controlled stop request, but it is never the only path to a safe state.
The safe state here is simple because the axis is horizontal: no gravity load to hold, so removing torque and letting the axis coast or brake to a stop is acceptable. I would still fit a brake if the stopping distance matters, and I would measure it.
Hardware chain
Wire the E-stop and the guard door switch as normally closed contacts in series, in dual channel if the risk assessment calls for it. Each device has two NC contacts. Channel 1 and channel 2 run in parallel pairs through a safety relay. The relay output drives the drive's Safe Torque Off input and a main contactor for motor power. The relay also has an external device monitoring input wired to the contactor's auxiliary contact.
| Event | Hardware result | Firmware sees |
|---|---|---|
| Door opened | Channel opens, relay drops, STO asserted, contactor opens | Diagnostic input goes low, state goes to SAFE |
| E-stop pressed | Same as above | Same as above |
| One wire broken | Channel opens, relay drops | Same as above |
| Contactor welded shut | EDM input stays high after relay opens, relay locks out | Fault latched, restart blocked |
| Firmware hangs | No effect on relay or STO | Watchdog resets MCU, outputs default low |
Dual channel is the point. A single channel design fails if a contact welds or a wire shorts to 24 V. With two channels, the relay compares them. Disagreement drops the output. That is the single fault tolerance ISO 13849-1 describes for Performance Level d, a common target for guarding on this class of machine.
The relay acts in tens of milliseconds. Firmware debounce of 20 to 50 ms is fine for diagnostics, but it must not sit in the hardware path.
Firmware: what it still has to do
Firmware mirrors the chain and controls restart. I would use four states: SAFE, READY, RUNNING, FAULT. Entry to RUNNING needs both channels high and agreeing, guard closed, no hard limit active, and a fresh start command after a deliberate reset. Pressing reset after an E-stop must not restart motion. It moves the machine to READY only. Motion needs a new start.
// Run every 1 ms in a safety task, separate from the control loop.
static bool chain_healthy(void) {
bool ch1 = gpio_read(CH1_PIN);
bool ch2 = gpio_read(CH2_PIN);
return ch1 && ch2 && (ch1 == ch2);
}
static void safety_task(void) {
if (!chain_healthy() || guard_open()) {
state = SAFE;
drive_disable();
profile_abort();
}
if (state == SAFE && reset_pressed() && chain_healthy()) {
state = READY; // no motion until a new start command
}
}The enable output to the drive needs a pull down so a reset or a hung MCU leaves it deasserted. The watchdog then only has to reset the controller. The hardware chain holds the safe state through that reset.
Checking it
I would test by opening the door at full speed, pressing the E-stop, pulling each channel wire, and shorting one channel to 24 V. Each test should drop STO and open the contactor, and the machine should need the full reset sequence before it moves again. I would also measure stopping distance from maximum speed and load. If the axis travels too far before it stops, I would add a brake, lower the speed near the guard, or move to a controlled deceleration before power removal. That measurement, not the wiring diagram, decides whether the design is safe enough.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-57Walk me through how PID tuning differs between the current, velocity and position loops on a servo axis, and why you tune them inside-out?
The 90-second answer
Tune inside-out, current first, then velocity, then position, and keep each loop roughly five to ten times slower than the one inside it. The current loop is electrical and fast. The velocity loop sees inertia and friction. The position loop sees the mechanics, backlash and resonance, and it is the slowest and softest of the three.
That ordering matters because the outer loops assume the inner loop is already a near-ideal actuator. If current is sluggish or ringing, velocity tuning chases a moving target and position tuning hides it with low gains until the axis feels spongy.
Current loop: PI, no derivative, tuned to the winding
A PMSM or BLDC phase current loop is usually PI only. The plant is dominated by inductance, so the proportional term sets how fast current can rise and the integral term removes the steady error from back-EMF and resistance drop. Derivative action buys nothing here. Current measurement already carries PWM ripple, and differentiating it amplifies switching noise into the duty cycle.
Tune it from the electrical time constant, not by ear. With winding resistance R and inductance L, the open-loop pole sits at R/L. For a typical small servo, R = 0.8 ohm and L = 2.5 mH gives L/R = 3.1 ms. A current loop bandwidth of 800 Hz to 1 kHz is realistic at a 16 kHz update rate, roughly one twentieth of the sample rate. Push toward 2 kHz and phase lag from the PWM delay and ADC sampling starts to eat the margin.
On hardware, command a small current step with the shaft locked or free, watch phase current on a scope, and raise Kp until rise time stops improving or ringing appears at the switching frequency. Set Ki to cancel the R/L pole, Ki = Kp * R / L in continuous terms, then check that current tracks a sine reference at rated speed without lag. Back-EMF is the disturbance this loop rejects. If current sags at high speed, the integral is too weak or the voltage limit is reached, and no amount of velocity tuning fixes that.
Failure mode to name in an interview: current loop oscillation shows up as audible whine, hot MOSFETs and torque ripple, and it contaminates velocity feedback. The fix is lower Kp or more filtering on the current sense, not a notch in the velocity loop.
Velocity loop: PI, tuned to inertia and friction
Velocity is where inertia first appears. The plant gain scales with 1/J, so doubling the payload roughly halves the achievable bandwidth for the same gains. Most velocity loops use PI. Integral action removes the steady error from friction and cable drag, which otherwise becomes a constant following error in position.
Derivative is usually omitted. Velocity is already a differentiated position signal, so a second derivative amplifies encoder quantization. At 1 kHz with a 17-bit encoder on a 5 mm lead screw, one count is about 0.04 um, but differentiating over a 1 ms window still leaves visible steps at low speed. Filtering that noise adds lag, which is why many drives estimate velocity with a tracking observer or a filtered difference and keep the derivative term out of the velocity loop entirely.
Tune velocity with position loop open or with position gain at zero. Apply a small velocity step, raise Kp until the response is fast without sustained ringing, then add Ki just enough to remove droop under load. A worked check: if a 0.5 m/s step settles in 25 ms with 10% overshoot, the loop is near 10 to 15 Hz closed-loop bandwidth for that axis. That is plausible for a belt-driven stage. A direct-drive stage with low inertia and a stiff coupling can run two to three times faster.
Watch for limit cycling at low speed. That is usually integral plus stiction, not a Kp problem. Lowering Ki or adding a small deadband on the integral helps more than lowering Kp.
Position loop: PID, tuned to mechanics and resonance
Position is the outer loop and the only one where derivative action is routinely useful, because it adds damping against mechanical resonance. The proportional term sets stiffness, meaning how hard the axis pushes back against a disturbance. The derivative term, computed on measurement rather than on error, damps overshoot without a kick when the setpoint changes. Integral action is kept small or removed on axes that must hold position against gravity, where it causes hunting around the target.
Position bandwidth is capped by the first mechanical resonance, often 40 to 120 Hz on a belt or ball-screw stage. A position loop at 30 Hz with a resonance at 60 Hz will excite it. The symptom is a sustained oscillation at a fixed frequency that does not change much when Kp changes, which points to resonance rather than gain. The fix is a notch filter at the resonance, lower position gains, or a stiffer mount, in that order of preference.
Tune position last, with velocity already closed. Raise Kp in small steps during a small step move, say 1 mm, and stop when overshoot exceeds about 10% or a ringing tone appears. Add derivative on measurement to recover damping, then add only enough integral to remove steady error under process load. Validate with a reversal test, because backlash and hysteresis hide in a single-direction step and show up as a dead zone on direction change.
| Loop | Typical rate | Terms used | Bandwidth set by | Too aggressive looks like |
|---|---|---|---|---|
| Current | 8-16 kHz | PI | L/R, PWM delay, sense filtering | Whine, ripple, hot bridge |
| Velocity | 1-4 kHz | PI | Inertia, friction, encoder noise | Chatter at low speed, limit cycle |
| Position | 100-500 Hz | PID, D on measurement | Resonance, backlash, stiffness | Ringing at fixed frequency, hunting |
A concrete tuning sequence
// Current loop, 16 kHz ISR. PI with output clamp.
float i_err = i_ref - i_meas;
float i_int += Ki * i_err * dt; // Ki already scaled by dt in practice
i_int = clamp(i_int, -v_limit, v_limit);
float v_cmd = Kp * i_err + i_int;Run that sequence loop by loop on the real axis, logging each step response. Current first with the motor unloaded, velocity next with a known payload, position last with the full tooling and process load fitted. Retune velocity and position after any payload change above about 20%, because inertia is the parameter that moved.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-58What does it mean when a sensor saturates, and how does its output behave as the input rises past full scale compared with a fixed offset?
The 90-second answer
Saturation means the input has gone past the sensor's full scale, so the output stops rising and stays flat at its maximum value. Raise the input further and the output does not move. Lower the input back into range and the output follows again. That flat top is the signature.
A fixed offset is different. The output is shifted by a constant amount at every input, including zero, but it still rises and falls with the input. It does not flatten at the top unless the shift pushes it there.
Clipping is the same flat top, but it happens in a stage before the sensor's rated full scale is reached. An amplifier or buffer hits its supply rail early. On a sweep, saturation pins at the sensor or ADC maximum count. Clipping pins below that maximum.
Worked trace
Take a 0 to 10 V sensor read by a 12-bit ADC, 0 to 4095 counts. Ideal output is 409.5 counts per volt.
| Applied input (V) | Ideal count | Saturating sensor | Sensor with +0.5 V offset |
|---|---|---|---|
| 0 | 0 | 0 | 205 |
| 2.5 | 1024 | 1024 | 1229 |
| 5.0 | 2048 | 2048 | 2253 |
| 7.5 | 3071 | 3071 | 3276 |
| 10.0 | 4095 | 4095 | 4095, pinned |
| 11.0 | out of range | 4095 | 4095, pinned |
| 0, return | 0 | 0 | 205 |
Read the columns. The saturating sensor tracks the ideal count until 10 V, then stays at 4095 at 11 V. The offset sensor is 205 counts high at every point in range, which is 205 / 409.5 = 0.50 V, and it reaches the rail early because the shift consumes headroom.
Comparison
| Fault | Output at zero input | Output as input rises past full scale | First check |
|---|---|---|---|
| Saturation | Correct, near zero | Flat at maximum count | Sweep past full scale and back |
| Clipping | Correct, near zero | Flat below maximum count | Probe the signal at the ADC pin |
| Fixed offset | Shifted by a constant | Still rising, unless the shift pushes it to the rail | Read raw counts with input at a known zero |
How to confirm it in practice
Set the input to a known zero, such as a vented pressure port or a stage at its datum, and record the raw count. Then apply about half of full scale, then full scale, then a little past full scale, then return to zero. Saturation shows a normal slope in range and a flat line past full scale, with recovery on the way back. Offset shows the same slope as expected but a nonzero count at zero.
A small counter in firmware shows how often a live signal hits the rail, which matters when only peaks clip:
// 12-bit ADC, counts 0 to 4095. Call once per sample.
static uint32_t total = 0, railed = 0;
void check_sample(uint16_t count) {
total++;
if (count >= 4093) railed++;
}
// railed * 100 / total is the percent of samples at the top rail.
// A few percent on a dynamic signal means the range or gain is too small.If the count pins exactly at the datasheet maximum, the sensor is behaving as specified and the process range or gain needs changing. If it pins below the maximum, find the stage that rails first. If zero reads high but the slope is right, correct the offset and recheck the top of range, since removing the offset often removes the apparent saturation too.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-59Walk me through how you would design a CAN bus for distributed machine control across a main controller, servo drives and I/O nodes, and how arbitration, bit timing and error confinement behave when frames collide or a node fails?
The 90-second answer
CAN is a multi-master serial bus where every node can transmit when the bus is idle, and collisions are resolved by identifier priority without destroying either frame. I would run the machine at 500 kbit/s on a twisted pair with 120 ohm termination at both physical ends, give safety and motion commands the lowest identifiers, and keep worst-case bus load below about 70 percent so a 1 kHz control path still meets its deadline. When a node fails, CAN error confinement stops it from flooding the bus: its transmit error counter rises, it goes error-passive, then bus-off, and it only rejoins after the bus is clean.
Arbitration, with real timing
CAN signals are dominant for logic 0 and recessive for logic 1. During arbitration every transmitter sends its identifier bit by bit and reads the bus. A node sending a recessive 1 while another sends dominant 0 loses, stops transmitting, and retries later. The winner continues without a restart. That is why the identifier is both the address and the priority.
At 500 kbit/s one bit takes 2 microseconds. A classic CAN data frame with an 11-bit identifier, 8 data bytes, stuff bits and interframe space is roughly 110 to 130 bits on the wire, so about 220 to 260 microseconds. A 29-bit extended frame adds about 20 bits. If a servo drive needs a command every 1 ms, one frame alone consumes roughly a quarter of that period before queueing behind other traffic. That arithmetic drives the design: short identifiers, 8-byte payloads, no extended identifiers unless I need the address space, and a measured load calculation for every node.
| Time slot | Node A, ID 0x100 | Node B, ID 0x180 | Result |
|---|---|---|---|
| Start of frame | Sends dominant 0 | Sends dominant 0 | Both continue |
| Identifier bit where they differ | Sends 0 | Sends 1 | B reads dominant, loses, goes silent |
| Rest of frame | Completes frame, CRC, ACK slot | Retries after interframe space | A wins, B is delayed, no data lost |
Lower identifier value means higher priority, because more dominant bits win. I would assign 0x080 to the safety stop, 0x100 to the main motion command, 0x180 to drive status, and 0x300 and above to diagnostics and I/O polling. A low-priority diagnostic frame can be delayed indefinitely under load, which is acceptable. A safety frame must not be.
Bit timing and physical layer
Each node samples the bus at a defined sample point, typically 75 to 87.5 percent of the bit time, using synchronisation on recessive-to-dominant edges and resynchronisation within the oscillator tolerance. All nodes must agree on nominal bit rate, time quanta, sync jump width and sample point. A mismatch does not always fail immediately. It often appears as intermittent stuff errors or CRC errors at temperature extremes, when oscillator drift pushes a sample point across an edge. I verify timing with a scope on CANH and CANL, check the sample point against the controller configuration, and confirm termination measures about 60 ohms across the pair with power off, which is two 120 ohm terminators in parallel.
Stubs off the main trunk should be short, ideally under 0.3 m at 500 kbit/s, because a stub is an unterminated reflection. Cable runs in a machine cabinet need the twisted pair routed away from motor power cables, with the shield bonded at one point to avoid a ground loop through the shield.
Errors and confinement
CAN detects five error types: stuff errors, where too many consecutive equal bits violate the stuff rule, CRC errors, form errors in fixed-format fields, ACK errors where no node pulls the ACK bit dominant, and bit errors where a transmitter reads back the opposite level outside arbitration. On detection the node sends an error flag, six dominant bits, which forces other nodes to discard the frame. Receivers then retransmit.
Error confinement is what keeps one faulty node from taking the machine down. Each node maintains a transmit error counter and a receive error counter. A transmitter that detects an error increments its transmit counter by 8, a receiver by 1, and successful transmission decrements them. Above 127 the node becomes error-passive: it sends only recessive error flags and cannot force the bus dominant. Above 255 it goes bus-off and stops transmitting entirely. It can only return after observing 128 occurrences of 11 consecutive recessive bits, then it resets its counters and rejoins as error-active. In firmware I expose those counters, count error frames per node, and raise a diagnostic when a drive repeatedly goes error-passive, because that usually means a wiring fault, a duplicate identifier, or a node transmitting while its local clock is out of tolerance.
Failure modes I design for
A duplicate identifier from two nodes sending different data is the classic trap. Both win arbitration, then one detects a bit error in the data field, both increment counters, and the bus fills with error frames. The fix is a single source of truth for the identifier allocation, checked in code review and at startup. A babbling node that transmits continuously is contained by bus-off, but only if other nodes do not also have high error counters. A missing terminator causes reflections that look like random bit errors at high load. A node that loses power mid-frame can leave the bus dominant if its transceiver fails short, which is why I use transceivers with dominant timeout and a bus guardian or independent watchdog on the main controller that commands a safe stop if no valid motion frame arrives within, say, 5 ms.
For the control design I would never put a hard real-time current loop on CAN. The servo drive closes current and velocity loops locally at 8 to 16 kHz, and CAN carries position or velocity setpoints at 250 Hz to 1 kHz plus status. That keeps the bus out of the fastest loop while still giving the main controller coordinated motion across axes.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-60Walk me through how you would design a hardware-software interface contract between firmware and hardware teams for a new servo axis?
The 90-second answer
I would treat the boundary as a versioned contract, not as a schematic plus a datasheet handed over late. Firmware owns the register and signal semantics, hardware owns the electrical guarantees that make those semantics true, and both sign the same document before layout. For a servo axis that means pin and clock definitions, register map with reset values, timing budgets, fault behaviour, and a simulation model firmware can run against before boards exist.
The contract has to answer four questions without a meeting. What does each signal do and when is it valid. What happens on power-up, reset, fault and loss of communication. What are the electrical limits and timing margins. How does either side detect that the other side has broken the contract.
All figures below are a worked example for a hypothetical axis. They show the form of the commitment, not a claim about a real part. In a live project each number is replaced by the value from the actual datasheet, measured on the actual board, with the source and revision recorded in the contract.
What goes in the document
| Area | Hardware commits to (example) | Firmware commits to |
|---|---|---|
| Clock and reset | 48 MHz crystal, reset held until rails are stable, POR threshold set in the power supervisor datasheet | No register access before the PLL lock flag is set |
| Encoder link | SPI mode 3, clock at or below the encoder datasheet maximum, CS setup and hold per that datasheet | Sample on the agreed edge, reject a frame whose CRC fails |
| PWM and enable | Gate driver UVLO per its datasheet, dead time generated in hardware at or above the MOSFET and driver minimum | Enable only after current sense offset calibration passes |
| Faults | Open-drain FAULT line, active low, pulled up to logic supply, asserted by the hardware overcurrent comparator | Latch the fault, stop issuing torque commands, report the code over the diagnostic interface |
| Limits | Current sense range and shunt value per the amplifier datasheet | Trip below the hardware limit, derate below the trip point |
That table is the negotiation. If hardware cannot meet the encoder timing at temperature, firmware changes the SPI timing or the encoder choice. If firmware needs a fast fault response, hardware cannot route the fault through a slow isolator and call it done.
Register map as code
I keep the map in a header both sides review, with access type and side effects explicit. A plain address list invites firmware to write a read-only status bit and hardware to assume a command bit is level sensitive when firmware pulses it.
// servo_axis_if.h, contract v1.2, example map for a hypothetical axis
#define REG_CTRL 0x00 // RW: bit0 enable, bit1 clear_fault, bit2 brake_release
#define REG_MODE 0x01 // RW: 0 = torque, 1 = velocity, 2 = position
#define REG_TORQUE_CMD 0x02 // RW: int16, 0.1 A per LSB, range -120..120
#define REG_STATUS 0x10 // RO: bit0 ready, bit1 fault, bits[5:2] fault_code
#define REG_CURRENT 0x11 // RO: int16, 0.1 A per LSB, updated at 1 kHz
#define REG_ENCODER 0x12 // RO: uint32, counts, wraps at 2^32
#define REG_FAULT_CNT 0x13 // RO: uint32, increments on each new fault
#define REG_VERSION 0x1F // RO: contract version, for example 0x0102Two details matter here. clear_fault is write-one-to-clear and self-clearing, so a firmware retry cannot hold the axis in a cleared state. REG_ENCODER wraps, and the contract states that firmware must handle wrap by unsigned subtraction, which hardware tests by forcing the counter near 2^32.
Timing and state behaviour
The timing budget sits beside that diagram, with two separate fault paths stated plainly. The hardware comparator disables the gate driver directly, so that path does not wait for firmware. Firmware learns of the fault on its next 1 kHz tick, which is 1 ms, and latches the code and stops issuing new torque commands. Those are different deadlines for different mechanisms, and the contract names both.
For the worked example, the encoder read runs at 1 kHz, a 1000 µs period. A 32-bit frame at a hypothetical 10 MHz SPI clock takes 32 / 10 MHz = 3.2 µs on the wire, plus CS setup and hold taken from the encoder datasheet. The current loop in this example runs at 20 kHz, a 50 µs period, and the budget requires the torque update to finish in under 10 µs worst case, measured with a GPIO toggle and a scope rather than estimated from average execution time. If that budget fails, we move the encoder read to DMA or lower the loop rate, and the contract records which choice was made and why.
Failure modes the contract must name
Loss of encoder frames: firmware counts consecutive CRC failures, declares an encoder fault after an agreed count, and the axis goes to the fault state above. It does not coast on the last velocity estimate, because a disconnected encoder during a move would otherwise drive the stage into a limit.
Stuck enable: hardware provides a watchdog input that firmware must toggle at an agreed interval while running. If the toggle stops, hardware disables the gate driver independently of firmware. That gives a second path to a safe state when firmware hangs with PWM enabled.
Version drift: the contract carries a version register at 0x1F, read at boot and logged. A mismatch between firmware expecting v1.2 and a board built to v1.1, for example a different fault polarity, is caught in the first bench test instead of during a customer install.
I would also require a loopback or simulation stub. Firmware runs against a PC model that returns encoder counts and injects faults, so the state machine and fault handling get tested before the first board arrives. Hardware gets a test firmware that toggles every output and reads every input, so the board is proven without the full control stack. When both stubs pass and the real pair fails, the fault is in the contract itself, which is exactly what the document is there to expose.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-61Walk me through how you would design a battery-powered mechatronics device for low power, including sleep modes, wake sources and the trade-offs between them?
The 90-second answer
Start from an energy budget, not a sleep mode. For a battery-powered actuator or sensor node, average current decides life, and average current is duty cycle times active current plus sleep current times the rest. Sleep modes only matter after you have cut the loads that stay on in sleep: motor holding current, sensor excitation, regulator quiescent current and any always-on radio.
I would pick the shallowest sleep that still meets wake latency and keeps state I need. Deep sleep saves microamps but costs milliseconds to seconds to wake, loses RAM or needs a sensor to warm up, and often forces a full re-initialisation of the motion controller. That trade is usually worth it for a device that wakes a few times a day. It is rarely worth it for a device that must respond to a limit switch or a command within 10 ms.
A concrete budget
Take a hypothetical 1-cell 2000 mAh lithium-ion pack, a small linear actuator and a controller that samples a position sensor, moves for 2 s, then sleeps. Label these as design targets to verify on the bench, not datasheet promises.
| State | What is on | Typical current | Wake latency |
|---|---|---|---|
| Active move | MCU at 80 MHz, driver, motor at 1 A peak | 350 mA average during move | none |
| Idle sensing | MCU at 16 MHz, sensor excited, driver disabled | 8 mA | 1 ms |
| Stop 2 | MCU clock stopped, RAM retained, sensor off, driver off | 6 uA | 5 ms |
| Standby | RAM lost, only RTC and wake pins live | 1.5 uA | 50 ms plus re-init |
Arithmetic for one cycle: 2 s at 350 mA is 700 mA-s. If the device then sleeps for 58 s at 6 uA, that is 0.35 mA-s. Average current is about 12 mA, so 2000 mAh gives roughly 165 hours. If the same device instead idles at 8 mA between moves, average current is about 19.7 mA and life drops to about 100 hours, even though idle looks harmless. The move dominates here, which tells you motor efficiency and move time matter more than shaving 4 uA off sleep.
Change the duty cycle and the answer flips. If the device moves once per hour for 2 s and sleeps the rest, sleep current dominates. At 6 uA, sleep alone would theoretically last decades, so self-discharge and regulator quiescent current set the real limit. A regulator that draws 30 uA quiescent would then be the largest load in the system. That is why I measure sleep current with the full board, at temperature, after a week, not just the MCU datasheet figure.
Sleep modes and wake sources
// STM32L4 style: configure wake before entering Stop 2
HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1); // limit switch, active low
HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 60, RTC_WAKEUPCLOCK_RTCLK_16S);
HAL_SuspendTick();
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
HAL_ResumeTick();
// On wake: read wake flag, decide whether to move, sense, or sleep againWake sources to consider, with their cost:
| Wake source | Latency | Power cost | Risk |
|---|---|---|---|
| RTC timer | 5 ms from Stop 2 | negligible | drift, missed deadline if clock domain off |
| GPIO interrupt from limit switch | 5 ms | negligible | bounce and false wake |
| Accelerometer threshold | 10 to 50 ms including sensor start | sensor must stay powered or poll | false wake from vibration |
| I2C address match or UART start bit | 20 ms | bus transceiver powered | bus held low blocks wake |
| BLE advertisement | 100 ms to seconds | radio dominates budget | stack start time, pairing state |
A limit switch wake needs hardware debounce or a latch, because a bouncing contact can wake the MCU dozens of times and each wake costs a sensor warm-up. An accelerometer wake needs a threshold with hysteresis and a minimum sleep time, otherwise a vibrating machine wakes the device continuously and the battery dies in days.
Failure modes I would test
Wake storms from a noisy sensor line. Brownout on wake, when the motor driver inrush pulls the rail down and resets the MCU before the move starts. Sensor warm-up, where the first position reading after wake is invalid for 20 ms and a controller that trusts it jumps. State loss in Standby, where RAM contents vanish and the axis position must be re-referenced before any move. Leakage at high temperature, where sleep current can rise tenfold compared with the 25 C datasheet value.
I would log wake reason, wake count per hour and charge per wake in firmware during development. If wake count is high, the fix is usually a better wake filter or a longer sleep interval, not a deeper sleep mode.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-62What three delays add up to make the total latency from sensor to actuator in a feedback loop?
The 90-second answer
Total latency is the sum of three delays in series: sensing, computing, and actuating. Sensing is the time from the physical change until the controller has a usable sample. Computing is the time to read that sample, run the control calculation, and write a new output. Actuating is the time from that output until the actuator actually produces force or torque.
If any one of those is large, the loop feels it as delay, even if the other two are fast. That is the rule I use when I budget a loop.
Worked budget
For a 1 kHz velocity loop, a hypothetical but typical bench measurement with a scope on two GPIOs gave:
| Stage | What is included | Time |
|---|---|---|
| Sensing | ADC conversion plus encoder read over SPI | 22 µs |
| Computing | PID calculation plus wait for the next PWM update | 510 µs |
| Actuating | Driver switching plus current rise in the winding | 90 µs |
| Total | Sensor change to actuator response | 622 µs |
The computing stage dominates here, and most of it is the wait for the next PWM update. At 1 kHz the period is 1000 µs, so a command written just after an update waits almost a full period. Averaged over random arrival times, that wait is about half a period, 500 µs.
// Cortex-M: timestamp the two ends of the computing stage
volatile uint32_t t_sample, t_output;
void control_isr(void) {
t_sample = DWT->CYCCNT; // GPIO high here for scope check
int32_t pos = encoder_read();
int32_t cmd = pid_step(pos);
pwm_write(cmd); // shadow register, applied next PWM edge
t_output = DWT->CYCCNT; // GPIO low here for scope check
}
// computing_us = (t_output - t_sample) / clock_mhzHow I measure and cut each part
I measure sensing by toggling a GPIO when the sample is taken and checking when the bus read completes. I measure computing with the DWT cycle counter shown above, confirmed on the scope. I measure actuating by comparing the command GPIO with a current probe on one phase. The current rise to about 63 percent of the commanded value is a practical end point for the actuator delay.
To reduce the total, I attack the largest term first. Aligning the ISR to the PWM carrier and writing the output in that ISR removes the random wait and makes the delay fixed. Moving a sensor from a slow bus to a faster one cuts sensing delay. Raising the PWM frequency cuts the average wait, but only helps if the bus and conversion still fit inside the shorter period. I remeasure after each change, because the next largest term is often a different stage than I expected.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-63Walk me through how gear ratio, reflected inertia and backlash trade off torque, speed and positioning accuracy when you size a gearbox for a servo axis?
The 90-second answer
Define the ratio first, because every other number follows from it. Let N = ω_motor / ω_load = θ_motor / θ_load. A 100:1 reducer means the motor turns 100 times for one load revolution. Ideally power is conserved, so speed divides by N and torque multiplies by N. With efficiency η, forward-driven load torque is τ_load = N · η · τ_motor. The catch is inertia and backlash. Load inertia reflected to the motor falls as 1/N², while motor rotor inertia reflected to the load rises as N². Backlash is a dead angle at the output that a motor-side encoder cannot see, so it appears directly as reversal error and can drive a limit cycle.
Worked example
Take a servo rated at 3000 rpm and 1.5 Nm continuous, driving through a 100:1 planetary stage with η = 0.80. Load inertia J_load = 0.010 kg·m². Motor rotor inertia J_motor = 5.0×10⁻⁵ kg·m².
| Quantity | Motor side | Load side | Relation |
|---|---|---|---|
| Speed | 3000 rpm | 30 rpm | ω_load = ω_motor / N |
| Torque (continuous) | 1.5 Nm | 120 Nm | τ_load = N · η · τ_motor |
| Load inertia seen by motor | 1.0×10⁻⁶ kg·m² | 0.010 kg·m² | J_ref = J_load / N² |
| Motor inertia seen by load | 5.0×10⁻⁵ kg·m² | 0.50 kg·m² | J_ref,load = J_motor · N² |
That last row decides the dynamics. The load inertia almost disappears from the motor, which sounds attractive, but the motor rotor now looks like a 0.50 kg·m² flywheel bolted to the load. Acceleration at the load is limited by that reflected rotor inertia, and the first torsional resonance drops. With gear stiffness k at the output, the resonance is roughly f = (1/2π)·√(k / J_eq), where J_eq is dominated by J_motor·N². Raise N to 200:1 and the reflected motor inertia quadruples to 2.0 kg·m², even though the load torque doubles. Bandwidth falls, and the servo gain that was stable at 100:1 can excite the resonance at 200:1.
Backlash in numbers
A typical planetary stage might specify 20 arcminutes of backlash. That is 20/60 = 0.333 degrees, or 5.8 mrad. On a 100 mm radius arm or pulley, that is 0.58 mm of free play at the tool point. A harmonic drive at under 1 arcminute gives about 0.029 mm at the same radius, which is why it appears in precision stages despite lower efficiency and higher cost. Backlash is not the same as compliance. Compliance is elastic deflection under load and recovers. Backlash is lost motion on reversal, independent of load, and it grows with wear and with tooth clearance set at assembly.
Detection is straightforward on hardware. Command a slow reversal and log motor encoder position against a load-side encoder or a dial indicator. Inside the dead zone the motor moves and the load does not. In a closed loop with only the motor encoder, the controller keeps integrating error while the load sits still, then the teeth re-engage with an impact. That impact excites the torsional resonance and shows up as a burst of following error or audible ticking on every direction change.
Trade-offs when choosing N
Higher N helps when the load needs torque at low speed and the motor would otherwise run near stall, where torque ripple and heating are worst. It also reduces the effect of load inertia disturbances on the motor. The costs are reflected rotor inertia, lower torsional stiffness per unit of output torque in many gear families, higher friction and stiction reflected to the load, and worse backdrivability. Friction matters at low speed: motor-side Coulomb friction τ_f appears at the load as roughly N·τ_f when driving, and it can exceed the process torque on a fine positioning move.
Efficiency also depends on direction. Forward driving might be 80 percent. Backdriving the same stage can be far lower, and some worm stages will not backdrive at all. If the axis must be backdrivable for manual jogging or for gravity to settle it safely, that constraint can rule out a high-ratio worm or a high-ratio planetary pair before torque calculations start.
A practical sizing check I run: compute reflected inertia both ways, estimate the resonance with the vendor stiffness figure, and convert backlash to linear error at the tool point. If backlash alone consumes more than half the repeatability budget, no amount of PID tuning fixes it. The fixes are a lower-backlash gear type, a load-side encoder so the loop closes around the dead zone, or mechanical preload such as a split gear or dual motor bias. Each adds cost or complexity, and a load-side encoder only helps if the controller can use it without destabilising the velocity loop through the compliant gear.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-64A motor driver runs cool on the bench but overheats and trips its protection after a few minutes under load on the machine. How would you debug it?
The 90-second answer
Reproduce it under the real load profile, not a bench spin. Log phase current, bus voltage, PWM duty, case temperature and the protection flag with timestamps, then compare the first minute against the minute before the trip. A driver that is cool at no load and hot under load is usually dissipating more than its thermal path can remove, or drawing more current than the load should demand. The split matters: extra current points at the machine or the control loop, correct current with excess heat points at the driver, its switching settings or its cooling.
Work the numbers before touching hardware
Take a hypothetical 24 V, 10 A three-phase drive running at 20 kHz PWM. Per phase RMS current is 6 A and Rds(on) is 12 mΩ at 25 °C, rising to about 19 mΩ at 125 °C.
| Loss | Estimate | Share |
|---|---|---|
| Conduction, 6 FETs | 6 × 6² × 0.019 = 4.1 W | Dominant at high current |
| Switching, per device | 24 × 8 × 100 ns × 20 kHz = 0.38 W | Grows with bus voltage and frequency |
| Gate drive and shunt | 0.5 to 1 W | Often missed in the budget |
Total dissipation is roughly 6 to 8 W. With a junction to ambient resistance of 8 °C/W on a small heatsink, that is a 50 to 65 °C rise. At 40 °C ambient the case sits near 100 °C, close to many thermal trip points, and Rds(on) rising with temperature makes conduction loss worse as it heats. That positive feedback is why it trips after minutes rather than instantly.
Trace the trip
| Time | Phase current | Duty | Case temp | Event |
|---|---|---|---|---|
| 0 s | 2 A | 25% | 28 °C | Start, unloaded bench profile |
| 60 s | 6.5 A | 70% | 52 °C | Full load applied |
| 180 s | 6.8 A | 72% | 84 °C | Current flat, temperature still climbing |
| 240 s | 6.8 A | 72% | 98 °C | Thermal trip, current collapses to zero |
Flat current with rising temperature means the load is not increasing. The fault is thermal capacity or loss, not a sudden mechanical jam. If current were climbing in step with temperature, I would look for friction, misalignment, a binding axis or a loop that is fighting itself.
Isolate the cause
Run the same motion at reduced current limit. If temperature rise falls roughly with current squared, conduction loss dominates. If it barely changes, switching loss or a hot spot elsewhere dominates. Swap in a known good driver on the same machine and load. If the fault follows the driver, inspect gate drive voltage, dead time and mounting pressure on the heatsink. If it stays with the machine, measure phase resistance and inductance for a shorted turn or imbalance, check supply sag under load, and confirm the cable and connector resistance. A loose phase connector can heat locally and raise current ripple without tripping the main protection.
Protection type also tells you something. An I²t or thermal trip after minutes fits sustained overload or poor cooling. An instantaneous overcurrent or desaturation trip at a specific position fits a short, a phase fault or a current spike on commutation. Read the fault latch and clear it only after the cause is logged, because repeated resets hide the pattern.
Fixes follow the diagnosis. Lower switching frequency only if switching loss dominates, and accept higher current ripple. Improve the thermal path with a larger heatsink, forced air or better interface material before raising the trip threshold. If current is genuinely high, reduce reflected load, fix the mechanical drag or retune the loop. Raising the current limit to stop the trips just moves the failure into the MOSFETs.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-65A servo stage's drive voltage spikes for one sample and overshoots when the setpoint steps. How does derivative-on-measurement in a two-degree-of-freedom PID remove that spike, and what trade-off does it create?
The 90-second answer
A standard PID acts on error e = r - y, where r is the setpoint and y is the measured position. When r steps, the proportional and derivative terms react to that jump before the stage has moved. Setpoint weighting, also called two-degree-of-freedom PID, splits the paths so proportional and derivative act mainly on the measurement while integral still acts on the error.
u(t) = Kp * (b*r - y) + Ki * integral(r - y) dt - Kd * d(c*r - y)/dtb weights the setpoint for proportional action and c weights it for derivative action. Both are normally between 0 and 1. b = c = 1 is the standard PID. c = 0 puts derivative on measurement only. b = 0 puts proportional on measurement only. Integral stays unweighted, so a step still settles with zero steady-state error.
Why the spike happens
Take a stage commanded from 0 to 10 mm, with Kp = 2.0 V/mm, Kd = 0.05 V*s/mm, a 1 ms sample period and a ±10 V drive limit. At the first sample after the step, y is still 0.
| Term | Standard PID (b=c=1) | Weighted (b=0.4, c=0) |
|---|---|---|
| Proportional | 2.0 * 10 = 20 V, saturates the drive | 2.0 * (4 - 0) = 8 V, inside the limit |
| Derivative | 0.05 * 10 / 0.001 = 500 V for one sample, clipped by the drive | 0, because y has not changed |
| Integral | 0 at the first sample, then grows | Same as standard |
That one-sample derivative spike is derivative kick. On real hardware it saturates the amplifier, excites a resonance, or trips a current limit. The proportional term does a slower version of the same thing. It demands full drive at once, so the stage accelerates hard and overshoots while the integral builds behind it.
With c = 0, the derivative term only sees changes in y. A setpoint step alone cannot create a spike. With b = 0.4, the proportional term still pushes toward the target but does not saturate the drive on the first sample. The integral keeps accumulating the full 10 mm error, so the stage still reaches 10 mm. The approach is softer and overshoot drops.
The trade-off
The feedback path is unchanged. A load disturbance still moves y, and the controller reacts to it the same way, because b and c only scale how r enters. What changes is the tracking path. Lower b means a setpoint change produces a smaller initial drive, so rise time grows. You are trading faster response to a new setpoint for less overshoot and no kick.
That trade is usually worth it for point-to-point moves, where the setpoint is a step and overshoot wastes settling time. It is less attractive when the setpoint is a moving trajectory, as in contouring. There you want the axis to chase r closely, and b = 0 adds following lag. In that case keep b near 1 and limit the trajectory with velocity and acceleration limits instead, so r never jumps.
A practical starting point for a point-to-point stage is b = 0.3 to 0.5 and c = 0. Raise b if the move feels sluggish and overshoot is still small. Keep c = 0 unless you have a reason to anticipate setpoint slope, since any c > 0 lets setpoint steps back into the derivative term.
Discrete implementation
# 1 kHz position loop, derivative on measurement with a first-order filter
Kp, Ki, Kd = 2.0, 8.0, 0.05
b, c = 0.4, 0.0
dt = 0.001
integral = 0.0
y_prev = 0.0
d_filt = 0.0
alpha = 0.2 # filter coefficient, set from encoder noise level
def pid_step(r, y):
global integral, y_prev, d_filt
e = r - y
integral += e * dt
d_raw = -(y - y_prev) / dt # c = 0, derivative on measurement only
d_filt += alpha * (d_raw - d_filt)
u = Kp * (b * r - y) + Ki * integral + Kd * d_filt
y_prev = y
return max(-10.0, min(10.0, u))The filter only has to smooth encoder noise, not setpoint steps. Weighting does not prevent integral windup on a large move, so clamp the integral when the output saturates. Check the result with a small step first, then the full move, and look at drive voltage as well as position. If voltage still slams into the limit, b is too high or the move needs a trajectory limit rather than more gain.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-66How would you implement CRC and sequence numbers on a serial link to detect corrupted or lost frames?
The 90-second answer
I put a sequence number and a CRC on every frame, and the receiver only accepts a frame when both check out in order. The sender increments the sequence number for each new frame, the receiver keeps the next sequence number it expects, and a gap, a duplicate, or a bad CRC triggers a retransmit request or a resend of the last good frame. That covers the two faults a serial link actually shows in a machine: bit flips from EMI and frames lost when a buffer overruns or a connector glitches.
A typical frame for a controller talking to a servo drive or sensor node over UART or RS-485 looks like this:
| Field | Size | Purpose |
|---|---|---|
| Start of frame | 1 byte (0xA5) | Resynchronisation after idle or noise |
| Length | 1 byte | Payload length, so the receiver knows where the frame ends |
| Sequence | 1 byte | Frame counter, modulo 256 |
| Type | 1 byte | Command, response, or error |
| Payload | 0 to 255 bytes | Data, for example position setpoint or sensor reading |
| CRC | 2 bytes, high byte first | Computed over length through payload |
The CRC is the error detector. A checksum (a simple sum) misses many burst errors and errors that swap bytes. A CRC-16 detects every single-bit and double-bit error in a frame this size, every odd number of bit errors, and burst errors up to 16 bits long. The exact variant matters and both ends must agree on it. Modbus RTU uses CRC-16/MODBUS, polynomial 0x8005 reflected as 0xA001, initial value 0xFFFF. CAN 2.0 uses a CRC-15, polynomial 0x4599. Many vendor protocols use CRC-16/CCITT, polynomial 0x1021. I pick one, document the polynomial, initial value, reflection and byte order, and verify both ends against the same test vector before the link goes live.
// CRC-16/CCITT-FALSE: poly 0x1021, init 0xFFFF, no reflection.
// Checked against the "123456789" test vector, which must give 0x29B1.
uint16_t crc16_ccitt(const uint8_t *data, size_t len)
{
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < len; i++) {
crc ^= (uint16_t)data[i] << 8;
for (int bit = 0; bit < 8; bit++) {
crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021)
: (uint16_t)(crc << 1);
}
}
return crc;
}On the transmit side I build the frame, compute the CRC over the length, sequence, type, and payload bytes, and append it. On the receive side I recompute the CRC over the bytes as received and compare it with the transmitted value. A mismatch means the frame is discarded whole. I never try to repair it, because a corrupted length field makes the frame boundary itself untrustworthy.
Sequence numbers handle what CRC cannot: a frame that arrives intact but out of order, duplicated, or missing. The receiver tracks expected_seq. The logic is:
if (crc_ok && seq == expected_seq) {
accept_payload();
expected_seq = (expected_seq + 1) & 0xFF;
send_ack(seq);
} else if (crc_ok && seq == ((expected_seq - 1) & 0xFF)) {
send_ack(seq); // duplicate, sender missed the first ACK
} else if (crc_ok) {
send_nak(expected_seq); // gap, ask for the missing frame
}A worked trace makes the behaviour concrete. Suppose the receiver expects sequence 41:
| Arrival | Seq | CRC | Receiver action |
|---|---|---|---|
| Frame A | 41 | OK | Accept, expect 42, ACK 41 |
| Frame B | 42 | Bad | Discard, NAK 42, sender resends |
| Frame B retry | 42 | OK | Accept, expect 43, ACK 42 |
| Frame C | 44 | OK | Gap at 43, NAK 43, hold or drop 44 |
| Frame D | 43 | OK | Accept, expect 44, then accept held 44 |
| Frame D retry | 44 | OK | Duplicate of accepted frame, ACK again, drop payload |
Two details decide whether this survives on real hardware. First, the sequence space must be wide enough for the worst case in-flight count. With a 1-byte sequence and a stop-and-wait protocol (one frame outstanding), modulo 256 is plenty. With a sliding window of, say, 8 frames, the window must stay below half the sequence space, so 8 against 256 is safe. Second, the sender needs a timeout. If no ACK arrives within, for example, 20 ms on a 115200 baud link carrying a 32-byte frame (about 2.8 ms on the wire), it resends the same sequence number rather than advancing. Resending with the same number is what lets the receiver recognise the retry as a duplicate instead of a new command, which matters when the payload moves a stage or fires a valve.
The failure modes I watch for: a CRC variant or byte-order mismatch between the two ends, which shows up as a 100% CRC failure rate from the first frame and is caught by the test vector before the link goes live; a length field corrupted in a way that still passes CRC by chance, which is rare with CRC-16 (about 1 in 65536 random frames) and is why safety-related payloads add a range check on the decoded values; and loss of synchronisation after a long noise burst, which the start-of-frame byte plus an inter-frame idle gap of at least 3.5 character times (the Modbus RTU rule) fixes by letting the receiver reframe. For a link where a missed frame only delays a telemetry sample, I can drop the ACK and just count sequence gaps to measure loss rate. For a link that carries motion commands, I keep the ACK and the resend, because silently dropping a setpoint leaves the axis running on stale data.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-67Walk me through how you would size a heatsink and apply derating for a 24 V, 10 A motor drive that must run at 60 °C ambient in a sealed cabinet, from loss calculation to junction temperature?
The 90-second answer
I start from losses, not from a heatsink catalogue. For a motor drive the loss budget decides the junction temperature, and the junction temperature decides how much current I am allowed to run at a given ambient. I calculate conduction, switching and gate losses at hot resistance, add them per device and in total, then build the thermal chain from junction to ambient and check it against a derated limit, not the absolute maximum.
Assume a 24 V H-bridge drive, 10 A peak, 20 kHz PWM, sealed cabinet at 60 °C ambient, MOSFETs rated 150 °C junction. I would design to 110 °C junction in continuous operation. That 40 K margin is not conservatism for its own sake. It buys solder and wirebond life, tolerance on thermal interface material, and headroom for a blocked vent or a hot day. The datasheet maximum is a survival limit, not a design target.
Loss calculation, worked example
Take Rds(on) = 8 mΩ at 25 °C. It roughly doubles by 125 °C, so I use 13 mΩ for the hot calculation. Using the cold value is the classic error that makes a bench prototype pass and a cabinet fail.
| Loss source | Basis | Power |
|---|---|---|
| Conduction, 6 MOSFETs | 6 A rms per device, I²R at 13 mΩ, duty weighted | 2.8 W total, 0.47 W per device |
| Switching, 6 MOSFETs | Eon + Eoff from datasheet at 24 V, 10 A, times 20 kHz | 1.5 W total |
| Gate drive and body diode | Qg × Vgs × fsw, plus diode recovery | 0.4 W total |
| Current shunt and driver IC | I²Rshunt plus quiescent | 0.3 W total |
| Total to heatsink | 5.0 W |
Per device dissipation is about 0.8 W. Total dissipation is what heats the shared heatsink.
Thermal chain and heatsink sizing
Tj = Ta + Ptotal × Rsa + Pdevice × (Rjc + Rcs)
With Rjc = 2.0 K/W for the package, Rcs = 0.5 K/W for the interface, and a heatsink to ambient Rsa = 4.0 K/W:
Tj = 60 + 5.0 × 4.0 + 0.8 × 2.5 = 60 + 20 + 2 = 82 °C
That passes with margin. If I instead picked a 10 K/W heatsink because it was cheaper, Tj becomes 60 + 50 + 2 = 112 °C, already over my design limit before any tolerance. The arithmetic is the selection.
Heatsink choice is not only Rsa. Fin orientation matters if air moves, mounting pressure changes Rcs, and anodising or a gap pad changes it again. I specify the interface in the design, not as an afterthought, and I measure Rcs on the first build by comparing case temperature against heatsink temperature under known power.
Derating
Derating has three axes. First, current versus ambient: the MOSFET datasheet gives a safe operating area and a thermal derating curve that assumes a specified mounting condition. I re-derive it from my chain. At 60 °C ambient with the heatsink above, continuous current is limited by Tj = 110 °C. At 85 °C ambient, the same hardware allows roughly 30 percent less current, because the available temperature rise shrinks from 50 K to 25 K. I put that curve in the drive firmware as a current limit table, not just in a PDF.
Second, transient overload. A servo axis may pull 3× current for 2 s during acceleration or a stall. Steady state Rth would forbid it, but the transient thermal impedance Zth(t) allows it. From the datasheet Zth curve, at 2 s the effective resistance might be 40 percent of the steady value, so a 15 W transient for 2 s adds only about 15 × 4 × 0.4 = 24 K to the heatsink rise, plus the device term. I check that the peak Tj stays under 125 °C and that repeated overloads do not ratchet the heatsink temperature upward. A single pulse test on the bench will miss the ratchet.
Third, environment. Sealed cabinets, altitude above 2000 m where air density and convection fall, and a failed fan all raise Rsa. For a fan cooled heatsink I either design for natural convection at the derated current or I add a temperature sensor on the heatsink and a firmware trip. A sensor on the heatsink reads 20 to 30 K below the junction in this example, so the trip threshold must be set from the chain, not guessed. I would trip at 85 °C heatsink temperature, which corresponds to roughly 107 °C junction at full load.
Failure modes I design against
Thermal runaway in parallel devices: if two MOSFETs share current, the hotter one has higher Rds(on) and takes less current, which is self correcting for conduction loss, but its switching loss and leakage rise. Uneven mounting pressure or a dry interface creates a hotspot that the average calculation hides. I check with an infrared camera under load and look for more than 10 K spread across the bridge.
TIM degradation and solder fatigue: repeated thermal cycling pumps out grease and cracks solder joints, raising Rcs over months. That shows up as a slow rise in case temperature at constant load. I log heatsink temperature in service where the machine allows it, and I avoid designs that depend on a thin grease layer surviving without a spring clamp.
The validation that closes the loop is a worst case run: maximum ambient, maximum continuous torque, blocked or failed fan if that is a credible fault, and the overload profile repeated at its duty cycle. I instrument the MOSFET case and the heatsink, not only the cabinet air, and I compare measured Tj against the chain prediction. If measurement and model disagree by more than 10 K, the interface or the loss estimate is wrong, and I fix that before signing off the heatsink.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-68Walk me through how you would run root-cause analysis on a servo stage fault that could be mechanical, electrical or firmware, and prove which boundary it sits on?
The 90-second answer
Freeze the evidence before changing anything. A fault that crosses boundaries usually looks different depending on which instrument you trust, so I capture one synchronised record that contains all three domains at the same timestamp: commanded position and velocity, encoder position, motor current and bus voltage, firmware state and task timing, plus an accelerometer on the stage and a microphone or current probe if available. Then I run discriminating tests that each return a different signature for a mechanical, electrical or firmware cause. I change one variable at a time and keep the original failing configuration reproducible until the signature points to one boundary.
Assume a servo stage that follows poorly, trips on following error, or stalls intermittently under load. The first pass is passive. I log at the control rate, for example 1 kHz for a velocity loop, with a common time base from the controller timer. A logic analyser or scope captures PWM, encoder A/B, drive fault and enable lines on the same trigger as the firmware fault flag. If the log shows current saturating while encoder velocity stays near zero, the loop is asking for torque the mechanics cannot deliver or the drive cannot supply. If current is normal, encoder counts jump in steps, and the accelerometer shows a spike at the same instant, I look at coupling, backlash or a loose encoder disc. If current and encoder are clean but the command itself steps or freezes, the fault is upstream in firmware, trajectory generation or communications.
Discriminating tests
| Test | Mechanical signature | Electrical signature | Firmware signature |
|---|---|---|---|
| Command a slow open-loop current ramp with the stage clamped, then unclamped | Breakaway torque varies with position, stick-slip on the accelerometer | Current ripple or dropout tracks bus voltage sag, drive temperature or PWM phase | Commanded current differs from the value the loop computed in the log |
| Move the stage by hand with power off and watch encoder and current | Cogging, tight spot or backlash dead zone at a repeatable position | Encoder counts drop out at a repeatable cable bend or connector angle | No effect, counts remain clean |
| Run the same trajectory at half speed and half acceleration | Error shrinks roughly with acceleration, pointing to inertia, friction or gravity load | Error tracks current limit or supply dip rather than speed | Error stays fixed in samples, pointing to a missed tick or stale setpoint |
| Swap drive, cable or encoder with a known-good channel, one at a time | Fault stays with the axis | Fault moves with the swapped part | Fault stays with the controller and firmware image |
The swap test is decisive when the first three are ambiguous, but I do it after logging because reseating a connector can erase the fault. I also check the boring causes early: a 24 V rail that sags from 24 V to 19 V under load, a ground offset between drive and controller, and a connector that opens for 200 microseconds when the cable dress pack flexes. Those show up as a voltage or continuity event coincident with the fault timestamp, and they masquerade as tuning problems.
Keeping the evidence intact
On the controller I keep a small fault snapshot in a ring buffer that the ISR writes and the main loop reads only after the fault. It stores tick, commanded and actual position, current command and measured current, bus voltage, and the last three task execution times. That gives me the firmware view without a debugger attached, and it survives a watchdog reset if I place it in no-init RAM.
// Checked against a Cortex-M4 at 168 MHz, 1 kHz control ISR.
typedef struct {
uint32_t tick;
int32_t cmd_pos;
int32_t enc_pos;
int16_t i_cmd_mA;
int16_t i_meas_mA;
uint16_t vbus_mV;
uint16_t task_us;
} FaultSample;
static FaultSample ring[256];
static volatile uint32_t ring_head;
void control_isr(void) {
uint32_t i = ring_head & 255u;
ring[i].tick = tick_1khz;
ring[i].cmd_pos = cmd_pos;
ring[i].enc_pos = enc_pos;
ring[i].i_cmd_mA = i_cmd_mA;
ring[i].i_meas_mA = i_meas_mA;
ring[i].vbus_mV = vbus_mV;
ring[i].task_us = task_us_last;
ring_head++;
}Failure modes I watch for
Changing the PID gains and the mechanical preload in the same test destroys the evidence, because a softer loop can hide a tight bearing for a week. I also distrust a fault that only appears after ten minutes of running. That pattern points to heating: winding resistance rises, a magnet or encoder drifts, or a connector expands. I log temperature alongside the other channels and repeat the test cold and warm. Finally, I confirm the fix by returning to the original failing trajectory and load, not by running an easier demo. If the signature is gone under the original conditions and the swapped-part test agrees, I have a root cause rather than a workaround.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-69Walk me through how joint limits, singularities and workspace constraints shape a robot motion plan, and how you would handle a target near a singularity or outside the reachable workspace?
The 90-second answer
I treat the three constraints as filters applied in order before any trajectory is generated. First, workspace: can the target be reached at all by the geometry. Second, joint limits: does an inverse kinematics solution exist inside the allowed range for every joint. Third, singularities: is that solution close to a configuration where the Jacobian loses rank and small Cartesian moves demand very large joint speeds. A target that passes the first two can still be a bad plan if the straight Cartesian path between waypoints crosses a singularity, a limit, or a hole in the workspace.
For a planar two-link arm with link lengths l1 and l2, the reachable workspace is an annulus centred on the base. The outer radius is l1 + l2, the inner radius is |l1 - l2|, and the Jacobian determinant is l1l2sin(theta2), where theta2 is the elbow angle. That one term explains most of the behaviour. When theta2 approaches 0 or pi the arm is fully extended or fully folded, the determinant approaches zero, and the arm loses the ability to move the tool radially. Near that condition the inverse Jacobian grows without bound, so a modest Cartesian velocity can demand joint velocities the drives cannot deliver.
Joint limits and workspace in practice
Joint limits are hard stops in the controller, but the planner should keep a margin inside them. I would plan to, say, 5 degrees inside a limit for a slow approach and more for a fast move, because following error, calibration error and cable forces all push the real joint past the commanded value. Limits also select between IK branches. A two-link arm has elbow-up and elbow-down solutions for the same target. One may sit comfortably inside the limits while the other requires theta2 beyond its range, so the planner must enumerate both and discard the invalid one rather than clamp it.
Workspace is more than the annulus. A Cartesian straight line between two reachable points can leave the annulus, pass through the base, or enter a region blocked by a fixture, a cable chain or the arm itself. I check the interpolated path, not just the endpoints, and I check it in joint space as well, because a path that is smooth in Cartesian coordinates can still drive a joint through its limit.
| Check | Test for l1 = 300 mm, l2 = 250 mm | Result for target at (520, 80) mm |
|---|---|---|
| Outer reach | r = sqrt(520^2 + 80^2) = 526 mm, limit 550 mm | Passes, 24 mm margin |
| Inner reach | r > | 300 - 250 |
| Elbow angle | cos(theta2) = (r^2 - l1^2 - l2^2) / (2l1l2) = 0.83, theta2 = 34 deg | sin(theta2) = 0.56, manipulability is healthy |
| Same target at (545, 20) mm | r = 545 mm, cos(theta2) = 0.96, theta2 = 16 deg | sin(theta2) = 0.28, radial stiffness falling, slow down or reorient |
| Target at (560, 0) mm | r = 560 mm > 550 mm | No IK solution, reject before motion |
The last row is the common failure. The operator asks for a point 10 mm beyond full extension. Clamping it to 550 mm moves the tool to the wrong place and can look like a successful move. The correct response is to reject the target, report the shortfall, and offer a reoriented approach or a moved base.
Handling a target near a singularity
Near a singularity I do not try to force the Cartesian path through it. Options, in order of preference: add a via point that keeps theta2 away from 0, approach the target along a direction the arm can still generate, reduce Cartesian speed in proportion to manipulability, or switch the final segment to joint-space interpolation so joint velocities stay bounded. Damped least squares, (J^T J + lambda^2 I)^-1 J^T, is useful in the controller to limit joint speed near the singularity, but it trades tracking accuracy for stability, so I treat it as a safety layer rather than a planning solution.
import math
def check_target(x, y, l1=300.0, l2=250.0):
r = math.hypot(x, y)
if r > l1 + l2 or r < abs(l1 - l2):
return None # outside workspace, no IK solution
cos_t2 = (r*r - l1*l1 - l2*l2) / (2*l1*l2)
t2 = math.acos(max(-1.0, min(1.0, cos_t2)))
manipulability = abs(math.sin(t2)) # proportional to |det(J)|
return {"r_mm": r, "theta2_deg": math.degrees(t2),
"manipulability": manipulability,
"slow_down": manipulability < 0.35}A manipulability below roughly 0.3 in this normalised form is where I would start scaling speed down and checking joint velocity limits explicitly, rather than trusting the Cartesian profile.
For a six-axis arm the same logic extends. Wrist singularities occur when axes align, typically when theta5 approaches 0, and shoulder singularities when the wrist centre passes over the base axis. The planner checks the full Jacobian condition number along the path, not just at the target, because a path can pass through a singularity between two perfectly valid endpoints and cause a wrist flip mid-move. That flip shows up as a sudden large joint velocity and a path deviation, and it is detected in simulation before the machine ever moves.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-70What termination does a CAN bus need, and where do you fit it?
The 90-second answer
A CAN bus needs 120 ohm termination at each physical end of the twisted pair, and nowhere else. CANH and CANL form a 120 ohm characteristic impedance line. The two end resistors in parallel present 60 ohm to every transceiver, which is the load the standard assumes when it specifies the dominant and recessive levels.
That single rule explains most CAN wiring faults. Fit termination at only one end and the unterminated end reflects the edge back along the cable. Fit it at a middle node as well and the load drops below 60 ohm, the driver has to source more current, and the differential swing shrinks. Both faults show up as ringing on a scope and rising error frames, often only on the longest cable run.
The trunk runs between the two resistors. Nodes tap off the trunk with short stubs. A stub is an unterminated branch, so it must stay short enough that its reflection returns after the bit has settled. At 500 kbit/s that is roughly 0.3 m or less in practice. Longer stubs are the usual reason a bench setup with two nodes works and the machine build with a drive on a drop cable does not.
Checking the load
The arithmetic is one parallel combination:
R_load = (120 × 120) / (120 + 120) = 60 ohm
A transceiver datasheet will state a minimum load, commonly 45 to 60 ohm. Two terminations meet it. Three terminations give 40 ohm, which is outside that range for many parts. That is why vendor drives and I/O modules that ship with termination enabled cause trouble. The module in the middle of the trunk adds a third 120 ohm that the integrator did not plan for.
| Wiring | Load seen by driver | What the scope shows |
|---|---|---|
| 120 ohm at both ends | 60 ohm | Clean dominant near 2 V differential, recessive near 0 V |
| 120 ohm at one end only | 120 ohm | Ringing at the far end after each transition |
| 120 ohm at both ends plus one in the middle | 40 ohm | Reduced swing, error frames under load |
| No termination | Open line | Large ringing, bus fails beyond a few metres |
How I verify it on hardware
Power off and measure resistance between CANH and CANL at any node. A correctly terminated bus reads about 60 ohm. About 120 ohm means one end is missing. About 40 ohm means a third termination is fitted somewhere. That measurement takes ten seconds and points straight at the wiring fault before any firmware is involved.
Then power up and probe differentially across CANH and CANL while the bus is active. At 500 kbit/s the dominant level should sit near 2 V and the recessive near 0 V, with no sustained ringing after the edge. If the levels are clean but a node still drops off, I look at its stub length and its connector before touching bit timing. Termination first, because it is the one thing that changes the electrical behaviour of every node at once.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-71Walk me through how you would design a hardware-in-the-loop rig to validate a servo controller before it goes on the machine, including plant emulation, timing determinism and fault injection?
The 90-second answer
I would start from the controller's interface contract, not from the rig. What signals does it consume, at what rate, with what timing tolerance, and what outputs must it produce within what latency? For a servo controller that is typically encoder feedback at 1 kHz, a setpoint over CAN or Ethernet, and PWM or analogue drive output. The rig has to reproduce the plant the controller will see, the faults it must survive, and the timing it will experience, while never being able to energise a real axis if the controller misbehaves.
That gives three layers: a plant emulator, a deterministic I/O and timing layer, and a safety and fault-injection layer. If any layer is non-deterministic, the rig will pass controllers that fail on the machine and fail controllers that would pass.
Plant emulation: pick fidelity against the question
| Approach | What it reproduces well | What it hides | Use when |
|---|---|---|---|
| --- | --- | --- | --- |
| --- | --- | --- | --- |
| --- | --- | --- | --- |
| Real motor, inertia disc and brake | Friction, cogging, backlash, current ripple | Nothing major, but load is fixed | Final validation, tuning checks |
| Dynamometer with torque control | Programmable inertia, disturbance torque, load steps | Motor electrical dynamics if drive is bypassed | Repeatable load profiles |
| Simulated plant on real-time target | Any inertia, friction model, sensor faults, cheap to change | Model error, no real current or thermal behaviour | Early control law and fault testing |
For most development I use the simulated plant, then confirm on a real motor. The model needs the parameters the loop actually feels: reflected inertia, viscous and Coulomb friction, torque constant, back-EMF, and a time delay. A second-order model is enough to expose instability and windup. It is not enough to validate current ripple or thermal limits, and I would say so in the test report.
The plant must run faster than the controller. If the velocity loop runs at 1 kHz, I run the plant at 10 kHz or higher on a real-time target such as a Linux PREEMPT_RT box or a dedicated real-time controller, with the encoder synthesis updated every plant step. At 0.5 m/s on a 5 mm lead screw with a 2000 count encoder, the count rate is 200 kHz. Synthesising that in software at 1 kHz would quantise velocity badly and make a good controller look noisy.
# Plant step, run at 10 kHz on the real-time target. Checked against Python 3.11.
# Hypothetical figures for a small linear axis.
def plant_step(state, torque_cmd, dt=1e-4):
pos, vel = state
inertia = 0.02 # kg m^2 reflected
viscous = 0.4 # N m s / rad
coulomb = 0.15 # N m, sign(vel) term
accel = (torque_cmd - viscous * vel - coulomb * (1 if vel > 0 else -1 if vel < 0 else 0)) / inertia
vel += accel * dt
pos += vel * dt
return pos, velTiming and latency budget
I measure the loop end to end, not just the ISR rate. Sensor sample, computation, output update and plant response add up. With a 1 kHz loop the period is 1000 microseconds. I budget 100 microseconds for computation, 50 microseconds for I/O, and I require jitter under 20 microseconds, measured with a logic analyser on a toggle pin, not from a log timestamp. A worked check: if jitter reaches 200 microseconds, that is 20 percent of the period, phase margin drops measurably, and a step test that passed on the bench can oscillate on the machine. The rig logs jitter on every run and fails the run if it exceeds the budget.
Fault injection and safety
Faults go in through the same path as real faults, not through a test-only API. Encoder dropout for 5 ms, encoder offset jump, current sensor stuck at zero, setpoint step of full scale, supply dip to 18 V for 100 ms, and loss of the fieldbus frame. Each fault has a defined expected response: controlled stop, torque limit, or safe state, and a detection time I assert in the test.
Safety is hardware, independent of the controller and the test PC. A hardwired interlock cuts drive power on guard open, E-stop, or rig fault, wired through a safety relay or contactor with normally closed loops. The controller under test cannot override it. The rig also limits current and speed in the drive stage itself, so a runaway controller saturates at a safe torque instead of spinning the test motor to destruction.
What I check before trusting the rig
I calibrate the rig against the real axis. I run the same step on the real motor and on the simulated plant, compare overshoot, settling time and steady-state error, and tune the model parameters until they match within a stated tolerance, for example settling time within 10 percent. I also run a known-bad controller, one with integral windup or a wrong sign on derivative, and confirm the rig catches it. A rig that has never failed a bad controller is decoration.
Common failure modes I have seen: the plant model runs on a non-real-time PC and jitter masquerades as plant noise, the encoder synthesis uses a lookup table that repeats every revolution and hides a real fault, and fault injection resets the controller instead of disturbing it, so recovery logic is never exercised. Each of those produces confident, wrong results, which is worse than no rig at all.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-72A stage sensor drifts 2 micrometres per month and your budget allows 6 micrometres of drift: how would you set the recalibration interval and spot that drift in service?
The 90-second answer
I set the interval from the drift rate and the error I can afford, then I check for drift in service at a position I already know. For a displacement sensor that drifts mainly in offset, the reading at a fixed home position should stay constant. If that reading creeps, the zero has moved. I trend it and recalibrate before the creep eats the tolerance.
Take a stated case. A linear sensor on a stage has a tolerance of plus or minus 10 micrometres at the tool point. Repeatability is 2 micrometres. I allow 6 micrometres for drift between calibrations and keep the rest as margin. Measured offset drift on the installed machine is 2 micrometres per month. That figure comes from logging the home reading over the first month, not from the datasheet alone, because cable movement and mounting stress change the real rate.
Setting the interval
The arithmetic is direct:
interval = drift allowance / measured drift rate
= 6 micrometres / 2 micrometres per month
= 3 monthsI would schedule recalibration at 3 months, or sooner if the trend detector fires first. If the measured rate doubles in summer because the cabinet runs hotter, the interval halves. The interval is only as good as the measured rate, so I record the as-found reading at each calibration. That value shows how far the sensor actually moved since the last visit and lets me update the rate.
A two-point calibration, zero and span, corrects offset and gain at the time of the visit. It does not stop the next drift. That is why the interval and the in-service check matter more than the calibration procedure itself.
Spotting drift in service
Every homing cycle the controller already drives to the home stop. I record the sensor reading there and compare it with the nominal home value stored at calibration. A slow change in that reading is offset drift. A reading that jumps on reversal but returns at home points to backlash or hysteresis, and recalibrating would not fix it.
Worked trace, hypothetical readings at home:
| Week | Home reading (micrometres) | Drift from nominal | Action |
|---|---|---|---|
| 0 | 0.1 | 0.1 | none |
| 4 | 1.9 | 1.9 | none, trend noted |
| 8 | 3.8 | 3.8 | warn, plan recalibration |
| 12 | 5.7 | 5.7 | recalibrate, near 6 micrometre allowance |
The trend is roughly 2 micrometres per month, which matches the measured rate. The warn level sits above repeatability so noise does not trigger it. The recalibrate level sits at the allowance from the budget.
A simple check in C, run once per homing cycle:
/* HOME_NOMINAL_UM set at calibration. Returns 0 ok, 1 warn, 2 recalibrate. */
int check_home(float reading_um)
{
float drift = reading_um - HOME_NOMINAL_UM;
if (drift > 6.0f || drift < -6.0f) return 2;
if (drift > 4.0f || drift < -4.0f) return 1;
return 0;
}In practice I smooth the reading with a short moving average over several homing cycles before comparing, because a single cycle includes repeatability noise of 2 micrometres.
Fixed interval versus condition-based
A fixed calendar interval is simple to plan and audit, but it can waste a visit when drift is slow and miss a fast drift when temperature changes. Condition-based recalibration uses the home trend to trigger the visit, so the machine is serviced when the data says so. The trade-off is that condition-based needs a trustworthy reference position and a logged trend. Without that reference, the calendar interval is the safer choice.
If drift returns within a week of a recalibration, I stop recalibrating and look for a cause. A loose connector, a cable that flexes with the axis, or a mount that slips under load will keep moving the zero. Resetting the zero each time hides the mechanical fault until it becomes a failure.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-73How do accuracy, resolution, repeatability and hysteresis differ on a precision stage, and how would you measure each one separately?
The 90-second answer
They describe four different ways a measurement or a stage can be wrong, and a good datasheet number for one tells you almost nothing about the others.
Accuracy is closeness to the true value. It is dominated by systematic error: scale factor error, offset, misalignment, thermal expansion. Resolution is the smallest increment the system can distinguish, usually set by the encoder count or ADC step. Repeatability is how tightly repeated moves to the same commanded position cluster, under unchanged conditions. Hysteresis is a direction dependent offset: the reading or position you get approaching a point from the left differs from approaching it from the right, because of backlash, friction, magnetic hysteresis or elastic windup.
A stage can have fine resolution and poor accuracy, and excellent repeatability with large hysteresis. That last case is common. It returns to the same place every time from the same direction, but not to the same place from the opposite direction.
Worked example
Take a linear stage with a 0.5 µm encoder, commanded to 10.000 mm, measured against a laser interferometer. Hypothetical figures, labelled as such:
| Approach | Mean measured | Spread over 10 repeats | Error vs true 10.000 mm |
|---|---|---|---|
| From left, increasing position | 10.0048 mm | ±0.0003 mm | +4.8 µm |
| From right, decreasing position | 10.0029 mm | ±0.0003 mm | +2.9 µm |
| Smallest encoder step | 0.5 µm | n/a | n/a |
Read it as: resolution is 0.5 µm. Repeatability is about 0.3 µm, the half width of the cluster. Accuracy is roughly 5 µm, because the mean sits 4.8 µm away from truth even though the cluster is tight. Hysteresis is the 1.9 µm gap between the two means, 4.8 minus 2.9. If you only ever approach from the left, you would never see that 1.9 µm, and your control loop would happily repeat the error.
That is why I measure them separately. Accuracy needs an external reference, interferometer or gauge blocks, over the full travel, not just at one point, because scale error grows with distance. Repeatability needs repeated cycles in one direction with no change in load, temperature or approach. Hysteresis needs paired runs in both directions to the same set of points, then a plot of forward minus reverse error against position. A constant gap points to backlash or lost motion. A gap that grows with load points to compliance. A gap that changes with speed points to friction or servo following error.
Where each one comes from, and what fixes it
Resolution is a floor, not a guarantee. A 17 bit encoder on a 360 degree shaft gives 360/131072 = 0.0027 degrees per count, about 2.7 millidegrees. That does not mean you can position to 2.7 millidegrees. Interpolation error, eccentricity and mounting runout can be several counts. On the ADC side, a 12 bit converter over 0 to 10 V has a step of 2.44 mV, but noise and reference drift decide how many of those bits are real.
Accuracy is usually calibration plus environment. A steel scale at 11.7 µm per metre per kelvin moves 11.7 µm over 1 m for a 1 K change. That alone can swamp a 1 µm repeatability spec. So accuracy claims without a temperature range and a stated reference are not usable.
Repeatability fails for reasons that vary run to run: stiction, cable forces, encoder noise, thermal drift during the test, and settling before you read the position. If repeatability is poor, I change one thing at a time. Longer settling time first, because reading during motion inflates spread. Then approach direction and speed, then load and cable routing. I do not reach for a software compensation table until the mechanical spread is stable, because a table fitted to noisy data just memorizes noise.
Hysteresis is the one most often mistaken for repeatability. Backlash in a lead screw or gear pair shows as a dead zone on reversal, which you saw in the 1.9 µm gap above. Preload, dual encoders with the second on the load side, or always approaching from one direction can manage it. Software backlash compensation can help, but it is fragile if the gap changes with load or wear, so I would verify it under the process load, not just unloaded on the bench.
In short: resolution is what you can see, repeatability is how consistently you land, accuracy is how close that landing is to truth, and hysteresis is how much the answer depends on which way you came in. Spec all four, measure all four, and never let a resolution number stand in for the other three.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-74How do you debug a race condition between an ISR, DMA, and main loop sharing a buffer?
The 90-second answer
Start by naming the shared object and who can write it. In the usual case the DMA engine fills a circular ADC or encoder buffer, a timer ISR consumes samples or updates a flag, and the main loop reads the same buffer to compute velocity or position. A race appears when the main loop reads a multi-word value while the ISR updates it, or when DMA wraps and overwrites data the main loop has not consumed yet. volatile only stops the compiler caching a variable. It does not make a 32-bit read atomic on every core, it does not stop DMA, and it does not stop an ISR from preempting the main loop halfway through a copy.
The fix that works on real hardware is to give each writer its own buffer and hand ownership over at a single point. Use two buffers. DMA writes only to the inactive one. When DMA completes, its half-transfer or transfer-complete interrupt marks that buffer ready and swaps the active index inside a short critical section. The main loop only reads the buffer marked ready, and it checks a sequence counter before and after the read. If the counter changed, the read was torn and you discard it.
// Cortex-M4/M7, C11. Two DMA buffers, one active index.
static uint16_t buf[2][256];
static volatile uint8_t active; // buffer main loop may read
static volatile uint32_t seq; // increments on each completed block
void DMA1_Channel1_IRQHandler(void) // transfer complete
{
__disable_irq();
active ^= 1; // hand the finished buffer to main
seq++;
__enable_irq();
DMA1->IFCR = DMA_IFCR_CTCIF1; // clear flag, retarget DMA to other buf
DMA1_Channel1->CMAR = (uint32_t)buf[active ^ 1];
DMA1_Channel1->CNDTR = 256;
DMA1_Channel1->CCR |= DMA_CCR_EN;
}
int main_loop_read(uint16_t *out)
{
uint32_t s1 = seq;
uint8_t a = active;
memcpy(out, buf[a], sizeof(buf[a]));
__DSB(); // order the copy before the check
return (seq == s1) ? 0 : -1; // -1: torn read, retry next cycle
}On a Cortex-M7 with data cache enabled, add SCB_InvalidateDCache_by_Addr for the DMA buffer before the CPU reads it, or place the buffers in a non-cacheable region. DMA writes bypass the cache, so without that step the CPU can read stale data even when the logic above is correct.
How you prove it is a race and not noise
Add a sequence counter and a dropped-block counter, and log them with a timestamp. A torn read shows up as a value that is half old and half new, for example a 32-bit encoder count that jumps by a large amount for one sample and then returns. Buffer overrun shows up as seq advancing by more than one between two main loop iterations while the main loop was busy. Toggle a GPIO at the start and end of the ISR and at the DMA complete interrupt, then capture all three on a logic analyzer. If the main loop copy overlaps the ISR window, you will see it directly.
| Symptom | Likely race | Check |
|---|---|---|
| One wild sample, then normal values | Torn multi-word read | Sequence counter mismatch on that sample |
| Data repeats or skips in blocks of 256 | DMA wrapped before main consumed it | seq delta greater than 1 |
| Works at 100 Hz, fails at 1 kHz | ISR preempts a longer critical section | ISR entry GPIO overlaps main copy window |
| Values lag by exactly one block | Reading the buffer DMA is writing | Active index changed mid-copy |
What not to do
Do not disable interrupts for the whole copy if the copy is long. At 1 kHz control rate a 256-sample copy can take tens of microseconds and will add jitter to the ISR that follows. Keep the critical section to the index swap and the counter read, a few instructions. Do not share a single buffer between DMA and main and hope the main loop is fast enough. Under load, a missed deadline turns into silent data loss. Do not use a plain flag set by the ISR and cleared by main without a memory barrier on a multicore part. On a single core Cortex-M the double buffer plus sequence check above is enough, and it fails safe because a torn read is detected and dropped instead of feeding a bad velocity estimate into the PID loop.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-75Walk me through BLDC commutation from trapezoidal to sinusoidal/FOC, and how you align Hall sensors or an encoder index to rotor flux to avoid torque loss and cogging?
The 90-second answer
Commutation is deciding which stator phases carry current, and in which direction, so the stator field stays ahead of the rotor magnets by the right electrical angle. For a trapezoidal BLDC drive that decision is six steps per electrical revolution. For field-oriented control it is continuous: measure phase currents, transform them into a frame rotating with the rotor, and hold the q-axis current at the angle that produces torque.
Sensor alignment is what makes either method know where the rotor actually is. A Hall sensor does not measure flux directly. It reports a sector, and the controller infers rotor angle from that sector plus an assumed offset. If that offset is wrong by 15 electrical degrees, the current vector is 15 degrees off the torque axis. Torque falls by cos(15°) and the d-axis component wastes current as heat and ripple. On a precision stage that shows up as torque ripple at pole-pass frequency, higher RMS current for the same load, and a position-dependent disturbance the velocity loop has to fight.
Trapezoidal commutation and Hall sensors
A three-phase BLDC with 120 degree Hall sensors gives six states per electrical cycle. Each state energises one phase positive, one negative, and leaves the third floating. The floating phase is where you can read back-EMF in a sensorless design, because its voltage is the induced EMF without the PWM drop across the conducting phases.
Hall placement is mechanical, not firmware. Three Hall devices sit 120 electrical degrees apart, aligned to the stator teeth and rotor pole pattern. Their outputs form a 3-bit Gray-like code. Only six codes are valid. A code that jumps by more than one sector, or an invalid code such as 000 or 111 for a typical arrangement, means a wiring error, a missed sensor, or a rotor that has slipped past a sensor at speed.
// Hall code to sector, 4-pole-pair motor, Halls wired A,B,C
// Valid sequence for forward rotation: 1,3,2,6,4,5 then repeat
static const int8_t hall_to_sector[8] = {
-1, 0, 2, 1, -1, 3, 4, -1
};
static const uint8_t sector_phase[6][3] = {
// {high_phase, low_phase, float_phase} for sector 0..5
{0, 1, 2}, {0, 2, 1}, {1, 2, 0},
{1, 0, 2}, {2, 0, 1}, {2, 1, 0}
};Alignment check on the bench: rotate the shaft slowly by hand and log Hall transitions against a known index mark. You should get six evenly spaced transitions per electrical revolution, each 60 electrical degrees apart, in the correct order. Uneven spacing points to Hall placement error or magnet asymmetry. A transition that arrives early on one sector and late on the next will produce a repeating torque dip every revolution.
Sensorless commutation and its limit
Sensorless trapezoidal control watches the floating phase. When its back-EMF crosses half the DC bus, the rotor has passed the midpoint of the current sector, so the controller advances to the next sector after a 30 electrical degree delay. That works once back-EMF is large enough to measure above PWM noise, typically above 5 to 10 percent of rated speed. Below that, back-EMF is millivolts, PWM ripple dominates, and the estimate fails. The standard fix is an open-loop ramp: force commutation at increasing frequency until back-EMF is reliable, then hand over. The failure mode is a stall during handover if load torque exceeds what the forced current can produce at low speed.
Sinusoidal drive and FOC
FOC replaces six steps with continuous control. Phase currents are sampled, Clarke transformed to alpha-beta, then Park transformed using the electrical angle theta_e. The controller regulates Id to zero for maximum torque per amp in a surface-magnet motor, and Iq for torque. Inverse Park and SVPWM generate the phase voltages.
Here encoder alignment is a single number: the offset between encoder counts and theta_e. Procedure I use on a new axis:
- Lock the rotor mechanically or hold it with a brake.
- Inject DC current into two phases to pull the rotor to a known magnetic axis, for example phase A positive, B and C negative in a star winding.
- Wait for settling, read the encoder count, and store it as the zero for that axis.
- Rotate the shaft one full mechanical revolution and verify the electrical angle advances by pole_pairs * 360 degrees.
- Run a slow open-loop rotation and check that Id stays near zero. A sinusoidal Id ripple at pole-pass frequency means the offset is wrong or the encoder is eccentric.
// Offset calibration: align to phase A axis, then store encoder zero
void calibrate_elec_offset(void) {
apply_dc_current(PHASE_A_POS, PHASE_B_NEG, PHASE_C_NEG, 0.3f * I_RATED);
delay_ms(500);
elec_offset = encoder_count(); // counts at known flux axis
save_to_flash(elec_offset);
}
float electrical_angle(void) {
int32_t d = encoder_count() - elec_offset;
return fmodf((float)d * 2.0f * PI / ENC_CPR * POLE_PAIRS, 2.0f * PI);
}Comparison
| Method | Rotor feedback | Torque ripple | Low speed | Alignment sensitivity |
|---|---|---|---|---|
| 6-step Hall | 3 Halls, 6 sectors | 10 to 15 percent typical | Good to stall | Sector offset error, coarse |
| 6-step sensorless | Back-EMF zero crossing | Similar to Hall | Fails below 5 to 10 percent speed | No sensor to align, handover risk |
| Sinusoidal Hall | Hall plus interpolation | 3 to 5 percent | Good | Interpolation error remains |
| FOC with encoder | Absolute or incremental encoder | 1 to 3 percent if tuned | Good to stall, smooth | Offset error creates Id ripple |
| FOC sensorless observer | Model plus back-EMF | Low at speed | Poor at stall without saliency tracking | Observer tuning, parameter drift |
Failure modes I check first
Wrong phase sequence reverses rotation or causes a locked rotor that draws rated current and trips on I2t. A Hall sensor wired to the wrong input gives a valid-looking code that runs backwards under load. Encoder offset drift after a motor swap is the classic FOC fault: the drive runs, current is high, the stage coggs at low speed, and the velocity loop saturates trying to correct a disturbance that is actually a 20 degree electrical misalignment. Temperature also moves Hall thresholds and magnet flux, so a design that relies on precise Hall interpolation for a 1 micrometre stage needs a temperature check across the operating range, not just at 25 C.
If alignment is off, no amount of PID tuning fixes the ripple. It is a feedforward error in the angle itself, and the current loop will faithfully produce the wrong vector.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-76Walk me through how you would size a fuse, relay, and flyback protection for a 24 V, 2 A solenoid actuator that switches 20 times per minute?
The 90-second answer
For a 24 V solenoid drawing 2 A, I size the three parts from three different currents. The fuse protects the wiring at 125% of continuous load, so a 3.15 A slow-blow fuse for a 2 A coil. The relay is chosen on its DC inductive break rating, derated to about half its resistive rating, so a relay specified for at least 4 A at 28 VDC inductive, not just 5 A resistive. The flyback diode across the coil carries the full 2 A coil current at switch-off and blocks at least twice the supply, so a 3 A, 100 V fast diode such as a UF5408, or that diode in series with a 33 V TVS if release time matters.
Assume a concrete coil so the numbers are checkable. Hypothetical but typical for a 24 V, 2 A solenoid: resistance 12 Ω, inductance 60 mH, duty 20 operations per minute, ambient up to 60 °C in the cabinet.
Coil current: 24 / 12 = 2 A. Stored energy at switch-off: 0.5 × L × I² = 0.5 × 0.06 × 4 = 0.12 J. That energy has to go somewhere in a few milliseconds. Without a clamp the coil voltage rises until something arcs or breaks down, often 150 to 300 V on a scope, and the relay contacts take the erosion.
The diode sits directly across the coil, cathode to the switched side, anode to ground. It is invisible while the relay is closed and conducts only during the decay.
Fuse sizing
The fuse does not protect the solenoid against overload in the usual sense. A solenoid that stalls still draws roughly its rated current. The fuse protects the cable and the supply against a short circuit or a seized mechanism that pulls the coil down to a low resistance fault.
Continuous current is 2 A. Apply the usual 125% continuous-load factor and ambient derating. At 60 °C a typical 3.15 A fuse is already derated to about 2.6 A, which still clears 2 A with margin. A 2.5 A fast fuse would sit too close to the operating point and nuisance-blow on a cold coil, where resistance can be 15 to 20% lower and current briefly higher. A 5 A fuse would protect the 0.75 mm² cable, rated around 6 to 8 A depending on bundling, but would let a partial short cook the relay contact for longer. I check the fuse I²t against the cable damage curve and against the relay contact withstand, then confirm on the bench that a dead short opens the fuse in under 100 ms while 20 normal operations per minute do not age it visibly over a shift.
| Part | Sizing rule | Choice for this coil | Check |
|---|---|---|---|
| Fuse | 1.25 × 2 A, derated for 60 °C ambient | 3.15 A slow-blow (T) | Opens on short, survives cold start |
| Relay contact | Inductive DC break rating ≥ 2 × coil current | 5 A, 28 VDC rated relay, used at 2 A inductive | No contact welding after 10k cycles |
| Flyback diode | I_F ≥ coil current, V_RRM ≥ 2 × supply | UF5408, 3 A, 100 V | Peak diode current 2 A decaying |
| Cable | ≥ fuse rating after bundling derate | 0.75 mm² | Voltage drop under 0.3 V over 2 m |
Relay sizing
Relay datasheets quote a resistive DC rating that flatters the part. Breaking 2 A into a 60 mH coil at 24 V is a harder job than breaking 2 A into a resistor, because the arc is sustained by the collapsing field. I look for an explicit inductive or motor rating, or I derate a resistive-only relay to 40 to 50% of its headline current. A 5 A resistive relay used at 2 A inductive is a reasonable starting point. I also check the minimum contact current. Some signal relays need 10 mA or more to keep contacts clean, which is irrelevant here, but the opposite problem appears with reed relays that cannot break 2 A at all.
If the relay welds, the usual cause is breaking current above the inductive rating or a missing clamp that lets the arc run long. I would detect that in test by measuring contact resistance after a run of operations and by watching for the coil staying energised after the drive signal drops.
Flyback protection and the release-time trade-off
A plain diode clamps the coil to about 0.7 V below the supply rail at switch-off. Current decays with time constant L/R = 60 mH / 12 Ω = 5 ms. The solenoid releases slowly because the current, and therefore the magnetic force, persists for roughly three time constants, about 15 ms to fall below 5%. For a clamp or a valve that must release in under 5 ms, that is too slow.
Putting a TVS in series with the diode raises the clamp voltage. A 33 V TVS in series with a diode clamps the coil at roughly 34 V. Decay is then approximately linear at V/L = 34 / 0.06 = 567 A/s, so 2 A falls to zero in about 3.5 ms. The cost is higher voltage stress on the relay contact and on any transistor driving the coil, so the contact and the driver need margin above 34 V plus supply tolerance. An RC snubber across the contact or the coil is a third option. It reduces arcing and EMI but dissipates the 0.12 J per operation as heat in the resistor and does not clamp as firmly as a TVS.
| Clamp option | Clamp voltage | Approx. release to near zero | Main cost |
|---|---|---|---|
| Diode alone | ~0.7 V above rail | ~15 ms | Slow release, low stress |
| Diode + 33 V TVS | ~34 V | ~3.5 ms | Higher contact and driver voltage |
| RC snubber | Soft, ringing | Intermediate | Resistor heating, less firm clamp |
Worked trace at switch-off, diode alone: current starts at 2.0 A, falls to 0.74 A after one time constant (5 ms), 0.27 A after two, 0.10 A after three. With the TVS version the same current falls roughly linearly and is near zero by 4 ms. I verify both with a current probe on the coil lead and a voltage probe across the relay contact, because the scope tells me whether the clamp is actually conducting or whether layout inductance is ringing above it.
Two failure modes dominate in the field. A diode fitted backwards, or open from a solder fault, leaves the coil unclamped. The symptom is a loud click, visible contact pitting within weeks, and spikes on the 24 V rail that reset nearby electronics. A diode that is undersized, for example a 1 A part on a 2 A coil, fails short or open after repeated operations and produces the same symptoms later. I therefore measure diode temperature after a burst of operations and confirm the part stays well under its rating at the worst-case duty cycle, not just at a single pulse.
Final bench check: 1,000 operations at full current, scope on coil voltage and contact voltage, contact resistance before and after, fuse intact, release time measured mechanically or by a position switch. If release time is the specification that matters, I start with the TVS version. If contact life matters more, I start with the plain diode and accept the slower release.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-77Walk me through how you would trade off cost, performance and reliability when selecting sensors and actuators for a production machine?
The 90-second answer
I start from a quantified envelope, then buy performance only where the control loop or the process actually needs it, and buy reliability where a failure stops the line or creates a safety risk. Cost is judged per machine over its service life, not per part on a BOM.
For a sensor or actuator I write three numbers before looking at a catalogue: the performance floor (resolution, bandwidth, torque, speed, repeatability under load and temperature), the reliability target (expected life, allowable drift, failure mode on loss of signal), and the cost ceiling at the intended volume. A part that exceeds the floor by 10x on bandwidth but costs 4x and needs a cleaner supply rarely wins. A part that just meets the floor on the bench and drifts out of tolerance at 60 C in a sealed cabinet loses, however cheap it is.
Make the trade-off explicit
| Choice | Unit cost at 1k/yr | Performance headroom | Dominant failure mode | What I check before accepting it |
|---|---|---|---|---|
| Consumer-grade magnetic encoder | $18 | 12-bit, 8 kHz, drift with temperature | Offset drift, air-gap sensitivity | Drift over 0 to 60 C, gap tolerance at assembly extremes |
| Industrial optical encoder, sealed | $85 | 17-bit, 100 kHz, specified drift | Contamination if seal fails, connector fretting | IP rating, cable strain relief, diagnostic output |
| Absolute encoder with battery or Wiegand backup | $140 | 17-bit plus position after power loss | Backup battery ageing, higher complexity | Battery life at temperature, behaviour on power cycle |
| Open-frame stepper | $45 | High torque at low speed, no feedback | Missed steps under load, no warning | Torque margin at speed, stall detection |
| Closed-loop servo with encoder | $220 | Controlled torque and speed, fault reporting | Drive electronics, tuning effort | Current limit, thermal derating, fault codes |
The table forces the real question: what does the extra money remove? In the encoder rows it removes drift and loss of position after a power cut. In the actuator rows it removes silent missed steps and adds diagnostics. If the process can re-home after every power cut and the load is predictable, the $18 part plus a homing routine may be the right engineering choice. If the stage holds a wafer or a tool under load and a silent error scraps product, it is not.
Where reliability is actually bought
Reliability rarely comes from the headline spec. It comes from margin and from detectable failure. I derate actuators to roughly 60 to 70 percent of continuous rating at worst-case ambient, because winding resistance rises about 0.4 percent per degree and torque falls as the motor heats. For sensors I specify temperature range, supply range and mechanical tolerance with margin beyond the installation, and I prefer a part that reports its own health, such as a CRC on an absolute encoder frame, a live-zero on a 4 to 20 mA loop, or a drive that flags overcurrent and overtemperature.
Connectors and cabling deserve the same attention as the sensing element. A $200 sensor on a friction-lock connector that frets under vibration will fail more often than a $60 sensor on a sealed M12 with a proper strain relief. I also ask what the system does on loss of signal: does the loop freeze, drive to a limit, or hold last value? A sensor that fails to a known state is worth more than a slightly more accurate sensor that fails to a plausible-looking wrong value.
Worked cost example
Suppose a machine uses four position sensors and ships 2,000 units per year. Choosing the $85 industrial part over the $18 part adds $268,000 per year in BOM cost. That is hard to justify on accuracy alone if the $18 part meets the 1 micrometre repeatability requirement after calibration. Now add field cost. If the cheap part has a 2 percent annual field failure rate and each failure costs $1,500 in travel, downtime and replacement, expected field cost is $60,000 per year for the fleet, plus warranty risk and reputation. If the industrial part cuts that to 0.3 percent, expected cost falls to $9,000. The gap narrows, but the BOM premium still dominates at this volume. At 200 units per year the arithmetic flips: the premium is $26,800 against a much larger share of revenue per machine, and a re-home routine plus periodic calibration may be cheaper than sealed encoders. Volume changes the answer, which is why I state the volume assumption out loud.
My closing check is a short list I can defend in a design review: performance floor met at temperature and supply extremes, failure mode detected by the controller, derating applied, connector and cable specified for the environment, and lifecycle cost calculated at the stated volume. If a cheaper part passes all five, I take it and spend the saved budget on calibration, spares or a second sensor where redundancy actually helps.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-78What is the first thing you check on a new control board before you enable the motor driver, and what does a failure there look like?
The 90-second answer
I check the power rails with the motor disconnected and the bench supply current-limited, before I enable the driver or flash anything that can energise it. A short, a reversed diode or a wrong regulator will destroy the driver or the controller in the first milliseconds, and no amount of firmware debugging recovers that.
For a typical 24 V board with a 3.3 V logic rail, I set the bench supply to 24 V and 0.5 A, connect only the input power, and measure each rail with a multimeter, then with a scope for ripple and sag when the logic is running.
| Rail | Expected | Pass | Fail that stops bring-up |
|---|---|---|---|
| 24 V input | 24.0 V ±5% | Voltage present, current near zero with motor disconnected | Supply in current limit, or voltage collapses to near zero |
| 3.3 V logic | 3.30 V ±3% | Stable under load, ripple under 50 mV peak to peak | 0 V, 5 V, or a rail that rises slowly and never settles |
| Driver gate supply, if separate | Per driver datasheet, often 10 to 15 V | Present only when the driver is enabled | Missing gate supply, so the MOSFETs sit half on and heat |
| Ground continuity | Near 0 Ω between logic ground and driver ground at the star point | One defined ground reference | Floating or multiple accidental references through the bench leads |
// Bench check, Cortex-M at 168 MHz. Read the ADC on a divider
// from the 24 V input before the driver enable pin is touched.
#define ADC_REF_V 3.3f
#define ADC_MAX 4095.0f
#define DIVIDER 11.0f // 100k / 10k divider, 24 V -> 2.18 V
float read_input_voltage(void) {
uint16_t raw = adc_read_once(ADC_CH_VIN);
return (raw / ADC_MAX) * ADC_REF_V * DIVIDER;
}
// Pass: 22.8 V to 25.2 V and supply current < 100 mA idle.
// Fail: current at the limit means a short downstream. Stop.Why this comes first
The controller, encoder and driver all assume the rails are correct. If the 3.3 V rail is at 5 V because a regulator was fitted wrong, the microcontroller may still enumerate over SWD and look alive while its inputs are being overstressed. If the 24 V rail is shorted by a solder bridge across the H-bridge, enabling PWM turns that short into a direct shoot-through current. The bench limit turns both cases into a safe, observable event: the supply folds back, the voltage drops, and I can find the short with a multimeter in resistance mode with power off.
Polarity matters for the same reason. A reversed input diode or a swapped motor supply pair will not show up in a firmware register read. It shows up as a rail that never rises, a driver that draws current at zero duty, or a MOSFET that gets hot with no command. Checking voltage and idle current catches it before the first PWM pulse.
What a failure looks like in practice
A supply sitting in current limit at 0.5 A with 0 V on the output is a dead short, usually a solder bridge, a reversed tantalum capacitor, or a driver fitted backwards. A 3.3 V rail measuring 3.3 V at rest but sagging to 2.1 V when the controller runs points to an overloaded regulator or a shorted peripheral on that rail. Ripple above a few hundred millivolts on the logic rail, visible on a scope set to AC coupling, points to a missing or wrong decoupling capacitor and will cause ADC noise and random resets later, even if the average voltage looks correct.
Once the rails pass, I move to the clock and debug link, then to one peripheral at a time. I do not skip the rail check because the board "lights up". An LED on the 24 V input only proves that some voltage arrived. It does not prove the logic rail is in tolerance, the grounds are tied correctly, or the driver is safe to enable.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-79Walk me through how you would document and communicate a design decision that affects mechanical, electrical and firmware teams, so each can act on it without guessing?
The 90-second answer
I write one decision record that all three teams sign, and I attach the interface changes each team has to implement. The record states the problem, the options considered, the chosen option with numbers, and the consequences per discipline. A meeting alone fails because mechanical remembers a tolerance, electrical remembers a voltage, and firmware remembers a timing assumption, and those memories drift apart. The document becomes the single source they can build against.
Take a concrete case: moving a linear stage from a motor-side incremental encoder to a load-side absolute encoder to hit 1 µm repeatability. That one choice touches mounting and alignment, signal integrity and power, and homing and control code. If I only tell firmware to expect absolute position, mechanical will design a bracket with no adjustment range and electrical will route a signal down a long cable next to a PWM drive without checking the datasheet limits for that cable length.
The record itself
I use a short Architecture Decision Record, stored with the design in version control, plus an updated interface table. The ADR is one page. Anything longer gets split into the interface document.
# ADR-014: load-side absolute encoder for X stage (worked example)
status: accepted 2026-03-04
decision: Use absolute linear encoder, differential serial protocol
per selected vendor datasheet, supply per datasheet
rejected: motor-side incremental (backlash 18 um on reversal, measured)
rejected: single-ended incremental load-side (no absolute position after power loss)
consequences:
mechanical: bracket with 0.5 mm shim range, scale mounted on fixed rail
electrical: shielded twisted pair, termination and cable spec per datasheet
firmware: home on index at power-up, velocity from 1 kHz position delta
validation: repeatability test, 30 cycles, sigma under 0.4 umThe rejected options matter as much as the choice. They stop a stakeholder reopening the debate three months later without new data, and they record why the cheaper option was not good enough. Every electrical figure in the ADR cites the datasheet section it came from, with the part number and datasheet revision. I do not copy a clock rate, termination value or supply range from memory into the record. If the datasheet gives a maximum clock rate, I record that maximum and the rate firmware will actually use, and I note the cable length at which that rate was verified on the bench. A rate that works on a 0.3 m bench lead can fail on the installed cable, so the verification note names the installed length used in the test.
What each stakeholder gets
| Stakeholder | What they need from the decision | Where it lives |
|---|---|---|
| Mechanical | Mounting datum, adjustment range, cable bend radius, tolerance stack | Updated drawing note + ADR consequences |
| Electrical | Supply voltage, signal type, termination, connector pinout, cable spec | Interface table revision, schematic note |
| Firmware | Protocol, timing, homing sequence, fault behaviour on comm loss | Interface table revision, driver ticket |
I do not write three separate documents. I write one ADR and update the shared interface table, with a revision number and date on every row that changes. Each team reviews only the rows they own, but they all see the same revision. That prevents the classic split where firmware implements the protocol at the datasheet maximum clock because the datasheet allows it, while electrical selected cable and termination for a lower rate, or the reverse.
How I communicate it
I circulate the draft before the meeting, with the open questions listed at the top. The meeting is for resolving conflicts, not for reading the document aloud. A typical conflict: mechanical wants the scale on the moving carriage for a shorter cable, electrical wants it on the fixed rail to keep the cable out of the flex chain. The ADR forces that trade into the open. Cable length affects signal integrity at the chosen clock rate, and flex life affects reliability, so we pick the fixed rail and accept a longer cable, then firmware confirms the timing margin at that length on the bench with the actual cable and connectors fitted. If the margin is not there, we lower the clock rate in the interface table and record the change, rather than discovering it on the machine.
After approval I announce the change in the project channel with three things: the ADR link, the interface revision, and the date the old design stops being valid. I also add the decision to the test plan. For this encoder that means a repeatability run, a power-loss homing test, and a comm-loss test where firmware must stop the axis within one control cycle rather than coasting on a stale position.
The failure mode I watch for is a decision that is agreed verbally and never written down. Six weeks later the bracket is machined, the PCB is laid out, and firmware has already written the driver, each against a different version of the idea. The ADR plus the versioned interface table costs an hour. Reworking a bracket, a PCB spin and a driver costs a quarter.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-80Your 1 kHz servo task averages 180 µs. How would you measure its worst-case execution time and check it still meets its 1 ms deadline when a higher-priority encoder ISR runs every 250 µs for 90 µs?
The 90-second answer
Average runtime tells me nothing about a deadline. I would measure the worst case the task actually hits, then add the interference from higher priority work and check the total against the period.
Take the stated case: a 1 kHz servo task, so a 1,000 µs period and deadline, with a higher priority encoder ISR every 250 µs that takes 90 µs. If the servo task itself takes 180 µs in the worst case, its response time is not 180 µs. The ISR can preempt it, possibly more than once.
I iterate R = C + ceil(R / T_isr) * C_isr, starting with R = C, until it stops changing. That gives the worst time from release to completion under fixed priority preemptive scheduling.
Measuring WCET on the controller
I use the Cortex-M DWT cycle counter and a GPIO pin. The counter gives me cycles, the scope confirms the counter and shows jitter the counter alone would hide.
// Cortex-M4 at 168 MHz, called at entry and exit of the servo task
static uint32_t wcet_cycles;
void servo_task(void) {
uint32_t start = DWT->CYCCNT;
GPIO_SET; // scope marker high
read_encoder();
pid_step();
write_pwm();
GPIO_CLEAR;
uint32_t elapsed = DWT->CYCCNT - start;
if (elapsed > wcet_cycles) wcet_cycles = elapsed;
}At 168 MHz, 30,240 cycles is 180 µs. I run that for minutes, not seconds, and I force the slow paths: a large step that saturates the output, anti-windup active, an encoder error retry, and DMA running at the same time. The maximum I record is still only a lower bound on the true worst case. It misses a path I did not trigger. That is the main trade-off against static analysis, which can bound every path from the binary but is often so pessimistic on a cached Cortex-M with flash wait states that it is useless for sizing. In practice I trust the measured maximum only after I have deliberately exercised the rare branches.
Checking the deadline with the numbers given
| Iteration | Calculation | R (µs) |
|---|---|---|
| 1 | 180 + ceil(180 / 250) x 90 | 270 |
| 2 | 180 + ceil(270 / 250) x 90 | 360 |
| 3 | 180 + ceil(360 / 250) x 90 | 360 |
R converges at 360 µs. That is the worst time from release to the PWM update being written, assuming the ISR always takes 90 µs and no lower priority code blocks the task. It leaves 640 µs of margin to the 1,000 µs deadline, so this task set is schedulable as stated.
Two assumptions decide whether that proof holds on hardware. First, blocking: if the servo task shares a bus or a multi-byte register update with lower priority code and interrupts are disabled for 40 µs, that 40 µs must be added to R. Second, the ISR cost must stay at 90 µs. If the encoder ISR grows because it now also logs or does a blocking I2C read, R grows with it and the margin shrinks fast. I would check both on a scope: trigger on the GPIO marker, measure the longest pulse over a long run, and measure release to completion including preemptions.
If R had exceeded 1,000 µs, I would not argue from the average. I would move logging out of the loop, shorten the ISR, or split the servo work so only the PID and PWM write run at 1 kHz, then repeat the measurement and the iteration.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-81For a robot inserting a peg into a hole, how does impedance control differ from direct force control, and how would you pick stiffness and damping so it aligns without jamming?
The 90-second answer
For peg-in-hole I would use impedance control. Direct force control can work, but impedance gives a safer default behaviour when the peg contacts the chamfer or the hole edge.
Impedance control commands a virtual spring and damper at the tool point instead of a force. In one axis the relation is:
M_d * x_ddot + D * x_dot + K * (x - x_d) = F_ext
x_d is the commanded position, x is the actual position, F_ext is the contact force, K is virtual stiffness, D is virtual damping and M_d is virtual inertia. The robot's inner position or torque loop tries to make the tool behave like that virtual system. In free space the tool follows the trajectory. On contact, a small position error creates a force through K, so the tool yields sideways and slides along the chamfer.
Direct force control closes a loop on measured force. A wrist sensor or joint torque estimate feeds a PI controller that drives the actuator until force equals the setpoint. That holds force accurately on a flat, compliant surface, but position is then free to drift. On a stiff hole edge, a high force gain can push hard before the sensor loop reacts.
| Impedance control | Direct force control | |
|---|---|---|
| Commanded quantity | Position, with virtual K and D | Force |
| Contact behaviour | Force rises with deflection, F = K * delta_x | Force held near setpoint, position moves to achieve it |
| Free-space behaviour | Normal trajectory tracking | Needs a separate position mode for approach |
| Main risk on a hole edge | Too stiff, so it jams | Too aggressive, so it chatters or pushes through |
| Sensing needed | Position, plus force if you want to adapt K | Accurate force or torque sensing is essential |
Picking stiffness and damping
Start with the largest lateral force you are willing to apply at the chamfer. Suppose the peg is 6 mm in diameter, the hole is 6.2 mm, and the chamfer can tolerate about 3 N of lateral force before friction wedges the peg. If you expect up to 2 mm of lateral misalignment during search, then:
K = F_max / delta_x = 3 N / 0.002 m = 1500 N/m
With that value, a 1 mm offset gives 1.5 N and a 2 mm offset gives 3 N. The peg presses lightly on the chamfer and the axial motion can walk it into the hole. Raise K to 20000 N/m and the same 2 mm offset gives 40 N. The peg wedges, insertion depth stops increasing, and motor current climbs while the position error stays large. That current rise with no progress in depth is the clearest sign of jamming.
Keep stiffness high along the insertion axis and low in the lateral plane. The axial direction needs enough stiffness to push the peg in, while the lateral directions need compliance to find the hole. Many controllers allow a different K per axis for exactly this reason.
Damping sets how the tool settles after contact. For a chosen virtual inertia M_d, set:
D = 2 * zeta * sqrt(K * M_d)
A damping ratio zeta between 0.7 and 1.0 gives a well damped response with little bounce. At zeta = 0.2 the tool oscillates on the chamfer, force ripples, and the peg can bounce out of the search pattern. In practice I would start with zeta = 0.9, run insertions at increasing misalignment, and lower K laterally before I touched the inner position gains.
A scalar version of the inner calculation at 1 kHz looks like this:
# dt = 0.001 s, one lateral axis
K = 1500.0 # N/m
D = 2 * 0.9 * (K * 0.5) ** 0.5 # M_d = 0.5 kg, zeta = 0.9
x_d = trajectory_position()
x = encoder_position()
x_dot = velocity_estimate()
F_cmd = K * (x_d - x) - D * x_dot
F_cmd = clamp(F_cmd, -5.0, 5.0) # limit lateral force to 5 N
send_torque_command(F_cmd)The clamp matters. Without it, a large trajectory error after a mode switch can command a force spike that drives the peg into the plate before the damping term catches it.
Failure modes to check on hardware
Force control chatter shows as a sustained force oscillation of more than about 10% of the setpoint while the position command is fixed. It usually means the force loop bandwidth is too high for a stiff environment or the sensor signal is delayed. Lowering the force gain or switching to impedance control removes it.
Impedance control that is too soft shows as slow insertion and a large steady position error under load. The tool deflects instead of pushing the peg home. The fix is to raise K only along the insertion axis, not in the lateral plane.
A drifting force sensor matters less in pure impedance control, because force is derived from deflection rather than measured directly. If you add force feedback to adapt K, tare the sensor when the tool is retracted in air and add a travel limit so a stuck reading cannot drive the tool through the part.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-82What is the standard fix for a ground loop between a controller and a sensor on a machine, without lifting protective earth?
The 90-second answer
Bond the grounds at one point only. Keep protective earth connected to both chassis for safety, but give the signal shield and the signal return a single bond to the controller ground. At the sensor end, terminate the shield through a capacitor to chassis if the cable needs high frequency shielding, and leave the low frequency path open. That breaks the loop while the chassis stay earthed.
A ground loop needs two conductive paths between the same two points. On a machine those paths are usually the protective earth through the frame and the cable shield or signal return. If the two earth potentials differ, current flows around that loop and the difference appears in series with the signal. Lifting protective earth would also break the loop, but it leaves a chassis floating and is not an acceptable fix.
Why the voltage appears
Suppose the cabinet earth and the stage earth differ by 80 mV at mains frequency because of leakage currents and load currents in the frame. A single ended sensor signal referenced to the stage ground and read by a controller referenced to the cabinet ground carries that 80 mV as an offset. On a 12 bit ADC spanning 0 to 5 V, 1 LSB is 1.22 mV, so 80 mV is about 65 counts. The reading will wobble at 50 or 60 Hz and will change when a drive starts, a heater switches, or another cable is connected.
I confirm it before changing wiring. I measure differentially between controller ground and sensor ground with the machine running, using a differential probe or two matched probes. A steady mains frequency voltage between the grounds, present with the signal cable connected and gone when the shield is disconnected at one end, confirms a loop. Measuring one ground against the oscilloscope earth lead does not confirm it, because the scope lead creates another path.
| Arrangement | Loop current | Signal error | Safety |
|---|---|---|---|
| Shield bonded at both ends | Flows through shield and frame | Mains hum in series with signal | Chassis earthed, shield earthed |
| Shield bonded at controller end only | No low frequency loop | Hum removed if return path is also single point | Chassis earthed, shield earthed at one end |
| Protective earth lifted at one chassis | No loop | Hum removed | Not acceptable, chassis can sit at mains potential on a fault |
| Differential or isolated input, shield bonded at both ends | Loop current flows in shield, not in signal pair | Rejected by common mode rejection, typically 80 to 100 dB at mains frequency | Chassis earthed, preferred where the cable cannot be changed |
Applying it on the machine
I route signal and return as a twisted pair so the loop area between them stays small. I bond the shield to the controller chassis at the entry gland, with a short connection, and I do not bond it again at the sensor. If the sensor needs a shielded enclosure for radio frequency interference, I connect the shield at the sensor through a 1 to 10 nF capacitor to chassis. That gives a high frequency path while keeping the low frequency loop open.
Where the cable already runs between two cabinets and both shields must be bonded for other reasons, I change the input instead. A differential receiver or an isolated analogue input rejects the voltage that appears between the grounds. With 90 dB of common mode rejection, an 80 mV loop voltage becomes about 2.5 uV referred to the input, which is below 1 LSB on the example ADC.
After the change I repeat the same differential measurement between the grounds and record the ADC counts with the drive off and on. If the mains component between the grounds is still present but the counts are clean, the input is rejecting it. If the counts still move, the return conductor is bonded at both ends somewhere else, often through a second cable, a USB connection to a laptop, or a sensor body bolted to the frame. That second bond is the one to find and remove from the signal path.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-83Walk me through how you would reduce vibration in a precision machine, from mounting to active damping?
The 90-second answer
I would treat vibration as a path problem, not a single fix. First I measure where the energy is, in frequency and in space, then I cut it at the source, break the transmission path, and only then add damping at the structure. Active damping is last because it can inject energy if the sensor, actuator and delay are wrong.
Start with a triaxial accelerometer on the tool point, the column, the base and the floor, plus a tach or encoder pulse for order tracking. Run the machine through its cycle, idle, rapid traverse, cutting or dispensing, and record a waterfall spectrum. A peak that tracks spindle speed is unbalance or misalignment. A fixed peak that appears only under load is usually a structural mode excited by the process. A peak at the motor electrical frequency or twice line frequency points to the drive.
For a worked example, assume a 120 kg machine on four mounts, a dominant floor input at 25 Hz, and a tool point budget of 2 µm RMS above 10 Hz. If I want the mounts to isolate at 25 Hz, transmissibility for a single degree of freedom system is T = sqrt((1 + (2ζr)^2) / ((1 - r^2)^2 + (2ζr)^2)), where r = f / fn. With fn = 8 Hz, r = 3.1, and ζ = 0.08, T is about 0.12. That is roughly 18 dB reduction before the structure amplifies anything. Static deflection under weight is δ = g / (2πfn)^2, which gives about 3.9 mm at 8 Hz. That deflection is the price of isolation, and it must not let the machine rock into its levelling screws or cable chain.
| Source or path | First check | Fix that usually works | What to avoid |
|---|---|---|---|
| Rotating unbalance | 1× running speed, phase across bearings | Balance to ISO 1940 grade, check coupling alignment | Adding mass to hide a 1× peak |
| Reciprocating or process force | Peaks at process frequency and harmonics | Reduce force at source, stiffen the load path, change the trajectory jerk | Softening the tool head mount |
| Floor input | Coherence between floor and base sensors | Lower fn with air or spring mounts, increase mass ratio | fn near a structural mode |
| Structural mode of column or gantry | Fixed frequency, high Q, excited by transients | Add constrained layer damping, ribs, or a tuned mass damper | A notch filter alone with no physical damping |
| Servo induced limit cycle | Peak moves with gain, present at standstill | Retune loop, check encoder mounting and backlash | Active damping on a noisy velocity signal |
Mounting and passive path
Mounts are chosen by fn, load per mount, and lateral stiffness, not by catalogue damping alone. Air mounts give fn of 1 to 3 Hz and excellent isolation above 10 Hz, but they need levelling, air supply, and protection against tilt. Elastomer mounts are simpler and tolerate shock, but their stiffness rises with frequency and temperature, so the measured fn on the machine often sits 30 to 50 percent above the catalogue value. I measure fn with a tap test or a swept sine on the installed machine and check all four corners, because one stiff mount tilts the mode and couples vertical input into rocking.
Inside the machine, I shorten the force loop. A spindle bolted through a thin sheet will ring at its panel mode. A cast or welded structure with ribs placed at the mode antinodes, bolted joints with controlled preload, and damping material constrained between two stiff skins raises modal damping from ζ = 0.005 to 0.02 or 0.03 without adding much mass. That change alone can cut resonant response by a factor of four to six.
Active damping
Active damping works when the actuator can apply force at the mode frequency with the right phase. The usual layout is a collocated pair, a piezo patch or inertial shaker and an accelerometer at the same location, so the loop sees the mode it controls. Collocation keeps the phase near 180 degrees across the mode, which makes velocity feedback stable over a wider band than a remote sensor.
The controller is deliberately narrow. I bandpass the acceleration around the mode, integrate to velocity, add phase lead to compensate for amplifier and sampling delay, and limit the output. Sampling at 10 to 20 times the mode frequency is a practical floor. At a 120 Hz mode, a 2 kHz loop with 0.5 ms total delay loses about 22 degrees of phase, which the lead term must restore.
/* Collocated active damping, 2 kHz loop, mode near 120 Hz */
float acc = read_accelerometer(); /* m/s^2 */
float vel = bandpass_integrate(acc); /* narrow band around mode */
float force = -gain * vel; /* velocity feedback */
force = clamp(force, -force_limit, force_limit);
write_piezo_amplifier(force);Gain is raised until the resonant peak in the measured spectrum drops, then backed off by 6 dB. If the peak moves or a new peak appears above the mode, the loop is fighting a higher mode or the delay is too large. I also add a watchdog in hardware. If the accelerometer saturates, disconnects, or the amplifier faults, the output must go to zero and the machine must revert to passive damping. An active system that drives at full force on a failed sensor will damage the tool faster than the original vibration.
Verification
I close the loop on numbers at the tool point, not at the actuator. The acceptance run repeats the waterfall at the same speeds and loads, with active damping on and off, and reports RMS displacement in the band above 10 Hz, the peak at the target mode, and the settling time after a rapid move stops. A good result on the example machine would be tool point motion falling from 6 µm RMS to under 2 µm RMS, with the 120 Hz peak down by at least 10 dB and no new peak within 20 percent of the mode. If the peak drops but the RMS does not, the energy moved to another mode, and the next fix belongs on that path rather than more gain.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-84Your motion controller has two flash banks and no JTAG access in the field. How would you use a trial boot and confirmation counter to roll back a bad update, and what does that cost you in flash?
The 90-second answer
With two flash banks and no JTAG in the field, I would run the new image from the inactive bank on a trial basis and keep the old image bootable until the new one confirms itself. The bootloader owns that decision. The application only gets to say "I booted and my checks passed." If it never says that, the bootloader falls back to the old bank after a set number of tries.
That costs flash. A 512 KB device split into two 256 KB banks gives you 256 KB for the application, not 512 KB. If the application grows past that, you either move to a larger part or add external flash, which is the main trade-off against a single-bank design with a recovery image.
How the trial boot works
Assume bank A runs version 4.2.0 and bank B is empty. The host downloads version 4.3.0 in chunks, each with a sequence number and CRC32, and the controller writes them to bank B. Missing chunks are re-requested by sequence number, so a dropped frame does not restart the whole download.
When the download completes, the controller checks the full image before it changes any boot flag. The CRC catches a corrupted transfer. A signature check catches an image built for the wrong board revision. Only then does it write a small metadata record for bank B with the image length, CRC, version, and a state of PENDING. The record is written twice with its own CRC, because a power cut halfway through a single metadata write is the easiest way to brick a dual-bank scheme.
On the next reset, the bootloader sees PENDING and boots bank B with a trial counter, say 3. The new application must pass a short self-test and then call confirm_boot(). For a motion controller that test is concrete: read the encoder index pulse, check both travel limit switches, sample the current sense input at zero command, and confirm the drive enable output is off. Drives stay disabled and brakes stay engaged throughout, so a trial boot cannot restart into motion.
// Bootloader decision, Cortex-M example, simplified
bank_t select_bank(const metadata_t *a, const metadata_t *b)
{
if (b->state == PENDING && b->trial_count > 0 && image_valid(b)) {
b->trial_count--;
write_metadata(b); // persist the decrement
return BANK_B; // trial boot
}
return BANK_A; // confirmed or fallback bank
}
void confirm_boot(void) // called by the app after self-test
{
metadata_t *b = active_metadata();
b->state = CONFIRMED;
b->trial_count = 0;
write_metadata(b);
}If the new firmware hangs before confirm_boot(), the watchdog resets the board. The bootloader decrements the trial counter again. After three failed trials it boots bank A and leaves a failure code in a noinit section so the host can read why the rollback happened.
| Event | What the bootloader does | Result |
|---|---|---|
| Power cut during chunk download | Bank B has no valid metadata | Boots bank A, update can be retried |
| Power cut during metadata write | Metadata CRC fails, record ignored | Boots bank A |
| New firmware boots, encoder check fails | No confirm, trial counter decrements | Rollback to bank A after 3 trials |
| New firmware confirms | State becomes CONFIRMED | Bank B is now the permanent image |
Why not a single bank with a recovery image
A single-bank design uses all the flash for the application and keeps a small recovery bootloader that can accept a new image over serial. It is cheaper in flash and simpler to lay out. The failure mode is the power cut. If power drops while the single bank is being erased or written, the old firmware is gone and the recovery image is all that remains. The machine then needs a technician with a cable and a host tool to finish the update, which is exactly what you wanted to avoid on a remote machine.
Dual-bank flips that. The old image survives any interruption during download, because the write target is never the running bank. The price is the halved application space and the extra metadata handling. For a motion controller where a bricked board means a stopped line and a site visit, I would pay that price. For a low-cost sensor node where a technician can recover it over USB, the single-bank recovery design is often the better fit.
One limit is worth stating. Rollback only covers failures to boot and pass self-test. Once the new firmware confirms, a fault an hour later is not automatically rolled back, because it may be a worn connector or a mechanical fault rather than the update. That case goes through a controlled re-update instead of an automatic revert.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-85Walk me through open-loop versus closed-loop stepper control, and when would you stay with open-loop rather than pay for feedback?
The 90-second answer
Open-loop stepper control counts steps and assumes the rotor followed them. Closed-loop control measures the shaft with an encoder and corrects the difference. That one difference decides everything else: whether a stall is silent or detected, whether you can run close to the torque limit, and whether the position you report is a command or a measurement.
I would stay open-loop when the load is predictable, the motion stays well inside the pull-out torque curve, and a missed step would be caught by a homing switch or a process check. I would pay for closed-loop when the load varies, the axis must not lose position under a disturbance, or I need to prove position to a customer or a safety case.
How each loop works
In open-loop, the controller sends step pulses and direction. The driver energises windings in sequence. Position is steps_sent x step_angle. There is no term in that equation for load torque, friction, or a bumped axis. If the required torque exceeds what the motor can produce at that speed, the rotor slips poles and the count is wrong from that point on, with no error flag.
In closed-loop, an encoder on the motor shaft (sometimes on the load shaft) reports actual angle. The drive compares it with the commanded trajectory at, typically, 1 to 4 kHz and adjusts phase current, and in vector drives the current vector angle, to pull the rotor back. A stall then shows up as a growing following error, not as a lost count.
// Open-loop: position is an assumption
for (int i = 0; i < steps; i++) { pulse_step(); }
position = steps * STEP_ANGLE; // never measured
// Closed-loop: position is a measurement, corrected each cycle
while (moving) {
int32_t actual = encoder_count();
int32_t error = commanded_count - actual;
if (abs(error) > STALL_THRESHOLD) raise_fault();
drive_set_current(error * KP + feedforward);
}Worked figures
Take a common hybrid stepper: 1.8 degrees per full step, 200 steps per revolution, driving a 5 mm lead screw.
| Quantity | Calculation | Result |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| --- | --- | --- |
| Travel per full step | 5 mm / 200 | 25 um |
| Travel per 1/16 microstep | 25 um / 16 | 1.56 um nominal |
| Steps for a 50 mm move | 50 mm / 25 um | 2,000 full steps |
Microstepping smooths motion and reduces resonance, but it does not make the axis accurate to 1.56 um. Incremental torque per microstep is small, so the rotor can sit a fraction of a full step away from the commanded microstep position under load. That error is invisible open-loop. Closed-loop with a shaft encoder removes the following error, though it still cannot see backlash or lead screw error downstream of the shaft.
For torque margin, suppose the axis needs 0.4 Nm at the motor shaft at top speed, including acceleration and friction. A motor rated at 1.2 Nm holding torque at standstill may only deliver about 0.6 Nm at 600 rpm on a 24 V supply, because winding inductance limits current rise. Open-loop, I want at least 50 percent margin at the worst speed, so 0.4 Nm against 0.6 Nm available is already marginal. Closed-loop does not create torque the motor does not have, but it uses the available torque efficiently, boosts current only when error grows, and flags the stall instead of losing count.
| Open-loop | Closed-loop | |
|---|---|---|
| --- | --- | --- |
| Position source | Step count | Encoder |
| Stall behaviour | Silent loss of position | Detected, axis can recover or fault |
| Current at hold | Fixed, often full rated | Reduced when error is small |
| Running near torque limit | Risky, no warning | Workable, with stall margin monitored |
| Cost and wiring | Driver plus step/direction | Encoder, cable, drive complexity |
| Typical use | 3D printer gantry, simple pick and place, valve actuator with end switches | Medical stage, semiconductor handler, axis where a jam must be reported |
When open-loop suffices, and when it does not
Open-loop suffices when three conditions hold together. First, the torque demand stays below roughly half the pull-out torque across the whole speed range, checked from the motor torque curve at the actual supply voltage, not the holding torque headline. Second, nothing external can push the axis, such as a process force, a cable chain snag, or a hand on the stage. Third, the system re-references itself, for example homing to a limit switch at the start of each cycle, so any drift is cleared.
It fails in predictable ways. Accelerating too hard through a resonance band, often a few hundred rpm for a NEMA 23 size motor, causes missed steps that look like a random position offset. A load that changes with the workpiece, such as a gripper picking empty versus full, can stall only on the heavy cycle. Neither fault announces itself.
Closed-loop earns its cost when any of those conditions break. If the axis must hold position against a varying process load, if a stall must stop the cycle rather than scrap a part, or if the drive must run at high acceleration to meet cycle time, feedback is the difference between a fault code and a silent defect. It also helps at low speed, where a stepper can cog and vibrate, because the drive can damp the oscillation instead of exciting it.
One limit to state plainly: shaft feedback does not fix a loose coupling, a worn lead screw nut, or backlash in a gearbox. If the encoder is on the motor and the load moves through a compliant element, closed-loop on the motor can be perfectly in position while the tool is not. That is a mechanical design problem, and no control mode papers over it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-86Walk me through how you analyze a step response trace to identify gain, delay, resonance, and friction problems?
The 90-second answer
I read a step response in a fixed order: final value first, then delay, then shape, then repeatability at small amplitudes. That order separates the four problems because each one leaves a different mark on the trace.
Final value gives DC gain. If I command 10.00 mm and the axis settles at 9.20 mm, the closed loop gain is 0.92 and the 0.80 mm steady state error is a gain or integral problem, not a dynamics problem. Delay is the flat time before the output moves at all, measured from the command edge to the first sustained departure from baseline, for example past 2% of the step. Shape gives resonance: a decaying oscillation at a frequency that does not move when I change proportional gain points to a mechanical mode or a structural resonance in the mount, screw or load. Friction shows up only when I repeat the test at small amplitudes: a 0.05 mm step that produces no motion, followed by a jump when the command builds up, is stiction and deadband, not low gain.
Worked trace
Hypothetical trace, 10 mm step on a ball screw stage, sampled at 2 kHz:
| Metric | Measured | Reading |
|---|---|---|
| Command | 10.00 mm | Reference |
| Final value | 9.20 mm | DC gain 0.92, steady state error 0.80 mm |
| Pure delay | 18 ms to 2% | About 36 samples, too large for a 1 kHz loop alone |
| Rise time, 10 to 90% | 65 ms | Sluggish after the delay |
| Overshoot | 22% | 11.4 mm peak, since 9.20 + 0.22 x 10.00 = 11.40 |
| Ringing | 38 Hz, decays in about 120 ms | Fixed frequency, check mount and screw mode |
| Small step, 0.05 mm | No motion for 3 steps, then 0.11 mm jump | Stiction, stick slip |
| Repeat, same step | Final value varies by 0.06 mm | Friction variation, not encoder noise at 1 µm resolution |
The 18 ms delay matters because it eats phase margin. At 38 Hz, 18 ms is 246 degrees of phase lag, which is enough to turn a nominally stable loop oscillatory. That is why the overshoot and ringing appear together here. Fixing gain alone would not remove the ringing.
How I separate the causes
| Signature on trace | Points to | Confirming test |
|---|---|---|
| Final value off by a constant ratio at all amplitudes | Gain error, wrong encoder scale, wrong gear ratio or screw lead in firmware | Repeat at 2 mm and 10 mm, ratio should stay the same |
| Final value off only at small amplitudes | Friction, backlash, deadband | Sweep step size from 0.02 mm upward and plot motion versus command |
| Flat delay before any motion, then normal shape | Sensor filtering, communication delay, current loop lag, or a large deadband | Log command, drive voltage and encoder on the same time base |
| Ringing frequency unchanged when proportional gain is halved | Mechanical resonance | Tap test or FFT of the ringing, check mounting torque and belt or screw preload |
| Ringing frequency rises with gain and amplitude falls as gain falls | Loop instability from delay or derivative noise | Reduce gain, add derivative filtering, retest |
| Staircase motion, limit cycle around setpoint | Stiction plus integral action | Disable integral for one test, see if the cycle stops |
A short script makes the reading repeatable instead of eyeballing peaks:
import numpy as np
def step_metrics(t, y, y0, y_final, cmd_t=0.0):
step = y_final - y0
i0 = np.searchsorted(t, cmd_t)
def crossing(level):
idx = np.where(y[i0:] >= level)[0]
return t[i0 + idx[0]] if len(idx) else np.nan
t02 = crossing(y0 + 0.02 * step)
t10 = crossing(y0 + 0.10 * step)
t90 = crossing(y0 + 0.90 * step)
peak = np.max(y[i0:])
overshoot = (peak - y_final) / step * 100 if step else np.nan
return {
"dc_gain": step / 10.0,
"delay_ms": (t02 - cmd_t) * 1000,
"rise_ms": (t90 - t10) * 1000,
"overshoot_pct": overshoot,
}For this trace that script returns dc_gain 0.92, delay 18 ms, and overshoot 22%, matching the table. I run it on the large step and on a series of small steps. Gain error scales with amplitude. Friction does not. Resonance shows as a peak in the FFT of the detrended ringing segment, typically between 20 and 80 Hz on a stage with a long screw or a flexible coupling, and it stays put when I change the controller.
What I change first
For this trace I would not retune PID blindly. I would first check the 18 ms delay: encoder filter settings, drive communication cycle, and any software averaging on position. Then I would check the 38 Hz mode mechanically, because a 22% overshoot driven by a structural mode will return after any gain increase. Only then would I address the 0.92 gain, usually an integral term or a scale factor, and the stiction with preload, lubrication or a dither and friction feedforward check. Each change gets the same step test, so I can show whether delay, ringing or deadband actually moved.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-87Walk me through how you would design the fail-safe state of an actuator for power loss and for communication loss, and how you would prove it reaches that state without firmware running?
The 90-second answer
I start by refusing to define fail-safe in firmware. I define it per actuator, from the physics of what happens when energy disappears, then I make the safe state the state the hardware falls into with no code executing. Firmware and the communication timeout can only request motion. They cannot be the thing that creates safety.
For each actuator I answer three questions in order. What does it do on total power loss, with the driver unpowered and the controller dead. What does it do on communication loss, with power present but no fresh command. And what stored energy, gravity, spring force or backdriving can move it after either event. Only then do I choose the mechanism.
| Actuator | Power loss, hardware state | Communication loss, power present | Why this choice |
|---|---|---|---|
| Vertical servo axis, 10 kg load | Spring-applied, power-released brake engages, drive disabled | Same brake engages after heartbeat timeout, drive disabled | Gravity will backdrive an unbraked axis. A brake is the only state that holds without power. |
| Pneumatic clamp or gripper | Spring-closed clamp, or dump valve vents air and spring opens it | Dump valve vents, clamp goes to spring state | Air pressure is stored energy. De-energising a solenoid alone does not release a trapped volume. |
| Solenoid valve on a process line | Normally closed valve, spring shut | Normally closed valve shut after timeout | NC means the spring, not the coil, defines the safe state. |
| Horizontal stage with no gravity load | Drive disabled, axis free to coast to stop | Drive disabled, controlled stop if power and braking remain | Holding position wastes energy and can trap a fault. Coasting is safe if travel is guarded and no process force pushes it. |
The distinction matters because the two losses fail differently. Power loss removes the ability to brake actively, to vent a valve through a powered solenoid, or to run a controlled deceleration. Communication loss leaves power available, so I can do a controlled stop, but I must not trust the last command indefinitely. A stage that keeps executing a stale velocity command because the link died mid-move is a classic failure.
In hardware I wire that path so a hung microcontroller cannot hold it up. A window watchdog or an independent supervisor receives a heartbeat toggle, not a static level. If the toggle stops, or arrives too early or too late, the supervisor output falls. That output sits in series with the drive enable and in parallel with the brake release circuit, so the brake applies when the output falls. The same output drives a pneumatic dump valve. I do not route this through a GPIO expander or a fieldbus node that needs its own firmware to fail safe.
For communication loss I use command age, not just link presence. A CAN or Ethernet link can stay up while the application stops sending new setpoints. The drive or local controller timestamps the last valid, CRC-checked command with a sequence number. If the age passes the timeout, it discards the command and goes to the predefined state.
/* Checked in the 1 kHz local loop. Timeout is a design value, not a default. */
#define CMD_TIMEOUT_MS 250
if ((now_ms - last_valid_cmd_ms) > CMD_TIMEOUT_MS) {
drive_enable = 0; /* hardware gate, also forced by supervisor */
brake_release = 0; /* spring applies the brake */
dump_valve = 0; /* spring vents the clamp */
motion_state = SAFE_STATE;
}The 250 ms figure is chosen from the motion, not copied. At 0.5 m/s, 250 ms of stale velocity is 125 mm of travel. If the guarded travel margin is only 50 mm, the timeout must be under 100 ms, or the drive must ramp to zero within that window. I size it from worst-case speed, stopping distance and the distance to the nearest hazard, then add margin for one missed frame and the local loop period.
Power loss needs its own arithmetic because the brake does not act instantly. Take a hypothetical vertical axis where the brake takes 30 ms to engage after power disappears. In free fall for 30 ms the load drops 0.5 x 9.81 x 0.03 squared, about 4.4 mm, and reaches about 0.29 m/s. If the process allows only 2 mm of drop, a motor brake alone is not enough. I then need a counterbalance spring, a worm gear that self-locks, a mechanical pawl, or a brake on the load side with a shorter engagement time. I measure engagement time on the real brake at temperature, because a worn or hot brake can take twice the datasheet value.
I also check the ugly cases. A brake that releases on power-up before the encoder is valid can cause a jump. So the brake release is interlocked with encoder validity, drive ready and a deliberate operator reset, not with power-on reset alone. A normally closed valve fails safe on power loss but can still pass if debris holds it open, so for a hazardous line I use two valves in series with a monitored intermediate pressure, rather than trusting one spring. A spring-return pneumatic cylinder can slam when air dumps, so I add a flow restrictor and check the end-of-stroke impact force.
Proof is by fault injection, not by inspection. I pull the communication cable mid-move at full speed and record travel after the timeout. I cut the 24 V rail with an oscilloscope on the brake and drive enable and measure the drop distance over repeated trials. I freeze the controller with the debugger, halt the heartbeat, and confirm the supervisor still forces the safe state. I repeat the power cut at the worst position, highest load and lowest supply voltage, because that is where brake engagement and stopping distance are worst. If any trial moves past the hazard margin, the design changes. Firmware never gets a second chance to fix it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-88Your single-axis stage runs a 1 kHz velocity loop and a 10 Hz display update. How would you choose between bare-metal scheduling and an RTOS, and what would you measure to confirm the loop still meets its deadline?
The 90-second answer
For a single axis with one fast loop and one slow display task, I would start with bare-metal scheduling. A timer interrupt runs the 1 kHz velocity loop, and the main loop handles the display between interrupts. That gives the loop the smallest and most predictable delay. I would move to an RTOS only if the number of asynchronous tasks, blocking communications, or future features made the superloop hard to keep correct.
The deciding trade-off is determinism and simplicity against modularity. Bare metal has fewer moving parts to verify. An RTOS makes it easier to add tasks that block on a queue or a bus, but it adds kernel overhead, stack sizing, and priority inversion as failure modes I must then control.
Applying it to the stated stage
Assume a 168 MHz Cortex-M, a 1 kHz velocity loop with a measured worst-case execution time of 180 µs, and a display update that takes 3 ms but only needs to run at 10 Hz. The loop period is 1000 µs, so the loop uses 18 percent of the CPU. The display uses 3 ms every 100 ms, or 3 percent. Total utilisation is about 21 percent, which leaves margin for encoder reads and fault handling.
In bare metal, the timer compare starts the loop. The loop reads the encoder, computes velocity, and writes the drive command. The display code runs in the main loop and is split into small chunks so it never masks interrupts for long. If the display code needs to wait for a slow bus, it uses a state machine rather than a blocking delay.
// Bare-metal structure, 1 kHz timer interrupt on a Cortex-M
void TIM2_IRQHandler(void) {
GPIO_SET(DEBUG_PIN);
encoder_read();
velocity_loop(); // 180 us worst case, measured on hardware
GPIO_CLEAR(DEBUG_PIN);
}
int main(void) {
for (;;) {
display_update_chunk(); // runs between loop interrupts
fault_check();
}
}I confirm timing with a scope on the debug pin. The pulse width gives the loop execution time. The interval between pulses gives the period and the jitter. If the pulse width stays at or below 180 µs and the period stays at 1000 µs with jitter under 20 µs, the loop meets its deadline with margin. I repeat the measurement while the display is updating and while a fault is being logged, because those are the cases most likely to stretch the main loop.
| Point | Bare metal | RTOS |
|---|---|---|
| Loop release | Hardware timer to ISR, short fixed path | Task released by timer or kernel tick |
| Slow display task | State machine in main loop | Separate low priority task that can block on a queue |
| Shared data | Short critical sections or single writer | Mutexes, with priority inversion possible if a low priority task holds a lock |
| Adding a second axis or protocol | More state machines in main loop | Easier to add a task, but each task needs stack and deadline checks |
| Main risk | A long main loop section delays work or masks interrupts | A blocked or deadlocked task, or an undersized stack |
When the answer changes
If the display task grew into Ethernet, logging to flash, and a second axis, each with its own period, I would reconsider an RTOS. I would put the velocity loop in the highest priority task, release it from the hardware timer rather than the kernel tick, and give the other tasks lower priorities. I would then check response time for each task: execution time plus interference from higher priority tasks must stay below its deadline. For the display task, that means its 3 ms execution plus preemptions from the 1 kHz loop must stay below 100 ms.
I would also check the two failure modes that decide whether the RTOS version is safe. First, priority inversion: if the loop task ever waits on a lock held by the display task, a medium priority task can delay the loop. The fix is to keep critical sections short, avoid holding a lock across a flash write or bus transfer, and use priority inheritance where the kernel supports it. Second, stack overflow: I size each stack from the measured high water mark plus margin, and I ban dynamic allocation in the loop task.
For the application as stated, with one loop and one slow task, bare metal is the choice I would defend. It meets the 1 ms deadline with measured margin, and the display task is simple enough for a state machine. The RTOS becomes the better choice when task count and blocking I/O, rather than loop speed, become the main source of complexity.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-89A servo axis at a customer site trips on following error and you cannot visit: how would you use its current and position logs to tell a mechanical bind from an encoder fault, and what one test would you ask the customer to run next?
The 90-second answer
I would start from the two traces that separate the causes: motor current and encoder position, both against time and against position. A mechanical bind raises the torque the drive must produce at a repeatable position. An encoder fault corrupts the position the controller believes, so the drive produces normal torque while the reported position jumps or freezes. I would ask the customer for the last 10 seconds before the trip at the control rate, then ask for one slow jog through the suspect position.
What the logs should show
Assume a 1 kHz velocity loop and a following error trip at 0.5 mm. I need, per sample, commanded position, encoder position, following error, and phase current, plus the fault code and drive enable state. Without current, a following error trip is ambiguous. With current, the two hypotheses make opposite predictions.
| Signature | Mechanical bind | Encoder fault |
|---|---|---|
| Current at trip | High, often near the current limit, and rising before the trip | Near the normal value for that move |
| Position where current rises | Same position on every failed cycle, within the repeatability of the axis | No consistent position, or current stays flat while position jumps |
| Encoder position during fault | Smooth, lagging the command as the axis stalls | Step, dropout to zero, or frozen while command advances |
| After the trip | Axis stays stalled until cleared, current falls when the drive disables | Position may recover on the next index pulse or stay offset |
A worked trace makes the distinction concrete. Hypothetical figures, axis moving at 100 mm/s:
| Time (ms) | Command (mm) | Encoder (mm) | Current (A) | Reading |
|---|---|---|---|---|
| 0 | 120.0 | 120.0 | 1.2 | Normal cruise |
| 40 | 124.0 | 124.0 | 1.3 | Normal cruise |
| 80 | 128.0 | 127.9 | 2.8 | Current rising at 128 mm |
| 100 | 130.0 | 128.1 | 4.5 | Axis stalling, error growing |
| 120 | 132.0 | 128.2 | 5.0 | Trip, current at limit |
That pattern points to a bind at about 128 mm. If the same table showed current at 1.3 A throughout while encoder position jumped from 128.0 to 126.5 mm in one sample, the drive was not being asked for extra torque. The controller was reacting to a false position.
Why the mechanism differs
In a bind, friction or a misaligned guide adds a load torque. The current loop supplies it, so current rises while the encoder still reports true motion, which slows. Following error grows because the axis physically cannot keep up. In an encoder fault, the load torque is unchanged, so current stays normal. The controller sees a sudden position error, commands a correction, and may trip on following error or on a velocity limit. A cable fault often appears at one position because that is where the cable flexes. That overlap is why position alone cannot decide it. Current breaks the tie.
The one test I would ask for
I would ask the customer to jog the axis slowly, at 5 mm/s, through the position where current rose, with the drive in a mode that logs current and position, and to report the current at three positions: 10 mm before, at, and 10 mm after the suspect point. A bind shows a current peak only at the suspect position even at low speed, because friction is present regardless of speed. An encoder cable fault often disappears at low speed if the fault was a dropout during fast motion, or it shows a position jump at the same flex point. I would give the exact jog steps and ask them to stop if current hits the limit.
If the fault is intermittent, I would also ask how often it occurs. A fault once per 200 cycles needs about 600 cycles for a 95 percent chance of seeing it once, from 1 minus 0.998 to the power 600. Twenty clean cycles would not rule anything out, and I would say that plainly rather than accept a false negative.
What I would not do
I would not ship a tuning change based on a following error code alone. Lowering proportional gain can hide a bind for a week and then stall mid cycle with a part in the tool. I would ship containment only if the bind can damage the machine, for example a lower current limit or an earlier warning, and I would label it as containment while the jog test runs. The root cause fix follows the discriminating trace, either clearing the mechanical obstruction and checking alignment at that position, or replacing the encoder cable and connector and verifying the trace is clean at full speed.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-90How many encoder counts should fall across a positioning tolerance band, and what does that rule give you?
The 90-second answer
Aim for at least 5 to 10 encoder counts across the tolerance band. That rule is the one step check: divide the tolerance band by the number of counts you want inside it, and that gives the largest encoder step you can accept. If the encoder step is larger than that, the controller can be one count away from target and still report that it is there.
I would state the assumptions first. Tolerance here means the total allowable positioning error at the load, and I am sizing the encoder before budgeting backlash, screw error, thermal growth and servo following error. The 5 to 10 count rule is a starting margin, not a guarantee of accuracy. It keeps quantization from dominating the error budget.
Worked example
Suppose a linear stage must position to ±5 µm, so a 10 µm tolerance band, using a 5 mm lead screw and a rotary encoder with quadrature decoding.
lead_um = 5000 # 5 mm screw lead
tolerance_um = 10 # total band
counts_across_band = 5 # design margin
max_step_um = tolerance_um / counts_across_band
counts_per_rev_needed = lead_um / max_step_um
# Quadrature x4: counts_per_rev = 4 * pulses_per_rev (PPR)
ppr_needed = counts_per_rev_needed / 4
print(max_step_um, counts_per_rev_needed, ppr_needed)
# 2.0 2500.0 625.0So I need at least 2,500 counts per revolution, or 625 PPR with x4 decoding. A standard 1,024 PPR encoder gives 4,096 counts per revolution and a step of 5,000 / 4,096 = 1.22 µm. That puts about 8 counts across the 10 µm band.
| Encoder choice | Counts per rev | Linear step with 5 mm lead |
|---|---|---|
| 512 PPR, x4 | 2,048 | 2.44 µm |
| 1,024 PPR, x4 | 4,096 | 1.22 µm |
| 2,048 PPR, x4 | 8,192 | 0.61 µm |
| 2,048 PPR, x1 (no quadrature) | 2,048 | 2.44 µm |
The x1 row is the trap. Datasheet PPR is pulses per revolution before quadrature. If firmware only counts rising edges on one channel, you lose the factor of four and the step doubles twice over.
Direct linear encoder
With a linear scale the same rule applies without the screw. Resolution is travel divided by 2 to the power of the number of bits, or the datasheet interpolation step if that is finer. For a 100 mm scale with 20-bit output, 100,000 µm / 1,048,576 = 0.095 µm per count. That looks excellent on paper, but it does not give you 0.095 µm accuracy. Scale accuracy, mounting, Abbe error and thermal expansion will dominate, which is why I never quote encoder resolution as stage accuracy.
Failure modes I would check
Quantization is only one term. If the screw has 20 µm of backlash on reversal, a 1 µm encoder step will not fix repeatability. If the encoder is on the motor shaft before a gearbox, gear ratio helps resolution at the output, since output step is lead divided by counts per motor revolution times gear ratio, but it also reflects gear backlash and compliance to the load side. For a tight tolerance I prefer a load side encoder or a direct linear scale when the budget allows, and I verify the result by measuring actual position with an independent reference, such as a laser interferometer or a calibrated scale, over the full travel and in both directions.
Velocity is the other check. Finer resolution means more pulses at the same speed. At 0.5 m/s on a 5 mm lead, the screw turns at 100 rev/s. An 8,192 count per rev encoder then produces 819,200 counts per second, which the counter hardware and the velocity estimation window have to handle without missing counts. If that rate is too high, I would use a coarser encoder with a longer velocity counting window, or move to a linear scale, rather than just buying the highest PPR available.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-91Walk me through how you synchronize three axes on a coordinated move with different travel distances, so they start and finish together without exceeding any axis's velocity, acceleration or jerk limit?
The 90-second answer
I do not time each axis independently and hope they coincide. I generate one path parameter, usually arc length or a normalized coordinate s from 0 to 1, and one time law s(t) for the whole move. Every axis position is then a function of that same s: q_i(t) = q_i_start + (q_i_end - q_i_start) * s(t) for a straight coordinated move, or the inverse kinematics evaluated at s(t) for a curved path. Because all axes share s(t), they start together, finish together, and hold the programmed path shape. The time law is the slowest axis stretched to fit, so no axis exceeds its velocity, acceleration or jerk limit.
The steps are: compute the minimum time for each axis alone, take the maximum, stretch every faster axis to that time, then interpolate all axes from the same clock at a fixed period.
Worked example: three linear axes
Hypothetical limits, trapezoidal profile, no jerk limit for the arithmetic:
| Axis | Distance | vmax | amax | Minimum time alone |
|---|---|---|---|---|
| X | 120 mm | 200 mm/s | 1000 mm/s2 | 0.80 s |
| Y | 60 mm | 150 mm/s | 800 mm/s2 | 0.59 s |
| Z | 30 mm | 100 mm/s | 600 mm/s2 | 0.47 s |
For X: acceleration distance is vmax^2 / (2*amax) = 20 mm each end, so 80 mm cruises at 200 mm/s (0.40 s) plus 0.20 s accelerating and 0.20 s decelerating. Total 0.80 s. Y and Z finish sooner alone, so X sets the master time.
Stretch factor for Y is 0.80 / 0.59 = 1.36. Its peak velocity becomes 150 / 1.36 = 110 mm/s and peak acceleration 800 / 1.36^2 = 433 mm/s2. Z stretches by 0.80 / 0.47 = 1.70, giving 59 mm/s and 208 mm/s2. All limits hold with margin, and the ratio of axis positions stays fixed through the move, which is what keeps a straight line straight.
With jerk limits I use an S-curve time law instead of a trapezoid and apply the same stretch. Velocity scales by 1/k, acceleration by 1/k^2 and jerk by 1/k^3 where k is the stretch factor, so jerk is the first limit to gain margin and the last to be violated if I stretch incorrectly.
# Stretch each axis profile to the master time T_master
def stretch(t_min, T_master):
k = T_master / t_min
return {"k": k, "v_scale": 1.0 / k, "a_scale": 1.0 / k**2, "j_scale": 1.0 / k**3}
for axis in axes:
axis.profile = stretch(axis.t_min, T_master)
assert axis.profile["v_scale"] * axis.vmax <= axis.vmax
assert axis.profile["a_scale"] * axis.amax <= axis.amaxInterpolation and synchronization in the controller
The interpolator runs on a fixed timer, typically 1 kHz, and writes the next position setpoint for every axis in the same tick. Drives that support it receive these over a synchronized bus such as EtherCAT with distributed clocks, so the setpoint for Y is not applied 300 microseconds after X because a drive processed its mailbox late. If drives are standalone, I use a common step and direction pulse train or a shared clock input and verify the skew with a scope on the drive enable and encoder index signals.
Look-ahead matters at segment joins. I keep at least two or three segments queued so the interpolator can blend velocity through a corner or decide to stop. If the queue empties mid move, the interpolator must decelerate to zero on the current segment rather than jump to the next segment start. That underrun is a classic cause of a visible dwell and a path deviation on a dispensing or laser cut move.
Failure modes I check for
Payload changes after the profile was computed. A gripper picks up a 5 kg part, Y now needs more torque and its following error grows while X tracks cleanly. The path is still synchronized in setpoint, but actual contour error appears. I monitor following error per axis and contour error, the perpendicular distance from the actual tool point to the programmed path, and abort or feed-hold if contour error exceeds a threshold such as 50 micrometres on a precision move. Feed-hold must decelerate along the path, using the same s(t) in reverse, not stop each axis independently.
One axis saturating mid move. If a drive hits its current limit, its actual position lags and the other axes keep going, so the tool leaves the path. Detection is a following error or drive fault flag per axis, and the response is a coordinated stop on s, then a replan with a lower master time or a reduced payload assumption. Independent axis stops would leave the tool in an unknown position relative to the path.
Interpolation jitter. If the interpolator task misses its 1 ms deadline, one tick repeats the previous setpoint and the next tick jumps by two steps. On a 200 mm/s move that is a 0.2 mm step in setpoint, which the servo turns into a torque spike. I measure worst case execution time and jitter of the interpolator task, and I log a counter for missed ticks during commissioning runs at full speed.
Singularity or a path that cannot be tracked at the programmed feed. On a robot arm, s(t) is evaluated through inverse kinematics, and near a wrist singularity a small change in Cartesian position demands a large joint velocity. The joint limit then becomes the master limit. I check joint velocity and acceleration along the whole path before the move, not just at the endpoints, and I slow the time law where the Jacobian condition number rises.
Validation is a dry run at reduced feed with encoders logged at the servo rate, then a full speed run measuring start and finish times per axis, peak following error, and contour error from a linear scale or laser interferometer on the tool point. If the axes finish within one interpolation tick of each other and contour error stays inside budget, the synchronization is proven on that machine, not just in the planner.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-92Your board will not connect to the debug probe and the bootloader will not run after a flash write: how do you debug that chain step by step?
The 90-second answer
I separate the chain into three links and test each one in order: power and reset, the probe link, then what is actually in flash. A probe that cannot connect is usually not a bootloader bug, and a bootloader that will not run is usually not a probe bug. I start with the board powered from a current-limited supply, motor driver disabled, and I measure before I attach anything.
First, rails and reset. I check VDD at the MCU pins, not at the regulator output, check that NRST is high and not held low by the probe or a supervisor, and check that the main clock source is present. On many STM32 and similar parts, SWD needs VTref, GND, SWCLK, SWDIO, and NRST. If VTref is missing the probe sees no target. If the chip is in a low power state or BOOT pins select system memory, the probe may connect but the user flash will not run.
Second, the probe link. I try a low SWD clock, for example 100 kHz instead of 1 MHz or 4 MHz, and I connect under reset. That matters when the firmware has already run and reconfigured the debug pins, disabled SWD, or entered stop mode. I also check for readout protection or option bytes. On STM32, RDP level 1 blocks flash readout and can block debug, and RDP level 2 is effectively one time programmable. A failed connect after a flash write often means the option bytes changed, not that the cable failed.
Third, flash contents. I read the first words of the image and compare them with the linker script. The first word must be a valid initial stack pointer inside SRAM, and the second word must be the reset handler address inside flash. If those are wrong, the core will fault on reset before any bootloader code runs.
/* Checked against a Cortex-M4 image linked at 0x08000000, SRAM at 0x20000000 */
#include <stdint.h>
#define FLASH_BASE 0x08000000u
uint32_t sp = *(volatile uint32_t *)(FLASH_BASE + 0);
uint32_t reset = *(volatile uint32_t *)(FLASH_BASE + 4);
/* sp must be 8-byte aligned and inside SRAM, reset must be odd (Thumb) and inside flash */If the vector table is correct but the bootloader still does not run, I check VTOR, the boot pin state, and whether the bootloader jumps to the application by setting the stack pointer and vector table before branching. A common failure is jumping to the application without resetting MSP, so the application starts with the bootloader stack.
| Symptom | Check | Interpretation |
|---|---|---|
| Probe reports no device | VTref, GND, NRST, SWCLK, SWDIO continuity and 100 kHz connect under reset | Wiring, power, reset held low, or target in low power |
| Probe connects, flash verify fails | Read back first 16 bytes and compare with the binary | Wrong base address, wrong binary, or flash not erased |
| Probe connects, flash verifies, no run | Read SP and reset vector, check BOOT0 and BOOT1 | Bad vector table, wrong boot source, or option bytes |
| Probe connects only after pressing reset | Firmware disables SWD pins or sleeps | Connect under reset, then fix pin remapping in firmware |
| Works on bench, fails on machine | Measure VDD and NRST during motor enable and E-stop chain | Brownout or reset from the machine power chain, not the image |
The failure modes I see most often on mechatronics hardware are specific. A board that worked on the bench fails on the machine because the 24 V rail dips when the drive enables, the MCU browns out, and the bootloader restarts into a half written image. I detect that with a scope on VDD and NRST triggered on the dip, not with a debugger. Another is a bootloader that erases the application sector and then loses power. That is why I use a dual bank or a trial boot with a confirmation counter on field updates, and why I never erase the only copy of a working bootloader in place.
For flash programming itself, I always do erase, program, verify, then reset. Verify is not optional. If verify fails at a fixed address, I check write protection, the flash base in the programmer config, and whether the binary was linked for the other bank. If verify fails randomly, I check supply during the write, because flash charge pumps are sensitive to rail droop.
I finish by leaving the board in a state I can recover. That means BOOT pins accessible, NRST accessible, and a known good image stored off board. If I cannot connect under reset at 100 kHz with correct VTref, I stop debugging software and fix hardware.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-93How would you review a junior engineer's motor driver and control code before it runs on a servo axis, and how would you mentor them through the fixes?
The 90-second answer
I review driver and control code in three passes, and I mentor through the first two. Pass one is safety and timing: can this code energise an actuator, miss a deadline, or corrupt shared state. Pass two is correctness on hardware: units, scaling, saturation and fault handling. Pass three is clarity: names, comments and structure that let the next engineer change it. I do not rewrite the junior's code for them. I mark the line, ask what they expected the hardware to do, and let them propose the fix. Then we prove it with a trace or a bench test, not with my opinion.
Pass one: safety and timing
For a motor driver I start at the outputs. What happens on reset, on a sensor fault, on a missed deadline. Is the enable pin defaulted off in hardware, does the code clear it before it touches the PWM registers, and does a watchdog or fault input force a safe state without firmware running. I check every shared variable between ISR, DMA and main loop. A 32-bit encoder count read in the main loop while a 1 kHz ISR writes it needs a critical section or an atomic read on that core. volatile alone stops the compiler caching it, it does not stop a torn read.
I also check what runs in an ISR. This pattern fails review:
// 1 kHz ISR: blocks on I2C, allocates, prints
void TIM1_UP_IRQHandler(void) {
encoder_count = read_encoder();
i2c_write(SENSOR_ADDR, buf, 4); // can block for ms
pid_update();
}The fix I ask them to write is to keep the ISR to capture, clear the flag and set a flag for the task, and move I2C and logging out. We then measure worst-case execution time with a GPIO toggle and a scope, and jitter against the 1 ms period. If the ISR plus the servo task exceed the deadline, no tuning discussion matters yet.
Pass two: correctness on hardware
I look for magic numbers without units, integer scaling that overflows, and saturation handled in one place. A velocity setpoint in rpm converted to counts per sample needs the encoder resolution, sample period and gear ratio stated at the conversion, not buried in a gain. I ask for the arithmetic in a comment: counts_per_sample = rpm * CPR * 4 / (60 * 1000) for a 1 kHz loop. Then I check the limits: output clamped to the drive voltage, integral clamped or frozen when saturated, derivative on measurement if the setpoint steps, and a fault latch that requires an explicit reset rather than auto-restarting into motion.
| Pass | Check | Evidence I ask for |
|---|---|---|
| Safety | Enable default off, fault forces safe state, no blocking in ISR | Scope trace of enable on reset and on fault |
| Timing | WCET and jitter inside the control period | GPIO toggle timing at 1 kHz, worst case over 10 s |
| Scaling | Units, fixed-point range, overflow | Worked conversion for min and max input |
| Saturation | Output and integral limits, anti-windup | Step response with and without a large step |
| Faults | Sensor timeout, overcurrent, limit switch | Fault injection log, not just code reading |
Mentoring in practice
I assign the driver in slices they can finish in a day: register setup and a scope trace first, then readback with a known input, then the control update. Each slice ends with a test they run on the bench, with the expected trace written before they run it. In review I use questions in order of risk. What does the hardware do if this function never returns. What value does this variable hold at 20,000 rpm in counts per sample. Show me the trace where the output saturates. If they cannot answer, that is the next task, not a defect to fix for them.
I also separate style from substance. Naming and formatting I leave to the linter and a formatter, so review time goes to timing, scaling and failure modes. When I do rewrite a section, I show the diff and explain the one mechanism behind it, for example why derivative on measurement removes the setpoint kick but adds noise sensitivity, and we measure both on the stage.
The outcome I want is a driver they can defend: they know its timing budget, its scaling limits, and exactly how it fails safe. That matters more than clean code on the first submission.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-94How do you decide whether a fault should be fixed in hardware, firmware, or mechanics?
The 90-second answer
I assign the fault to the layer that the evidence follows when I change one thing at a time. If the fault follows a swapped part, it is hardware. If it follows a command, a timing event or a software state, it is firmware. If it follows position, load or direction, it is mechanics. I do not start by rewriting code or stripping the machine. I start with a test that can move the fault.
Three cheap tests usually settle it. First, reproduce it with logging on: command, encoder position, motor current, supply voltage and fault flags on the same time base. Second, bypass one layer: drive the motor from a bench supply or jog it by hand with the controller disconnected, or run the same firmware against a simulated encoder. Third, swap or substitute: another cable, driver, sensor or a known good firmware build. The layer that changes the behaviour owns the fix.
| Evidence | Points to | Confirming test |
|---|---|---|
| Fault moves with a swapped cable, sensor or driver | Hardware | Fault disappears on the known good part and returns when the suspect part is refitted |
| Fault appears at a fixed time after a command, mode change or buffer fills | Firmware | Log shows the trigger, and a fixed or older build changes it without any hardware change |
| Fault appears at the same axis position, on reversal, or under load | Mechanics | Current rises and following error grows at that position, and hand movement feels stiff or gritty there |
| Fault appears only when the drive switches or the supply sags | Hardware, usually power or grounding | Scope shows a voltage dip or spike coincident with the fault, and a bench supply removes it |
A worked trace makes the call concrete. Suppose a stage stalls mid travel. The log shows position frozen, current at 4.2 A against a 1.1 A running current, and no firmware fault flag. The stall always happens 38 mm from home, in both directions, and the axis is stiff to move by hand at that spot. That pattern follows position, not a command or a part. I would check the guideway, belt tension and any cable carrier pinch at 38 mm before touching the PID gains. If instead the stall happened 200 ms after every direction change regardless of position, with normal current, I would look at the firmware state machine and the reversal logic.
The bypass test is the tie breaker when logs are ambiguous. Power the actuator directly and move the axis through the suspect region. If it still binds, firmware is innocent. If it runs cleanly, the fault sits in the controller, its wiring or its code. Likewise, feed the controller a recorded encoder trace from a good run. If the controller still faults, the problem is downstream of the sensor. If it behaves, the sensor or the mechanics feeding it are suspect.
Two failure modes catch people out. The first is fixing firmware to mask a mechanical bind, for example raising the current limit or the following error tolerance until the axis pushes through. The machine then passes a short test and wears the guideway faster. The second is replacing hardware for a firmware timing fault, because a new driver happens to power up slower and hides a race. Both are detected by asking whether the fix changed the evidence or just moved the threshold. A real fix makes the original reproducing test pass with the original limits, on the original part, after a cold restart and a full travel run.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-95Walk me through how you would design a precision servo stage for manufacturability, calibration and serviceability, from first assembly to a field swap?
The 90-second answer
I would design the stage as three field-replaceable units with one mechanical datum, a built-in calibration artifact, and a stored per-unit parameter set. The motor and encoder form one cartridge, the linear guide and carriage form a second, and the controller forms a third. Assembly needs no selective fitting, calibration runs from firmware without a technician adjusting pots, and a swap means unplugging two connectors, fitting dowels, and re-running a five-minute routine. If any of those three needs a shim, a screwdriver adjustment, or a laptop-only tool, the design has failed.
Take a worked example, with hypothetical figures: 200 mm travel, 1 µm repeatability target, 10 kg payload, ball screw with a 5 mm lead. The decisions below come from trying to build that axis 500 times a year, not once.
Manufacturability: remove adjustment from assembly
Put the encoder and motor on a common machined plate, then align that plate to the screw shaft with two dowels and a spigot bore. The spigot sets concentricity, the dowels set clocking. No slotted holes, no "tighten while watching the dial indicator." The guide rail sits on a ground flat with a machined edge as datum, located by dowels in the base casting. Fasteners are all one size per subassembly, captive where a technician would otherwise drop one into the screw.
Tolerance stack decides whether that works. Suppose the tool point error budget is 25 µm, with four contributors each allocated 10 µm in this example: rail straightness, screw lead error, encoder eccentricity, and carriage play. Worst case sums to 40 µm and fails. Root-sum-square gives sqrt(10² + 10² + 10² + 10²) = sqrt(400) = 20 µm, which passes with margin for thermal growth. I design to the RSS number and verify with a sample of 20 assemblies measured on a CMM, because a single hand-built prototype hides the distribution.
Connectors carry the same thinking. Power, encoder, and limit switches use keyed, locking connectors rated for 50 mating cycles, not bare wires soldered at the factory. A harness that needs soldering in production will be soldered differently on unit 400 than on unit 1.
| Decision | Manufacturing effect | Calibration effect | Service effect |
|---|---|---|---|
| Dowel plus spigot alignment | No selective fitting, 12 min assembly in this example | Encoder offset repeatable to under 2 µm after swap | Cartridge swap without re-machining |
| Keyed connectors, one harness per unit | Harnesses pre-tested as assemblies | Wrong connection is physically impossible | Swap needs no soldering iron |
| Captive fasteners, single torque spec | Torque audit by tool setting | No preload change from a lost fastener | No dropped hardware in the screw |
| Test pads and a service UART on the controller | End-of-line test without opening the enclosure | Calibration data written over the same port | Fault codes read on site |
Calibration: designed in, not bolted on
Calibration needs a reference the machine carries with it. I would fit a reference scale or a known gauge block position at one end of travel, plus the encoder index pulse. The routine homes to the index, moves to the reference, and fits two parameters: encoder offset and scale factor. A two-point fit corrects gain and offset. It leaves periodic error from screw lead variation and encoder eccentricity untouched, so I state that residual in the spec instead of pretending the fit removed it. In this hypothetical example, acceptance against a laser interferometer might show about 4 µm peak residual over 200 mm; that number would come from measurement, not assumption.
Parameters live in non-volatile memory as a versioned record, tied to the serial number of the cartridge. If the cartridge is swapped, the old record is invalid and the controller forces a recalibration before motion is enabled.
# Example calibration record (illustrative values, not measured data)
record = {
"serial": "AX-1042",
"encoder_offset_counts": 18342,
"scale_ppm": 12.4, # correction to nominal counts per mm
"reference_pos_counts": 401120,
"temp_c_at_cal": 21.5,
"residual_um_pk": 4.1, # example only; verify by interferometer
"schema": 3,
}The routine also logs the raw counts at the reference before and after the fit. A drift of more than 3 µm between monthly self-checks in this example flags the axis for inspection, which catches a loosening encoder coupling months before repeatability fails in production.
Serviceability: mean time to repair as a design target
I set a target of 20 minutes for a motor or encoder swap with hand tools, and I design the fault tree to match. The controller reports a specific code, for example encoder signal lost, following error above 0.5 mm for 200 ms, or limit switch open, each with the last 10 seconds of position and current logged. A technician reads that code, swaps one unit, and runs the calibration routine. For wear items, I would write a design requirement, for example that the selected screw nut and wipers must have a vendor datasheet life of at least 20 million cycles under the stated load and speed, and I would set an inspection interval at a fraction of that rated life. I would not quote a life figure for a real component without that datasheet. Belts, if used, are tensioned by a spring idler so replacement needs no tension gauge.
The trade-off I accept: dowels and spigots cost more to machine than slotted holes, and a reference artifact adds a part. That cost buys a machine a field engineer can return to specification without a CMM or a laser tracker. For a product built in volume and serviced away from the factory, that is the cheaper system.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-96How would you measure and specify latency, jitter and determinism for a safety-related 1 kHz control loop, and what limits would you put in the safety case?
The 90-second answer
For a safety-related loop I specify worst-case values measured on the target hardware, and I design the safe state for a missed deadline. Average latency tells you nothing about the cycle that runs late during a fault.
Take a 1 kHz velocity loop. I define three separate numbers. Latency is time from the sample captured at the timer tick to the PWM update that acts on it. Jitter is the maximum deviation of the control period from 1.000 ms. Determinism is a proven bound that every cycle finishes before its deadline, measured from tick to PWM update, under worst-case load. End-to-end latency from an asynchronous sensor event can exceed one period without missing that deadline, because the event may just miss a tick and wait for the next one. I keep those two figures apart in the specification.
How I measure it
I toggle GPIOs at ISR entry and after the PWM write, and capture both edges with a scope or logic analyzer on the real board under load. A cycle counter gives execution time without printf in the loop.
// Cortex-M, checked on STM32H7 at 480 MHz
void control_isr(void) {
uint32_t t0 = DWT->CYCCNT;
GPIOA->BSRR = GPIO_PIN_0; // high: ISR entry
float v = read_velocity();
float u = pid_step(v);
write_pwm(u);
GPIOA->BSRR = (uint32_t)GPIO_PIN_0 << 16; // low: done
log_cycle(t0, DWT->CYCCNT - t0); // histogram later, no printf here
}I run this for at least 24 hours with the encoder ISR, fieldbus stack, logging and fault injection active, because the worst case usually comes from a lower priority task blocking a shared bus. I record period, execution time and tick-to-PWM latency as histograms and report the maximum observed value, then add margin. I also do static response-time analysis: worst-case response time is the task WCET plus interference from every higher priority ISR that can preempt it in that window. If analysis and measurement disagree, I trust neither until I find the missing interference.
Worked budget for this loop
Assume a 1 ms period, a 250 µs encoder ISR costing 90 µs, and a control task costing 180 µs. These are hypothetical figures for the worked example.
| Stage, from tick | Worst case | Notes |
|---|---|---|
| Encoder ISR interference | 90 µs | One preemption per period |
| Control computation | 180 µs | Measured WCET, not mean |
| Wait for PWM update | 500 µs | PWM at 2 kHz, update on next edge |
| Tick to PWM update | 770 µs | Deadline 1000 µs, margin 230 µs |
Separately, an asynchronous sensor event that arrives just after a tick waits up to 1000 µs for the next sample, so worst-case event-to-actuator latency is 1770 µs. That does not miss the tick-to-PWM deadline. I specify both: tick-to-PWM no worse than 800 µs, event-to-actuator no worse than 1.8 ms, period jitter no worse than ±10 µs.
Jitter and delay cost phase margin. At a 50 Hz velocity crossover, 0.77 ms of tick-to-PWM delay costs 360 × 50 × 0.00077 = 13.9 degrees. The full 1.77 ms event-to-actuator figure is not the right number for loop phase, because the loop acts on sampled data at the tick rate. If the design has 45 degrees of phase margin before delay, 13.9 degrees leaves about 31 degrees. If that is too thin, I raise the sample rate, synchronise the PWM update to the ISR, or lower the crossover.
What goes in the safety case
I write testable limits: period 1.000 ms with jitter no worse than ±10 µs, control WCET no worse than 200 µs under maximum bus and ISR load, tick-to-PWM latency no worse than 800 µs, and a deadline miss detected by a window watchdog and a hardware timer not started by the control task. Safe Torque Off is defined in IEC 61800-5-2, but its response time is not fixed by that standard. I take the maximum STO response time from the specific drive datasheet, verify it by test with firmware halted, and write that measured figure into the safety case rather than assuming a value. Determinism comes from fixed-rate timer scheduling, bounded ISRs, no dynamic allocation in the loop, short critical sections on shared data, and double buffering for DMA so a half-written sample is never used. An RTOS is acceptable only if its tick and scheduling jitter fit inside the ±10 µs budget and are measured the same way. If jitter grows when logging or diagnostics run, those features move to a lower priority or get a strict time budget, because a safety loop that is deterministic only when idle is not deterministic.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-97Eight weeks before delivery, a customer asks to replace a 0-10 V pressure sensor with a 4-20 mA one on a nearly finished stage. How would you check if it is a drop-in change and what would you update?
The 90-second answer
I would treat it as a small interface change, not a drop-in part swap, until the numbers prove otherwise. A 0 to 10 V sensor and a 4 to 20 mA transmitter both carry pressure, but they differ in scaling, fault detection, wiring and what the ADC actually sees. I would freeze the current calibration, work through those differences on paper, prototype the new loop on the bench, and only then update drawings, firmware and tests.
Start with the electrical interface. A 4 to 20 mA loop needs a burden resistor to become a voltage for the ADC. With the common 250 ohm resistor, 4 mA gives 1 V and 20 mA gives 5 V. That fits a 0 to 5 V ADC input directly, which is convenient, but it uses only part of the ADC range and it puts the live zero at 1 V. I would check the burden power first. At 20 mA, dissipation is I squared R, so 0.0004 times 250, or 0.1 W. A quarter watt part runs hot in a sealed cabinet, so I would use at least 0.5 W or two 500 ohm resistors in parallel.
Then check resolution in engineering units. On a 12-bit ADC with a 5 V reference, one count is about 1.22 mV. The pressure span occupies 4 V, from 1 V to 5 V, so the span uses roughly 3277 counts. If the sensor is 0 to 10 bar, that is about 0.003 bar per count. I would compare that with the tolerance band. If the spec needs 0.01 bar resolution, this passes with margin. If it needed 0.001 bar, the change would force a higher resolution ADC or a different burden value, and it would stop being a minor change.
| Item | 0 to 10 V sensor | 4 to 20 mA transmitter | What to verify |
|---|---|---|---|
| Signal at ADC | 0 to 10 V, needs divider for 5 V ADC | 1 to 5 V across 250 ohm | Input range, burden power, common mode |
| Zero and span | 0 V at zero pressure | 1 V at zero pressure, 4 mA live zero | Firmware scaling and calibration points |
| Fault detection | Open wire reads 0 V, same as zero pressure | Below about 3.6 mA means open or failed loop | Fault threshold and alarm behaviour |
| Wiring | 3 wire, sensor powered separately | 2 wire loop powered, polarity matters | Loop supply, cable screen, connector pinout |
| Dynamics | Response time from old datasheet | Often slower, check t90 | Step test against control loop expectations |
Firmware changes are mostly scaling and fault handling, but they need a bench test with known pressures. The conversion should clamp and flag out of range values rather than silently saturate.
// 12-bit ADC, 5 V reference, 250 ohm burden, 0 to 10 bar sensor
// Checked against a bench supply and hand pump with a reference gauge.
#define ADC_COUNTS 4096.0f
#define VREF 5.0f
#define BAR_MAX 10.0f
float pressure_bar(uint16_t adc, bool *fault)
{
float volts = (float)adc * VREF / ADC_COUNTS;
float ma = volts / 250.0f * 1000.0f; // 4 mA at 1 V, 20 mA at 5 V
*fault = (ma < 3.6f) || (ma > 21.0f);
float bar = (ma - 4.0f) / 16.0f * BAR_MAX;
if (bar < 0.0f) bar = 0.0f;
if (bar > BAR_MAX) bar = BAR_MAX;
return bar;
}I would calibrate at zero, mid span and full span, then repeat the zero after a warm up. The old sensor may have had a different temperature drift, so a single point check is not enough. I would also run a step in pressure and compare the transmitter response with the old sensor. A transmitter with a 100 ms response where the old part had 10 ms will look like a tuning problem in the loop, with extra phase lag and a tendency to oscillate. That is the point where I would tell the customer the change affects control behaviour, not just wiring.
The decision then has two credible paths. Accept the change and absorb the updates to the wiring diagram, BOM, firmware constants, calibration certificate and test script, with a measured schedule cost. Or keep the 0 to 10 V sensor for this delivery and schedule the 4 to 20 mA loop for the next revision, where the harness and loop supply can be designed properly. I would present both with the bench results attached. If the prototype meets spec with margin, the first path is usually cheaper. If resolution, response time or loop power fails, the second path protects the delivery date.
What I would not do is swap the part, adjust one scaling constant until the display looks right, and ship. That misses the open wire fault, the burden heating and the dynamic lag, and all three show up at the customer site rather than on the bench.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-98Walk me through how you use version control, simulation, and automated tests for embedded control firmware?
The 90-second answer
I treat firmware like any other control code: every change is in Git, every build is reproducible from a tagged commit, and no commit reaches the machine unless it passes host tests and a simulation run in CI. On a servo axis that means I can answer which exact source built the binary on a customer machine, replay a fault in simulation, and catch a PID or state machine regression before it becomes a following error on hardware.
Git is the record. I use short lived feature branches off main, one branch per axis or driver change, and merge with a review that checks the diff, the test results and the timing budget. Releases are annotated tags such as v2.4.1-stageA that point at a commit plus the toolchain version, compiler flags and board revision. The binary is built in CI from that tag, never from a laptop, and the tag, commit hash and CRC are embedded in the firmware so version over the debug console reports them. If a stage trips in the field I pull the log, check the hash, and check out that exact tree locally.
Simulation sits between unit tests and hardware. I keep the control law in a hardware independent module, so the same C code runs on the target and in a host simulation with a plant model for motor, load and encoder. That is software in the loop. For a new axis I model inertia, friction and a 1 kHz loop delay, run the step and trajectory profiles I expect on the machine, and check overshoot, settling and saturation before I enable a driver. Hardware in the loop comes later, with the real controller driving a simulated plant through its actual PWM and encoder interfaces.
Automated tests run on every push. Unit tests run on the host with the HAL mocked. Integration tests run the full loop in simulation. A small set of on target tests runs on a bench board in CI when a rig is free. A failure blocks the merge.
// test_pid.c, built on the host with gcc and Unity, no hardware needed
#include "unity.h"
#include "pid.h"
void test_integral_does_not_wind_up_when_saturated(void) {
pid_t pid;
pid_init(&pid, 2.0f, 0.5f, 0.0f, -10.0f, 10.0f); // Kp, Ki, Kd, out limits
float out = 0.0f;
for (int i = 0; i < 1000; i++) {
out = pid_step(&pid, 5.0f, 0.0f, 0.001f); // large step, plant stuck at 0
}
TEST_ASSERT_EQUAL_FLOAT(10.0f, out);
TEST_ASSERT_TRUE(pid.integral <= 20.0f); // clamped, not 2500
out = pid_step(&pid, 0.0f, 0.0f, 0.001f);
TEST_ASSERT_TRUE(out < 10.0f); // recovers promptly once error clears
}That test fails on the first version of a PID I wrote with an unclamped integral. It passes now, and it runs in under a second in CI, so a later refactor that breaks anti windup is caught before a bench run.
| Level | Runs where | What it catches | What it misses |
|---|---|---|---|
| Unit test | Host, mocked HAL | PID maths, state machines, CRC, scaling, limit logic | Timing, noise, real sensor behaviour |
| Simulation, SIL | Host, plant model | Overshoot, saturation, trajectory tracking, fault response | Model error, wiring, EMI |
| Hardware in the loop | Bench controller, simulated plant | ISR timing, encoder decoding, driver interface, watchdog | Real mechanics and load |
| On target test | Bench machine | Full loop on real hardware | Customer load and environment |
The failure modes I watch for are specific. A test that only runs on my laptop hides a toolchain difference, so CI builds with a pinned container image and the same flags as the release. A simulation that uses a perfect plant hides friction and backlash, so I add a friction term and a dead zone to the model and compare the simulated step response against a measured one from the bench. A mocked HAL hides a race between ISR and main loop, so the HIL rig runs the real 1 kHz ISR and I check jitter with a scope on a GPIO toggle. If a test is flaky I quarantine it with a ticket and a log capture rather than deleting it, because a flaky timing test on a control loop usually points at a real deadline problem.
When not to use this setup: for a one off prototype on a bench, a full HIL rig is overkill and a scripted bench test plus a tagged Git commit is enough. The cost that stays is the tagged, reproducible build. Without it I cannot prove what is running on a machine that is moving a load.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-99Walk me through how you would present a trade-off between performance, cost and schedule to a product team for a new precision stage?
The 90-second answer
I would present three buildable options, not one recommendation with a price. Each option gets the same four numbers: measured or specified performance against the customer spec, unit cost at a stated volume, non-recurring cost, and a schedule with the long-lead part named. I then show what each option gives up in terms the product team can price, such as cycle time and scrap, with the customer model stated separately from our manufacturing cost.
The figures below are a hypothetical worked example, labelled as such, to show the format. I would replace them with bench data before a real decision.
| Option | Architecture | Repeatability | Unit cost at 500 machines/yr | NRE | First article |
|---|---|---|---|---|---|
| A | Ball screw, servo, optical linear encoder | 0.4 µm specified | $2,850 | $180k | 26 weeks |
| B | Ball screw, servo, rotary encoder only | 1.8 µm specified | $1,950 | $95k | 18 weeks |
| C | Belt, closed-loop stepper, rotary encoder | 4.5 µm specified | $1,150 | $55k | 12 weeks |
Against a 1 µm repeatability spec, B and C are non-compliant on paper. I mark them as such instead of letting the team carry them as if they pass. That turns the discussion into a real choice: pay for A, or relax the spec and accept B.
Making the customer cost visible
Unit cost is per machine. Throughput and scrap are per part the customer makes, so I keep them in a separate customer model and do not net them against unit cost unless product agrees a price premium.
Hypothetical customer model, assumptions stated: 16 hours per day, 250 days per year, part cycle 60 s with option A and 68 s with a slower stage. Capacity is 3600/60 × 16 × 250 = 64,000 parts per year for A, and 3600/68 × 16 × 250 = 52,941 for the slower option. The difference is 11,059 parts per year of capacity. At a $20 contribution margin per part, that capacity is worth $221k per year to the customer if demand exists to fill it. If demand does not exist, the value is zero, and I say so.
Scrap is simpler. If repeatability slipping from 0.4 µm to 1.8 µm raises scrap from 0.2% to 2.0% on a $400 assembly, the extra scrap is 1.8% × $400 = $7.20 per part. At 10,000 parts per year that is $72k per year. Again, that is customer value, not a direct saving on our bill of materials.
Assembly and calibration time belongs in our cost. A $40 encoder that needs 40 minutes of alignment per machine, versus a $90 absolute encoder that self-calibrates in 5 minutes, adds 35 minutes per machine. At 500 machines per year that is 292 hours. At a loaded $75 per hour for labour and test, that is about $22k per year, which narrows the apparent $50 parts saving.
Schedule as a dated critical path
I break the schedule into design freeze, long-lead order, prototype build, and validation. In this example the ground ball screw and optical encoder are 14 weeks lead, so they set the date. Ordering them at week 2, before the bracket is final, and accepting one bracket rework, pulls first article from week 26 to about week 22. I show that as a separate decision: spend roughly $12k on early hardware to buy 4 weeks, with the risk that the bracket changes.
What goes on the page
One page per option, same layout: drawing, repeatability trace from the bench, cost breakdown by motor, drive, encoder, screw, machining and assembly minutes, and a Gantt bar naming the critical part. I also name supply risk. If option A depends on one encoder supplier, I quote the second source, its unit price, and the requalification time, rather than leaving that as a surprise after the decision.
I close with a conditional recommendation and a decision date. For example: recommend A if the customer model above holds and product can capture part of the $221k capacity value in price, because the $900 per machine delta over B is $450k per year at 500 machines and needs that customer value to justify it. If volume is lower or demand cannot fill the extra capacity, recommend relaxing the spec to 2 µm, taking B, and re-running the error budget over temperature to prove B holds 2 µm. I ask for the freeze by a specific week, because after that week the long-lead order slips and launch slips with it.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-100Walk me through how you would design a complete mechatronics system from requirements to validation, and how you would prove it works?
The 90-second answer
I would start from a requirements table, not a motor. For a single-axis servo stage I would fix travel, payload, repeatability, cycle time, environment and safe state before choosing any part. Example, labelled as a worked example: 200 mm travel, 5 kg payload, 5 µm repeatability, 2 s point-to-point cycle, 20 to 35 °C, factory floor with a 24 V supply. Every later choice traces back to one of those numbers, and validation is a test per requirement, not a general demo.
Sizing with real arithmetic. Ball screw with 10 mm lead and efficiency 0.90, acceleration 1.5 m/s², friction and seal drag 40 N. Force at peak acceleration is 5 × 1.5 + 40 = 47.5 N. Screw torque is F × lead / (2π × efficiency) = 47.5 × 0.010 / 5.65 = 0.084 N·m. Speed at 0.5 m/s is 0.5 / 0.010 = 50 rev/s, or 3000 rpm. I would pick a servo rated at 0.30 N·m continuous at 3000 rpm, with peak torque around 0.9 N·m, so normal moves use under 30% of continuous rating and leave margin for misalignment and reflected inertia. If the calculation needs more than 70% of rated torque in normal moves, the screw, gear ratio or motor is wrong, not the tuning.
Encoder resolution must put many counts inside the tolerance band. A 5 µm band with a 1 µm encoder gives only five counts, so I would use a linear encoder or a rotary encoder on the screw with interpolation to 0.1 µm per count, and verify that quantization noise does not dominate the velocity estimate at low speed.
Architecture and interfaces. Mechanics, drive and controller are designed as one loop: current loop in the drive at 8 to 16 kHz, velocity loop at 1 kHz, position loop at 250 Hz to 1 kHz depending on measured bandwidth. The firmware and hardware contract states sample rates, jitter budget, encoder format, current limit, limit switch wiring and the hardware safe state. A normally closed limit chain and a drive enable that drops on watchdog timeout or guard open mean power loss cannot leave the axis energised or restart into motion. That is proved by pulling power and cutting comms with firmware halted, not by reading code.
| Requirement | Design choice | Proof |
|---|---|---|
| 5 µm repeatability | Linear encoder, stiff guide, preload | 100 bidirectional moves, laser interferometer, report σ and range |
| 2 s cycle | Trapezoidal profile within torque limit | Timestamped trajectory log, p95 cycle time |
| Safe on fault | NC limits, hardware enable, watchdog | Power cut, comms cut, E-stop tests with drive disabled |
| 20 to 35 °C operation | Thermal margin on motor and drive | 8 h soak at 35 °C, drift and trip log |
Validation that proves it. Bench first: step responses to read overshoot, settling time and steady-state error, then a frequency sweep to find the first resonance and set loop separation below it. Then hardware-in-the-loop with a plant model and fault injection for encoder loss, current limit and following error. On the machine, repeatability is measured separately from accuracy: accuracy against the interferometer at several positions, repeatability as the spread returning to one point 100 times.
import statistics
positions_um = [12.1, 11.8, 12.4, 11.9, 12.0] # example, µm from target
print(f"mean {statistics.mean(positions_um):.2f} um")
print(f"stdev {statistics.stdev(positions_um):.2f} um")
print(f"range {max(positions_um) - min(positions_um):.2f} um")Pass criteria are written before the test: for this example, range under 5 µm and no following-error trip in 1,000 cycles. If repeatability fails, I change mechanics first (preload, alignment, backlash) because no PID gain fixes a loose guide. If accuracy fails but repeatability passes, I calibrate scale and offset. Endurance and thermal soak close the loop, and each production unit gets the same short calibration and repeatability check so the design, not one hand-built prototype, is what ships.
Curated: · Written: · Reviewed: —
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.