Technical Knowledge.

From chips and firmware to control algorithms and industrial communication.

Technical fields

Embedded Development

Embedded Development

C/C++ and Memory

Integers and type boundaries · Pointers, lifetime, and ownershipExpand the C/C++ and Memory Knowledge Directory
  • Integers and Type Boundaries
  • Pointers, Lifetime, and Ownership
  • volatile and Concurrent Access
  • Register Operations and Portable Interfaces

Integers and Type Boundaries

Choose integer types by starting with physical quantities and protocol ranges. Raw current counts, signed speed, accumulated position, and byte lengths have different meanings; do not use the same type for everything simply because the processor is 32-bit. Write down the ranges of maximum inputs, scale factors, and intermediate products, paying particular attention to whether a multiplication performed before a division overflows before that division. A wider result variable does not automatically widen calculations on narrower operands; widening must happen before the operation.

The modular wraparound of unsigned arithmetic can be used for counter differences, provided the observation interval stays within the agreed range; it is no substitute for capacity checks. When signed values and length types are mixed, a negative value may become a very large positive value before a comparison. Decode communication parameters according to the field width in the message, validate the physical range, and only then convert to the internal type, so that casts do not make invalid inputs appear valid.

Fixed-point control also requires distinguishing representable range from arithmetic precision. Reserve accumulation bits for multiplication, and establish consistent rules for right shifts, rounding, and saturation rather than relying on instructions the target compiler happens to generate. Log raw counts and engineering values during debugging and check sign extension. Host tests can cover arithmetic boundaries, while target disassembly confirms actual widths, instructions, and execution costs; both must use the same scaling definitions.

Debugging Checks
  • Cover zero, the largest positive value, the smallest negative value, and adjacent inputs; verify that a failed conversion returns an explicit error and does not continue updating control parameters.
  • Enable conversion and signedness warnings and inspect each product and shift; document the maximum permitted observation interval for every intentional wraparound.
References

Pointers, Lifetime, and Ownership

A pointer expresses a location; by itself, it cannot express how long an object lives or who must release it. Firmware interfaces should also specify the referenced buffer, valid length, write permissions, and validity period. A synchronous call can borrow the caller's buffer, but an asynchronous transmission that stores only the address of a local array may read invalid data after the function returns. A static array remains alive, yet the next request may overwrite it before transmission finishes.

When handing data to DMA or a communication queue, either copy it or explicitly transfer buffer ownership. A buffer pool can represent ownership with states such as free, filling, pending transmission, and transmitting; only a completion event may return a block to the free pool. Cancellation and timeouts also need reclamation paths, and a late completion interrupt must not release a block that has already been reassigned. Checking callbacks against sequence or generation numbers is more reliable than merely testing whether a pointer is non-null.

C++ resource wrappers are useful for managing files, locks, and memory in ordinary tasks, but the context in which a destructor runs must still meet real-time constraints. If an object may be destroyed in an interrupt, its destructor must not implicitly block or perform unpredictable deallocation. Raw pointers can remain as borrowing interfaces, provided ownership is clear; C interfaces can express the same rules through structures and state constraints. To debug dangling accesses, first trace allocation, submission, completion, and release over time, then inspect the invalid address.

Debugging Checks
  • Make the asynchronous interface finish transmission only after the function returns; cover cancellation and late callbacks, and check buffer contents and the number of returns to the pool.
  • Review every member that stores a pointer and document its owner and lifetime; detect double frees, duplicate pool returns, and pool exhaustion.
References

volatile and Concurrent Access

volatile primarily tells the compiler that an access has externally observable significance; memory-mapped registers are a common example. It does not make an increment atomic, establish synchronization between tasks, or automatically maintain coherence between DMA and the data cache. Declaring a status flag volatile does not mean the associated array has been published in the correct order, nor does it guarantee that readers see a complete parameter set.

First identify the contexts that access shared data. Tasks and interrupts on a single core can use sufficiently short critical sections that preserve the previous interrupt-mask state; tasks can use RTOS synchronization primitives; ordinary data in a multicore or language threading model should use atomics and locks appropriate to that model. Check whether atomic types are lock-free on the target to avoid invoking an underlying lock implementation in a high-priority interrupt. Barriers constrain access order or completion conditions; they do not replace mutual exclusion and ownership.

For a command snapshot containing mode, setpoint, and sequence number, write the inactive buffer first, then hand over its index with appropriate synchronization. Readers consume only a published version, and the buffer may be reused only after consumption finishes. Log every publication and consumption sequence number during debugging instead of looking only at final values. Arm DMB, DSB, and ISB serve different purposes, and their insertion points depend on memory attributes, peripheral requirements, and chip errata; do not copy a barrier sequence and claim it works for every MCU.

Debugging Checks
  • List all readers and writers of shared variables and verify that each group of fields has a strategy for consistency as a whole; adding a qualifier only to the flag is insufficient.
  • Inspect the target's atomic implementation, maximum critical-section duration, and DMA cache handling; stress tests should cover compiler optimization and interrupt nesting together.
References

Register Operations and Portable Interfaces

Memory-mapped register interfaces must preserve addresses, access widths, and side effects. CMSIS device headers describe register layouts with structures and distinguish read/write access attributes; these definitions provide an entry point for understanding peripherals, but do not prove that every access sequence is correct. Driver initialization must also account for clocks, resets, and peripheral states so that the relevant bus is available when accessed.

A common mistake is to apply read-modify-write to every register. Write-one-to-clear bits, read-to-clear bits, write-only commands, and reserved bits have different semantics; read-modify-write may clear other events or write invalid bits. If a chip provides separate set and clear registers, GPIO operations should use them according to the manual. Software register shadows must also account for hardware changing state independently; a shadow is not a live status value.

A portability layer should encapsulate engineering operations, such as requesting a set of synchronized samples, setting duty cycle, or reading a fault cause, rather than exposing every vendor register name to application logic. The platform implementation handles bit fields and timing, while the upper interface defines units, return values, and calling context. When changing MCUs, verify trigger timing, resolution, and fault behavior individually; identical interface names do not imply identical peripheral capabilities. On an exception, preserve the original values of key registers before clearing events as specified, so that cause and effect can be reconstructed.

Debugging Checks
  • Annotate read/write, write-one-to-clear, and reserved bits from the register table and verify that event handling does not accidentally clear other channels.
  • Check structure offsets, access widths, and clock-enable order; use target disassembly to verify that critical reads and writes meet peripheral requirements.
References
Embedded Development

Data Structures and Data Flow

Ring buffers, queues, and protocol buffers · Producers and consumersExpand the Data Structures and Data Flow Knowledge Directory
  • Ring Buffers, Queues, and Protocol Buffers
  • Producers and Consumers
  • Complexity and Execution Bounds
  • Capacity, Bounds, and Concurrency Limits

Ring Buffers, Queues, and Protocol Buffers

A ring buffer maps a continuous input stream onto a fixed-capacity array and suits serial reception and event logging. Before designing it, define whether an element is a byte or a complete message, whether read/write indices identify the next position or the last completed position, and how empty and full are distinguished. An implementation that reserves one slot has less usable capacity than its array length; implementations using counts or monotonic indices must prove that differences and wraparound rules are unambiguous.

A byte-stream parser must not treat a DMA completion as a complete frame. A header may span the array boundary, and a length field may arrive in several installments. Check the minimum header first, validate the declared length against the protocol maximum, and submit a message only once the full frame is available; after a bad frame, follow an explicit policy to find the next candidate start. Preserving parser state avoids scanning from the beginning for every received byte, reducing additional overhead as input pressure increases.

A zero-copy interface can obtain contiguous space in two spans, then submit the actual length once the producer finishes filling it. Consumers must not see contents before submission, and data must not be overwritten before consumers release it. Zephyr's ring buffer alone does not replace all application concurrency design; multiple producers need additional serialization. Log peak occupancy, lost-byte counts, and parsing failure reasons together to distinguish insufficient capacity, message errors, and index races.

Debugging Checks
  • Construct inputs whose header, length, and checksum fields fall across the array boundary, and verify that split-copy and zero-copy paths produce identical results.
  • Test empty, exactly full, over-capacity, and repeated-wraparound conditions; verify that resynchronization after overflow does not repeatedly parse bad data forever.
References
  • Zephyr Ring Buffers — Ring Buffers; Concurrency; online page checked 2026-10-07, not a frozen release

Producers and Consumers

Producers and consumers describe data ownership and rate relationships, not merely two function names. Interrupt acquisition, communication-task decoding, and control-cycle command adoption may form a multistage pipeline. Each stage should define production time, submission conditions, consumption time, and release conditions. Allowing intermediate samples to be skipped and requiring every sample to be processed are different requirements, and the queue policy must reflect that distinction.

RTOS queues normally copy entries of a specified size; if an entry contains a pointer, only the address is copied, and the application still manages the underlying data. The interface contract must state whether a producer may modify a buffer after successful submission. Interrupts must use the corresponding nonblocking interface and request scheduling according to port-layer rules; ordinary tasks may wait for capacity, but the wait limit must stay within their own deadlines. Failed returns must feed statistics or a fault policy rather than being silently ignored.

A stable rate does not guarantee an absence of burst backlogs. When several communication frames arrive at once, limit parsing per iteration and leave the rest for later iterations. If control setpoints use a latest-value mailbox, retain sequence numbers, expiration times, and missed-update counts; event commands may instead require individual acknowledgments. To debug, plot submission and consumption sequence numbers first, then analyze duplicates, omissions, and reordering. When clearing a queue, reclaim resources referenced by pointer entries as well, so recovery does not cause a memory leak.

Debugging Checks
  • Pause the consumer, increase producer burst size, and cancel requests separately; verify feedback after the queue fills and check buffer ownership.
  • Check that interrupt and task interfaces are not mixed, and confirm that command freshness, duplicate processing, and release counts are traceable.
References

Complexity and Execution Bounds

Choose real-time data structures by considering execution bounds rather than comparing only average complexity. Searching a fixed-length array is linear, but a small, explicit maximum length may make it easier to analyze than a dynamically allocated tree. A single ring-queue insertion usually has a fixed amount of work, but the total time to parse a batch still grows with its backlog; assuming that constant time per operation means constant time for an entire task iteration overlooks risk.

Every loop needs an explainable bound. Bound communication scanning by maximum frame length, diagnostic uploads by an entry limit per iteration, and control algorithms by fixed dimensions. Pay particular attention to error paths: searches for a header, waits for peripheral flags, and repeated lock attempts without exit conditions are difficult to expose with normal-input tests. Dynamic allocation, log formatting, and some library functions can also introduce input-dependent execution times.

Asymptotic complexity cannot replace target timing analysis. Cache hits, Flash wait states, DMA contention, and compiler optimization affect actual execution time, so measure under specified clock, link-location, and load conditions. Control tasks can move variable work to lower-priority tasks and reserve an explicit budget for periodic work. The longest observed execution remains only the maximum within the measurements' coverage; combine loop bounds and preemption analysis to derive a more conservative range.

Debugging Checks
  • Check every loop and peripheral wait for a capacity or time bound, covering maximum-length frames, all error conditions, and peak backlogs.
  • Compare target disassembly with cycle measurements and record both per-operation cost and operations per iteration; do not accept deadline compliance based on averages.
References

Capacity, Bounds, and Concurrency Limits

Capacity calculations must consider input bursts and the consumer's longest pause together. If data arrives at a given number of bytes per second and higher-priority control work may pause the consumer, baseline capacity must at least hold arrivals during that pause, plus frame-assembly and scheduling margins. This reasoning assumes the consumer can catch up after the pause; otherwise, a larger array merely delays failure.

Validate lengths before computing addresses, avoiding out-of-bounds pointer arithmetic in the first place. For offsets and lengths, checking whether length exceeds remaining capacity generally avoids integer wraparound more easily than adding first and comparing afterward. An incoming message length must not directly determine copy or allocation size; validate the protocol maximum, local array size, and application limits separately. Advancing indices must also preserve empty/full conditions and occupancy invariants.

Concurrency limits matter as much as array bounds. A structure in which one producer and one consumer each exclusively own an index may lose its correctness when extended to two producers. Clearing, resetting, and handling overflow also write indices and must not be overlooked. The application should explicitly choose whether to drop the newest data, drop the oldest data, or stop receiving, and expose counters. Recovery must restore buffer state and also decide whether to retain unfinished protocol transactions.

Debugging Checks
  • Test copying with the maximum legal length and lengths beyond the limit, covering offsets near the end of capacity and the maximum integer value.
  • Insert controlled context switches among clearing, full-queue conditions, and concurrent submissions; check index invariants, data-loss statistics, and transaction recovery.
References
Embedded Development

MCU/DSP Selection and Device Documentation

Resources, real-time capabilities, and device selection · Datasheets, reference manuals, and errataExpand the MCU/DSP Selection and Device Documentation Knowledge Directory
  • Resources, Real-Time Capabilities, and Device Selection
  • Datasheets, Reference Manuals, and Errata
  • Clocks, Reset, Memory, and Startup
  • Platform Differences and Application Notes

Resources, Real-Time Capabilities, and Device Selection

Select a device for motor firmware by allocating resources across the complete control chain rather than ranking clock speeds alone. List requirements for PWM channels, complementary outputs, dead time, hardware shutdown, simultaneous ADC sampling, position interfaces, and industrial communication, then determine whether these functions can coexist in the same package and pin assignment. Advertised peripheral totals do not equal simultaneously usable resources; pin-multiplexing conflicts, trigger routing, and DMA request allocation may all impose limits.

Evaluate computational capability against actual operations and memory accesses. Floating-point units, multiply-accumulate, division, and trigonometric implementations affect algorithm cost; DSPs and coprocessors also introduce data-transfer and launch overhead. Flash wait states, caches, and bus contention at maximum clock speed may reduce available margin. First construct a small program with the target data size, estimate its budget under expected interrupt and communication loads, and choose conservative headroom rather than converting instructions per second directly into control bandwidth.

Also check operating temperature, supply requirements, analog accuracy, Flash endurance, and startup recovery. For protection, confirm that comparators, timers, and output-disable paths meet fault-response requirements; for communication, check pin electrical characteristics and isolation. A selection table should identify mandatory, substitutable, and unverified conditions. Preserve unconfirmed manufacturer abbreviations as written rather than guessing part numbers or attributing unrelated devices' capabilities to the design.

Debugging Checks
  • Create pin and trigger-resource tables for the actual package and verify combinations that operate PWM, sampling, encoders, and communication simultaneously.
  • Estimate control, communication, and diagnostic loads together, record toolchain and memory settings, and identify margin not yet verified on target hardware.
References
  • ST STM32G4x4 Documentation — STM32G4x4 documentation index; datasheet/reference manual/errata, index checked online; not proof of all document contents

Datasheets, Reference Manuals, and Errata

Datasheets answer electrical and device-resource questions, reference manuals explain registers and peripheral operation, core programming manuals describe processor mechanisms, and errata list known limitations and workaround conditions. First establish the exact part number, package, silicon revision, and document revision rather than inferring details from a neighboring family. Official documentation indexes help locate these materials, but opening an index does not mean register timing has been individually verified.

When investigating a peripheral issue, break system requirements into locatable entries. For lost ADC conversions, for example, examine trigger sources, conversion sequences, overrun handling, and DMA configuration rather than searching only for a function name. Preconditions and exceptions in documentation matter as much as the main text: a clock range, operating mode, or revision may determine whether a limitation applies. Save page, section, and table numbers together with relevant conditions so later changes can trace the conclusion's source.

Driver source and application notes help explain implementations but cannot replace device specifications. Vendor examples may target one board, default frequency, or library version, so ported code still requires individual comparisons. Debug notes should distinguish verified facts, engineering inferences, and open questions; preserve documentation conflicts and seek updated explanations. For protection or storage decisions, do not modify code based only on search summaries; consult the formal entry and actual hardware behavior.

Debugging Checks
  • Create a correspondence table for part numbers, silicon revisions, and document revisions, and check every used peripheral for errata relevant to its operating mode.
  • Record original sections and conditions for critical configurations and verify them with minimal target experiments; if documentation cannot be downloaded, mark it unverified rather than guessing.
References
  • ST STM32G4x4 Documentation — STM32G4x4 documentation index; datasheet/reference manual/errata, index checked online; not proof of all document contents

Clocks, Reset, Memory, and Startup

Clocks, reset, and startup form interdependent initialization conditions. The CPU, buses, timers, ADCs, and communication peripherals may use different dividers or clock sources; after changing the system clock, recalculate their actual frequencies. Timer configuration determines the control period, and the relevant kernel clock determines UART baud rate; updating a single global frequency variable does not mean every peripheral changes in step.

Reset causes help distinguish power-on, software requests, watchdogs, and supply abnormalities. Early startup should read and save the cause according to chip rules before clearing the flags; some flags accumulate, so not every set flag represents the most recent event. Entering an application from a bootloader also differs from a true reset: interrupt, DMA, clock, and cache state may be inherited. The handover protocol must define which states have been cleaned up and which the application reestablishes.

Memory layout must match the startup path. Execution location, vector address, Flash load images, and RAM initialization ranges jointly determine correct operation; retained fault storage must be distinguished from ordinary zero-initialized memory. External-crystal failure, clock-switch timeouts, and Flash configuration errors need diagnosable fallback paths. Prefer staged initialization with verifiable completion conditions, avoiding a single complex call that fails with no observable detail beyond a default exception handler.

Debugging Checks
  • Verify cold power-on, software reset, watchdog reset, and bootloader handover, recording reset causes and the initialization stage reached.
  • Calculate peripheral frequencies from actual dividers, check Flash wait-state requirements and peripheral trigger periods, and test clock-source failure handling.
References

Platform Differences and Application Notes

When porting firmware, sharing the Arm architecture does not imply identical platform behavior. Individually check whether the core has a data cache, whether peripheral DMA can reach each RAM region, how floating-point context is saved, and how many interrupt-priority bits exist. ST's cache application note covers relevant Cortex-M7 cases in STM32F7 and STM32H7 devices; its strategies cannot be directly applied to devices without the same cache or bus structure.

Application notes usually describe one working combination; actual projects must compare devices, boards, driver libraries, clocks, and memory settings. After copying a DMA example, linking its buffer to different RAM may make transfers unreachable or cause coherence problems; after changing ADC families, identically named sampling settings may have different cycle counts. A differences table and separation of common algorithms from platform implementations concentrate initialization, cache maintenance, and trigger routing in one place rather than scattering device checks throughout application functions.

Porting acceptance should use tests that directly prove interface semantics. For PWM, compare actual edges and update times; for sampling, compare channel order, timestamps, and raw counts; for storage, compare erase/program granularity and failure recovery. Prove the minimal chain first, then add control and communication load. Original-platform test inputs reveal differences, but include boundaries unique to the new platform as well. A successful example proves only the conditions it covers, not reliability in every operating mode.

Debugging Checks
  • Build a comparison table for caches, DMA reachability, floating-point ABI, and interrupts, and confirm that related strategies are implemented centrally in the platform layer.
  • Compare actual timing and failure behavior for each interface, recording the devices covered by application notes and conditions that differ from the current configuration.
References
Embedded Development

Peripherals, Triggers, and Sampling

PWM, timers, and hardware triggers · ADC, DMA, and data consistencyExpand the Peripherals, Triggers, and Sampling Knowledge Directory
  • PWM, Timers, and Hardware Triggers
  • ADC, DMA, and Data Consistency
  • GPIO, Comparators, and Protection Paths
  • UART, SPI, I²C, and CAN Interfaces
Reading Guide: Real-Time Budgets for PWM, ADC, and Control Calculations

PWM, Timers, and Hardware Triggers

PWM uses hardware counters, comparators, and output logic to create repeatable edges rather than toggling GPIO in a software loop. First define counting mode, carrier frequency, complementary outputs, and dead time, then choose ADC triggers and duty-cycle latch events. In center-aligned mode, count direction and update conditions may affect the number of triggers, so calculate according to the specific timer's rules rather than inferring the control period from the period-register value alone.

Writing a duty cycle and applying it may occur at different times. Preload mechanisms let software write pending values and transfer them to active registers together at a specified event, preventing multiphase outputs from mixing old and new values within one cycle. Coordinated timers also require defined master/slave triggers, counter phases, and initial startup order; starting them one at a time in software can introduce fixed sampling-phase offsets or nonrepeatable variation through startup jitter.

Observe PWM edges, sampling markers, and calculation-completion markers together to build a hardware timeline. Check whether zero duty, maximum duty, and values near dead-time boundaries follow output rules so that no boundary case produces unintended narrow pulses. Verify hardware shutdown inputs, output enable, and reenable policy separately. Application notes explain common structures, but the actual update events, trigger mappings, and protection actions must follow the selected device's reference manual.

Debugging Checks
  • Measure PWM and trigger edges during initial startup, steady operation, and parameter updates, checking that trigger counts per carrier cycle match the design.
  • Cover minimum/maximum duty cycles and synchronized multiphase updates; verify that an ordinary subsequent update does not automatically resume output after shutdown.
References

ADC, DMA, and Data Consistency

Trustworthy ADC data requires analog settling, sampling time, conversion time, and data handover to be correct. Input-source impedance and sampling capacitance affect settling, and too short a sampling interval can introduce errors dependent on the previous channel. Channel switching, amplifier bandwidth, and filter networks also affect transients, so calculate and verify against the actual analog front end rather than treating nominal bit depth as effective system accuracy.

DMA moves conversion results into memory, but a completion flag only indicates that the associated transfer condition has been met; it does not guarantee the application reads a complete sequence that has not been overwritten. Double buffering or half-buffer processing must define which span belongs to DMA and which to the CPU, and processing must finish before the next overwrite. Check channel order, data width, and circular indices together; never combine an incomplete half-frame with the previous frame into a new sampling snapshot.

Platforms with a data cache must also manage CPU/DMA visibility. Cleaning dirty cache before transmission and invalidating the required region after reception are common directions, but exact steps depend on memory attributes and DMA paths. Giving a buffer exclusive ownership of complete cache lines prevents maintenance from damaging adjacent data. MCUs without the relevant data cache should not inherit this overhead blindly. Logging sample sequence numbers and times and comparing raw counts, DMA destinations, and consumed snapshots helps distinguish analog errors from digital handover mistakes.

Debugging Checks
  • Use known levels and channel steps to verify settling time, channel order, and overrun handling, checking for crosstalk from the preceding channel.
  • Cover DMA half-full, full, and processing-delay cases; check reachable RAM, alignment, cache-line ownership, and margin before data overwrite.
References

GPIO, Comparators, and Protection Paths

Analyze a protection path stage by stage from the fault signal to actual power output. Comparator detection, input filtering, timer shutdown, gate drivers, and power devices all add delay; interrupt processing is only one possible stage. If a hazardous output must stop rapidly, first evaluate hardware paths that directly disable PWM, using software to log causes, latch faults, and control recovery rather than assigning the entire response to an ordinary task.

Define GPIO states during reset, initialization, and faults as well. Pins may power up as inputs or in another default mode, and an incorrect output-configuration order can create transients; external pull resistors and the driver's default disabled state must be designed together with firmware. Validate comparator thresholds, polarity, blanking, and filtering against normal switching noise and real faults. Excessive filtering may reduce false trips while also delaying protection.

Fault latching and automatic recovery are different policies. After reading the cause, software should clear flags as specified and enter a recoverable state only when bus, sensor, and command conditions are satisfied; a fault pin returning to normal must not immediately restart operation. Test with limited energy or controlled signal injection and observe actual outputs, not just state variables. General timer application notes explain shutdown structures but do not replace system functional-safety analysis or product-level protection verification.

Debugging Checks
  • Measure the time from fault input to actual output disable, separately covering a busy CPU, masked interrupts, and initialization.
  • Check comparator polarity, filtering, and reenable conditions; verify that fault clearing neither replays expired setpoints nor produces unintended pulses.
References

UART, SPI, I²C, and CAN Interfaces

Understand physical transmission, peripheral transactions, and upper-layer protocols separately for UART, SPI, I²C, and CAN. UART carries bytes using an agreed baud rate; SPI organizes exchanges around a controller's clock and chip select; I²C includes addressing and acknowledgments; CAN shares a bus through frames and arbitration. A driver's transfer-complete return does not necessarily mean the remote device has executed a command at the application level; upper-layer acknowledgment or status reads may still be necessary.

Define transaction boundaries first. For SPI, check clock polarity, phase, word width, and chip-select hold time; for I²C, check address representation, repeated starts, acknowledgments, and bus-occupation timeouts; for UART, distinguish DMA completion from transmission of the final stop bit. Successfully queuing a CAN transmission also differs from receiving a bus acknowledgment, and applications must handle congestion, error states, and recovery. Every blocking wait needs an exit condition so that one failed peripheral cannot stall the control chain.

Debug by comparing wire waveforms with driver counters. Request sequence numbers, byte counts, completion events, and error codes help distinguish length, timing, and upper-layer parsing errors. I²C open-drain pull-ups, capacitance, and permitted speed are related; lowering the software clock alone must not conceal incorrect electrical design. When multiple tasks share a bus, arbitration must cover the entire transaction; do not release a lock while chip select is active or between parts of a combined operation and allow another task to intervene.

Debugging Checks
  • Use a logic analyzer to inspect transaction start, completion, and error paths, verifying that bus and chip-select states recover to their defined conditions after a timeout.
  • Cover missing acknowledgments, receive overrun, busy buses, and concurrent requests, and state precisely whether success means queued, transmitted, or acknowledged by the application.
References
Embedded Development

Firmware Architecture and Interfaces

BSP/HAL and application-layer boundaries · State machines and eventsExpand the Firmware Architecture and Interfaces Knowledge Directory
  • BSP/HAL and Application-Layer Boundaries
  • State Machines and Events
  • Parameter, Command, and Snapshot Interfaces
  • Decoupling Control and Communication Tasks
Reading Guide: Parameter, State, and Fault Boundaries in Drive Firmware

BSP/HAL and Application-Layer Boundaries

Layering concentrates change in appropriate places. The BSP describes board connections, supplies, and pins; the HAL or low-level drivers describe peripheral access; application logic expresses operating modes, commands, and fault policies. If a current-loop function also changes pin multiplexing, parses messages, and erases/programs Flash, proving unchanged control behavior after a board or protocol change becomes difficult. Layers should constrain dependencies through interfaces, not merely occupy different folders.

Platform interfaces should express capabilities required by the application. For example, a sampling interface returns a complete raw-count snapshot and timestamp, an output interface submits a set of duty cycles and states when they take effect, and a storage interface returns explicit failure reasons. Upper layers need not know register bit names, but must know accuracy, latency, and validity conditions. Excessive abstraction can hide important constraints, so do not wrap every driver in a generic call that supposedly never fails and always finishes immediately.

Debugging still needs visibility across interfaces. The platform layer can expose a limited diagnostic view containing key registers, trigger counts, and error codes; application logs record adopted snapshots and state transitions, linked by sequence numbers. Replace pure application interfaces during tests to verify algorithms, then use target tests to check real peripheral semantics. If a port changes sampling or output latency, revise timing and repeat acceptance; successful interface compilation does not prove equivalence.

Debugging Checks
  • Review application code for direct dependencies on board registers and check every platform interface's units, timing, and failure returns.
  • Run tests with substitute interfaces and target peripherals separately, checking that their contracts agree on valid data, latency, and error conditions.
References

State Machines and Events

State machines make a drive's permitted actions explicit. First distinguish states, events, and conditions: ready is a state, receiving an enable command is an event, and valid bus voltage and feedback are conditions. A transition table should specify prior state, event, guard, action, and next state, especially rejected commands and internal faults. Independent Boolean flags for enable, running, and fault can create unexplained combinations; explicit states reduce that ambiguity.

Event delivery must account for order and duplication. Start, stop, and mode-change commands submitted by communication tasks may arrive in the same cycle, so define priority and expiration policies. Fault events usually take precedence over ordinary commands, but the state machine and protection design still determine the action. Keep transition actions short; lengthy calibration or storage work can enter a substate and wait for a completion event rather than blocking all control and communication in one transition.

Logging states before and after transitions, event sequence numbers, and rejection reasons is more useful than printing only the current state. Handle duplicate events idempotently or identify them by transaction sequence; late completion events must match the current action generation so an old callback cannot advance a canceled start. Tests can traverse the transition table and inject disallowed events, covering combinations such as enable during a fault, stop during recovery, and invalid feedback rather than checking only the normal startup path.

Debugging Checks
  • Review the transition table entry by entry, covering every rejection condition and fault priority, and confirm that every state has an explainable exit path.
  • Inject duplicate, out-of-order, and late events; check transaction generations, idempotent behavior, and the causal relationship between logged transitions.
References

Parameter, Command, and Snapshot Interfaces

Parameters, commands, and snapshots have different timing semantics. Parameters describe operating configuration, commands request an action or a new target, and snapshots represent a complete observation at a particular instant. Placing all three in an arbitrarily readable and writable global structure allows communication parameter writes to take effect during control calculations and diagnostics to combine results from different cycles. Each interface should specify validation, submission, activation, and reading separately.

Parameter updates can first populate a candidate set, check ranges and cross-constraints, and then commit it atomically as a set. For example, current limits and control gains may depend on each other; applying individual fields immediately can temporarily violate the design. Commands should include mode, sequence number, and validity period, with separate feedback for acceptance and actual execution. The control context generates feedback snapshots at a fixed stage, and communication reads only completed versions rather than a changing set of internal variables.

Double buffering or queues still need defined buffer-reuse and whole-set synchronization rules; an atomic index write does not automatically guarantee visibility to every language thread or DMA. Persistent parameters also require distinguishing active values from saved values so a modified display is not mistaken for power-loss persistence. Log candidate versions, active versions, and snapshot sequence numbers, verify units and byte order across interfaces, and trace rejection reasons.

Debugging Checks
  • Change related parameters together and verify that only complete, valid sets take effect, while rejection leaves the old version consistent.
  • Check snapshot sequence numbers under maximum communication read/write pressure, ensuring that command acknowledgment, actual execution, and completed saving are not treated as the same result.
References

Decoupling Control and Communication Tasks

Decoupling control and communication tasks begins with a timing boundary. A control cycle should consume only validated, published command snapshots; the current loop must not wait for a UART, bus lock, or complete message arrival. Communication tasks parse messages, validate permissions and ranges, and pass complete commands to control. Control switches versions at a fixed adoption point so one calculation cannot mix an old mode with a new setpoint.

Communication traffic needs budgets and backpressure. Limit parsed entries or processing time per scheduling turn, and expose the result when a queue is full. Use feedback snapshots for parameter reads and bounded buffers with loss statistics for diagnostic logs, preventing high-frequency queries from traversing control internals directly. Critical commands and ordinary diagnostics benefit from different service policies, but higher priorities remain constrained by the RTOS port's permitted interrupt-call range and the control budget.

Define faults and timeouts at the interface too. When commands remain unchanged too long, the control state machine should enter a designed hold, limited, or stopped state; the communication task must not arbitrarily change PWM registers. After reconnection, reconfirm mode and enable conditions first to prevent bulk execution of queued commands. Correlating message reception, submission, adoption, and output activation times reveals whether latency comes from the bus, scheduling, or the control-update mechanism.

Debugging Checks
  • Measure control margin under communication congestion, message errors, and full logging load, and confirm that control cycles do not wait for lower-priority resources.
  • Pause command updates and resume them; verify expired-command rejection, adopted sequence numbers, and recovery conditions, ensuring actions from before disconnection are not replayed.
References
Embedded Development

Interrupts, RTOS, and Real-Time Budgets

Sampling-to-update deadlines · Interrupt priorities and nestingExpand the Interrupts, RTOS, and Real-Time Budgets Knowledge Directory
  • Sampling-to-Update Deadlines
  • Interrupt Priorities and Nesting
  • Task Scheduling, Locks, and Shared Data
  • Worst-Case Execution Time and Overload Handling
Reading Guide: Real-Time Budgets for PWM, ADC, and Control Calculations

Sampling-to-Update Deadlines

Define the sampling-to-output-update deadline from the hardware event chain. Identify sampling trigger, end of sample-and-hold, conversion completion, data availability, control calculation, and PWM latch times, then determine which update event the calculation must meet. A control function averaging less than one carrier period can still miss its latch window because the usable computation time occupies only part of that period and must exclude trigger phase and conversion latency.

Separate fixed latency from jitter. A fixed one-cycle delay can enter the control model, while random delay changes effective phase and can affect noise or stability margin. Include interrupt-entry time, nested preemption, bus contention, and snapshot publication in the budget. If a calculation does not finish, explicitly define whether output holds the previous value, enters a limited mode, or stops; a late result must not be written at an incorrect carrier phase.

Use a shared counting reference to record trigger and completion sequence numbers and verify correspondence between input samples and output commands. GPIO markers expose external waveforms and cycle counters estimate software-segment duration, but platform availability and counter overflow must be checked. Include communication, diagnostics, and error handling in the measurement load; do not report margin only with all other interrupts disabled. State the tested load and deadline event in acceptance criteria so measurement coverage is clear.

Debugging Checks
  • Plot trigger, data-ready, and latch edges within the same cycle, checking the sample sequence used and the permitted output delay.
  • Apply communication and interrupt stress, count deadline misses and minimum margin, and verify that the overrun path cannot produce partially updated multiphase outputs.
References

Interrupt Priorities and Nesting

Design interrupt priorities from task importance and service deadlines rather than peripheral names. On Cortex-M, smaller priority numbers generally indicate greater urgency; implemented bits and grouping depend on the core and device. Distinguish logical values accepted by configuration APIs from shifted register encodings, since mixing them changes actual order from the intended configuration. Nesting lets a more urgent interrupt preempt the current handler and therefore also affects shared resources.

With FreeRTOS, the interrupts allowed to call kernel APIs are constrained by the port and maximum system-call priority. Interrupts above that threshold can maintain lower latency but may not freely call queues or semaphores; perform bounded work independent of the kernel, then hand it over through a permitted context. The kernel's interrupt-masking mechanism differs from globally disabling interrupts, so a critical section does not imply that every protection event stops receiving a response.

Start debugging by reading actual priorities, grouping, and current mask registers and comparing them with the configuration table. Listing each interrupt's longest processing time, possible nested handlers, and shared data exposes implicit coupling beyond priority inversion. Verify direct hardware protection paths separately; software diagnostic-interrupt latency does not represent hardware response latency. After adding a high-frequency interrupt, recheck lower-priority services for persistent starvation.

Debugging Checks
  • Read the target's actual priority encoding and check implemented bits, grouping, and the range in which FreeRTOS permits kernel API calls.
  • Inject simultaneous and sustained high-frequency events, measure nesting depth and service latency, and check unserviced events and stack space.
References

Task Scheduling, Locks, and Shared Data

Task scheduling maps runnable tasks to CPU time, while locks constrain resource access; analyze them together. A high-priority control task waiting for a resource held by a low-priority task cannot progress despite its own priority. Priority inheritance mitigates certain inversion cases, but does not shorten an unbounded critical section or solve deadlocks, conflicting resource order, or peripheral transactions without timeouts.

Choose shared-data mechanisms by access pattern. Small configuration copies can fit within bounded critical sections, long messages suit queue transfers, and ordinary tasks can share peripherals through mutexes. Mutexes have task ownership and must not be used in interrupts; use a permitted interrupt-to-task notification interface instead. Do not hold locks during lengthy printing, Flash erase, or waits for another task, because maximum lock duration enters every waiter's real-time budget.

Lock interfaces also need failure and timeout semantics. If acquisition fails, the caller should preserve old state or return an error rather than accessing protected data anyway. Acquire multiple locks in a consistent order and avoid callbacks that reenter a module while its lock is held. Logging wait-start, acquisition, and release times and correlating them with task states helps explain stalls. Regular queue-peak, lock-wait, and task-execution statistics reveal scheduling risks better than average CPU utilization alone.

Debugging Checks
  • List every resource the control task may wait for, and check maximum lock duration, timeouts, and recursive or crossed acquisitions in the call chain.
  • Create contention between a low-priority lock holder and a high-priority requester; verify inheritance configuration, timeout feedback, and continued operation after release.
References

Worst-Case Execution Time and Overload Handling

Worst-case execution-time analysis concerns the maximum resources a path may require under specified conditions; the measured maximum is only one piece of evidence. Control-task paths should include limiting, fault branches, exceptional inputs, and algorithm switches; nested interrupts, cache misses, and memory waits also extend response time. A maximum measured in normal steady operation cannot establish that every fault condition meets its deadline.

Break the budget into the task's computation, blocking, preemption interference, and fixed peripheral latency. Even lower-priority communication tasks can indirectly affect control through bus or cache contention. Set batch limits for variable work and retry-count or time limits for errors, and define where dynamic allocation and logging are allowed. Putting these bounds in interfaces and configuration gives measurements an explainable input range and makes later reevaluation decisions possible.

Define overload-handling goals first. Diagnostics may discard older records and count losses, control commands may reject expired sequence numbers, and protection events must retain their required action path. An indefinitely larger queue cannot conceal a sustained lack of consumption capacity. Deadline-miss counters should include stage and version, and the first context may need latching to avoid logging that worsens overload. After recovery, check backlog freshness instead of executing every delayed command in order.

Debugging Checks
  • Cover maximum-length messages, algorithm boundaries, and fault branches; record actual configuration and measurement coverage, distinguishing observed maxima from derived bounds.
  • Continuously apply input beyond consumption capacity and verify backpressure, discard counts, and control-deadline responses; protection or freshness must not be lost silently.
References
Embedded Development

Storage, Updates, and Recovery

Flash erase/program and endurance constraints · Parameter consistency and power-loss recoveryExpand the Storage, Updates, and Recovery Knowledge Directory
  • Flash Erase/Program and Endurance Constraints
  • Parameter Consistency and Power-Loss Recovery
  • Bootloaders and Firmware Integrity
  • Update Failures, Rollback, and Compatibility

Flash Erase/Program and Endurance Constraints

Writing Flash is not ordinary RAM assignment. Erase granularity, minimum programming unit, alignment, and permitted bit transitions depend on the device, and operations may block reads or instruction fetches from the same memory array. Check the target manual to determine whether execution can continue during erase, whether RAM execution is required, and whether read-while-write across banks is supported; the term 'internal Flash' does not imply uniform behavior.

Base endurance budgets on actual erase counts and write amplification. Erasing an entire page for each parameter change over communication amplifies small updates into many erase cycles; circular logs and page migration consume endurance too. Append-only records, wear leveling, and coalesced saving can reduce hotspots, but temperature, retention conditions, and specified endurance ranges still matter. Estimates in an application note apply only to its device and algorithm assumptions, not as guaranteed figures for every product.

Run storage services in permitted states and contexts, avoiding direct erase/program operations from control interrupts. Before committing, check supply conditions and space; afterward, inspect error flags and read back data, retaining recoverable state after power loss or failure. Deferred coalescing can limit write frequency, but define when the user receives a 'saved' acknowledgment. Log page migration, remaining capacity, and write failures without creating new hotspots through frequent erases for the logs themselves.

Debugging Checks
  • Document erase and programming constraints for the exact part number, and verify alignment, writes crossing boundaries, and read-blocking behavior.
  • Estimate hotspot endurance at the worst update rate, inject write failures and undervoltage, and check returned results, old data, and maintenance counters.
References
  • ST AN4894 EEPROM emulation — AN4894 Rev 12; EEPROM emulation, page states and wear-leveling; only applicable devices listed in the note

Parameter Consistency and Power-Loss Recovery

Parameter consistency requires each save to form a complete version. Per-field checksums alone can still combine fields from different times after power loss. A record should contain format version, length, sequence number, parameter data, and an integrity check, with a final commit marker distinguishing complete records from interrupted writes. On reading, validate structure and ranges before choosing the newest valid version; do not simply select the largest sequence number.

Common implementations retain old values in two regions or an append-only log. During migration, write and verify complete data in the new region, update validity state, and only then reclaim the old region; the order must respect Flash programming rules. Power loss can interrupt the commit marker itself, so recovery must recognize intermediate states. Checksums detect random corruption but do not authenticate data; malicious-tampering risks require a separate security design.

Separate persistent formats from runtime structures when upgrading parameters. Compiler padding, byte order, and added or removed fields make raw structure writes fragile; use explicit field encoding or versioned migration functions. Supply validated defaults for missing fields and handle unknown fields through compatibility rules. After recovery, submit the complete parameter set to control rather than using fields immediately one at a time during startup. Log candidate records, selection reasons, and migration results so recovery problems are not visible only as an unexplained default value.

Debugging Checks
  • Cut power at every programming, commit, and page-migration step, verifying that restart yields either the complete old version or the complete new version.
  • Cover checksum errors, length errors, sequence wraparound, and old-format migration; check that recovery selection and defaults preserve parameter cross-constraints.
References
  • ST AN4894 EEPROM emulation — AN4894 Rev 12; EEPROM emulation, page states and wear-leveling; only applicable devices listed in the note

Bootloaders and Firmware Integrity

A bootloader selects and verifies an executable image under agreed conditions; its download channel merely supplies bytes. Images should contain target type, version, length, and integrity information, and verification must cover actual executable content and relevant metadata. An ordinary checksum detects some transmission errors, while digital signatures concern source authenticity; neither replaces the other, and signatures also require protection of the trust root and key configuration.

Define boot, primary-image, candidate-image, and state regions first, accounting for erase granularity and maximum image growth. An unverified candidate must not overwrite the only bootable version. MCUboot supports several update methods whose slot requirements, swap state, and power-loss recovery depend on configuration. Confirm capacity and limitations for the selected mode rather than assembling a process from incompatible modes.

Before jumping, handle stack, vectors, interrupts, and active peripherals as well as the entry address so the application does not inherit unintended state. Checking that the entry and stack pointer lie within permitted regions detects some corruption but cannot replace full-image verification. Successful application confirmation should depend on necessary initialization and self-tests rather than occurring blindly on entry to main. Release records should preserve bootloader version, signing-configuration identifier, and image hash for traceability without placing private keys in logs or repositories.

Debugging Checks
  • Modify image content, length, and identity fields to test every rejection path; confirm that verification covers the region actually executed.
  • Test empty slots, maximum-size images, power loss, and invalid entry points, checking the retained bootable version and application-confirmation conditions.
References
  • MCUboot Bootloader Design — Image format, image trailer, test/permanent/revert; online design, implementation version must be pinned separately

Update Failures, Rollback, and Compatibility

Define failed-update rollback behavior across download, verification, trial execution, and confirmation. Interrupted downloads leave the old version running, failed verification rejects the candidate, and unconfirmed trials revert to a confirmed version according to policy. The actual bootloader mode must support this policy; a dual-partition layout does not automatically provide power-loss recovery or automatic rollback. Every state write may fail, so recovery decision rules are required.

Compatibility covers hardware, boot protocol, parameter format, and communication interfaces. A new application may migrate old parameters, while the rolled-back application may not understand the new format; retaining only old code while overwriting parameters can prevent restoration of the previous operating state. Design reversible migrations or retain old copies, and define handling for versions that cannot be rolled back. Security anti-rollback mechanisms may also restrict downgrades and must be coordinated with availability rollback in one version policy.

A maintenance tool reporting download completion does not mean the device successfully adopted the new version. Reading the running image identifier, confirmation state, and parameter version distinguishes transfer success from operational success. Bench tests should interrupt power or communication and trigger watchdogs at every stage, then verify the version actually booted. Recovery should keep outputs safe until hardware, configuration, and command conditions are reestablished, preventing handover between versions from replaying unfinished actions.

Debugging Checks
  • Test both directions of new/old firmware and parameter-format combinations, documenting rollback coverage and explicit errors for unsupported combinations.
  • Interrupt download, verification, trial execution, and confirmation separately, checking the boot image, confirmation flags, and output-recovery sequence.
References
  • MCUboot Bootloader Design — Image format, image trailer, test/permanent/revert; online design, implementation version must be pinned separately
Embedded Development

Fault Context and Diagnostics

Exception registers and call context · Watchdogs and liveness checksExpand the Fault Context and Diagnostics Knowledge Directory
  • Exception Registers and Call Context
  • Watchdogs and Liveness Checks
  • Stack, Heap, and Resource Monitoring
  • Fault Records, Timestamps, and Version Identifiers

Exception Registers and Call Context

Fault context is valuable because it preserves the original failure state rather than immediately assigning an exception a name. On applicable Cortex-M cores, for example, fault status, valid fault-address registers, and the exception stack help distinguish invalid accesses, bus faults, and instruction problems. Register availability, valid bits, and stack-frame forms vary with core and floating-point state. Identify the exact core first, then interpret addresses according to validity flags rather than assuming every chip shares one structure.

A handler should determine whether the main or process stack was active before the exception and carefully read saved program counter, link register, and status. With an already corrupted stack, complex formatting or linked-list traversal can fault again; a small reserved record area can save essential bytes before reset or entry to a limited state. Floating-point extended frames, nested exceptions, and stack alignment also affect offsets, so blindly applying a fixed structure can read the wrong location.

Offline decoding requires the ELF and link addresses matching the failed image. The program counter identifies a failing or related location, but an imprecise bus fault, for example, may not point directly to the causal write. Examine registers, preceding calls, and memory layout, then validate the inference with a minimal reproduction. Preserve the first fault, version, and record integrity so reset loops do not overwrite key evidence. Successful address decoding is only a clue; the origin of the invalid value still needs explaining.

Debugging Checks
  • Verify that the recorder can preserve minimal context despite stack corruption and nested exceptions, checking frame type, valid bits, and address ranges.
  • Decode fault addresses with the matching release ELF, preserve raw registers and bytes, and never substitute symbols from another version for evidence from the fault.
References

Watchdogs and Liveness Checks

A watchdog detects whether it has been serviced within an agreed interval; it does not automatically prove correct system function. A high-priority periodic task that keeps servicing it can prevent reset even when communication or control logic is stuck. Link servicing to progress in multiple critical tasks, such as advancing cycle numbers, completed state-machine work, and updated sample data, rather than merely checking that tasks once started.

Liveness monitoring must distinguish permitted waiting from abnormal stalls. Calibration, updates, and shutdown may have different deadlines, but relaxed limits must follow explicit state entry rather than allowing any task to extend them indefinitely. The monitor reads a consistent health snapshot and services the watchdog only when all required conditions meet their deadlines. Hardware-watchdog clock, reset coverage, and debug-pause behavior depend on the device; consult its manual and test without a debugger attached.

If information can safely be saved before reset, write only a bounded minimal record; complex Flash operations may consume the remaining time. On the next startup, read reset causes and recent progress to distinguish watchdog trips, supply problems, and intentional resets. Recovery must not automatically enable the motor; configuration, sensors, and communication setpoints require revalidation. Watchdogs provide recovery after lost progress, but logs, state, and resource information are still needed to diagnose the root cause.

Debugging Checks
  • Freeze control, communication, and diagnostic tasks separately; verify that stalls in monitored tasks trigger the required response while permitted waits do not cause false detection.
  • Test timeouts, reset causes, and restart outputs without a debugger, checking the monitoring interval against the actual hardware timeout.
References

Stack, Heap, and Resource Monitoring

Monitor task stacks, exception stacks, heap, fixed pools, and queues. Stack high-water marks show space already used but cannot guarantee safety for the deepest call or exception nesting not yet exercised; fill-pattern scanning may also be affected by reserved space that was never written. Units and stack layouts differ among RTOS ports, so establish whether reported values are bytes or stack elements and which stack the measurement covers.

Embedded systems can statically allocate predictable objects; dynamic allocation needs rules for permitted phases, failure handling, and fragmentation. Sufficient total free heap does not imply a sufficiently large contiguous block or acceptable allocation time. Count buffer-pool exhaustion and full queues as distinct resource events rather than labeling all of them out-of-memory. Confirm prohibited control-path allocations and large local arrays through interface review together with actual link information.

Tests should exercise deepest protocol paths, diagnostic formatting, floating-point interrupts, and error recovery rather than observing only the idle loop. Boundary canaries, heap-integrity checks, and resource peaks detect some problems, but observation has a cost and belongs in an appropriate context. Historical resource peaks and allocation-failure counts before a fault help distinguish persistent leaks from brief bursts. Rebuilding resources on startup without releasing them may reveal a problem only after repeated recovery cycles.

Debugging Checks
  • Check monitoring units and port behavior, apply deepest-call and nested-interrupt loads, and inspect task-stack and exception space separately.
  • Repeatedly start, stop, and cancel transactions; check heap fragmentation, pool returns, queue peaks, and resource recovery after failures.
References

Fault Records, Timestamps, and Version Identifiers

Fault records should include event type, operating state, key values, sequence number, timebase, and firmware identity. A lone error code rarely distinguishes states before and after a failure, while large text logs may take too long at the critical instant. Small fixed-format records allow bounded copying in high-priority contexts, followed by parsing or export from lower-priority tasks; count buffer overflows too.

Timestamps need a defined source and unit. System ticks suit slower events and hardware counters describe fine timing, but wraparound, clock switching, and sleep affect interpretation. Prefer a shared timebase across contexts or preserve conversion relationships; subtracting host time from device time does not directly yield precise latency. Event sequence numbers supplement timestamps and preserve some ordering when resolution is insufficient or records are lost.

Version identifiers must match the running image rather than merely the current branch in a development directory. Preserve commit or build identifiers, image-hash mappings, board versions, and parameter versions so offline tools can choose correct symbols and definitions. Persistent logging needs its own endurance and power-loss-integrity design; writing Flash directly every cycle is inappropriate. After export, retain raw bytes and the parser version so later field changes do not misinterpret old contexts or overwrite the only failing sample after a fix.

Debugging Checks
  • Create closely timed events and counter-wraparound events, checking sequence numbers, units, and parsing rules, and ensure lost records are explicitly identifiable.
  • Read versions and decode faults using the actual release image, verify board/parameter/symbol correspondence, and preserve raw records and integrity status.
References

Technical fields

Motor Control

Motor Control

Motor models and parameters

Model boundaries for PMSM, BLDC, and induction motors · Mechanical angle, electrical angle, and pole pairsExpand the Motor Models and Parameters Knowledge Directory
  • Model Boundaries for PMSM, BLDC, and Induction Motors
  • Mechanical Angle, Electrical Angle, and Pole Pairs
  • Resistance, Inductance, Flux Linkage, and Dimensions
  • Load, Inertia, Torque, and Speed
Reading Guide: Align Coordinates, Signs, and Units Before FOC

Model Boundaries for PMSM, BLDC, and Induction Motors

A motor's name alone does not determine its control model. A permanent-magnet synchronous motor with sinusoidal back EMF is naturally described in rotor-flux coordinates. For a common trapezoidal-back-EMF BLDC motor operating with six-step commutation, commutation regions and freewheeling states directly affect torque, so average torque relationships from a sinusoidal model do not hold at every instant. Induction motors also have rotor current and slip, and their flux-establishment dynamics cannot be replaced with a constant permanent-magnet flux. Define whether the model should explain the current loop, startup commutation, or mechanical response before selecting it.

For firmware tuning, start with a lumped-parameter model to analyze sampling delay, gains, and limiting, then add nonideal terms to address observed faults. Explaining current spikes requires switching states, dead time, and measurement channels; explaining load-side vibration requires transmission elasticity, backlash, or multiple inertias. Greater complexity introduces more unknown parameters and computational cost, so add structure based on observed evidence rather than enabling every module and expecting waveforms to resemble the equipment automatically.

Document model boundaries alongside the parameter package, including winding connection, back-EMF waveform, coordinate normalization, iron-loss treatment, and saturation. In salient permanent-magnet motors, unequal direct- and quadrature-axis inductances produce reluctance torque; the approximately equal-inductance assumption for surface-mounted motors does not apply universally. An induction-motor model for a variable-frequency drive should state whether orientation follows stator or rotor flux, with temperature-related rotor-parameter error verified separately. Stable model operation proves only internal consistency under the chosen assumptions.

Debugging Checks
  • Check winding connection and back-EMF definitions in the motor manual, then compare model inputs, phase currents, and average torque using consistent axes and units.
  • Document an observable residual for each neglected effect; for example, investigate harmonics and sampling for periodic errors near commutation, and transmission modeling for load-side oscillation.
References

Mechanical Angle, Electrical Angle, and Pole Pairs

Mechanical angle describes actual rotor-shaft position; electrical angle describes the magnetic-field cycle. For a permanent-magnet synchronous motor with p pole pairs, and matching positive mechanical and field directions, electrical angle can be written as θe=wrap(p·θm+θ0), with both angles in radians and θ0 the electrical-zero offset. If configuration stores a mechanical-zero offset, multiply it by the pole-pair count before using it in the electrical-angle calculation. Confusing total poles with pole pairs, or adding a mechanical offset directly to electrical angle, creates periodic misalignment over a full revolution.

Speed also needs a clear level: mechanical angular velocity is in radians per second and electrical angular velocity is p times that value; mechanical speed in revolutions per minute additionally requires multiplication by 2π/60. The current loop uses electrical angle for coordinate transformations, while position planning normally uses unwrapped mechanical position. Preserve separate variables and type semantics rather than compressing every angle into a zero-to-one per-unit variable and losing revolution count, direction, and validity information.

When a counter difference crosses wraparound, calculate the signed increment from the modulus and maximum permitted displacement instead of ordinary subtraction. Electrical-angle wrapping suits trigonometric functions, but taking the shortest path for mechanical position error depends on the axis: unlimited rotary axes and travel-limited axes differ. Pole-pair count, direction, and offset must also take effect together during parameter updates; changing only one while running abruptly changes control coordinates and may create unintended torque.

Debugging Checks
  • Increase the input mechanical angle through one full revolution and verify exactly p electrical-angle wraps; cover forward and reverse rotation, zero crossings, and counter overflow separately.
  • Log raw counts, unwrapped mechanical angle, electrical angle, and offset units together, and verify that speed conversion includes pole-pair count and the rotational-speed unit factor.
References

Resistance, Inductance, Flux Linkage, and Dimensions

Control-parameter names must include physical definitions. Specify whether resistance is per-phase or line-to-line, its measurement temperature, and winding connection; specify direct/quadrature axis, test frequency, and bias current for inductance; specify permanent-magnet or total axis flux linkage. Standardize ohms, henries, webers, and amperes at the firmware parameter-conversion entry. Treating millihenries as henries corrupts both current-model time constants and feedforward terms, and compensating with gains then conceals the cause.

Back-EMF constants are often expressed as line-to-line peak or RMS voltage per thousand rpm, while flux linkage in equations usually corresponds to a phase quantity under a specific coordinate normalization. Derive conversions step by step from the manual's definition rather than applying a fixed factor based on a constant's name. Distinguish DC-bus voltage, phase-to-neutral fundamental peak voltage, and normalized modulation values as well. A simple line-to-line/per-phase resistance relationship for star windings requires balanced phases and a defined measurement path; delta connections need separate treatment.

Firmware may store both engineering-unit parameters and derived coefficients, but derived coefficients should state their sampling-period and base-value dependencies. Temperature rise affects resistance, magnetic saturation affects inductance, and magnet temperature may affect flux linkage, so identified values are not exact constants over the full speed/current range. Check units and definitions before discussing nonlinearity when comparing model and equipment; order-of-magnitude errors usually determine results before complex control theory does.

Debugging Checks
  • Create a parameter table containing definitions, units, connection, sources, and valid operating conditions, and manually check the order of magnitude of one set of resistive voltage drops and inductive voltages.
  • Generate floating-point and per-unit parameters from the same engineering-unit set, convert back to check consistency, and verify that the parameter package is bound to the correct sampling period.
References

Load, Inertia, Torque, and Speed

Mechanical dynamics can begin with a rigid single-inertia model: J·dωm/dt=Te−TL−B·ωm. Here J is inertia referred to the motor shaft in kilogram square meters, ωm is mechanical radians per second, electromagnetic and load torques are in newton meters, and B is viscous damping in newton meters per radian per second. The equation assumes consistent positive directions, approximately rigid transmission, and a unified load-torque sign convention; load-side sensor readings cannot be inserted directly into a motor-shaft equation.

Inertia determines acceleration for a given net torque, while damping, friction, and external load determine required torque at different speeds and directions. Gearbox-reflected inertia depends on the square of the transmission ratio, but first define whether that ratio means motor speed divided by load speed or the reverse. Efficiency and friction make torque conversion differ between forward motoring and reverse power flow, so one unsigned ratio cannot cover every motion mode. Flexible couplings may also produce load-side resonances absent from a motor-shaft model.

During speed-loop debugging, record acceleration torque caused by setpoint changes separately from load torque at constant speed. Smooth no-load rotation does not prove reliable loaded tuning; inertia changes, gravity direction, and friction dead zones all alter error. If torque for inertia estimation comes only from current conversion, state the motor torque constant, coordinate peak convention, and loss assumptions. Do not treat estimated torque as calibrated measured shaft torque, or later tuning will rest on incorrect evidence.

Debugging Checks
  • Check net-torque signs separately during acceleration, deceleration, and constant-speed motion with a known positive direction, and verify units, direction, and transmission ratio between motor and load shafts.
  • Compare speed error and current requests under different loads, check for saturation or elastic resonance, and then assess whether a single-inertia model remains suitable.
References
Motor Control

Modulation, Sampling, and Delay

PWM/SVPWM and voltage vectors · Dead time, sampling windows, and current reconstructionExpand the Modulation, Sampling, and Delay Knowledge Directory
  • PWM/SVPWM and Voltage Vectors
  • Dead Time, Sampling Windows, and Current Reconstruction
  • Trigger, Computation, and Output-Update Timing
  • Voltage Utilization and Modulation Limits
Reading Guide: Real-Time Budgets for PWM, ADC, and Control Calculations

PWM/SVPWM and Voltage Vectors

Switching combinations in a three-phase two-level inverter form a finite set of voltage vectors. Space-vector modulation allocates their durations within a period so the average voltage approximates the target stationary-frame vector. Firmware often adds a common offset to inverse-transformed three-phase references before converting them to duty cycles. This can express the same modulation goal as sector-based duration calculations, but normalization, zero-vector allocation, and switching order must match; function names alone do not establish equivalent output behavior.

Duty cycle is not instantaneous phase-to-neutral motor voltage. DC-bus variation, dead time, power-device drops, and neutral-point movement make actual voltage differ from the ideal. Observer voltage should correspond to the actual applied period, duty cycles, and bus measurement rather than the controller output before limiting. Center-aligned and edge-aligned operation also change sampling-window locations and effective delay, so define modulation together with timer counting mode.

When porting a space-vector module, verify axes and scaling first, then switching sequences. A zero input vector should produce the defined neutral duty cycles; sweeping angle across six sectors should keep phase sequence and average line-to-line voltage continuous. A common offset changes leg-to-bus waveforms but should not change the ideal line-to-line fundamental target. Discontinuous modulation clamps a leg over a region, changing losses, noise, and measurement conditions, so validate it independently rather than retaining continuous-modulation sampling assumptions.

Debugging Checks
  • Generate duty cycles for zero input, axis-aligned inputs, and six-sector boundaries, checking ranges, phase sequence, common offset, and reconstructed average line-to-line voltage.
  • Log voltage before and after limiting, sampled bus voltage, and final compare-register values together, and verify that the observer uses the period actually applied.
References

Dead Time, Sampling Windows, and Current Reconstruction

Dead time leaves a gap between upper- and lower-switch transitions, but its actual voltage error depends on current direction, device drops, and propagation delay. Near zero current, noise may repeatedly reverse compensation sign; switching a fixed compensation directly with current sign can create jitter. Explicitly define the compensation region, sign hysteresis, and output limit, and preserve raw current so compensated results do not conceal measurement offset.

Single DC-link-shunt sampling needs at least two distinguishable current observations during active vectors. Map them to phase currents using switching states, then reconstruct the third phase only where there is no neutral wire and the current sum is approximately zero. Window width must include post-dead-time settling, amplifier settling, ADC sample-and-hold, and trigger error. Active vectors may become too short near sector boundaries or at low modulation; obtaining a number does not make it valid. Reconstruction functions should receive window-validity and sector information.

Two- and three-shunt arrangements cannot measure at arbitrary instants either. Low-side sampling depends on the relevant switches conducting, and extreme duty cycles may shorten the shared valid window. If pulse shifting expands a window, update voltage reconstruction and delay models with it; if previous-cycle currents are substituted, mark their age and restrict their use. To locate current discontinuities, observe raw ADC values, sector, trigger time, and validity bits together; smoothed d/q currents alone rarely reveal the cause.

Debugging Checks
  • Scan the shortest valid window across six sectors and modulation levels, accounting individually for hardware settling, ADC sampling time, and trigger margin.
  • Inject invalid windows, sector crossings, and near-zero currents; verify that reconstruction does not treat stale samples as new and dead-time compensation does not continually reverse because of noise.
References

Trigger, Computation, and Output-Update Timing

Explicitly divide a current-control cycle into triggering, sample-and-hold, conversion completion, data transfer, control calculation, shadow-register writing, and hardware loading. Interrupt-entry timing covers only one part; even a fast calculation may apply voltage one period late if it misses the shadow-load point. Timing diagrams should show PWM count direction and the period number for every event so half-period and full-period updates are not confused.

Angles also have sampling times. Feedback-transform angle should align with current sampling, while inverse-transform angle may need to account for actual output activation. Predictive compensation converts mechanical speed to electrical speed using pole pairs and multiplies by delay in seconds; it assumes speed changes are modest and delay estimates are credible. Blind fixed-angle compensation can be wrong during reversal or acceleration; one steady-state high-speed improvement does not validate every operating condition.

Firmware must distinguish fixed delay from random jitter. Fixed delay can enter a model as a shift or continuous delay; jitter and occasional overruns require distributions and worst-case records. Communication interrupts, cache waits, and log transmission may affect only a few cycles, so average execution time cannot prove deadline compliance. Explicit state logic must define how an overrun holds or revokes output and whether it latches a fault, while ensuring expired calculations cannot overwrite results from newer cycles.

Debugging Checks
  • Use hardware events or GPIO markers to measure the path from sampling trigger to actual PWM loading, covering nested interrupts, communication stress, and enabled logging.
  • Deliberately make computation cross the loading point; check cycle sequence numbers, overrun counts, and output handling, ensuring angle prediction does not use stale speed.
References

Voltage Utilization and Modulation Limits

Voltage utilization requires an explicit voltage definition. For an ideal two-level three-phase inverter, balanced sinusoidal targets, and amplitude-invariant transforms, linear space-vector modulation guarantees a maximum phase-to-neutral fundamental peak of DC-bus voltage divided by √3 at every angle; sinusoidal modulation has a corresponding limit of half the bus voltage. These relationships describe ideal average voltage within the linear region, not a universal conversion between a measured bus voltage and any software per-unit value.

Practical implementations need margin for dead time, minimum pulse width, sampling windows, and bus-measurement error. As bus voltage falls, shrink the feasible d/q voltage region accordingly and feed actual clipping into anti-windup. Limiting each axis independently can still produce a vector outside the circular boundary despite legal individual components. Preserving vector direction, prioritizing the d axis, and prioritizing the q axis are distinct policies that must be chosen in light of field-weakening and torque goals.

Overmodulation changes the relationship between average voltage and reference vector and introduces additional harmonics and measurement difficulties. Entering overmodulation cannot mean merely clipping duty cycles to zero and one while retaining linear observer and current-loop models. Engineering acceptance should distinguish the normal linear region, active field-weakening region, limited overmodulation region, and unacceptable region, defining sample validity, integrator handling, and exit conditions for each. Check voltage headroom before further increasing proportional gain when current tracking deteriorates at high speed.

Debugging Checks
  • Check software voltage bases using the same peak and normalization definitions, then scan limiting boundaries and final duty cycles across vector angles.
  • Simulate falling bus voltage and short sampling windows; confirm that voltage limits, anti-windup feedback, and sample-validity decisions change together, and record whether overmodulation is explicitly enabled.
References
Motor Control

FOC and Cascaded Control Loops

Clarke/Park and sign conventions · d/q current loops and voltage limitingExpand the FOC and Cascaded Control Loops Knowledge Directory
  • Clarke/Park and Sign Conventions
  • d/q Current Loops and Voltage Limiting
  • Speed and Position Loops and Operating Modes
  • Decoupling, Feedforward, and Anti-Windup
Reading Guide: Align Coordinates, Signs, and Units Before FOC

Clarke/Park and Sign Conventions

First fix phase sequence, axes, and normalization for coordinate transforms. This text uses amplitude-invariant Clarke transformation: when the three phase currents sum to zero, iα=ia and iβ=(ia+2ib)/√3. For Park transformation, the d axis coincides with α at zero angle: id=iαcosθe+iβsinθe and iq=−iαsinθe+iβcosθe. Currents are in amperes and θe is electrical angle in radians. A power-invariant form changes amplitude relationships and power coefficients, so replacing only the matrix while retaining every torque parameter is invalid.

These definitions must remain consistent through phase-current measurement, encoder direction, torque sign, inverse transforms, and modulation output. After swapping phase wires or current channels, a motor may still rotate while feedback axes and feedforward signs no longer match. Use known vectors for algebraic tests, then limited output to verify the equipment's positive direction. Randomly flipping pairs of signs until rotation works can leave new errors for reversal and field weakening.

Imbalance, measurement offset, or common-mode leakage can violate the assumptions of a two-input Clarke transform. When reconstructing the third phase from a zero current sum, preserve applicability limits and abnormal-condition diagnostics. Begin transform verification with forward/inverse round-trip error and check whether balanced sinusoidal currents become approximately constant in the matching rotating frame. For twice-frequency or fundamental ripple, check angle, phase sequence, and calibration first, then distinguish harmonics, asynchronous sampling, and mechanical factors.

Debugging Checks
  • Apply zero, α-axis, β-axis, and four-quadrant angle inputs, verifying forward/inverse round-trip error and the defined positive q-axis direction.
  • Document the normalization coefficients used for power or torque calculations, and verify that electrical angle is mechanical angle multiplied by pole pairs and aligned to current-sampling time.
References

d/q Current Loops and Voltage Limiting

d/q current loops output voltage requests limited by the inverter's currently available voltage. With ideal decoupling and approximately constant parameters, each axis can initially be treated as a resistance-inductance plant, then extended with cross-coupling, back EMF, sample-and-hold, and computation delay. This simplification supports initial tuning, but high speed, magnetic saturation, and bus variation increase deviations; low-speed current steps alone do not establish full-speed performance.

Form the final feasible voltage vector by clipping after all feedback and feedforward terms are summed. Limiting PI output before adding feedforward can still yield an out-of-range total; clipping only inside the modulator without informing the controller can let the integrator keep accumulating. Circular vector scaling preserves direction, while axis-priority policies allocate remaining voltage; these produce different flux and torque errors, so define the feasible region and axis priorities explicitly.

Control-loop data structures can retain error, proportional term, integral term, feedforward, unclipped voltage, and clipped voltage separately. When current fails to track, this distinguishes insufficient gain, inaccurate angle, distorted measurements, and exhausted voltage resources. Derive limits from current bus measurements and modulation conditions rather than a constant rated voltage. Continuing to tune gains while voltage is unavailable mistakes a constraint problem for a controller problem and increases recovery risks after saturation ends.

Debugging Checks
  • Apply d-axis, q-axis, and diagonal voltage requests; verify that clipped vectors remain feasible and axis-priority policy matches field-weakening goals.
  • Log bus voltage, limiting flags, and integrator changes, then reduce the setpoint after sustained saturation and check that current recovery does not retain incorrect voltage for a long time.
References

Speed and Position Loops and Operating Modes

Cascaded-loop interfaces must define physical quantities and update times: the position loop outputs mechanical-speed requests, the speed loop outputs torque or q-axis-current requests, and the current loop outputs d/q voltages. Function call order alone is insufficient; define snapshots and limiting feedback between fast and slow tasks. Position and speed loops are usually slower than current loops, but rates and bandwidth separation depend on mechanical dynamics, measurement noise, and total delay; one fixed ratio cannot guarantee stability for every drive.

Torque mode does not disable the current loop, and speed mode does not imply that position commands may continue affecting output. Each mode must define active setpoints, whether outer loops run, whether integrators track, and where speed/travel limits apply. Before switching modes, align the incoming controller's internal state with current output so an old position error or speed integral cannot suddenly take over. While an outer loop is disabled, it may track actual output or reset according to design, but either behavior must match reenable procedures.

When a slow loop requests more than available current, inform the outer loop that its request was not executed; otherwise speed integration accumulates during inner-loop current limiting. Position planning must also consider current speed and available acceleration/deceleration rather than relying on downstream clipping to replace trajectory design. Log requests and actual values at every layer together; position error alone rarely distinguishes upstream command jumps, speed limits, torque limits, and current-sampling problems.

Debugging Checks
  • Verify active setpoints and loop-enable flags in each mode, ensuring inactive interfaces cannot keep affecting output through historical integrals or feedforward.
  • Check every loop's state together during current limiting, speed limiting, and mode changes; ensure the new mode's first output is continuous and outer loops receive actual constraint information.
References

Decoupling, Feedforward, and Anti-Windup

For rotor coordinates with d aligned to permanent-magnet flux and q defined by the negative-sine convention, a constant-parameter PMSM model can use feedforward vd_ff=−ωeLqiq and vq_ff=ωe(Ldid+ψm). Current is in amperes, inductance in henries, flux linkage in webers, and output in volts; ωe=pωm, with both angular velocities in radians per second. Feedforward signs follow the selected equations and cannot be copied to other axis conventions; in particular, mechanical-speed values must not be inserted directly as electrical angular velocity.

Feedforward reduces known disturbances, while feedback addresses parameter errors and unmodeled effects. Using measured versus reference current, filtering speed, and varying parameters with current all affect phase and noise. Recheck total-voltage feasibility after adding feedforward; an unsaturated current-loop output does not mean the combined modulation request is realizable. If decoupling performs poorly, check axes, units, time alignment, and motor parameters first rather than treating increased gain as the only remedy.

Anti-windup should use the difference between final applied and requested outputs; back-calculation, conditional integration, or tracking suit different situations. The back-calculation coefficient sets integrator-release dynamics: too fast may amplify noise, while too slow prolongs recovery. Pausing integration should still allow errors to drive output away from saturation. Outer-loop limits, slew-rate limits, and mode changes also create execution mismatches; addressing only voltage clamping inside the current loop misses accumulation elsewhere in the cascade.

Debugging Checks
  • Check feedforward signs at forward/reverse speeds and positive/negative q-axis currents, verifying in consistent units that every product yields volts.
  • Include falling bus voltage, feedforward enable/disable, and outer-loop current limiting in saturation-release tests; verify that back-calculation uses final applied output and permits integration toward release from saturation.
References
Motor Control

Position Feedback and Startup

Hall sensors, incremental encoders, and absolute encoders · Direction, zero position, and angle alignmentExpand the Position Feedback and Startup Knowledge Directory
  • Hall Sensors, Incremental Encoders, and Absolute Encoders
  • Direction, Zero Position, and Angle Alignment
  • Start/Stop, Alignment, and Transition Conditions
  • Feedback Faults and Limited Operation

Hall Sensors, Incremental Encoders, and Absolute Encoders

Position sensors provide different levels of information. Three Hall signals normally identify coarse electrical sectors; speed-based interpolation between edges loses credibility during low-speed dwell and changing acceleration. Incremental encoders provide relative counts, and total quadrature counts must be distinguished from lines per revolution. An index pulse helps establish a reference but does not automatically supply absolute multiturn position before that reference is found after power-up. Absolute encoders return encoded position, yet their mechanical installation zero still differs from the motor-flux electrical zero.

Feedback interfaces should return position, timestamp, direction, and validity together. Serial absolute encoders may also provide CRC, alarm bits, or multiturn data; transmission period and sampling time contribute to angle age. Count-based interfaces must handle counter wraparound, lost pulses, and input-filter delay; Hall decoding must reject illegal combinations and implausible sector jumps. Reusing the last angle after decoding fails while leaving validity true prevents the control loop from detecting lost fresh feedback.

Select count differencing, edge-period measurement, or fusion according to the speed range. Low-speed differences suffer quantization, while high-speed edge periods become short and timing-resolution sensitive; switching should avoid output jumps. A position-source abstraction can standardize engineering units while retaining each sensor's information limits. Replacing a high-resolution encoder with Hall interpolation may no longer satisfy some position-control or holding functions, so redefine supported modes.

Debugging Checks
  • Check lines per revolution, decoding multiplier, pole pairs, and counts per revolution; cover illegal Hall codes, encoder wraparound, serial-check failures, and multiturn-data jumps.
  • Align position-data sampling time with current sampling and verify that switching between low- and high-speed measurement does not introduce unexplained direction or magnitude jumps.
References

Direction, Zero Position, and Angle Alignment

Verify feedback direction separately from electrical zero. First confirm that the mechanical positive direction increases counts under limited conditions, then check phase sequence and current channels, and finally determine flux zero. Reversing this order can let a zero offset temporarily conceal a direction error: the motor may run one way but lose correct coordinates in reverse or at high speed. Mounting direction at the shaft end also changes rotary-sensor count sign; wire colors alone do not establish it.

Alignment normally applies a known stator field to bring the rotor to a reference direction before reading sensor position; it produces torque and is affected by load, friction, and mechanical constraints. Heavy loads or constrained axes may not reach the expected angle, and waiting a fixed time does not prove alignment. Define current limits, permitted displacement, settling criteria, and timeout handling. Pole identification or high-frequency injection requires separate motor-saliency and signal-processing conditions; these are not all the same zero-calibration method.

Saved offsets should specify mechanical/electrical units, sign, pole pairs, sensor resolution, and parameter version. Replacing the motor, encoder, or mechanical installation invalidates old offsets, and updates during operation require state control. Low-risk observations of d/q current, estimated torque, and direction consistency can help verify zero, but a small q-axis current is not the sole proof for all installations. Manage multiturn position reference independently from electrical zero too.

Debugging Checks
  • Apply a known mechanical direction manually, check count, speed, electrical-angle, and torque conventions, then perform limited alignment and verify actual settling conditions.
  • Verify offset source, units, and version after restarts and parameter-package changes; alignment timeout or obstruction must block modes that depend on that zero reference.

Start/Stop, Alignment, and Transition Conditions

Startup should comprise states with preconditions, exit conditions, and failure paths. A typical sensored sequence checks bus voltage and measurement channels, confirms current offsets, feedback validity, and zero, then gradually establishes current and outer-loop setpoints. Sensorless startup may also require alignment and open-loop acceleration. Identical stage names do not imply identical conditions; choose paths according to motor type, sensor capability, and current rotation rather than applying one unconditionally fixed sequence to both standstill and windmilling starts.

At closed-loop handover, angle source, speed estimate, and integrator state must match current execution closely. Compute the difference between sensor/observer and open-loop angles with electrical-angle wrapping, and migrate smoothly using a validated policy while retaining current, voltage, and acceleration limits. Interpolation cannot repair arbitrary angle errors; excessive angle differences or inadequate observer validity must reject handover and enter a defined recovery path.

Stopping also involves output and energy. Immediate PWM removal, controlled deceleration, and torque holding have different mechanical consequences, and deceleration may return energy to the bus. Design fault stops according to product hardware and risk analysis rather than assigning every servo and variable-frequency drive the same action. Define which states reset or track on restart, whether absolute position is retained, and whether old commands expire, preventing reconnection from automatically executing stale pre-stop motion requests.

Debugging Checks
  • Inject feedback loss, obstructed alignment, and startup timeout in every state, ensuring conditions cannot be bypassed and invalidated setpoints are not reused.
  • Check angle and integrator continuity during restarts from standstill, residual reverse rotation, and controlled deceleration, recording bus responses during startup and stopping.
References

Feedback Faults and Limited Operation

Feedback faults include more than disconnection: delay, repeated frames, jumps, invalid counts, direction contradictions, and implausible acceleration also matter. Detection should combine physical bounds and sampling intervals; simply comparing consecutive positions may falsely flag wraparound or miss a slowly developing freeze. Preserve raw data, protocol validity bits, and receive times so faults can be associated with the angle actually used by control.

Limited operation requires evidence that substitute information supports the selected mode. Switching to sensorless estimation after encoder failure may work only with a suitable motor and speed range, a converged observer, and satisfied handover conditions; back-EMF observation generally cannot maintain stationary position holding. Hall fallback may support only low-precision speed or torque control. Allowed speed, current, and duration depend on equipment capability; the existence of a backup algorithm does not prove automatic fallback is usable.

Separate fault latching and recovery from reestablishing credible feedback. One correct frame does not prove subsequent stability or justify automatically clearing a drive fault and replaying commands. Continuous valid windows, realignment, or rehoming may be recovery conditions, but window duration must reflect the error type and real-time requirements. Logs should distinguish raw abnormalities, derived speed abnormalities, and controller limiting, avoiding contradictory root causes for one sensor problem.

Debugging Checks
  • Inject frozen counts, repeated valid frames, angle jumps, and reversed direction; verify that detection handles wraparound and checks data age.
  • Prove that angle and speed information required by each fallback mode remains available; for failures at low speed and standstill, verify that stopping and recovery do not automatically resume old motion.
References
Motor Control

Sensorless Observation and Estimation

Voltage, current, and back-EMF observation · SMO and PLL boundariesExpand the Sensorless Observation and Estimation Knowledge Directory
  • Voltage, Current, and Back-EMF Observation
  • SMO and PLL Boundaries
  • Open-Loop Startup and Closed-Loop Handover
  • Low Speed, Noise, and Estimation Reliability

Voltage, Current, and Back-EMF Observation

Back-EMF observation starts from voltage balance, interpreting the difference between measured current behavior and actual applied voltage as internal motor EMF. In a simplified stationary-frame model of a surface-mounted permanent-magnet motor with approximately equal axis inductances, subtract resistive voltage drop and the inductive current-change term from voltage. This relies on parameters, measurement, and time alignment. Using voltage before limiting or bus voltage from the previous cycle misattributes inverter error to back EMF and creates angle error.

An observer should use the voltage period matching its current samples and state whether voltage is measured or reconstructed from PWM. Reconstruction needs assumptions for actual duty cycle, bus voltage, dead time, and device drops. Current offset, gain errors, and asynchronous phase samples enter the residual directly; low-pass filtering reduces high-frequency disturbances while adding phase delay. Bind observer coefficients to execution period rather than retaining old discrete parameters after changing the control-interrupt frequency.

For salient motors, unequal axis inductances and current dynamics may require extended back-EMF or other models; a simple surface-mounted model may be inadequate. State whether observer angle is electrical or mechanical; mechanical-speed outputs must correspond to EMF frequency through pole pairs. In a permitted development environment, an independent position sensor can provide a reference for same-time error comparisons; motor rotation alone is insufficient evidence of correct angle estimation.

Debugging Checks
  • Align voltage-application, current-sampling, and observer-update cycles, and check that reconstructed voltage uses final duty cycles and valid bus measurements.
  • Sweep resistance error, current offset, and sampling delay, observing angle error and residuals; when a reference sensor is available, compare electrical angles at the same instant.
References

SMO and PLL Boundaries

A sliding-mode observer constructs a correction from current-estimation error to bring estimated current toward actual current, then extracts information associated with back EMF. Discrete switching terms, saturation functions, boundary layers, and filtering jointly determine convergence, chattering, and noise. Higher sliding-mode gain may correct errors faster but amplify quantization and sampling noise; ideal continuous-time convergence is not a performance guarantee for finite-precision firmware.

A phase-locked loop tracks phase and frequency from quadrature signals, smoothing angle and maintaining speed state, but cannot create rotor information absent from its inputs. Input amplitudes, axes, phase order, and normalization must agree, with unstable division or normalization handled at low amplitude. Analyze observer-filter phase shifts together with the PLL and output timing to avoid duplicate compensation or incorrect signs.

Record current-estimation error, back-EMF amplitude, phase-lock error, and estimated speed separately. A small current residual with wrong phase may indicate voltage-model or angle-compensation issues; a smooth PLL is not necessarily correct, and stable-looking speed may reflect heavy output filtering. Tune by validating inputs and the discrete model first, then the observer, then PLL dynamics, covering acceleration, deceleration, and reversal. Each stage needs explicit validity criteria.

Debugging Checks
  • Verify the PLL independently with quadrature inputs of known frequency and direction, covering amplitude mismatch, near-zero amplitude, and angle wraparound.
  • Record sliding-mode correction, EMF before and after filtering, and phase-lock error separately; check whether increased gain adds chattering or filter compensation is duplicated.
References

Open-Loop Startup and Closed-Loop Handover

Back-EMF methods lack sufficient signal at standstill. A common startup establishes a stator field, then accelerates with limited current and an open-loop angle until EMF information becomes usable. The open-loop electrical-angle rate defines synchronous-field speed; actual rotor position may lag due to load or inertia, so planned angle is not true rotor feedback. Startup current, acceleration rate, and duration must respect equipment capability and load conditions rather than being copied directly from example software.

Closed-loop handover should check estimated direction, speed range, back-EMF quality, angle difference, and continuous settling time together. Switching solely at a target speed misses loss of synchronism, reverse rotation, and unconverged observers. Use wrapped electrical-angle differences and pole-pair conversion between electrical and mechanical speed. Gradual angle blending must follow the shortest phase path across zero rather than directly averaging two numbers between zero and 2π.

Coordinate current references, speed-loop integrals, and limits at handover too. A closed-loop speed controller taking over from zero integral may not support the existing load, while mismatched historical integration can cause a current surge. Define the fallback state after failure, whether retry is allowed, whether stopping is required first, and how the observer resets. Repeated startup failures should become diagnosable outcomes rather than endless alignment/acceleration cycles that disguise a mechanical stall as ordinary startup.

Debugging Checks
  • Check handover criteria under different inertias, load directions, and bus conditions, saving open-loop angle, estimated angle, electrical-angle difference, and continuous valid duration.
  • Inject incorrect observer direction and loss of synchronism and verify handover rejection; during valid handover, check continuity of current requests, integrators, and final voltage.
References

Low Speed, Noise, and Estimation Reliability

Low-speed reliability depends on useful signal relative to error. Permanent-magnet motor back EMF usually falls with speed, while current offset, resistance error, and inverter dead-time effects do not diminish proportionally. No universal minimum speed applies to every motor, sampling topology, and observer. Define operating regions from actual signal-to-noise ratio, parameter ranges, load, and angle-error requirements, distinguishing startup, sustained low speed, and zero-speed holding.

High-frequency injection can exploit saliency or saturation to provide extra position information, but requires suitable motor properties and modulation/sampling bandwidth and may add noise, losses, and acoustic effects. It does not confer zero-speed capability merely by adding a filter to an ordinary back-EMF observer. Surface-mounted motors, salient motors, and different saturation states have different observability conditions, so document algorithm assumptions explicitly.

Combine EMF amplitude, current-model residuals, phase-lock error, speed continuity, and data age for reliability decisions rather than using one amplitude threshold. Define entry and exit conditions to prevent repeated boundary switching, followed by a specified limited action on exit. Heavy filtering can delay loss-of-lock detection, so observe unsmoothed key quality signals too. Published research demonstrating feasibility on a particular platform cannot replace complete low-speed acceptance on the target equipment.

Debugging Checks
  • Sweep speed, load, current offset, and temperature-related parameters, recording angle errors and loss-of-lock counts and identifying regions without sufficient evidence.
  • Accelerate, decelerate, and reverse slowly near estimation boundaries; check validity hysteresis, fault delay, and exit actions rather than treating smooth speed as proof of lock.
References
Motor Control

Motion Commands and Trajectories

Position, speed, and torque commands · Trapezoidal/S-curve profiles and constraintsExpand the Motion Commands and Trajectories Knowledge Directory
  • Position, Speed, and Torque Commands
  • Trapezoidal/S-Curve Profiles and Constraints
  • Mechanical Quantities, Transmission Ratios, and Electronic Gearing
  • Following Error and Command Continuity

Position, Speed, and Torque Commands

First define the control level of a motion command. Position requests specify a mechanical target or increment, speed requests specify mechanical speed, and torque requests specify shaft torque or an agreed current-equivalent quantity; scaling, signs, and update times differ. New bus values need permission, mode, range, and sequence checks before becoming a control-task snapshot. Three interfaces sharing an integer type does not make the same register a valid setpoint in every mode.

Position mode needs a reference coordinate, absolute/relative semantics, travel limits, and current speed; speed mode needs acceleration/deceleration constraints and timeout policy; torque mode still requires current feedback control and product-defined motion constraints. Retain command and limiting layers separately: original target, planned target, current loop input, and actual feedback serve different purposes. Logging only the final clipped request loses evidence of unreasonable upstream targets.

On mode changes, define whether previous commands remain valid, whether ongoing motion may transfer directly, and how the new mode initializes internal state. Converting torque to q-axis current requires stated motor-model, flux-linkage, and d-axis-current conditions; a simple constant ratio does not universally apply to salient motors. For cyclic communication setpoints, also define missing updates, duplicate sequence numbers, and the first frame after recovery so reconnection cannot suddenly resume an old trajectory.

Debugging Checks
  • Check command units, active interfaces, and signs in every mode, together with out-of-range requests, duplicate sequence numbers, timeouts, and the first frame after reconnection.
  • Save every stage from original command to final loop input and verify that mode switching cannot reactivate another mode's historical target or integral.
References

Trapezoidal/S-Curve Profiles and Constraints

A trapezoidal velocity profile limits velocity and acceleration but changes acceleration abruptly at phase boundaries. An S-curve additionally limits jerk for smoother acceleration transitions. Specify whether an S-curve uses piecewise constant jerk, a fifth-order polynomial, or another generator, because relationships among maximum speed, acceleration, and duration differ. A smooth position curve does not automatically establish acceptable drive current or mechanical resonance; trajectories must reflect axis dynamics and available torque.

Short moves may have no constant-speed phase. Recalculate phases from distance, initial/final speed, and constraints rather than cutting the normal trapezoid's middle phase into a negative duration. Online target changes should continue from the current planned state, preserving position and velocity continuity; acceleration continuity additionally requires current acceleration as a new initial condition. Independently regenerating a zero-speed trajectory from current position every cycle repeatedly breaks command continuity.

Discrete implementations must reconcile phase duration, sampling period, and the final point. If duration is not an integer multiple of the sampling period, use final-step interpolation or redistribute phases rather than forcing a target jump in the last frame. Integer position accumulation can also accumulate rounding error; use sufficiently wide internal state and explicit error handling. Feasible deceleration depends on regenerated energy and mechanical load too, so derive trajectory constraints from equipment capability rather than mathematical speed/acceleration limits alone.

Debugging Checks
  • Cover zero distance, short moves, nonzero initial/final speed, and mid-motion target changes; verify nonnegative phase times and continuous position and velocity.
  • Calculate velocity, acceleration, and jerk bounds at discrete samples and phase boundaries, ensuring a single-frame position jump is not used to correct the endpoint.
References

Mechanical Quantities, Transmission Ratios, and Electronic Gearing

Mechanical conversion needs a complete unit chain. Define motor counts per revolution, transmission-ratio direction, load displacement per revolution, and user units before mapping commands to internal position. If n is motor revolutions divided by load revolutions, ideal rigid transmission makes motor angular speed n times load speed; screw lead converts load revolutions to linear travel. Angles, pulses, millimeters, and user units must not be interchanged through implicit constants across modules.

Electronic gearing normally uses a rational ratio; define numerator, denominator, rounding direction, and remainder accumulation. Truncating each pulse creates cumulative long-distance error, while retaining the remainder preserves total displacement according to the ratio. When changing the ratio, specify whether physical position, user coordinates, or a newly established reference is preserved. Direct ratio replacement while running changes both position and speed interpretation and can create setpoint jumps.

Transmission ratios also affect torque and inertia reflection, but position-conversion formulas do not apply directly to all physical quantities. Ideal lossless transmission obeys power balance, and reflected inertia depends on the square of the speed ratio; efficiency, friction, backlash, and elasticity need separate models. For absolute-position axes, save mechanical reference, encoder multiturn counts, and user-coordinate offsets independently and bind them to parameter versions, so sensor or mechanical changes reveal which coordinates remain trustworthy.

Debugging Checks
  • Check counts, load displacement, and accumulated remainders with positive/negative full revolutions and noninteger ratios, covering integer overflow and reversal.
  • Check continuity of physical position, user coordinates, and speed requests when changing transmission ratio or electronic gearing, and verify that inertia reflection uses the squared ratio in the correct direction.
References

Following Error and Command Continuity

Following error is planned position minus feedback position in the same coordinate system at the same instant, not the difference between arbitrary log fields. Bus commands, trajectory outputs, adopted control setpoints, and encoder samples may belong to different cycles; time misalignment creates apparent speed-dependent error. Unify mechanical units, reference offsets, and sample times first, and distinguish a planning target not yet reached from actual tracking deficiency.

Error decisions can consider magnitude, duration, and motion state. Acceleration, braking, and stationary holding have different noise and load characteristics, so one instantaneous threshold is often unsuitable. Derive thresholds from allowed mechanical deviation, sensor resolution, and product requirements. If current or speed limits cause the error, record the constraint reason rather than reporting an expected capability limit as merely a position-loop fault.

Continuity tests should cover new targets, cancellation, emergency-stop requests, communication pauses, and mode switches. Continuous position does not imply continuous velocity, and continuous velocity does not imply continuous acceleration; required order depends on mechanics and process. After large errors, do not hide abnormalities by suddenly forcing planned position back to feedback. Execute the defined pause, controlled stop, or replanning procedure and retain original target, actual position, and triggering conditions. Recovery must also prevent old trajectories from continuing to produce stale setpoints.

Debugging Checks
  • Align command-latch, trajectory-output, and feedback timestamps, checking position, velocity, and acceleration continuity separately and covering communication-setpoint interruptions.
  • Create sustained following error under current and braking constraints; check timing, state-dependent decisions, fault evidence, and invalidation of old trajectories after recovery.
References
Motor Control

Feedback Systems and Discrete Models

Open loop, closed loop, and stability · Transfer functions and state spaceExpand the Feedback Systems and Discrete Models Knowledge Directory
  • Open Loop, Closed Loop, and Stability
  • Transfer Functions and State Space
  • Discretization and Sample-and-Hold
  • Model Assumptions and Feedback Direction

Open Loop, Closed Loop, and Stability

Open-loop operation does not use output-feedback error to correct current control action; closed-loop operation uses measurements in control decisions. A motor drive may have closed-loop current and open-loop speed simultaneously, so identify the level under discussion. An open-loop field angle also does not mean open-loop voltage control; current regulation may still operate internally. Draw setpoint, error, controller, actuator, plant, and measurement paths rather than letting one open/closed-loop label conceal the structure.

For finite-dimensional linear time-invariant models, asymptotic stability requires continuous-time poles strictly in the left half-plane or discrete-time poles strictly inside the unit circle. Integrators and marginal oscillation require distinguishing stability concepts; input-output stability must not conceal internally unstable canceled states. A stable controller and motor separately do not guarantee a stable connected feedback system, since feedback direction, delay, and gain change the poles.

Real drives contain limiting, friction, mode changes, and protection, so linear small-signal stability is only local evidence. Steady operation without oscillation does not prove stability across full load and fault recovery; integral windup can cause long recovery or limit cycles. Establish linear conclusions at specified operating points, then verify startup, saturation, and transitions under nonlinear conditions. State model, sampling period, parameter ranges, and feedback paths for every conclusion rather than interpreting one stable simulation trace as proof of global equipment safety.

Debugging Checks
  • Draw the actual closed loops layer by layer, checking measurement direction, delay, and limiting locations in current, speed, and position paths.
  • Check continuous or discrete closed-loop poles and internal states, then verify behavior under saturation, switching, and parameter variation, preserving boundaries of untested conditions.
References

Transfer Functions and State Space

Transfer functions describe linear input-output relationships with zero initial conditions; state space explicitly retains internal states such as current, flux, and speed. A simplified resistance-inductance current-loop plant can use a transfer function from voltage to current, while induction motors and multi-inertia mechanics are easier to track with state space for coupling and initialization. Both representations may describe the same linear dynamics, yet state choices and physical meanings need not match.

For continuous equations dx/dt=Ax+Bu and y=Cx+Du, define the units of every state component. Current, mechanical speed, and position cannot share an unexplained dimensionless scale without base values. Matrix values have meaning only after state order, input definitions, and coordinate conventions are fixed. Also define whether disturbances represent load torque, bus variation, or measurement noise, since different injection points produce different output responses.

Nonlinear motor models usually need linearization around an operating point. Results apply to specified current, speed, and parameter ranges; saturation and state transitions lie outside that same linear relationship. During model conversion, similar simplified input-output curves do not justify deleting unobservable internal risks: states weakly visible at the current output may still affect startup and protection. Firmware ports must retain state initialization and reset semantics, avoiding a mismatch between assumed zero initial states and actual operating state.

Debugging Checks
  • Check state order, physical units, initial values, and disturbance locations, using known inputs to verify the signs of matrix-generated derivatives.
  • Compare state-space and transfer-function responses at the same operating point, then move away from it to examine error growth and document the linearization range.
References

Discretization and Sample-and-Hold

Digital control includes both controller discretization and held plant inputs; model these separately. When average PWM voltage is approximately constant between updates, zero-order hold is a common plant-discretization assumption. Forward Euler, backward Euler, and bilinear methods provide different discrete approximations for the controller. Merely assigning a nonzero sample-time property to a continuous model does not correctly convert its dynamics.

For linear constant-coefficient plants, zero-order-hold discretization captures state evolution at sampling instants under piecewise constant input, but computation, loading, and measurement delays still need explicit representation. Fractional-cycle delays can use suitable approximations whose accuracy depends on the analysis band. Express control periods in seconds, and restrict discrete frequency analysis below Nyquist. Sampling at only twice a signal frequency does not ensure required control margins; hold and delay phase costs also matter.

Current may be sampled once or several times per PWM period, while outputs update at half-period events, so derive equivalent models from the hardware timeline. Changing PWM frequency may change sampling windows, execution budgets, and algorithm coefficients. Compare continuous, ideal discrete, and actual-delay models to separate discretization error from implementation timing. Passing an ideal discrete simulation does not establish firmware performance with jitter and missed cycles.

Debugging Checks
  • Compare discretization methods under the same input-hold assumption, checking sample-period units and magnitude/phase error in the target band.
  • Add actual sampling-to-output-load delay and one missed update, examining changes in closed-loop margins, step response, and timeout policy.
References

Model Assumptions and Feedback Direction

Check model assumptions backward from the actual feedback path. If error is setpoint minus feedback, positive control output must physically move feedback toward the setpoint. Reversed sensors, changed phase sequence, or an incorrect torque-interface sign can turn negative into positive feedback. Occasional no-load rotation does not prove sign consistency; connect count, speed, q-axis current, and positive torque in one verifiable chain.

The analyzed plant also includes measurement scaling, actuator gain, and filtering. Assuming volts when firmware interprets controller output as modulation omits bus-dependent gain; assuming radians per second when the interface uses rpm changes error and gain units. State whether the model includes inner loops, which loops are closed during outer-loop analysis, and whether limits are inactive at linearization.

Every minimal-model simplification needs a scope: rigid transmission, balanced windings, fixed bus voltage, or constant inductance aid derivation but may omit faults. Begin direction checks with numerical tests disconnected from power output, then inspect equipment response under limited conditions while retaining hardware protection. If model and firmware directions differ, correct interface definitions and rerun regression rather than adding canceling signs in multiple places that later maintainers cannot explain.

Debugging Checks
  • Apply small positive and negative changes at each interface and compare measurement scaling, control output, and plant-response signs point by point with the model.
  • List linearization points, closed loops, and neglected effects, then assess whether assumptions still hold as bus voltage, load, and parameters vary.
References
Motor Control

Discrete PI/PID and Limiting

Gains and sampling period · Positional and incremental implementationsExpand the Discrete PI/PID and Limiting Knowledge Directory
  • Gains and Sampling Period
  • Positional and Incremental Implementations
  • Anti-Windup and Output Limiting
  • Derivative Filtering, Noise, and Initialization

Gains and Sampling Period

Gain meaning depends on input/output units and the discrete equation. For a parallel PI with current error in amperes and output in volts, proportional gain is volts per ampere and continuous integral gain is volts per ampere-second. With backward rectangular integration and sampling period Ts in seconds, update the integral state as xI[k]=xI[k−1]+Ki·Ts·e[k]. This describes only one discrete implementation and must not be mixed with forward Euler or trapezoidal integration.

Some interfaces accept continuous Ki and multiply by Ts internally; others directly accept the discrete coefficient KiTs. Their values differ by one sampling period, making duplicate multiplication or omission easy when names match. Derivative coefficients also depend on sampling and filtering and cannot use continuous Kd directly on an error difference. Per-unit gains require conversion through current, voltage, or speed bases; changing bases requires rechecking the entire coefficient chain.

After changing control frequency, rediscretize and analyze total delay rather than assuming that scaling the integral by period preserves all dynamics. A fixed continuous bandwidth goal may have different attainable margins as discrete sampling and output-update positions change. Parameter files should record engineering-unit gains, discretization method, execution period, and final firmware coefficients so validation tools can detect mismatches. Inertia or inductance changes also alter the plant; recalculated gains need stated parameter sources and valid ranges.

Debugging Checks
  • Manually check a one-cycle integral increment and whether the interface accepts Ki or KiTs, avoiding separate Ts multiplications in both model and firmware.
  • After changing the sampling period, compare coefficients, delay, and closed-loop response, and convert per-unit gains back to engineering units to confirm consistency.
References

Positional and Incremental Implementations

Positional form directly calculates current output, usually retaining separate proportional, integral, and derivative states; incremental form calculates the output difference and accumulates it. They can be equivalent when linear, using the same discretization and initial state without differing limits or resets. In practice, output clamping, applied-output tracking, and transition initialization break simple equivalence, so incremental form is not inherently immune to windup and positional form is not inherently more prone to loss of control.

For parallel PI with backward rectangular integration, the unlimited increment is Δu[k]=Kp(e[k]−e[k−1])+KiTs·e[k], with Ts in seconds and error/output in their respective engineering units. Define whether the accumulator stores requested or actually clipped output; simply overwriting final output with a limit may change internal equivalence. If feedforward and slew-rate constraints are added, identify their locations in state updates too.

Choose implementations for diagnosability, numeric range, and mode switching. Positional terms make the integral easy to inspect; incremental form may be more sensitive to initial output and error history. Both must handle resets, saturation recovery, parameter changes, and first calls. One steady input is insufficient to verify equivalence: replay steps, sign reversals, and sustained limiting from equal initial states and explain differences caused by state-handling policies.

Debugging Checks
  • Compare both implementations sample by sample without constraints and from identical initial states, then add limiting and resets to confirm differences follow explicit policies.
  • Cover the first cycle, parameter changes, and mode switching, checking that output accumulators, previous errors, and integral states are initialized and do not overflow.
References

Anti-Windup and Output Limiting

Output limiting constrains requests to actuator feasibility, whereas anti-windup handles persistent differences between requested and applied outputs. Current loops face voltage limits, speed loops face current/torque limits, and trajectories may face acceleration limits, so design anti-windup along the real execution path. Fixed integral-state limits can reduce accumulation but do not necessarily match proportional terms, feedforward, and changing voltage capability.

Conditional integration pauses accumulation when output is saturated and error pushes farther into saturation while allowing error that helps release it. Back-calculation corrects integration using actual output minus the unsaturated request. Its coefficient and Ts must match the discrete equation, and its response cannot be made arbitrarily fast. If an actuator has slew limits or inner-loop dynamics, static-clamp feedback alone may be inadequate; consider tracking the realizable output and documenting delay.

Focus verification on release from saturation rather than a smooth-looking saturated trace. Sustained large requests may build deep integration, causing delays, surges, or excessive reversal when requests shrink or reverse. Feedforward addition, bus decline, outer-loop current limiting, and fault recovery all require the same requested/applied mismatch analysis. Anti-windup does not increase motor or inverter capability or replace hardware protection; it improves constrained-controller state evolution, with performance conclusions tied to the plant and operating range tested.

Debugging Checks
  • Inject sustained positive/negative saturation and setpoint reversal, recording integration, requested output, and applied output to verify prompt recovery on release.
  • Include feedforward, slew limits, and bus dynamics, checking that back-calculation or tracking uses actual constrained outputs and does not multiply by sampling period twice.
References

Derivative Filtering, Noise, and Initialization

Derivative action represents rate of change; direct differencing amplifies high-frequency noise and quantization. Differentiating position/speed error can produce derivative kick from setpoint steps; differentiating measurements changes this effect but also changes control structure. State whether differentiation acts on error or measurement and whether the setpoint is planned or filtered rather than providing only Kd without its signal source.

Practical derivatives usually include first-order or other filtering; filter time constant, sampling period, and discretization determine usable bandwidth. Lower cutoff suppresses noise but adds phase lag and weakens fast-change information. For motor current loops, first assess whether PI is sufficient rather than adding derivative action because PID sounds more complete. Speed/position loops with encoder quantization or mechanical resonance also require analysis of derivative effects on current, sound, and vibration.

Initialize historical input, filter state, and integrator state consistently with current operation. Setting the previous measurement to zero when starting at nonzero speed creates a first-cycle difference; resetting only integration during a mode change can still cause a jump through filter state. Bumpless transfer may track internal states to current applied output, but feedforward, proportional action, and limits must be checked. Define skipped-update or reset policies for invalid data and discontinuous timestamps so rates are not computed over invalid intervals.

Debugging Checks
  • Add quantization noise to constant measurements and apply setpoint steps, observing derivative terms and final outputs separately and checking filter bandwidth and signal-source definitions.
  • Cover startup at nonzero speed, mode switching, and recovery from missed samples; verify aligned input history and filter states without a first-cycle surge.
References
Motor Control

Time Domain, Frequency Domain, and Performance

Steps, disturbances, and steady-state error · Bode plots and frequency responseExpand the Time Domain, Frequency Domain, and Performance Knowledge Directory
  • Steps, Disturbances, and Steady-State Error
  • Bode Plots and Frequency Response
  • Bandwidth, Margins, and Delay
  • Performance Costs of Noise and Filtering

Steps, Disturbances, and Steady-State Error

Specify the changed quantity and amplitude for a step response. Current-setpoint steps, speed-setpoint steps, and load-torque disturbances enter different paths, so overshoot and steady-state error mean different things. Test amplitude also determines whether current limiting or voltage saturation occurs; do not merge small-signal linear and large saturated responses into one tuning result. Logging setpoint, actual value, applied output, and limit flags distinguishes control dynamics from capability constraints.

Rise time, settling time, and overshoot require explicit criteria and reference final values. A short record may not reach steady state, and treating its last sample as final underestimates error; noise or periodic ripple may repeatedly cross a settling band, so state the observation window and persistence requirement. Distinguish static bias from mean steady-state error too; with friction, dead time, and quantization, integration does not guarantee zero error under every definition.

Inject load changes, bus changes, and measurement noise separately for disturbance verification. Faster setpoint tracking does not necessarily improve disturbance rejection; feedforward may improve known commands without helping external load disturbances. Apply suitable disturbances to mechanical axes in a controlled experimental environment rather than claiming repeatable conclusions from an unknown hand-applied load. Label model results, host replay, and bench data by source, and assess time-domain metrics together with peak current, thermal load, and fault state.

Debugging Checks
  • Define step amplitude, reference final value, settling band, and recording window; check saturation flags and consistent conditions across repeated trials.
  • Compare setpoint steps and load disturbances separately, recording steady-state mean, variation, and applied current instead of using the last sample as steady state.
References

Bode Plots and Frequency Response

Bode plots show frequency gain and phase for a specified input-output path, so identify whether the plot represents the plant, loop gain, or closed-loop response. Phase margin requires loop gain; a closed-loop speed-response curve does not directly provide the same margin. Distinguish hertz from radians per second, which differ by 2π, and distinguish mechanical rotation frequency, electrical frequency, and sampling frequency. Label axes with units and signal paths.

Continuous-model frequency response is evaluated on the imaginary axis, while discrete response is evaluated on the unit circle using the actual sampling period. Results above Nyquist are not independent observable dynamics. Measured frequency response needs appropriate excitation and signal-to-noise ratio: too small is buried in noise, while too large enters limiting or nonlinearity. Use sufficient frequency resolution near resonance, since interpolation between sparse points can miss narrow peaks and rapid phase changes.

Include actual paths such as current loops, speed-estimation filters, command latching, and output delays when comparing model and equipment frequency responses. Plotting only motor resistance and inductance does not describe the entire loop. Attach operating point, load, firmware version, and excitation method to measurements; poor repeatability calls for checking synchronization and operating-point drift first. Smooth plots are not necessarily credible; retain raw inputs/outputs and quality information, and do not use strong smoothing to hide phase jumps or low-SNR regions.

Debugging Checks
  • Label each frequency-response plot with input, output, loop opening/closing location, and frequency units, and verify the discrete-model sampling period.
  • Sweep excitation amplitude and check saturation, add frequency points around resonance and crossover, and retain raw magnitude, phase, and quality data.
References

Bandwidth, Margins, and Delay

Bandwidth, crossover frequency, and stability margins are related but distinct. Closed-loop bandwidth is the frequency where a specified response falls to an agreed level; loop-gain crossover supports feedback-stability analysis. Gain and phase margins assume a specified negative-feedback structure; with multiple crossovers, internal instability, or special cancellations, one positive margin cannot replace complete stability analysis. Reports should identify the model, frequency range, and all important crossovers.

A pure delay τ seconds introduces phase lag ωτ radians at angular frequency ω radians per second, so raising crossover magnifies the effect of the same delay. Sample-and-hold, computation, PWM loading, speed measurement, and communication latching can all add delay. Shorter calculations improve phase only if actual output activation changes; if shadow loading remains one period late, reducing average algorithm time may not change total control delay.

A cascaded outer loop should include the closed inner loop and its delay as part of its plant before choosing bandwidth. Mechanical resonance, parameter variation, and load inertia may constrain the speed loop; a fixed inner/outer bandwidth ratio is unsuitable universally. Choose within feasible constraints using response, disturbance rejection, noise, and margins together. If faster response requires much less filtering or much greater gain, check current noise and saturation so one improved frequency metric does not worsen overall behavior.

Debugging Checks
  • Add actual delay components to the loop model and compare phase at crossover, checking delay units and conversion from hertz to angular frequency.
  • Check every crossover and the worst margin across parameter ranges; outer-loop analysis must include the closed inner loop and mechanical resonance rather than reporting one nominal-model value.
References
  • margin — Gain and phase margins; crossing warnings
  • c2dOptions — Discretization methods

Performance Costs of Noise and Filtering

Filter effects depend on location. Current-feedback filtering affects inner-loop phase, speed filtering affects the speed loop, and setpoint filtering mainly changes command response; one low-pass block cannot represent all three effects. Removing measurement noise may also weaken real fast disturbances, so include filter delay in the loop rather than only in data display. Display filtering can be stronger, but its trace must not be mistaken for the signal actually used by control.

In a single-input/single-output linear negative-feedback structure, sensitivity and complementary sensitivity reflect tradeoffs among disturbance rejection, tracking, and measurement-noise propagation. The transfer from a particular noise source to output or actuator also depends on injection point; one closed-loop curve does not establish every noise effect. Higher bandwidth can improve low-frequency tracking while admitting more high-frequency measurement noise into current requests, increasing actuator activity and heating.

Firmware filters need defined sampling rates, coefficient methods, initial states, and invalid-data handling. Coefficients used with another task period change actual cutoff; updating after missed samples may repeatedly treat old data as new. Verify raw signals, filtered signals, control output, and actual response together, including startup and mode changes. Choose filter strength from useful signal bands and mechanical requirements rather than treating prettier waveforms as proof of better control.

Debugging Checks
  • Label control and display filters separately, check task periods and actual frequency responses, and measure magnitude/phase changes near cutoff.
  • Inject repeatable noise under identical conditions and compare feedback variation, applied current, and disturbance recovery, checking whether noise reduction costs excessive delay.
References
Motor Control

Tuning and Operating Limits

Current, speed, and position tuning order · Sampling periods and gain unitsExpand the Tuning and Operating Limits Knowledge Directory
  • Current, Speed, and Position Tuning Order
  • Sampling Periods and Gain Units
  • Response, Disturbance Rejection, and Robustness
  • Current, Voltage, Temperature Rise, and Saturation Constraints

Current, Speed, and Position Tuning Order

For cascaded tuning, verify measurements, direction, modulation, and protection before starting with the inner current loop. It determines whether torque and flux requests can be executed; if current response already oscillates, angle is wrong, or voltage is limited, tuning speed transforms inner-loop issues into complex outer-loop symptoms. Initially tune current under conditions with known feasible voltage, cover both d and q axes, and record sampling delay and actual output rather than examining only a speed trace.

Tune speed using the verified closed current loop as its plant, considering torque constant, reflected inertia, friction, speed filtering, and mechanical resonance. Then analyze position on top of the closed speed loop with trajectories, transmission error, and feedback resolution. Outer loops are generally slower, but no fixed bandwidth ratio fits every axis; determine separation from the complete model, frequency margins, and measured response, avoiding flexible-transmission problems hidden by a single-inertia assumption.

Check constraint propagation and state initialization at every stage. During speed-loop current limiting, integration must know that torque was clipped; a speed-limited position loop also needs protection against accumulating requests. Load changes or field weakening can invalidate previous tuning, requiring key-condition regression. Autotuning yields candidate parameters for a specified plant and experiment, still requiring checks of units, disturbances, saturation, and mode changes; tool-generated gains do not constitute full acceptance.

Debugging Checks
  • Freeze or disable unverified outer loops and preserve requests, feedback, limits, and stability evidence layer by layer from current to speed to position.
  • Check outer loops with different inertias and both directions, verifying resonance, measurement filtering, and constraint propagation rather than accepting only nominal no-load response.
References

Sampling Periods and Gain Units

Tuning records must specify execution periods and physical units for every loop. Current loops output voltage, speed loops output current or torque, and position loops output speed, so identically named proportional gains have different dimensions. Changing speed from radians per second to rpm, or position from radians to encoder counts, changes error scaling; copying previous numbers into a new interface does not preserve the controller.

Continuous-to-discrete gain conversion must specify integration and differentiation methods with sampling period in seconds. Per-unit implementations also need current, voltage, speed, and position bases, with angle bases consistent with mechanical/electrical level. A current loop executing every PWM half-period must not use the full period as Ts, and a divided-rate speed loop must not reuse the current-loop period. Parameter validation can retain engineering values, execution periods, and final coefficients together and detect mismatches at startup.

Sampling-period changes affect Nyquist frequency, execution budget, sampling windows, and delay. Even if integral coefficients scale with period, unchanged output-update points or filter coefficients still change dynamics. Tune with the target firmware's scheduling and final compiler configuration, while allowing a separately reduced logging rate. Distinguish control updates from log samples when interpreting tests, avoiding incorrect execution-rate or first-cycle conclusions from sparse logs.

Debugging Checks
  • Create per-loop input/output unit tables and check conversions among continuous gains, per-unit bases, and discrete coefficients, confirming Ts is not multiplied twice.
  • After changing PWM frequency or loop-rate dividers, check filters, observers, integration, and actual loading times, then rerun original step and limit-recovery cases.
References

Response, Disturbance Rejection, and Robustness

Fast response, strong disturbance rejection, and parameter robustness require joint tradeoffs. Higher proportional/integral action may shorten tracking time but increase current, noise propagation, and delay sensitivity. Acceleration feedforward can improve known trajectories, yet depends on inertia and torque models and does not guarantee the same benefit for unknown load disturbances. Define separate metrics for tracking, disturbance recovery, noise, and actuation.

Assess robustness over realistic uncertainty ranges. Resistance varies with temperature, inductance with current, and load inertia with process; sensor filters and computation delays may differ too. Check single-factor directions before plausible combinations rather than using impossible simultaneous extremes as the sole design point or checking nominal values alone. Resonance variation in flexible axes may matter more than single-inertia parameter error and needs suitable models or measurements.

Distinguish linear and constrained regions in validation. Good small-signal response with prolonged saturation for large requests may call for reduced trajectory demands or better anti-windup rather than more linear-gain tuning. After controller changes, retain before/after replays with identical inputs, including limiting duration and recovery. If improvement increases noise current or temperature rise, evaluate the tradeoff against equipment requirements rather than showing only the fastest curve and omitting operating costs.

Debugging Checks
  • Measure setpoint changes and load disturbances separately, logging applied current, noise, and limiting duration with identical comparison inputs.
  • Sweep credible ranges of electrical parameters, inertia, and total delay, check worst responses and margins, and document unmodeled resonance or backlash.
References

Current, Voltage, Temperature Rise, and Saturation Constraints

A controller's operating region is jointly constrained by current, voltage, speed, thermal state, and mechanics. Current feasibility governs torque and losses, voltage feasibility changes with bus voltage and speed, and temperature rise depends on load duration and cooling. Short-term peak capability is not continuous capability, and software current limiting does not replace hardware short-circuit protection. Product thresholds must come from power-device, motor, and cooling design and verification data.

At higher speed, permanent-magnet motor back EMF consumes more voltage; some conditions require field weakening while satisfying both d/q-current and voltage constraints. Field weakening changes torque capability and magnet risk, so arbitrary negative d-axis current must not be traded for speed. Variable-frequency drives must also consider flux, slip, cooling, and low-speed load capability according to motor type. Models help draw candidate boundaries but cannot independently prove every equipment limit.

Implement separate layers for soft limits, derating, controlled stops, and hard faults, with hysteresis and recovery rules. Temperature sensors have locations and delays, and software thermal models have parameter error; one sensor temperature is not every device's junction temperature. Feed limit changes back to integrators and trajectories so outer loops do not keep requesting pre-derating torque. Acceptance should cover sustained loads, bus variation, and repeated acceleration/deceleration, documenting actual thermal conditions and unverified ranges.

Debugging Checks
  • Check current circles and voltage boundaries jointly, verifying synchronized adjustments of limits, integrators, and trajectory demands during bus decline and derating.
  • Distinguish peak from continuous capability and sensor temperature from device junction temperature; check product-data sources for every threshold and controlled recovery conditions.
References

Technical fields

Industrial Communication

Modbus

Industrial Communication

Modbus: Interfaces and Device Roles

RS-485/UART and RTU layers · Device addresses and request/responseExpand the Modbus: Interfaces and Device Roles Knowledge Directory
  • RS-485/UART and RTU Layers
  • Device Addresses and Request/Response
  • Transmit/Receive Direction, Termination, and Biasing
  • Timeouts, Broadcasts, and Device Responsibilities
Reading Guide: A Modbus RTU Device, from Messages to Parameter Interfaces

RS-485/UART and RTU Layers

RS-485 specifies differential line signaling and transceiver electrical behavior, UART converts serial bits to characters, and RTU adds addressing, function codes, frame boundaries, and checksums to the character stream. Count errors separately by layer: abnormal levels belong to the physical link, parity errors or overruns to UART reception, and CRC mismatches or frame-gap errors to RTU. Receiving bytes does not mean a driver has correctly identified messages.

The device receive path can comprise UART/DMA transfer, timer-based boundary detection, protocol-task validation, and parameter-interface execution. Interrupts should record only data positions, error flags, and times rather than parsing and writing control variables directly. Bound receive buffers; after overflow, discard the contaminated frame and wait for a complete silent interval to resynchronize rather than interpreting the remaining tail as a new command.

Serial settings must match the master: baud rate, data bits, parity, stop bits, and total character time. A UART IDLE event is not automatically RTU frame completion; chip-specific detection may occur before the protocol boundary. Combine last-receive time with protocol timing to detect complete frames. Implement fixed high-baud-rate timing according to the serial-line guide rather than shortening it indefinitely with character length.

During board bring-up, disable application writes first, send known characters to inspect raw UART data, then check timing boundaries and CRC before connecting register access. If errors occur only while the inverter bridge operates, compare differential waveforms, common-mode conditions, and receive-error counters before changing function-code logic. When reception and current control share a CPU, record worst-case interrupt occupancy under communication stress.

Debugging Checks
  • Inject UART parity errors, receive overruns, and CRC errors separately; confirm distinct counters and no application-parameter modifications.
  • Vary interbyte spacing for the same message and check the timing relationship between UART events and RTU frame-complete events.
References

Device Addresses and Request/Response

The master initiates every RTU-bus transaction; devices process only addressed unicast requests and specified broadcast writes. Unicast addresses range from 1 to 247, with address 0 reserved for broadcast. Device address is link addressing, not a register start address; store station number, serial settings, and application register maps separately so changing a station number is not mistaken for changing parameter mapping.

A suggested receive sequence is complete-frame detection, address filtering, CRC validation, function/range validation, application submission, and response construction. Other devices' addresses must neither acquire application locks nor produce exceptions. Responses should reflect the protocol operation completed for this transaction rather than combining old cached read data with a new request. Copying multiple runtime values from one snapshot preserves timing consistency within a response.

Masters normally keep only one serial transaction in flight, but devices must still handle requests repeated after master timeouts. Make ordinary register assignments idempotent where possible; commands with side effects, such as start, fault clear, and save, need explicit trigger semantics. The protocol does not guarantee deduplication for every application action; identical function codes and data alone do not prove two requests are the same transaction.

Changing a device address also raises which address the response uses, when switching occurs, and how it persists through power loss. Define the activation point in the product interface and commit configuration in the background to avoid changing transceiver state halfway through a reply. Conflicting addresses may cause collisions or malformed responses; connect devices individually to confirm station numbers before increasing master wait time and concealing duplicate replies.

Debugging Checks
  • Replay the same request to this device, another station, and broadcast, confirming that only unicast to this device produces a reply.
  • Repeat ordinary assignments and side-effect commands and check that application execution counts match interface definitions.
References

Transmit/Receive Direction, Termination, and Biasing

For two-wire half-duplex RS-485, transmission enable must follow actual line activity. An empty UART transmit register or completed DMA may mean only that the last byte reached the shift register, not that its stop bit has finished. Release DE according to UART transmission-complete status and transceiver timing; too early truncates the final byte or CRC, while too late may overlap the master's next transmission.

Organize the bus as a trunk with short stubs, matching termination to cable characteristic impedance at both trunk ends rather than terminating every node. Biasing establishes a definite receive state during idle or failures; choose values using transceiver thresholds, built-in failsafe behavior, parallel termination load, and supply voltage. Treating fixed resistor values as universal for all boards can reduce drive capability or noise margin.

Implement direction switching as a small separate state machine with enable, transmission, final-character completion, release, and return-to-receive states. Restore DE after transmission errors, resets, and cancellations so a node cannot occupy the bus indefinitely. Apply one consistent policy for whether hardware receives local echo and whether software discards it; otherwise, a device may parse its own response as the next request.

When investigating lost first bytes or corrupted final bytes, observe DE, UART TX, differential A/B, and receive-completion markers together. Check node common-mode range, signal reference, and isolated-supply conditions too; A-to-ground voltage alone is insufficient. When long cables and power switching coincide with failures, compare idle levels, overshoot, reflections, and position-dependent errors individually to identify hardware causes.

Debugging Checks
  • Trigger on DE's falling edge, confirm completion of the last stop bit on the line, and measure release margin before the master changes direction.
  • Keep termination only at the two trunk ends, measure idle differential level and the far-end waveform, then compare communication error rates.
References

Timeouts, Broadcasts, and Device Responsibilities

Distinguish three timing concepts: receive-frame timeout, request-processing budget, and application communication loss. Frame timeout determines whether a byte stream is complete; master response timeout governs transaction waiting; stale operating setpoints depend on product risk and conditions. Arbitrary bytes or invalid frames must not refresh command liveness, or noise can maintain an old speed setpoint.

Broadcast requests produce no response; in particular, broadcast register reads must not make every node reply simultaneously. First validate the frame and supported write function, then apply the same permissions and ranges as unicast; broadcast is not a way around application validation. Masters must reserve processing time after broadcasts. If result confirmation is required, read individual stations afterward rather than adding a private broadcast acknowledgment.

Communication tasks validate commands, form transaction results, and hand candidate values to the application; they do not directly decide whether the motor may be enabled. The drive application centrally evaluates operating state, latched faults, parameter activation, and control ownership. Use controlled background requests for lengthy Flash saves, and state whether a response means received, committed, or saved so the master does not assume guaranteed persistence through power loss.

For timeout policies, record the time and source of the last valid operating command and enter an explicit hold, limited-deceleration, or stopped state after the defined window. Do not replay expired start edges automatically on reconnection; the product determines whether a new enable is needed. Neither inflate timeouts to hide periodic blocking nor make them arbitrarily short without considering mechanical inertia and braking capability.

Debugging Checks
  • Continuously inject bad frames and frames for unrelated addresses, confirming that this traffic cannot refresh the communication-loss timer.
  • Replay broadcast writes, reads, and out-of-range writes, checking that none produces a response or unauthorized parameter changes.
References
Industrial Communication

Modbus: Messages and Exceptions

RTU frames, CRC, and frame gaps · Function codes and length checksExpand the Modbus: Messages and Exceptions Knowledge Directory
  • RTU Frames, CRC, and Frame Gaps
  • Function Codes and Length Checks
  • Exception Responses and Request Boundaries
  • Bad-Frame, Lost-Frame, and Timeout Tests
Reading Guide: A Modbus RTU Device, from Messages to Parameter Interfaces

RTU Frames, CRC, and Frame Gaps

An RTU wire frame comprises device address, PDU, and CRC; the PDU contains the function code and its data. Receivers must validate both content checks and timing boundaries. A valid CRC only means the byte combination passes its checksum, not that RTU timing is satisfied. If an internal intercharacter gap exceeds the permitted interval, follow serial-line rules rather than executing simply because the remaining bytes eventually complete the declared length.

Interframe silence divides a continuous serial stream into separate messages. Record character-arrival times, receive errors, and candidate-frame length, then freeze data once end conditions are met before handing it to the parser. The guide recommends fixed timings above 19200 baud; at lower rates, calculate complete character time including start, data, parity, and stop bits rather than dividing only eight data bits by baud rate.

CRC calculation excludes the CRC field itself, and its low byte is transmitted first; this differs from high-byte-first transmission of register values. For library functions, confirm initialization, bit processing, and return-value byte-order semantics: some return a numeric value, while others already swap its bytes. Start tests with independently known messages so the master and device cannot pass each other using the same incorrect implementation.

Use double buffering or frozen indices so DMA cannot overwrite the current transaction during parsing. Boundary detection needs a monotonic clock and overflow handling; host tests verify byte algorithms, while timing accuracy and UART-error propagation still require target-board checks. Under high communication load, preserve raw bytes and last-receive time together to distinguish CRC-algorithm errors from preempted frame reception.

Debugging Checks
  • Check numeric CRC values and wire byte order against known vectors, then deliberately swap only the CRC bytes to verify rejection.
  • Replay messages across intercharacter and interframe timing boundaries, checking concatenated frames, truncated frames, and timer-wraparound behavior.
References

Function Codes and Length Checks

Function codes have different request fields and quantity limits; one generic minimum-length check cannot replace per-function parsing. Read registers, write single register, and write multiple registers have different structures; multiple-object writes also require matching quantity, byte count, and actual remaining bytes. Confirm accessible length before reading a field rather than accessing out of bounds and discovering a CRC error afterward.

Create a description table for each supported function, listing fixed fields, variable regions, legal quantities, response format, and application interface called. Widen addresses and quantities to sufficiently large integers before checking mapped-table boundaries, avoiding 16-bit wraparound in start address plus quantity. A valid message does not imply valid parameters; check application permissions and operating state as well.

Decode multiple-register writes into a temporary transaction, validate every item and combination, then commit once. Writing two values before rejecting an out-of-range third creates ambiguity: the master sees failure while the device has partially changed. Check response-buffer capacity too; an unvalidated request quantity must not directly allocate or populate an unbounded reply.

Unit tests should cover zero and extreme quantities, data one byte shorter than declared, extra trailing bytes, end-of-address-space cases, and unsupported functions. Pure parsing functions suit host boundary tests and fuzzing, while substitute application interfaces record whether actions were invoked. On target, test buffers, task duration, and control periods under extreme continuous requests, ensuring rejection paths are bounded too.

Debugging Checks
  • Generate minimum, maximum, and over-limit requests for each supported function and verify that rejected requests perform no application writes.
  • Place the start address at the table end, vary quantity and byte count, and confirm no integer wraparound or out-of-bounds access.
References

Exception Responses and Request Boundaries

An exception response reports that the device recognized a valid request addressed to it but could not complete it under protocol or application conditions. Its function code sets the original code's most significant bit and includes an exception code; unsupported function, inaccessible address, and invalid data must be distinguished. Bad CRC, physical corruption, and another device's address are not ordinary application exceptions and must not all receive error packets.

Application interfaces should map failures to a finite documented result set, such as nonexistent register, unwritable current state, out-of-range value, or execution failure. Protocol exception codes are not detailed device logs; finer reasons and request summaries can remain internal, but external formats must follow the selected interface. Unimplemented functions must not silently return zero data and pretend success.

Draw a clear boundary between validation and execution for writes with operating side effects: retain old values if parameter-combination checks fail, and do not describe an already executed action as though nothing happened. Asynchronous long operations need explicit application-state registers and polling; an ordinary write response must not mean that an entire mechanical action has completed. Document whether timeout retries repeat execution too.

Log request address, function, quantity, exception code, and application-failure type together, using counters rather than blocking prints in every serial callback. A master timeout may also result from DE release, response-frame length, or a wrong address; inspect whether an exception response actually exists on the bus before tracing application rejection. Error paths must obey the same response budget and buffer bounds.

Debugging Checks
  • Distinguish unsupported-function, out-of-range-address, and invalid-value requests, comparing wire exception codes with internal failure reasons.
  • Inject bad CRCs and requests to other stations; confirm silent discard rather than exception responses.
References

Bad-Frame, Lost-Frame, and Timeout Tests

Communication reliability tests must prove more than successful normal reads/writes: observe whether reception resynchronizes after errors. Bad CRC, UART overrun, missing bytes, inserted bytes, concatenated messages, and abnormal gaps affect different layers. Each fault case should define whether the current request may execute, whether it replies, and how the next complete request recovers, preventing accumulated errors from trapping reception in an intermediate state.

Test tools can generate byte-and-gap sequences and record raw input, device responses, and before/after application values. For CRC faults, alter checksum or data without recalculating CRC; for length faults, preserve contradictory fields. If a master library automatically completes, retries, or filters errors, tool output no longer represents actual injection; capture the wire to confirm that the intended bad frame was transmitted.

Lost-frame and timeout tests must include lost requests, lost responses, and replies arriving after the master's wait window. Repeated ordinary assignments should cause no extra actions; edge-triggered commands require product-defined deduplication or reconfirmation. After communication recovery, check for buffered old commands; an earlier timed-out request must not be applied later to an operating state that has changed.

Associate error statistics with firmware version, serial configuration, and control load, reporting valid frames, rejected frames, overruns, processing timeouts, and control-deadline violations separately. Error rates describe symptoms and do not identify causes. After host parsing tests pass, target hardware must still exercise actual paths such as DMA switching, timer wraparound, power-switching noise, and high-priority interrupt preemption.

Debugging Checks
  • Send several kinds of bad frame followed by one valid frame, confirming state reset, correct response, and no residual side effects.
  • Drop one write response and let the master retry; check assignment results, action counts, and recovery state after disconnection.
References
Industrial Communication

Modbus: Parameter Mapping

Coils, discrete values, and register models · PDU addresses and documented numberingExpand the Modbus: Parameter Mapping Knowledge Directory
  • Coils, Discrete Values, and Register Models
  • PDU Addresses and Documented Numbering
  • Multiword Data and Word-Order Conventions
  • Write Permissions, Limiting, and Consistency
Reading Guide: A Modbus RTU Device, from Messages to Parameter Interfaces

Coils, Discrete Values, and Register Models

The Modbus data model provides four logical tables: coils, discrete inputs, input registers, and holding registers, representing bits or 16-bit words with different access directions. These are not the MCU's physical memory layout and do not automatically specify motor actions. Map operating values, configuration, commands, and diagnostics to explicit addresses rather than letting masters overwrite internal structures through memory offsets.

Register descriptions should include name, unit, scale, default, legal range, access permissions, state conditions, and activation time. Writable holding registers are a protocol-model capability, not permission to write every device object in every state. Distinguish command bits from persistent configuration bits: a fault-clear pulse is not a switch held at one forever, and arbitrary data writes must not automatically grant operation permission.

When returning current, speed, and fault words in one response, generate values from a consistent application snapshot instead of repeatedly accessing a structure being updated by interrupts. Route configuration writes through object-level interfaces for unified value validation, combination constraints, and version updates. If multiple logical tables reference the same application object, ensure they expose the same meaning and explicitly define which write paths are authorized.

Documentation and firmware tables can be exported from the same controlled definition, but the generated results must be checked for unique addresses, data widths, permissions, and gaps. Reserve stable ranges for future expansion; do not reassign the meaning of existing addresses between versions. Master compatibility tests should read the device identity and parameter-table version, then check representative objects. One successful Read Holding Registers request does not establish compatibility with the entire interface.

Debugging Checks
  • Compare documented addresses, function types, units, and actual firmware values item by item, particularly distinguishing read-only operating values from writable settings.
  • Read continuously while the control interrupt updates multiple variables, and check that each response comes from a complete snapshot.
References

PDU Addresses and Documented Numbering

The on-wire PDU uses zero-based address fields, whereas manuals may use one-based entry numbers or traditional numbers prefixed by table type. Holding register number 40001 cannot simply be inserted unchanged into the 16-bit PDU address. Whether to subtract one depends on the manual's numbering convention; do not subtract one from every number by default.

Ideally, specify the logical table, PDU start address, displayed documentation number, and access function together. For example, state that an object has hexadecimal PDU address 0010 in the holding-register table and can be read using function 03. If the manual also lists traditional numbers, provide the conversion rule. Input fields in different master tools may apply offsets themselves. Capture packets during integration to verify the actual on-wire fields, rather than comparing only UI screenshots.

Address-range checks must use the logical table selected by the request function. The same numerical address can exist in different tables; Read Input Registers and Read Holding Registers must not share pointers without regard to type. Quantity checks must consider address continuity, undefined gaps, and the number of registers occupied by each object. The trailing word of a multiword object should not be mistaken for an independently writable parameter.

When migrating an old parameter table, retain stable compatibility aliases or explicitly increment the table version and provide conversion instructions. Do not change an address from a speed reference to a current limit within the same version: an old master could then issue a valid but incorrect write. For troubleshooting, implement an address-echo test returning several distinct fixed identification values to diagnose offsets, functions, and word order without driving the power output.

Illustration: list displayed documentation numbers and PDU addresses separately; do not transmit 40001 as on-wire address 40001.
Debugging Checks
  • Capture reads of the first entry and an entry in the middle of the table. Check whether the tool already subtracts one, so the software does not subtract it again.
  • Test requests spanning gaps or the trailing words of multiword objects, and requests using different functions at the same address, to confirm that only defined logical objects are accessed.
References

Multiword Data and Word-Order Conventions

The specification encodes 16-bit register data with the high byte first, but the device interface must separately define how 32-bit integers, floating-point values, and 64-bit quantities span multiple registers. Byte order within a register and high/low word order between registers are separate issues; the CRC at the end of an RTU frame has its own byte ordering. Mixing these swaps can produce plausible but incorrect values.

The protocol layer should use byte-access functions and explicit shifts to assemble data, rather than casting a network buffer directly to a float pointer. This avoids alignment, host-endianness, and aliasing issues. The parameter table must specify signedness, two's-complement representation, floating-point format, invalid values, and scaling. Reject or explicitly handle unsupported special floating-point values at the application boundary; do not let NaN bypass validation through limit comparisons.

Multiregister updates also require transactional consistency. If the master writes a 32-bit reference in two operations, the application may temporarily see half new and half old data. Require a single Write Multiple Registers commit, or use staging storage and a commit command. Likewise, freeze a complete counter snapshot before splitting it into registers, so a carry in the low word cannot produce a combination that existed at no actual instant.

Use test values with distinctive hexadecimal bit patterns during integration to verify bytes, words, and signs separately. Choose a 32-bit pattern with different bytes, along with negative and near-boundary values. Testing only zero or integer one rarely exposes ordering problems. Record on-wire bytes, decoded raw values, and converted engineering units together to distinguish endianness errors from scaling, sign, or type-definition errors.

Debugging Checks
  • Replay a 32-bit pattern with four different bytes and negative values, checking agreement among the documented convention, on-wire bytes, and engineering values.
  • Read concurrently during multiword counter carries and segmented writes, confirming that the snapshot or commit mechanism never exposes partially updated data.
References

Write Permissions, Limiting, and Consistency

Register write permissions must reflect each object's meaning and the operating state; do not make all holding registers writable. Motor parameters, feedback settings, or control gains may be editable only while stopped. A speed reference may be updated during operation but still requires control ownership and rate limits. A successful protocol write and the motor's adoption of the value are separate events. The interface must state whether feedback means a candidate value, an accepted value, or an effective value.

Validate type, scaling, and individual ranges first, then parameter combinations, such as minimum limits not exceeding maximum limits and references staying within current capability. Invalid configurations should generally be rejected while retaining the previous values, rather than silently clipped into another configuration. Continuous operating commands may follow published limiting rules, while exposing the value actually used and the reason for limiting.

The commit path can freeze a pending transaction and pass it to the application, then atomically swap a version or complete parameter block in a defined execution context. The communication task must not modify fields individually in a structure being read by the control interrupt, or block the fast loop with a long-held mutex. Saving to Flash is a separate stage; record its result and the configuration version. An accepted response must not imply that the data already survives power loss.

Permission tests must cover operation, stopped state, faults, and control-ownership changes, checking whether invalid writes leave partial state changes. Also verify consistency of defaults, retained values, and migration rules after reset or upgrade. Arbitrate access to shared parameters through a common application interface across protocols. A configuration rejected by Modbus must not be writable directly through CANopen or a local debug port in a way that violates system constraints.

Debugging Checks
  • Make only the last value in a parameter group out of range, and confirm that the whole group is rejected while the version, effective values, and stored contents remain consistent.
  • Write settings during operation and fault states, checking that responses, pending values, actual control values, and storage state match the documentation.
References

CANopen

Industrial Communication

CANopen: Networks and Devices

CAN Physical Layer and Arbitration Basics · NMT and Node StartupExpand the CANopen: Networks and Devices Knowledge Directory
  • CAN Physical Layer and Arbitration Basics
  • NMT and Node Startup
  • Heartbeat and Node Monitoring
  • EMCY and Fault Reporting
Reading Guide: CANopen and CiA 402: Distinguishing Network and Drive States

CAN Physical Layer and Arbitration Basics

CANopen runs over the CAN link, but a healthy link and usable application objects are different criteria. Classical CAN uses dominant and recessive bits for nondestructive arbitration; the identifier determines arbitration priority rather than directly representing a device address. A node's ability to transmit frames does not establish that its configuration, node ID, and PDO meanings are correct. Nor should the frame-capacity rules of classical CANopen CC be automatically applied to CANopen FD.

During board bring-up, first check the transceiver, supply and common-mode range, bus topology, termination at both ends, and bit timing. Determine the sample point, propagation delay, and clock-error allowance from cable length and bit rate. Software should read receive and transmit error counts, error-active/error-passive status, and bus-off status. Packet-loss counts alone cannot distinguish line reflections, inconsistent bit timing, and a controller going offline.

Arbitration delay varies with bus load and high-priority traffic; periodic transmission does not guarantee periodic arrival. Budget PDO, heartbeat, SDO, and diagnostic traffic separately, and observe worst-case arrival times. Excessively frequent high-priority messages can prevent other nodes from transmitting for long periods and cause higher-layer timeouts. Retransmissions after bus errors also increase jitter.

For engineering tests, start with two nodes and a small fixed set of frames to verify transmission, reception, and termination, then add the complete CANopen stack and other nodes. Test duplicate node IDs, duplicate COB-IDs, and connection/disconnection faults separately. Bus-off recovery must retain diagnostics and application-level loss-of-communication handling. After restarting the controller, do not continue driving with the previous enable state and reference.

Debugging Checks
  • Measure the differential waveform at the remote end and record error counts. Vary the load to check whether high-priority traffic starves other messages.
  • Configure duplicate node IDs or disconnect termination at one end, and check whether link diagnostics and the drive's communication-loss strategy distinguish the causes.
References

NMT and Node Startup

NMT manages CANopen node communication states, commonly Initialization, Pre-operational, Operational, and Stopped. These do not directly correspond to the motor drive's enabled state. A node may already be Operational yet produce no torque because of a drive fault, an unconfirmed mode, or missing control permission. Startup logs should retain both NMT and drive application states, rather than using 'online' for both meanings.

Firmware initialization establishes hardware, the object dictionary, communication objects, and the application's initial state in sequence, then sends boot-up according to the protocol and enters the configurable phase. PDO availability depends on NMT state; SDO and error monitoring support configuration and management. Verify supported services and states against the selected stack and public interface definition. Do not assemble a simplified protocol that merely uses the same state names.

Master configuration should be a traceable transaction: confirm node identity, set required parameters, verify readback, and check PDO and monitoring configuration before requesting Operational. Design the application consequences of Reset Node and Reset Communication separately, especially which parameters revert to defaults, which retain stored values, and whether references become invalid. A communication reset must not bypass safe initial conditions for power output.

When debugging stalled startup, inspect raw NMT commands, boot-up messages, and SDO responses before dictionary configuration; do not rely solely on a green indicator in the host software. An unexpected boot-up during operation indicates node reinitialization or a network change, so the master should reconfirm identity and configuration. The application control chain requires a new valid command and explicit permission; do not treat this startup as a natural continuation of earlier cyclic data.

Debugging Checks
  • Replay startup through initialization, configuration, Operational, and Stopped, verifying PDO, SDO, and application output separately.
  • Trigger a communication reset during operation, and check boot-up, configuration restoration, and invalidation of old references, confirming that the drive does not automatically re-enable.
References

Heartbeat and Node Monitoring

Heartbeat periodically publishes node liveness and NMT state, allowing consumers to determine whether the producer still exists and is in the expected communication state. It does not prove the health of the motor's closed loop: a node may keep transmitting heartbeats while its control task is blocked or position feedback has failed. Design and log heartbeat timeouts, PDO freshness, and internal drive liveness monitoring separately.

Producer periods and consumer timeouts must account for bus arbitration, task scheduling, and occasional delays, leaving reasonable margin while meeting the application's tolerable communication-loss time. Too short a window mistakes normal jitter for a fault; too long a window delays a controlled stop. Read configuration to confirm each node's actual heartbeat period. Do not let the master use a default consumer timeout while the slave is configured for a different period.

Consumers should refresh liveness only on a valid heartbeat from the target node, not on any CAN frame. Handle boot-up and NMT state changes separately, avoiding interpretation of initialization messages as continued Operational state. Error-monitoring tasks should use monotonic timing and cover counter wraparound. Forward events only to application fault/recovery interfaces; do not execute complex stopping procedures in the CAN receive interrupt.

Define whether communication loss limits operation, initiates deceleration, or stops the drive, and choose the implementation according to mechanical and power constraints. Link recovery does not mean the old command remains fresh; the master must recheck node identity, state, and required configuration. Test interrupted heartbeats, normal heartbeats with stalled PDOs, node resets, and whether consumers adjust when heartbeat periods change.

Debugging Checks
  • Freeze only PDOs while maintaining heartbeats, confirming that the application detects stale references instead of treating normal liveness as normal control.
  • Pause and restore the target node's heartbeat. Measure timeout triggering and recovery permission, and check that old run commands are not replayed.
References

EMCY and Fault Reporting

EMCY reports internal device error events. Its payload includes an error code, error register, and manufacturer-specific information, unlike cyclic process data. It provides event notification, not a remote shutdown chain replacing local drive protection. Fast faults such as overcurrent must first be handled inside the device according to hardware and application design, then reported over communication. Do not wait for the master to receive EMCY before disabling output.

Map fault sources, severity, EMCY codes, active fault bits, latched records, and recovery conditions. Do not resend the same fault event every control cycle. Fault history must remain readable so host software can review it after losing an event message. The error register represents categories; do not treat it as a complete fault log containing all operating details.

Manufacturer information can carry a compact state or record index, while detailed current, bus voltage, mode, and timestamps are saved in a bounded incident buffer. When multiple faults occur together, preserve the earliest valid cause before recording subsequent faults. For example, a bus-voltage drop after shutdown must not overwrite the original overcurrent. Retain the local fault fact if the transmit queue is full or the bus is off; communication failure must not clear an active fault.

After receiving EMCY, the master may restrict the application or initiate diagnostic reads, but recovery must check whether the actual fault has disappeared, the drive permits reset, and a new enable command has arrived. Clearing history, clearing active faults, and clearing communication errors are different actions. Integration tests must cover a single event and a persistent fault, multiple events in rapid succession, and record completeness during communication outages.

Debugging Checks
  • Inject a persistent fault. Verify event-based reporting and that the active fault remains valid rather than clearing when transmission succeeds.
  • Let the first fault cause subsequent faults, then read the log to verify that the first cause and event sequence are preserved.
References
Industrial Communication

CANopen: Object Dictionary and Transfers

Index/Subindex and Access Attributes · SDO and Parameter AccessExpand the CANopen: Object Dictionary and Transfers Knowledge Directory
  • Index/Subindex and Access Attributes
  • SDO and Parameter Access
  • PDO Mapping, Triggering, and Synchronization
  • Configuration Persistence and Compatibility
Reading Guide: CANopen and CiA 402: Distinguishing Network and Drive States

Index/Subindex and Access Attributes

The object dictionary interfaces CANopen communication with the application, identifying objects and their members by Index and Subindex. Entries also contain data type, length, access attributes, and relevant communication capabilities; the dictionary is more than an array mapping addresses to variable pointers. It should describe stable external meanings. Moving internal structure fields must not make the same index refer to a different application quantity.

Use a controlled description table and access callbacks to separate protocol decoding from application reads and writes. Read-only measurements come from snapshots; writable settings undergo type, range, state, and combination checks. Object length and signedness must agree, particularly the member counts and valid ranges of records/arrays. A nonexistent Subindex must not accidentally read adjacent memory. For PDO-mappable objects, also specify direction and bit length.

Index defines interface identity and Subindex identifies the member; manufacturer-specific and standardized application areas must not be repurposed interchangeably. Provide standardized objects only to the extent actually supported. Do not add a dummy object that always returns zero merely to prevent master errors. Check mandatory support, bit meanings, and mode-specific details against the chosen specification version and device manual, rather than claiming full compatibility from a public overview alone.

Configuration documentation and EDS files can be generated from the same controlled dictionary, but runtime readback remains the final verification step. On upgrades, compare object sets, data widths, defaults, and access conditions, retaining meanings relied upon by older clients. Test incorrect type lengths, writes to read-only objects, unknown indices, unknown subindices, and boundary values, confirming that every rejection leaves application state unchanged.

Debugging Checks
  • Enumerate dictionary and documented objects, checking consistency of indices, member counts, lengths, access attributes, and actual access results.
  • Write to unknown Subindices and read-only objects, confirming explicit failure and no changes to adjacent data.
References

SDO and Parameter Access

SDO provides acknowledged object-dictionary access suitable for configuration and diagnostics; it should not serve as a real-time reference channel for every fast-loop cycle. Small data can use expedited transfer; longer data uses segmented or block transfer, depending on stack and product support. Receiving an initial request does not mean that the entire long object has been committed.

The server maintains bounded state, length, received position, and timeout for each transaction. Segments enter staging storage first and are submitted to the application only after complete validation, preventing a broken connection from leaving a partial parameter block. Interrupted transfers, sequence errors, or length mismatches must end the transaction and release buffers; the next request must not inherit its cursor. Never allocate unbounded memory from an unvalidated length.

SDO abort reasons should correspond to specific boundaries such as nonexistent objects, permissions, length, value, or application state, allowing the master to distinguish configuration errors from a required device-state change. Flash saving and motor actions are usually slower than SDO parsing. Handlers must be bounded and return results according to the interface definition. Do not wait for erasure or programming in a CAN interrupt, causing PDOs and heartbeats to time out as well.

Begin integration by reading device identity and reading/writing ordinary settings to confirm basic object access, then test long data and failure recovery. With automatic master retries, ordinary configuration writes should produce stable results, while commands with side effects require explicit semantics. Log index, subindex, direction, total length, and failure stage to distinguish message-state errors from application rejection. After protocol success, also read the effective value; do not rely solely on an SDO acknowledgment.

Debugging Checks
  • Stop a segmented transfer midway or change its length, checking timeout cleanup and preservation of the complete previous effective configuration.
  • Run parameter access concurrently with PDO traffic. Record control-cycle and heartbeat delays to confirm that SDO does not block the real-time path.
References

PDO Mapping, Triggering, and Synchronization

PDO packs selected process quantities from the object dictionary in a defined order and bit length for cyclic or event-driven exchange. A classical CANopen CC PDO carries at most eight bytes of application data; do not insert a longer structure without changing protocol type. Communication parameters define the identifier and triggering, while mapping parameters define content. Check both as one consistent configuration.

When designing mappings, list the data needed for operating references, controlword, status, and feedback, then verify direction, length, and update time for each item. From the slave's perspective, received PDOs are RPDOs and transmitted PDOs are TPDOs; do not reverse the names based on the master's perspective. Reordering objects can make the master interpret speed as position even when total length is unchanged, so mapping versions and readback checks matter.

Synchronous PDOs relate to SYNC, while event-driven or timed PDOs have separate publication conditions. Master transmission, device reception, and control-task adoption still occur at different times; synchronization does not automatically eliminate arbitration and local execution delays. Publish an application snapshot after receiving a complete PDO and record its sequence number or time, avoiding bytewise reads of a buffer being updated by the control interrupt.

Variable mappings must follow supported states and specified steps: invalidate the mapping, update content, validate total length, and restore validity. Do not change object order during operation while continuing to parse old frames. Add high-priority traffic, dense event changes, and SYNC loss to tests, observing worst-case delay and application communication-loss detection. PDO has no separate per-request acknowledgment; waiting for a reply cannot establish that a reference was used.

Debugging Checks
  • Swap two equal-width objects in a mapping, confirming that readback and version checks detect the change before operation instead of checking only total byte count.
  • Capture control adoption times while varying the interval between SYNC and PDO arrival, checking complete snapshots and stale-data detection.
References

Configuration Persistence and Compatibility

Node configuration includes communication parameters, object mappings, and application parameters; document their storage policies separately. A successful SDO write usually means the access operation succeeded. Whether it has reached nonvolatile storage depends on the object and product behavior. Persistence commands should not run by default on every speed-reference change, avoiding Flash wear and blocking of real-time tasks.

Separate pending configuration, effective configuration, and stored images into three stages, attaching version, length, and integrity information to each commit. On power-up, validate the image and hardware identity first; on failure, enter an explicit default or restricted state and provide diagnostics. A multipage Flash scheme must also account for power loss during erase/program operations and validity-marker ordering. A CRC alone does not make every commit transactional.

Interface upgrades must check compatibility of object indices, data widths, scaling, defaults, and PDO mappings. Explicitly migrate or reject old configurations; do not cast them to a new structure and continue using them. Define activation and restart conditions when changing node ID, bit rate, or critical communication parameters. If storage contains new values while live messages still use old values, expose a readable state explaining this.

When integrating a replacement device, read its identity and firmware/dictionary versions before importing a validated configuration; do not assume the same product name accepts the same parameter block. Test blank storage, damaged images, older configurations, save failures, and resets during saving. Every failure should preserve a route to restore communication, but communication recovery must not automatically restore the previous enable state.

Debugging Checks
  • Cut power at each saving stage, then reboot and check the effective version, default fallback, error reason, and whether communication parameters are explainable.
  • Import an old object configuration into new firmware and check migration or rejection. Scaling and object meaning must not change silently.
References
Industrial Communication

CiA 402: Drive Application Model

Controlword and Statusword · Drive State Machine and Enable ConditionsExpand the CiA 402: Drive Application Model Knowledge Directory
  • Controlword and Statusword
  • Drive State Machine and Enable Conditions
  • Operating Modes and Target/Actual Values
  • References from CANopen and EtherCAT CoE
Reading Guide: CANopen and CiA 402: Distinguishing Network and Drive States

Controlword and Statusword

CiA 402 uses the controlword to express the master's requested drive-state transitions and the statusword to express the device's actual application state. They are not transmit/receive mirrors of one variable. After the master writes an enable command, the device must check internal permissions and complete the transition before returning the corresponding state. Never copy the received controlword directly into the statusword, misleading host software into believing the drive is ready.

Separate controlword decoding, transition-condition checks, action execution, and statusword generation, preserving actual transition results. The statusword includes state bits and other mode/diagnostic bits. Use the specified mask relationships to determine the main state; whole-word equality can overlook additional bits that change during operation. Verify meanings of mode-specific and optional bits against device support and version.

During operation, controlword and targets should come from the same application snapshot with an update timestamp. Fault reset often has edge or transition semantics: holding a bit does not mean reset should repeat every cycle. For illegal transitions or requests lacking permission, retain the true state and expose fault/limitation information. Do not hide causes or perform power-output actions prematurely in protocol parsing functions.

During master debugging, log controlword, statusword, decoded state, permissive conditions, and power permission, checking each transition. Display communication Operational and drive Operation enabled separately. The former describes communication state only and does not prove permission to energize the motor. Test commands during additional status-bit changes, quick stop, and fault reset, ensuring that mask-based decisions and status output remain stable.

Debugging Checks
  • Determine the main state while other valid statusword bits change, confirming that whole-word comparisons do not cause misclassification.
  • Write enable requests continuously while blocking one internal permissive condition, and check that the statusword reports the true state rather than echoing the controlword.
References

Drive State Machine and Enable Conditions

The drive state machine describes application behavior from not ready and switch-on disabled through ready to switch on, switched on, and operation enabled, as well as quick stop and fault reaction. It is independent of NMT or the EtherCAT ESM and must be implemented separately. A network state permitting operation does not mean that the bus, feedback, protection, and operating mode satisfy torque-production conditions.

The transition table should list input commands, internal conditions, exit actions, and entry actions. Before enabling, check hardware faults, DC bus, feedback validity, parameter validity, and control initialization. During fault reaction, implement the output behavior before generating communication status. One 'enabled' Boolean must not conflate drive logical state, PWM permission, and the safety chain.

Actual stop and quick-stop behavior is also constrained by supported options, mechanical inertia, and braking capability. Document ramps, holding torque, output inhibition, and completion criteria in the product interface; a command name alone cannot establish that the axis is stationary. Fault reset handles only faults eligible for recovery and reestablishes operation permission through a new command. Clearing historical logs alone must not enable the drive.

Verify complete transition traces: check rejection of commands in inappropriate states, whether faults override run requests at every critical stage, and whether old references remain after reset. First use simulation or controlled low-energy tests to verify the relationship between status output and control permission, then examine the real stop path. Public CiA overviews explain the model; validate implementation details against the chosen specification and device manual.

Debugging Checks
  • Exercise common legal transitions and illegal jumps, recording state, power permission, and rejection reason, and checking that all three agree.
  • Inject invalid feedback or a fault during enabling, checking fault priority and the conditions for operation after reset.
References

Operating Modes and Target/Actual Values

A drive may support position, velocity, or torque modes, with different target objects, feedback objects, limits, and status bits. Separate the requested mode from confirmation of the actual mode. The master must not write a mode request and immediately drive using a different target format while the device remains in the old mode. The product interface must explicitly define supported profile or cyclic synchronous modes and optional behavior.

Fix units, scaling, signs, and update times for targets and actual quantities in the application interface. Document position-counter wraparound, velocity direction, and torque scaling in the object documentation. Decodable numbers do not guarantee matching physical meanings, especially when devices support manufacturer parameters or optional scaling differently. Begin testing with unenergized reads/writes and unit checks, rather than spinning the motor to guess scaling.

On mode changes, handle the old mode's integrator state, trajectory buffers, feedforward, and unconsumed targets so the new mode cannot interpret an old value as another quantity. The application may require switching while stopped or provide a controlled transition; both choices require published constraints. Return commanded targets, limited targets, and actual feedback separately, revealing when capability limits prevent adoption of a master's value.

Cyclic synchronous modes also require fresh process data and defined local control execution timing. Each received PDO must not trigger unbounded interpolation or disturb the fast-loop period. During integration, record requested mode, displayed mode, targets, actual values, and statusword. Verify individual modes before switching and timeout tests. CiA 402 support does not imply support for every mode and object or complete interchangeability.

Debugging Checks
  • Change the mode request while delaying confirmation, checking that targets are interpreted according to the actual mode and old trajectories do not leak through.
  • Use commands with explicit positive/negative directions and scaling to test targets, adopted limited values, and feedback objects, confirming that unit definitions can be compared.
References

References from CANopen and EtherCAT CoE

CiA 402 is a drive application interface model; CANopen and EtherCAT CoE can each carry its objects and process data. What is reused is object meaning and drive-state behavior, not unchanged CAN frames transmitted over EtherCAT. CANopen has NMT and CAN arbitration, while EtherCAT has ESM, mailboxes, mappings, distributed clocks, and other mechanisms. Do not merge their communication state machines into one table.

Firmware can use a shared drive application layer for state transitions, target validation, units, and faults, with protocol adapters handling decoding, dictionary access, and data publication. Protocol layers pass complete candidate snapshots to the same control interface, preventing CANopen and CoE paths from using different limiting or recovery rules. Each adapter retains its own link diagnostics and lifecycle state.

Cross-protocol integration must verify matching indices, lengths, access directions, scaling, and effective behavior for the same objects, rather than comparing names alone. PDO organization and cycle conditions remain defined by each communication interface. EtherCAT OP permits the corresponding process-data operation, but CiA 402 enabling remains separate. The same separation of communication and drive operation applies to CANopen Operational.

When both interfaces are supported, define control ownership explicitly: which link supplies run commands and whether the other is read-only or used for configuration. Do not automatically let the last received PDO win as the command source; switching could apply a stale target to the axis. Test protocol switching, disconnection of the active control link, and slave reset, ensuring that shared application state and each communication state remain traceable.

Debugging Checks
  • Read the same feedback or write the same setting through both protocols, comparing units, permissions, and activation rules for complete consistency.
  • Maintain EtherCAT OP without enabling the drive and confirm that power output is not automatically permitted. Changing control sources requires a new valid command.
References

EtherCAT

Industrial Communication

EtherCAT: Devices and Communication States

ESC and Host/PDI Interface · INIT, PREOP, SAFEOP, OPExpand the EtherCAT: Devices and Communication States Knowledge Directory
  • ESC and Host/PDI Interface
  • INIT、PREOP、SAFEOP、OP
  • Mailbox and Process-Data Paths
  • AL States and Error Diagnosis
Reading Guide: EtherCAT Device Side: States, CoE, and Synchronization

ESC and Host/PDI Interface

The EtherCAT Slave Controller (ESC) handles line-side frames and process-data storage; the local MCU accesses registers, mailboxes, and process data through the PDI. Forwarding frames on the line does not mean the local application has retrieved references in time: network exchange and control computation are separate paths. Board design must first define the ESC, PDI interface width, access timing, interrupt mechanism, and available bandwidth.

During initialization, verify reset, clocks, PHY connections, identity configuration, PDI reads/writes, and event interrupts separately. Reading a known register establishes basic interface connectivity, but burst lengths, address increments, and byte order still need independent checks. Alignment restrictions, busy states, and wait cycles depend on the selected ESC manual; do not directly transplant example functions from another chip.

Process data connects line-side and local access through SyncManager consistency mechanisms and FMMU mappings. The application must obtain a complete image using the supported buffered-access protocol. A PDI interrupt only signals an event; it does not guarantee decoding into the application's required format. Copy the image and publish a snapshot in a bounded service path for the control task, rather than issuing a slow external-bus read for every control variable.

Observe link state, ESC event, PDI transaction completion, and control adoption as four separate timing points. Insufficient PDI bandwidth may appear as cyclic-data delay or watchdog problems; do not focus only on the master's cycle. Stress-test concurrent mailbox reads and cyclic exchange, checking complete access under contention, lost events, and preservation of both ESC and local-application states after faults.

Debugging Checks
  • First read/write a controlled test area to verify PDI addresses, byte order, and boundaries; then measure bounded access time for the maximum process image.
  • Increase mailbox and cyclic-data loads together. Record delay from PDI events to control adoption, and check for buffer overwrites.
References

INIT、PREOP、SAFEOP、OP

The EtherCAT State Machine (ESM) determines device communication functions and process-data permissions, with different checks at INIT, PREOP, SAFEOP, and OP. PREOP generally permits mailbox configuration. SAFEOP allows input exchange while outputs remain in the prescribed state; OP permits the corresponding normal output path. SAFEOP is not a functional-safety certification state: its name does not mean STO has been implemented or SIL requirements met.

In state-transition callbacks, the slave checks availability of mailboxes, SyncManagers, mapping lengths, synchronization mode, and application resources, returning explicit errors. Do not ignore configuration mismatches merely to let the master reach OP; process data could be decoded incorrectly. Tie output permission to the actual communication lifecycle. When leaving an operational state, the application must apply an explicitly defined communication-loss or stop strategy.

Keep ESM independent of the CiA 402 application state machine. After reaching OP, the drive must still check parameters, feedback, faults, and controlword before deciding whether to enable operation. Do not turn on PWM directly in the OP callback. A drop in communication state does not necessarily mean the mechanism has stopped; deceleration, braking, and output inhibition also involve inertia and energy handling and must be implemented explicitly by the drive application and protection paths.

Advance integration step by step: verify mailbox reads/writes, then mapping and synchronization, then cyclic outputs. If stuck in SAFEOP, inspect AL errors and mapping checks instead of repeatedly writing OP to hide the failure. Test master transitions back to PREOP, line interruptions, slave resets, and invalid configuration. Record ESM, drive state, and output behavior to locate the problem in communication or the application.

Debugging Checks
  • Keep OP without issuing drive enable and confirm that PWM permission is not automatically granted. Return to SAFEOP and check the defined output behavior.
  • Deliberately change image length or synchronization configuration, verifying rejection of the state transition and a diagnosable AL reason.
References

Mailbox and Process-Data Paths

Mailboxes handle acyclic requests such as configuration and diagnostics; process data carries cyclic control and feedback. Their scheduling and completion semantics differ. Successful CoE object access does not prove correct process-image mapping, and changing PDO values does not prove mailbox configuration has been persisted. Track service delay, buffer use, and failure reasons separately for both paths rather than summarizing every function with one communication-success flag.

Mailbox transactions may involve long objects and multiple processing steps; complete them in background work or a bounded protocol service task. Process-data copying and control adoption require a fixed cadence, preventing expensive object callbacks from preempting the fast loop. When both paths access the same application object, use a shared read/write interface or snapshot handoff. Do not let SDO write individual fields of settings being read by the control interrupt.

Define inputs and outputs on the cyclic path from the slave's perspective: outputs generally travel from master to device, and inputs from device to master. Application structures, PDO order, mapping dictionary, and ESI description must agree. Decode the byte image into explicit data types and handle alignment and endianness. Do not copy compiler structures directly and assume their padding and layout match the wire format.

Prove mailbox objects and cyclic images separately before testing concurrent operation. Heavy diagnostic reads, parameter saving, or master configuration changes must not starve cyclic data. If the device remains OP but references do not update, check image reads, synchronization events, snapshot publication, and control consumption rather than merely increasing mailbox retries. On abnormal exit, discard unfinished transactions and stale references so delayed commands cannot take effect after recovery.

Debugging Checks
  • Verify matching units between an object's SDO read value and PDO feedback, and that configuration checks detect an intentionally incorrect mapping order.
  • Perform continuous mailbox reads and record worst-case cyclic-path latency, confirming that background service does not violate control deadlines.
References

AL States and Error Diagnosis

AL states and error codes explain EtherCAT application-layer state transitions and communication-configuration problems. When a slave remains in a different state from that requested by the master, read its actual state, error flag, and reason rather than relying on link LEDs. Port links, working counters, ESM, and drive faults provide different evidence; a normal result at one layer cannot replace checks at the others.

In transition callbacks, save the requested state, rejection stage, mapping parameters, and local check results as an ordered diagnostic record. AL errors may indicate configuration, synchronization, or communication problems; the drive application should separately log its fault sources. Do not label every power overcurrent as a generic mapping error or report only 'motor not ready' for a SyncManager configuration failure.

Troubleshoot identity and wiring first, then mailbox/process-data resources, PDO lengths, and synchronization, and finally application permissions. If a node cannot maintain PREOP, resolve basic communication first. If it stops in SAFEOP, inspect image and synchronization checks. If it reaches OP but the axis does not move, inspect drive state, mode confirmation, and target adoption. This layering avoids trying to fix protocol-configuration errors by tuning PI gains.

For reproduction, preserve the master's configuration and ESI version, device identity and firmware version, and AL/drive states before and after the fault. Reset may erase the most valuable cause, so read and log it before controlled recovery. Revalidate necessary configuration after communication recovers. Do not repeatedly clear errors and enter OP until an inconsistent system occasionally runs, losing reviewable evidence.

Debugging Checks
  • Deliberately create identity mismatches, image-length mismatches, and synchronization errors, checking that each leaves distinct, diagnosable status information.
  • When OP is active but the axis does not move, capture AL, CiA 402 state, mode display, and target together instead of judging from link LEDs alone.
References
Industrial Communication

EtherCAT: CoE and PDO

Object Dictionary and SDO Services · PDO Assignment, Mapping, and LengthExpand the EtherCAT: CoE and PDO Knowledge Directory
  • Object Dictionary and SDO Services
  • PDO Assignment, Mapping, and Length
  • ESI Description and Device Consistency
  • Carrying the CiA 402 Drive Interface
Reading Guide: EtherCAT Device Side: States, CoE, and Synchronization

Object Dictionary and SDO Services

CoE applies object-dictionary access and related process-data concepts to EtherCAT device interfaces. It reuses ideas from the CANopen object model, but services run through EtherCAT mailboxes and the device stack; it does not add a CAN controller to the ESC. Object types, access attributes, and application semantics must remain consistent. Matching index names alone do not prove full CiA 402 drive support.

Dictionary access callbacks should check lengths, access attributes, operating conditions, and combination constraints, returning explicit stack-defined results. Read-only feedback uses consistent snapshots. Parameter writes enter candidate objects first and take effect at a defined time after validation. Long objects and save operations have independent background states; request arrival does not mean storage has completed or mechanical action has finished.

The device supplies the online dictionary, while configuration files supply offline descriptions. Old files or firmware updates can make them inconsistent. A tool displaying an editable object does not mean the device currently permits writing. Compare online reads, offline definitions, and effective application values to distinguish nonexistent objects, permission rejections, type mismatches, and actual transfer timeouts.

A shared parameter service should make Modbus, CANopen, and CoE use the same object-validation logic, with each protocol adapter retaining its own byte decoding and exception mapping. Keep index meanings and units stable when upgrading the dictionary; explicitly increment interface versions when necessary. Test supported and unsupported access, aborted long transfers, and frequent reads/writes, ensuring mailbox callbacks neither block local control nor exhaust buffers.

Debugging Checks
  • Compare the online dictionary, offline description, and application readback, checking consistent widths, permissions, and units at each index.
  • Access objects that prohibit writes during operation and issue SDOs with incorrect lengths. Confirm clear failure and no partial changes to effective parameters.
References

PDO Assignment, Mapping, and Length

PDO mapping describes how objects combine by bit length; PDO assignment determines which PDOs a process-data channel uses. Both levels require validation. A valid mapping with missing assignment can still leave master and device disagreeing on total process-image length. Define RxPDO and TxPDO from the slave's receive/transmit perspective, specifying each object's width and meaning.

Validate object existence, permitted direction, and correct bit length first, then calculate each PDO and total image length and check channel, buffer, and application-structure capacity. Reordering objects without changing total length evades length-only checks, so read back the complete mapping and compare it with the version definition. Do not treat master byte offsets as the natural layout of a firmware structure.

Update mappings as complete transactions in supported communication states: stop using the old configuration, validate the new one, then resume process data. Fixed-mapping devices must explicitly reject unsupported changes rather than acknowledging SDO writes while continuing with the old layout. Use explicit access functions to decode process data, avoiding unaligned accesses and incorrect multiaxis object offsets.

During integration, assign distinct identification patterns to fields and verify correspondence between on-wire bytes and local values without permitting power output. Then check units, positive direction, and update events for real references and feedback. Detect incorrect mappings before operation; discovering them only through abnormal motor movement indicates insufficient interface validation. Log the effective mapping, total length, and configuration version to aid field replacement and upgrade diagnosis.

Debugging Checks
  • Swap two fields without changing total length, checking that complete mapping validation and identification-pattern tests detect the semantic misalignment.
  • Set an invalid assignment count or bit length, confirming rejection of the transition to operation and preservation of the complete old configuration.
References

ESI Description and Device Consistency

The ESI file is an important master-side device description, including identity, mailbox and process-data capabilities, objects, and synchronization information. It must match actual hardware, firmware, and dictionary, not merely let the master recognize a product name. ESI, local slave identity information, and the online dictionary have different sources; check them separately during upgrades rather than overwriting them to simulate compatibility.

A controlled build can export the dictionary and parts of ESI from a common interface definition, then validate them by reading back the actual device. Focus on Vendor ID, Product Code, Revision, PDO directions, bit lengths, object types, and synchronization capabilities. Old product identities or unimplemented optional modes left in template XML can make the master select configurations the device cannot support.

When releasing new firmware, specify compatibility with old ESI files and configuration-migration rules. A vendor's revision-compatibility policy is not a universal EtherCAT rule; a higher Revision does not necessarily imply backward compatibility. Changing EEPROM/SII contents may also affect calibration or factory configuration, so plan according to the actual design. Reprogramming identity is not an ordinary text rename.

During integration, save the hash of the master's ESI file and the device's online identity. Check automatic scanning, then manual configuration and device replacement. An object readable online but absent offline may indicate an outdated description; the reverse may mean the master loaded an old file. Diagnose explicit configuration differences rather than repeatedly clearing caches and rescanning until OP occasionally succeeds.

Debugging Checks
  • Configure the same device separately with old and new ESI files. Check identity, total PDO length, and synchronization settings, recording reasons for acceptance or rejection.
  • Scan the actual device and compare key identifiers with build artifacts, checking that template remnants and unimplemented functions are detected early.
References

Carrying the CiA 402 Drive Interface

Providing a CiA 402 interface over CoE requires connecting drive states, modes, and target/actual quantities to the real application, not merely creating a few indices. TI's official examples demonstrate integration of controlword, statusword, position, velocity, torque, and other objects. Example behavior differs in scope from complete product control, protection, and timing verification; running an example does not establish compliance with every drive requirement.

Decouple object access, ESM, and the drive state machine, publishing target snapshots and feedback at defined cycles. After entering OP, remain in a valid drive-disabled/awaiting-enable state, advancing the application through controlword requests and internal permissions. Express drive faults through application state and diagnostics, while the communication layer retains the true status of mailbox and process-data capabilities.

When mapping controlword, mode request, and targets, define when all fields are adopted together, avoiding a new mode with a previous-cycle target. Statusword and actual mode must also come from one application snapshot. For multiaxis devices, verify index ranges, per-axis configuration, and independent faults against the selected specification and object layout. Do not map all objects by simply adding a structure offset to the first axis pointer.

Begin with unenergized object reads/writes to verify modes, units, and state transitions, then connect closed-loop motor control under controlled conditions. Check actions on quick stop, fault reset, cyclic-data timeout, and the master leaving OP. Standard indices visible to the master do not prove its targets reached the control loop. Observe application-adopted values, PWM permission, and feedback together to verify the entire chain.

Debugging Checks
  • In OP, issue mode and controlword changes step by step, checking drive state, actual mode, and PWM permission rather than only reading object echoes.
  • Introduce a mapping error or fault on one axis, checking that other axes and shared communication state behave as defined without targets being misapplied across axes.
References
Industrial Communication

EtherCAT: Synchronization and Diagnostics

Free Run, SM Event, and DC Modes · Sync0/Sync1 and Control SamplingExpand the EtherCAT: Synchronization and Diagnostics Knowledge Directory
  • Free Run, SM Event, and DC Modes
  • Sync0/Sync1 and Control Sampling
  • Data Snapshots and Clock-Domain Boundaries
  • Missed Cycles, Latency, and Synchronization Observation
Reading Guide: EtherCAT Device Side: States, CoE, and Synchronization

Free Run, SM Event, and DC Modes

Free Run operates the slave on its local cycle; SM event mode links application updates to process-data channel events; DC mode uses distributed clocks to generate synchronization events. Choose according to device capabilities and control goals; selecting DC in a UI is not inherently better. Some objects or synchronization parameters may not be exposed through CoE, so do not assume every slave offers the same writable indices.

In Free Run, reference arrival and sampling generally have different phases; record data age and use complete snapshots. In SM event mode, define whether receiving the output image triggers copying followed by computation, or merely publication to the local fast loop. DC mode also requires defined relationships among period, phase shift, synchronization events, and local execution. Their budgets and exception checks must not share one undifferentiated 'synchronization OK' flag.

When changing modes, stop using old timing, rebuild event sources and counters, and revalidate deadlines from sampling to PWM update. The network cycle may be slower than the current loop, requiring rules for using each network target over multiple control cycles. Do not arbitrarily vary the control-interrupt period with packet jitter to follow frame arrivals unless the controller and timing design explicitly support that approach.

Test absent cyclic data, normal cycles, late data, and master mode changes separately, observing causality among events, snapshots, and outputs. Stable DC does not prove fresh targets, and continuing SM events do not guarantee timely local computation. Record synchronization configuration and actual execution paths to explain differing latency and jitter at the same master cycle in different modes.

Debugging Checks
  • For each of the three supported modes, capture network events, local sampling, and output times, confirming that the selected event source is actually active.
  • Change the network period and fast-loop ratio, confirming that snapshot adoption and timeout detection follow the defined cycle relationship.
References

Sync0/Sync1 and Control Sampling

Sync0 and Sync1 are distributed-clock synchronization events that can trigger or coordinate local tasks, but they do not automatically align ADC, computation, and PWM at ideal phases. Define how events reach the MCU on the board, generate interrupts, or trigger peripherals, including delay and jitter at each step. Network synchronization coordinates execution timing; status registers alone cannot establish alignment of the complete control chain.

Work backward from PWM activation to sampling, angle updates, and control computation, then place the selected Sync event on the same timeline. If the network cycle is slower than the current loop, Sync may update targets or slower tasks while the fast loop remains driven steadily by a local timer. Define whether Sync1 serves a second-stage task, input latching, or another cycle according to device capability; its name does not imply a fixed purpose.

Bound interrupt work and handle excessively frequent or repeated events to avoid accumulating periodic tasks. Fix the order of process-data copying, control computation, and feedback publication. Base any phase compensation on an actual delay model; do not add an arbitrary angle constant to hide a cycle mismatch. Mismatched feedback-angle and current sampling times can also cause control errors at high speed.

Observe the Sync pin, ADC trigger, ISR boundaries, and PWM loading together to distinguish network phase, MCU interrupt waiting, and actual output delay. Test configuration changes, master-cycle changes, and worst-case CPU load, counting missed events. Host simulation can verify cycle logic but cannot establish board propagation or hardware-trigger accuracy; those require target-hardware records.

Debugging Checks
  • Measure delay and jitter from Sync to ADC and PWM loading, separately recording hardware propagation, interrupt waiting, and computation time.
  • Change synchronization periods at the highest expected load, checking consistency of event counts, deadlines, and feedback sampling times.
References

Data Snapshots and Clock-Domain Boundaries

Network frames, ESC accesses, and control interrupts may advance from different events or clocks, so handle both data consistency and freshness. Updating controlword, mode, and targets field by field, even in contiguous memory, can expose a combination belonging to no complete cycle. SyncManager maintains consistency within its interface scope; it does not replace publication protocols for shared MCU structures.

The receive path first obtains a complete process image, validates length and state, decodes a candidate snapshot, then publishes a version or pointer at a defined handoff. Consumers use only completed snapshots and record sequence, source, and age. Double buffering is not inherently safe: a producer can still tear data by overwriting a slot the consumer is using. Define buffer ownership and lifetimes.

Across clock domains, use one timebase or an explainable conversion. ESC timestamps cannot be directly subtracted from MCU timer readings without defined offset, frequency, and wraparound rules. The application can initially assess freshness using receive sequence numbers and local adoption times, adding network-time conversion if needed. Do not mix two unverified clocks merely to produce apparently precise microseconds.

Invalidate old snapshots on communication loss, reset, or mode transitions, requiring a new complete target before restoring application permission. Logging receive, publish, and adoption sequence numbers plus limiting reasons diagnoses more than a final speed alone. In regression tests, deliberately overlap publication and consumption and vary PDI access duration, checking for partial updates and repeated treatment of the same target as a new cycle that refreshes liveness.

Debugging Checks
  • Update controlword, mode, and targets concurrently, checking that consumed sequence numbers and field combinations always identify one complete snapshot.
  • Reset ESC or MCU independently and exercise timer wraparound, checking time conversion, old-snapshot invalidation, and new-command recovery conditions.
References

Missed Cycles, Latency, and Synchronization Observation

Cycle diagnostics need at least three layers: line exchange, device process-data service, and control execution. Working counters and link status provide network evidence but cannot alone prove timely MCU adoption of references. DC clock synchronization, process-data freshness, PDI liveness, and control deadlines have different meanings and need separate counters and fault conditions.

Missed-cycle handling must define tolerance windows, hold or deceleration policies, and invalidation of old references on recovery. Do not turn every communication anomaly into a reset or hold an old target indefinitely after occasional delays. SyncManager and PDI watchdogs supervise different interface activity; actual output behavior depends on device design and configuration. A vendor terminal's default behavior is not a complete policy for a custom drive.

Record time differences among frame/SM event arrival, snapshot publication, control adoption, and output loading. Report worst-case latency and missed-cycle counts, not just averages. Use bounded log buffers and mark dropped records so logging itself does not cause more timeouts. Recheck timing budgets after changing master periods, mailbox load, or compiler optimization instead of reusing one earlier unloaded measurement.

Reproduction tools can inject master stops, delayed process data, lost synchronization events, and local slave blocking, comparing diagnostic bits and application actions. After recovery, confirm configuration, mode, and fresh targets before reestablishing operation permission. If evidence includes only network captures without local control timing, limit conclusions to communication exchange rather than declaring the entire motor-control execution chain healthy.

Debugging Checks
  • Stop network PDOs and local PDI service separately, confirming distinguishable watchdog indications and application communication-loss causes.
  • Restore operation after deliberately delaying one or more cycles. Record states, reference age, and re-enable conditions, checking that old commands are not replayed.
References

Engineering tasks

Design and implementation

Design and implementation

Requirements, metrics and acceptance

End Applications and System Boundaries · Performance Metrics and Measurable ConditionsExpand the Requirements, Metrics, and Acceptance Knowledge Directory
  • End Applications and System Boundaries
  • Performance Metrics and Measurable Conditions
  • State, Exception, and Interface Requirements
  • Mapping Requirements to Tests
Reading Guide: Industrial Motor-Control Firmware: From Requirements to Verification

End Applications and System Boundaries

The end application determines which problems firmware must solve. Servo positioning, fan speed control, and conveyors have different command, load, stop, and feedback needs even with similar motors. Requirements should identify the controlled plant, transmission, sensors, power stage, and higher-level system, distinguishing firmware behavior from conditions guaranteed by external hardware. Do not attribute whole-system performance to one control function.

System boundaries also include energy and faults. For supply variation, lost communication, feedback loss, and load jams, specify where each enters the system, who detects it, who acts, and who permits recovery. Some performance depends on bus voltage or load inertia; some protection depends on hardware comparators and gate drivers. Do not bury these prerequisites in implementation notes. Track unknown mechanical or electrical conditions as open items rather than choosing a default and presenting it as fact.

Before implementation, diagram interface and state boundaries, separating command, energy, and observation flows. Use these boundaries to build a resource table for chip selection and verify capabilities against official documentation. Device documentation establishes chip-level conditions, not whole-product compliance. Perform acceptance tests on agreed objects and conditions. State coverage when using substitute loads or simulation, preventing a successful development-board demo from being interpreted as validated end-product performance.

Debugging Checks
  • List system inputs, outputs, and external guarantees, checking that every exception has assigned detection, action, and recovery responsibilities.
  • Check the test object, mechanical parameters, and supply range. Mark unconfirmed boundaries so unverified assumptions do not enter published metrics.
References
  • ST STM32G4x4 Documentation — STM32G4x4 documentation index; datasheet/reference manual/errata, index checked online; not proof of all document contents

Performance Metrics and Measurable Conditions

Performance metrics need a quantity, unit, conditions, and decision method. 'Fast response' cannot be accepted objectively; response time and permitted error under specified load, reference step, and sampling settings produce comparable results. Speed error, position-following error, communication latency, and control jitter are different metrics with different measurement points. Using host-display refresh time as control response mixes communication and display overhead into the conclusion.

Measurement conditions should include mode, bus voltage, temperature, limits, filters, and mechanical state. A small step may never reveal saturation; a large step may mainly reflect voltage and current constraints, so distinguish small-signal and constrained responses. Agree error-statistics windows, settling criteria, repetition counts, and anomalous-sample handling before testing. Do not change windows after seeing results to obtain better numbers.

Break metrics into executable checks: host tests verify deterministic calculations and interface logic, while target measurements verify timing and physical response. Tools can automate tests and save results but do not determine whether metrics are reasonable. Preserve raw waveforms, timebase, and measurement configuration, then calculate metrics during analysis. A single final pass line loses information needed to diagnose error and scope. Leave unmeasured conditions unverified; do not present estimates as measurements.

Debugging Checks
  • For each metric, specify units, measurement point, input amplitude, and load conditions, checking that decision windows were fixed before testing.
  • Preserve raw samples and tool configuration. Repeat identical conditions to assess variation, distinguishing simulation, target measurements, and unverified scope.
References
  • CTest Manual — CMake 3.31.12; test selection, timeout, output and repeat

State, Exception, and Interface Requirements

Interface requirements must describe responses in different system states. The same parameter write or start command may have different permissions during enable, operation, stop, calibration, and fault states. Listing command IDs without allowed states leaves critical decisions to implementation guesswork. Return values should distinguish format errors, range errors, busy status, execution rejection, and execution failure so the higher-level system can recover correctly.

Exception requirements should include thresholds, duration, actions, reporting, and clearance conditions. Brief missing sensor samples and complete failure may use different strategies, but data validity and maximum tolerance must be explicit. Holding a reference, controlled deceleration, or inhibiting outputs after disconnection is an application decision; a protocol stack's default timeout cannot replace it. Define fault-reporting time separately from actual output-action time.

Data interfaces must also specify units, scaling, byte order, update time, and atomic commit scope. A multifield command should take effect at one adoption point; a feedback snapshot should represent one cycle. Receipt acknowledgment for an asynchronous command cannot replace completion acknowledgment. Define how late completion events are handled after cancellation. Walk through valid, invalid, and concurrent requests during design to find state gaps before coding, then test normal and rejected paths against these contracts.

Debugging Checks
  • Create a state-permission table for each command covering duplicates, cancellation, timeout, and late responses, checking return values and recovery behavior.
  • Review detection and clearance conditions for every exception, confirming unambiguous units, data validity periods, and multifield commit boundaries.
References

Mapping Requirements to Tests

Requirements-to-test mapping should state which evidence supports each behavior. Give requirements stable IDs and associate implementation modules, test inputs, expected results, and actual results. One requirement may need multiple test levels; one test may cover several related boundaries. Test counts alone do not establish coverage. Focus on observable criteria for permitted conditions, rejected conditions, and fault recovery.

Break vague requirements into assertable behavior. For example, successful parameter writing may include valid ranges, atomic activation, and power-loss persistence timing; these need different experiments. Host tests verify encoding and state transitions, target tests verify interrupts, DMA, and storage, and bench tests verify actual outputs. A successful test double proves calling logic only, not equivalent real-peripheral action. State each evidence type's applicable level in the matrix.

Expected results must come from requirements or independent calculations, not be generated backward from the function under test, or tests and implementation may share an error. Record reasons for requirement changes before updating expectations and regression scope; do not simply relax tolerances after failures. Preserve inputs, assertion locations, build versions, and raw outputs for repeatable review. Assertions and fixtures organize experiments; specific conditions and evidence determine compliance.

Debugging Checks
  • Check that every critical requirement has normal, rejection, and necessary exception tests, with explicit host, target, or bench coverage.
  • Check that expected results are independent of implementation. Preserve failing samples and versions; every tolerance change requires a requirement-based reason.
References
  • GoogleTest Primer — Assertions and test fixtures; online primer, project dependency version must be pinned separately
Design and implementation

Modules, interfaces and implementation

Control, Driver, Communication, and Diagnostic Layers · Data Ownership and Execution ContextExpand the Modules, Interfaces, and Implementation Knowledge Directory
  • Control, Driver, Communication, and Diagnostic Layers
  • Data Ownership and Execution Context
  • Versioned Parameters and Command Semantics
  • Dependencies, Test Entry Points, and Code Organization
Reading Guide: Parameter, State, and Fault Boundaries in Drive Firmware

Control, Driver, Communication, and Diagnostic Layers

Module layers should describe both functions and dependency direction. Low-level drivers manage registers and hardware timing, control manages algorithms and cyclic outputs, communication manages messages and object mappings, and diagnostics manages recording and export. The application state machine coordinates permitted actions, but every layer should not directly modify shared global flags. Dependency graphs expose cycles: communication calling control updates while control synchronously calls communication transmission can introduce unbounded transfers into real-time paths.

Interfaces hand off complete data and explicit results. Drivers return sampling snapshots, control submits output sets, communication submits validated commands, and diagnostics consumes bounded events. Shared rules may validate parameters, but activation occurs at a control-owned adoption point; hardware protection retains an independent path. Abstractions must preserve units, timing, and error semantics rather than disguising asynchronous operations as immediately successful functions.

Code organization should match test entry points. Pure calculations and state decisions should not depend on specific registers, enabling host verification. Platform adapters use narrow interfaces whose implementations are verified on target. Diagnostics must not write arbitrary internal control state for observation, nor may communication derive protocol fields from structure layouts. Assign new functions to responsibilities before adding interfaces and tests, reducing cross-layer coupling caused by convenient calls.

Debugging Checks
  • Review dependency graphs and control call chains, ensuring that synchronous communication, dynamic logging, and Flash operations do not enter fixed-period paths.
  • Check interface units, timing, and failure results. Verify pure modules and real hardware adapters separately so abstractions do not hide constraints.
References

Data Ownership and Execution Context

Data ownership defines who may modify data; execution context defines when. Put both in one table. List state owned by control interrupts, communication tasks, storage tasks, and diagnostic tasks; other contexts access it through commands or snapshots. A single writer simplifies races, but readers still need consistency and visibility rules, especially for multifield structures and asynchronous buffers.

Cross-context interfaces must distinguish copying from ownership transfer. If a copied queue entry contains pointers, define when underlying buffers may be reused. After starting DMA through a driver, a task must not immediately modify the same transmit block; cancellation must account for late completion callbacks. Use buffer states and transaction generations to define ownership and traceable reclamation after success, timeout, failure, or reset.

Document execution restrictions near interfaces for maintainability: task-only calls, interrupt-safe calls, potentially blocking functions, and lock requirements. Concentrate updates to control-owned state at fixed phases rather than letting every received frame directly alter algorithm integrators. Reviewing complete data lifecycles reveals more gaps than searching only for lock calls. Use submit, adoption, and release sequence numbers to locate ownership failures.

Debugging Checks
  • For shared objects, record writers, readers, lifetimes, and handoff mechanisms, checking that cancellation and fault paths cannot release them twice.
  • Review complete call chains of interrupt-callable functions, verifying that they cannot block, allocate dynamically, or invoke prohibited kernel operations.
References

Versioned Parameters and Command Semantics

Versioned parameters and commands require both representation and semantics. Changing units or permitted states can break compatibility even if field numbers stay unchanged. Protocol documentation should specify types, scaling, defaults, ranges, permissions, and activation conditions. Persistence formats track versions independently of compiler structure layouts. Decide in advance how new fields affect old-configuration migration and reading after rollback.

Command semantics also include acknowledgment. Receiving a mode-change command means its message is valid; completion means control has entered the new mode, possibly several cycles later. Correlate requests, acceptance, completion, and failure with transaction sequence numbers to avoid duplicate actions on retries. Define idempotent parameter settings separately from one-shot actions. Communication retransmission must not repeatedly execute alignment or homing.

Build a compatibility matrix covering host tools, application firmware, Bootloader, and parameter data. Unknown enumerations, missing fields, and unsupported versions should return explainable errors rather than silently selecting default actions. Preserve old-format samples and test migration and bidirectional interaction. Image rollback does not guarantee migrated parameters can roll back; preserve old copies or state downgrade restrictions, and reflect the actual scope in release notes.

Debugging Checks
  • Cross-test old and new configurations and commands, checking units, enumerations, defaults, and rejection of unsupported versions.
  • Resend and cancel the same transaction, checking receipt, adoption, completion feedback, and parameter rollback against the contract.
References
  • MCUboot Bootloader Design — Image format, image trailer, test/permanent/revert; online design, implementation version must be pinned separately

Dependencies, Test Entry Points, and Code Organization

Code organization should let build and test systems express module dependencies. Interface headers expose necessary types and contracts; internal state stays private. Public headers must not inadvertently spread platform headers into every algorithm module. Successful compilation does not prove correct configuration: conditional macros, include paths, and target options affect module behavior and need explicit ownership in build files.

Design test entry points around replaceable dependencies. Parsers receive byte arrays, state machines receive events, control calculations receive samples and parameters, and target adapters implement peripherals. Do not expose many internal variables as public globals for testing or depend on incidental private layouts. Controllable completion, error, and cancellation events on asynchronous interfaces allow complex-path tests without hardware for every test.

Compilation databases help static tools obtain real compilation commands, but check generator support and cross-tool recognition. Test and target builds differ in macros, word widths, and libraries; record these differences and verify sensitive behavior on target. Retain pinned dependency versions and necessary source before upgrades, avoiding accidental library downloads that change artifacts. Directories should support these boundaries; renaming or splitting files does not itself prove reduced coupling.

Debugging Checks
  • Check public-header dependencies and build macros, confirming that static analysis uses commands from the actual target configuration.
  • Use test doubles to trigger asynchronous completion, errors, and cancellation, confirming that host tests neither depend on target registers nor expose internal ownership.
References

Engineering tasks

Modeling and simulation

Modeling and simulation

Model assumptions and MATLAB

Parameter Scripts, Units, and Sources · Electrical and Mechanical EquationsExpand the Model Assumptions and MATLAB Knowledge Directory
  • Parameter Scripts, Units, and Sources
  • Electrical and Mechanical Equations
  • Continuous/Discrete Models and Loads
  • Parameter Sweeps and Result Comparison

Parameter Scripts, Units, and Sources

Parameter scripts should be repeatably loadable engineering inputs, not temporary notes depending on workspace history. Each parameter needs a physical definition, units, source, applicable conditions, and version; derive coefficients from base parameters. Store per-phase motor resistance, d/q inductances, pole pairs, flux linkage, inertia, and sensor scaling separately. Do not mix hardware defaults and identified values in one variable without source labels.

Loading should clearly separate motor, inverter, sensor, processor, and controller parameters. A hardware change may affect only sampling gain and timer clocks; it must not implicitly rewrite motor parameters. Replacing a motor requires rechecking angle offset and current limits. Scripts may check dimensions, signs, and orders of magnitude, such as positive inductance, integral pole-pair count, and reasonable sample periods, but these checks do not prove accurate real-world identification.

Centralize unit conversions in boundary functions and use consistent units inside models. Preserve original speed constants, line-to-line peak voltages, and phase flux linkage values with conversion bases for review. Bind derived parameters to sample periods and per-unit bases; do not retain old control coefficients while silently changing the base period. Save the actual parameter snapshot and script version with each simulation so results reproduce independently of the developer's workspace. Mark placeholders as not yet hardware-identified.

Debugging Checks
  • Run the script in a fresh workspace. Check sources and units for all variables and confirm independence from values left by an earlier model.
  • Save snapshots of base parameters, conversion rules, and derived coefficients. After motor or sample-period changes, confirm that related coefficients and validity flags update together.
References

Electrical and Mechanical Equations

Electrical and mechanical equations must use consistent axis conventions. For a constant-parameter permanent-magnet model with amplitude-invariant transforms and the d-axis aligned to PM flux, voltage balance includes resistive drops, inductive derivatives, and electrical-speed coupling. Electrical speed equals pole pairs times mechanical speed. The mechanical equation uses electromagnetic torque minus load torque and damping; do not substitute electrical speed directly into mechanical inertia relationships. Resistance, inductance, flux linkage, current, and voltage use ohms, henries, webers, amperes, and volts respectively.

First verify current direction for a standstill voltage step, then back-EMF and feedforward signs during rotation, and finally mechanical dynamics. This separates unit, coordinate, and load errors. Torque relationships must match normalization; equal-inductance surface-PM and salient-pole models differ. With saturation, state-dependent inductance or flux may require lookup tables and fuller equations. Replacing one constant does not establish coverage of all nonlinearities.

Energy and power provide useful cross-checks. Input electrical power, copper loss, mechanical output, and stored-energy change should agree within assumptions. Large imbalance may indicate sign errors, peak/RMS confusion, or incorrect load-shaft referral. State omitted iron loss, inverter loss, and friction separately rather than attributing every residual to inertia. Induction motors also require flux and rotor dynamics; a permanent-magnet constant cannot replace excitation.

Debugging Checks
  • Check current changes and back-EMF direction at standstill and constant speed separately, confirming electrical speed equals p times mechanical angular speed in rad/s.
  • Check dimensions and signs of input electrical power, copper loss, mechanical power, and stored-energy change, specifying omitted losses.
References

Continuous/Discrete Models and Loads

Continuous plants and discrete controllers can coexist in one model, but integration solver step size and control sample period must be set separately. A smaller simulation step does not make the firmware controller run faster; discrete state should update only at specified times. Averaged PWM models suit control-loop analysis, while switching models suit ripple and sampling-window studies. Choose according to required fidelity and solver cost.

Distinguish constant-torque loads, speed-dependent loads, inertia, and elasticity. Imposing mechanical speed as an ideal input hides inertia and load dynamics; it suits some electrical tests but cannot validate speed-loop tuning. Specify input holds when discretizing continuous models and mark load-step timing and sign. Multirate control needs explicit data transfer and initial conditions, preventing simulation execution order from providing immediate information unavailable in firmware.

Check numerical convergence by reducing solver steps or selecting an appropriate solver, rather than accepting one runnable setting without assessing error. Save controller states, initial plant current and position, and load conditions together. Discontinuous switching or stiff electrical networks can introduce solver errors; distinguish numerical problems from algorithm instability. Real-time simulation also requires fixed-step execution within budget; successful offline simulation does not prove timeout-free real-time computation.

Debugging Checks
  • List plant solver step, current-loop period, and outer-loop period independently, checking that controller updates occur only at designated events.
  • Repeat the same load test with smaller solver steps and compare results. Check whether speed-input mode accidentally hides inertia and mechanical dynamics that need verification.
References

Parameter Sweeps and Result Comparison

Parameter sweeps seek operating boundaries and sensitive factors. Define varied parameters, ranges, distributions, and fixed conditions first. Sweep resistance, inductance, inertia, bus voltage, and delay individually, then combine credible operating conditions. Derive ranges from manuals, identification errors, or application needs rather than assigning every uncertainty one arbitrary percentage. Label results as model predictions; plots must not imply completed device measurements.

Match comparison metrics to the task: current loops may use peaks, settling time, and voltage saturation; speed loops may use load recovery and current demand; position control may use following error and continuity. Reset states for every run or explicitly define continuation so previous integrators do not affect the next case. For random sweeps, save seeds and parameter samples for isolated failure replay. Averages alone miss critical anomalous combinations.

Sweeps must identify both worst cases and failure causes. Insufficient voltage capability, mechanical resonance, observer failure, and numerical solver errors require different responses; do not call them all insufficient gain. Link result tables to parameter snapshots, model versions, time windows, limit flags, and raw signals. Keep inputs and acceptance criteria fixed when comparing gains instead of selecting favorable plot segments for each set. Limit conclusions to swept models and ranges, retaining unmodeled conditions.

Debugging Checks
  • Save parameter combinations, initial states, random seeds, and versions for each sweep. Replay failing cases independently to verify repeatability.
  • Compare candidates using common metrics, separately flagging saturation, observer failures, and solver problems. Do not report only averages or the best curve.
References
Modeling and simulation

Parameter identification and validity range

Resistance, Inductance, and Flux-Linkage Parameters · Test Excitation and ObservablesExpand the Parameter Identification and Validity Range Knowledge Directory
  • Resistance, Inductance, and Flux-Linkage Parameters
  • Test Excitation and Observables
  • Temperature, Frequency, and Operating-Condition Effects
  • Identification Error and Model Applicability

Resistance, Inductance, and Flux-Linkage Parameters

Resistance, inductance, and flux linkage represent different physical processes; one operating waveform cannot identify all accurately without conditions. Analyze resistance voltage drops where back-EMF is negligible and current nearly steady, subtracting or estimating lead and inverter effects. Inductance tests examine current change or AC impedance and depend on resistance, excitation frequency, rotor position, and sampling delay. Flux-linkage or back-EMF-constant estimation requires reliable speed and voltage definitions.

D- and q-axis inductances require known axis directions or an appropriate identification procedure. Salient motors respond differently by axis; under saturation, distinguish incremental inductance from an averaged inductance. Small-signal values are not automatically valid throughout the high-current range. Flux conversion must specify line-to-line versus phase voltage, peak versus RMS, and mechanical-speed units, with the pole-pair relationship explicit.

Manage identification separately from normal operation, bounding excitation and recording actual voltage/current. Mark results invalid after timeout or interruption. A numerical output does not prove success; check status, repeatability, phase consistency, and residuals. Preserve old parameter versions and raw records before writing new values so incomplete tests cannot overwrite usable parameters. Validate the model with separate data rather than claiming accuracy from the fitting waveform alone.

Debugging Checks
  • Check prerequisites for resistance steady-state segments, inductance excitation, and flux-linkage speed measurement separately. Record winding connections, axis, temperature, and voltage-amplitude definition.
  • Interrupt identification and inject invalid samples, checking that results are not adopted. After completion, validate with independent waveforms and compare phase values and repeated tests.
References

Test Excitation and Observables

Identification excitation must make each estimated parameter's influence distinguishable in observations. Constant input may suit static resistance but cannot readily separate dynamic inductance from delay. Choose sweeps, steps, or other excitation for the target plant. Too little amplitude disappears in noise and quantization; too much causes saturation, heating, or limiting. Derive excitation limits from motor and power-stage capability rather than copying official-example current or frequency defaults.

Preserve actual applied voltage, raw current, position, speed, and timing. Using only requested controller voltage lets limiting and dead time contaminate estimates. Closed-loop current excitation changes input/output statistics; state whether the method accounts for feedback. Test equipment and firmware filters affect phase, so record sample periods and filter coefficients together. Otherwise an estimated 'inductance' may partly represent measurement delay.

First examine identifiability and sensitivity in the model, then validate with constrained bench tests. Estimate in stages if necessary, carrying confirmed parameters and their uncertainty into later steps. Each excitation segment needs start, settle, acquire, complete, and exit states, preventing startup transients from entering steady-state data. For poor results, report signal-to-noise ratio, limiting, and indistinguishable factors rather than widening fit bounds until curves look similar.

Debugging Checks
  • Check that actual excitation covers required dynamics without sustained saturation, recording sampling rate, sensor filtering, and final executed voltage.
  • Vary excitation amplitude and frequency separately to assess estimate stability. Preserve raw data and limit flags, investigating whether parameters and delay are indistinguishable.
References

Temperature, Frequency, and Operating-Condition Effects

Identified parameters carry operating-condition labels. Winding resistance changes with temperature; magnetic saturation makes inductance depend on current and axis; magnet state affects flux linkage; AC test frequency can alter impedance results. Treating room-temperature standstill small-signal values as exact hot, high-speed, high-current parameters introduces systematic feedforward and observer errors. Record temperature measurement location, excitation frequency, bias current, and rotor position.

Separate true physical changes from measurement-chain errors. Amplifier gain drift, ADC-reference changes, bus-sampling timing differences, and inaccurate inverter-drop compensation can all resemble parameter variation. Compare using consistent test methods and cross-check independent quantities or repeated tests. Sensor-location temperature may differ from winding or magnet temperature; label thermal-state sources accurately.

Online parameter updating depends on control goals and observability. Closed-loop inputs, load changes, and limits influence online identification; unconverged results should not directly drive feedforward. Operating-condition tables, bounded update rates, or confidence gates may help but require validation; not every variation is automatically compensable online. Use complete snapshots within each control cycle so resistance, inductance, and derived coefficients do not update independently and become temporarily inconsistent.

Debugging Checks
  • Repeat the same identification method over explicit temperature and current ranges, comparing parameter trends with possible measurement-gain and bus-voltage errors.
  • Check online-update validity, rate limits, and snapshot consistency. Retain a diagnosable restricted strategy when convergence fails or conditions exceed known ranges.
References

Identification Error and Model Applicability

Identification errors arise from noise, model structure, insufficient excitation, and timing misalignment. Low fitting error may explain the test segment yet fail during startup, field weakening, or load changes. Separate identification and validation data, comparing predictions or simulations in new conditions with explicit initial states and error definitions. Confidence intervals and repeatability aid credibility but cannot repair an unsuitable model structure.

Residual analysis reveals unexplained dynamics. Strong correlation with past inputs may indicate missing input response; periodic residuals may arise from harmonics, phase sequence, sampling, or mechanical cycles. Interpret closed-loop correlation with feedback in mind rather than mechanically applying open-loop criteria. Distinguish one-step prediction, free simulation, and long-term drift; each matters differently for the intended model use.

The final parameter package should specify valid speed, current, temperature, and load ranges and out-of-range policies. Simplified values for initial current-loop tuning may not support accurate torque estimation or low-speed sensorless control. Add nonlinearities individually when residuals justify them instead of overfitting many free parameters. Preserve data, fitting settings, versions, and failed conditions so maintainers receive more than untraceable constants.

Debugging Checks
  • Use independent data covering the target frequency range to check prediction and simulation errors, comparing different initial states and operating conditions.
  • Examine residual periodicity and input correlation. Record confidence intervals, valid ranges, and out-of-range policies; training-data fit is not validation.
References

Engineering tasks

Debugging and validation

Debugging and validation

Waveforms, logs and reproduction

PWM/ADC/ISR Timing · Phase Currents and d/q VariablesExpand the Waveforms, Logs, and Reproduction Knowledge Directory
  • PWM/ADC/ISR Timing
  • Phase Currents and d/q Variables
  • Angles, Commands, and State Changes
  • Conditions, Timestamps, and Minimal Reproduction
Reading Guide: AI-Assisted Debugging: Build the Evidence Chain Before Changing Code

PWM/ADC/ISR Timing

To locate real-time problems, observe the complete timing path. PWM edges, ADC sampling triggers, conversion completion, ISR entry, computation completion, and compare-register loading are different events. Toggling GPIO at interrupt entry measures only part of the path. Label oscilloscope or logic-analyzer channels as physical signals or software markers, specifying probe delay and sampling resolution so instrument bias is not mistaken for firmware latency.

Center-aligned PWM has count directions and half-cycle events; sampling triggers must match actual measurable windows. With DMA current reads, check transfer completion and data cycle identity together. ISR timing must cover worst-case branches, nested interrupts, cache or memory waits, and debugging features. Averages miss rare cycles that miss loading deadlines. Cycle sequence numbers and timeout counts correlate hardware traces with software snapshots.

Measurement perturbs systems: synchronous printing and frequent breakpoints can change real-time behavior. Prefer low-overhead counters, bounded event buffers, or hardware tracing, marking lost records. Power-side measurements require instruments suited to the node and isolation conditions; never casually attach an ordinary ground clip to a switching node. Preserve timelines with parameters, clock settings, and firmware versions. Recheck triggers and loading after porting; higher CPU frequency does not replace path verification.

Debugging Checks
  • Capture trigger, ISR, and loading markers together. Check count direction, cycle numbering, and ADC data age, including missed update events.
  • Enable communication stress and required diagnostics before recording worst-case execution time. Confirm that logging does not visibly alter waveforms, and report dropped buffer records and measurement resolution.
References

Phase Currents and d/q Variables

Compare phase currents and d/q variables at the same instant. Raw ADC values become phase currents through offset and gain conversion, then transform using phase sequence and electrical angle. Reading log fields in different interrupts misaligns sinusoidal currents and rotating angle, creating false d/q ripple. Use one control snapshot and cycle number, preserving raw values, calibrated values, and transformation angle.

For abnormal current, first separate measurement from actual output. Channel offset creates zero errors; gain mismatch may create periodic components; inadequate sampling windows create spikes tied to duty cycle or sector. A near-zero three-phase sum is a useful check, but a third phase reconstructed from two phases satisfies it by definition. That identity is not independent proof of measurement accuracy. Filtering can also hide invalid samples.

Steady d/q values need not always be constant, nor must d-axis current always be zero. Field weakening, salient-motor maximum torque per ampere, and harmonic compensation change references; understand the mode before analysis. Observe requested current, feedback error, feedforward, voltage limits, and final modulation together. If poor current tracking coincides with voltage saturation, check available voltage first. Without saturation, angle-correlated errors suggest coordinates, calibration, or sensor time alignment.

Debugging Checks
  • Save raw ADC, phase currents, transformation angle, and d/q currents in cycle snapshots, verifying that transformation inputs come from the same sampling event.
  • Locate anomalies by sector, duty cycle, and operating mode. Distinguish independent measurements from reconstructed phase currents, and inspect unfiltered data and voltage limits.
References

Angles, Commands, and State Changes

Control faults often occur near state changes, so put angle, references, integrators, limits, and drive states on one timeline. Startup alignment, observer takeover, speed reversal, mode changes, and fault reset transfer internal state; steady-state waveforms alone can miss the cause entirely. Event records should include previous state, trigger conditions, next state, and adopted command sequence, not just a final error code.

Compare electrical angles using wrapped differences and identify sensor, open-loop, or estimated sources. Mechanical position may remain continuous over multiple turns while electrical angle wraps periodically; mistaking wraparound for a jump causes false diagnoses. Predicted output and feedback-transform angles may legitimately refer to different times; record their timing semantics. Distinguish raw bus targets, trajectory outputs, limited requests, and actual adopted values, avoiding mislabeling planning changes as communication errors.

Triggered buffers preserve pre/post-fault windows but need defined capacity, overwrite policy, and loss flags. When several states change together, infer causality from event order and internal conditions; the first printed event is not automatically the root cause. Preserve initial state, command order, and intervals during reproduction, eliminating invalid angles, integrator transfer, and limit release individually. If logging changes alone hide a fault, assess timing disturbance before declaring it resolved.

Debugging Checks
  • Record raw angle sources, electrical-angle differences, command sequences, and integrators around state transitions, covering wraparound, reversal, and closed-loop takeover.
  • Preserve event pre/post-states and triggers. Check log order against actual execution time and confirm that triggered buffers cover the pre-fault window.

Conditions, Timestamps, and Minimal Reproduction

Reproduction records first fix device and software conditions: board revision, motor and sensor, firmware commit, toolchain, parameters, load, and communication inputs. Describe expected versus actual behavior, trigger sequence, and frequency rather than naming an unproven root cause as the symptom. For intermittent problems, record attempts and failures. One normal run cannot prove a fix when reproduction is unstable.

Timestamps need clock source, units, resolution, and wraparound handling. Device clocks, host clocks, and instrument triggers may not be synchronized; correlate them through common events while recording synchronization error. Logged receive time may differ from command activation, and sensor-read time may differ from sampling time. Cycle, command, and state sequence numbers often reveal data-chain mismatches more clearly than absolute time alone.

A minimal reproduction retains essential operating constraints while gradually removing irrelevant traffic, states, and functions. Do not remove the load or timing that causes the fault merely to simplify it. Include raw inputs and key intermediate values for host/model replay. After fixing, rerun the same reproduction and adjacent boundaries, labeling conclusions from models, software replay, or hardware. Retain physical-verification limitations rather than presenting inference as bench evidence.

Debugging Checks
  • Save replayable inputs, versions, and parameter snapshots. Label timestamp sources, wraparound, and synchronization error, and count attempts and failures.
  • Reduce conditions one by one to find necessary triggers. After fixing, rerun identical inputs and nearby boundaries, labeling model, host, and hardware evidence separately.
References
Debugging and validation

Comparing models, firmware and platforms

Fixed Point, Floating Point, and Numerical Range · Model Sampling and Firmware UpdatesExpand the Model, Firmware, and Platform Comparison Knowledge Directory
  • Fixed Point, Floating Point, and Numerical Range
  • Model Sampling and Firmware Updates
  • Different Boundaries of SIL/PIL/HIL
  • Timing and Behavioral Regression After Porting

Fixed Point, Floating Point, and Numerical Range

Numerical porting starts with range and precision. Fixed-point variables need signedness, word length, fractional bits or scaling; floating-point variables also need precision and maximum-value checks. Intermediate products, sums of squares, integrators, and accumulated angles may exceed final output ranges. Final limiting cannot prevent earlier overflow. Retain overrange margin after conversion to per-unit values rather than fitting every valid value exactly to the maximum representation.

Rounding and overflow handling change control behavior. Truncation can introduce bias, wraparound can turn positive voltage negative, and saturation needs defined locations. Use sufficiently wide intermediate types for fixed-point products before specified rescaling; follow target-language and compiler semantics for signed shifts and conversions. Explicitly handle nonfinite floating-point values, division by zero, and very small normalization magnitudes. Floating point still has numerical boundaries.

Test positive, negative, near-zero, maximum-range, and long-term accumulated inputs against a sufficiently precise reference. Tolerances must cover numerical error while meeting physical requirements, not hide sign errors or state drift. Evaluation order and fused operations affect final bits, while tables, trigonometric approximations, and quantization affect angle-sensitive regions. Porting reports should state tested and unproven inputs; compilation alone is not numerical equivalence.

Debugging Checks
  • Derive intermediate ranges operation by operation. Test extremes of sums of squares, integration, and angle accumulation, checking truncation, saturation, and wraparound policies.
  • Test nonfinite floating-point inputs and low-amplitude normalization. Compare fixed-point positive/negative boundaries and long-term small-error accumulation against high-precision references.
References

Model Sampling and Firmware Updates

Models and firmware need identical update semantics, not merely matching sample-period numbers. A model may update integrators before output calculation while firmware does the reverse, creating a one-sample difference with the same coefficients. Sample holds, control execution, reference latching, and PWM loading may use different events. Align comparisons by cycle index and effective time rather than overlaying arrays by index.

Match how multirate outer-loop outputs are held between fast cycles, when they first become visible, and whether double buffering is used. Simulation scheduling may differ from interrupt preemption; communication updates can arrive at arbitrary times. Firmware should adopt complete snapshots at control boundaries, and models must express the same age and initial values. Check rate-transition block determinism and delay settings rather than assuming zero-delay connections.

Start regression with single-step algorithms and fixed inputs, comparing state/output sample by sample, then add scheduling and hardware. For a fixed one-cycle offset, check update order and loading before shifting curves to remove differences. Timing tolerance is justified only by clear physical timing semantics. Revalidate model timelines after PWM-event or ADC-trigger changes, including one missed update and task overload, ensuring consistent exception behavior.

Debugging Checks
  • Check sampling, integrator update, output calculation, and PWM loading order. Use cycle indices to locate the first difference instead of arbitrarily shifting curves.
  • Check fast/slow task snapshots, initial values, and data age. Add asynchronous parameter updates and missed cycles, confirming identical model/firmware limiting policies.
References

Different Boundaries of SIL/PIL/HIL

Software-in-the-loop usually executes code on a host, checking numerical or state equivalence with models. Processor-in-the-loop runs code on the target processor or corresponding environment, exposing target numerical, compilation, and some execution differences. Hardware-in-the-loop connects real control hardware to a real-time plant simulation for interface, scheduling, and fault-flow tests. Their boundaries differ; one pass flag cannot establish verification of all device behavior.

SIL generally cannot prove real ADC-trigger and power-output timing; PIL communication wrappers may not represent final interrupt scheduling. HIL approximates real interfaces, but plant models, steps, I/O delays, and fault-injection capability bound its credibility. State separately whether actual switches, dead time, sensor noise, and thermal behavior are adequately represented. Averaged-model HIL is not a measurement of real power-stage protection latency.

Collect evidence for each requirement in an appropriate environment. Prefer host tests for parsing and pure state logic; use processor environments for target numerics and execution budgets, HIL for cyclic interfaces and recovery, and specified device tests for final power/mechanical conditions. Preserve code/model versions, parameters, initial states, and tolerances, reporting failures and untested items. Toolchain support for a mode does not mean the project completed those tests or obtained certification.

Debugging Checks
  • Assign SIL, PIL, HIL, or bench environments to each requirement, checking plant-model, I/O-delay, and real-time-step applicability.
  • Compare equivalence with identical inputs and initial states. Save numerical, timing, and fault evidence separately, stating uncovered real power-stage and thermal behavior.
References

Timing and Behavioral Regression After Porting

Porting requires rechecking peripheral semantics. Timer clocks, counting modes, shadow loading, dead-time polarity, ADC triggers, and DMA completion conditions may differ, changing actual sampling and outputs even with unchanged control source. Floating-point capabilities, memory placement, optimization, and interrupt nesting also change worst-case execution time. CPU frequency or vendor algorithm benchmarks alone are insufficient.

Keep requirements and inputs consistent during behavioral regression: power-up, sensor calibration, normal control, limits, start/stop, mode changes, and fault recovery. Numerical tests check transforms, limits, and integration; interface tests check cycle sequences and data integrity; hardware tests check sampling windows and protection. Old-platform logs provide a baseline, but allowed differences need physical or interface justification rather than arbitrary tolerance changes.

Porting evidence must trace to build artifacts, parameter packages, and board revisions. Specify acceptance scope for added or removed functions. Unconnected sensors and unimplemented protection must not be silently bypassed with defaults. Regress logging and diagnostics too, since losing timestamps or fault records reduces maintainability. If only algorithm unit tests pass, retain outstanding timing and bench checks; claim corresponding completion only after target verification.

Debugging Checks
  • Check PWM/ADC/DMA events against the target manual. Record maximum observed execution time with final optimization and memory settings, and analyze execution upper bounds for uncovered paths.
  • Replay a common operation/fault matrix, preserving firmware artifacts, board identity, parameters, and raw results. Distinguish permitted differences from unfinished interface verification.
References
Debugging and validation

Unit, integration and system verification

Algorithm and Parameter Boundary Tests · Communication and State-Machine IntegrationExpand the Unit, Integration, and System Verification Knowledge Directory
  • Algorithm and Parameter Boundary Tests
  • Communication and State-Machine Integration
  • Fault Injection and Recovery Paths
  • Operating-Condition Matrix and Acceptance Evidence
Reading Guide: Industrial Motor-Control Firmware: From Requirements to Verification

Algorithm and Parameter Boundary Tests

Start algorithm-boundary tests with pure calculations independent of power hardware. Test transform round trips, quadrants, and normalization; zero modulation input, sector boundaries, and duty ranges; positive/negative integrator saturation and release; and short trajectories, nonzero initial speeds, and endpoint continuity. Derive expected values from independent formulas, trusted references, or explicit requirements. Copying current outputs into expectations does not establish adequate testing.

Parameter boundaries include not only minima/maxima but zero denominators, wrong units, mismatched sample periods, invalid pole pairs, and out-of-table inputs. Floating point needs nonfinite handling; fixed point needs intermediate-overflow and rounding checks; counters and angles need wraparound and reversal. For invalid parameters, test specified rejection, old-value retention, or error-state behavior rather than merely absence of crashes.

Test state sequences too. First calls, resets, live gain updates, mode changes, and long-term small errors expose issues absent from single-step inputs. Seeded random inputs supplement boundaries but cannot replace critical invariants. Host passes prove only the tested algorithm/environment; verify target numerical differences, real-time scheduling, and sensors at appropriate levels. Preserve failing inputs and the first divergent state for independent replay.

Debugging Checks
  • Define invariants and independent expectations for transforms, limits, integration, and trajectories, covering positive/negative extremes, zero, wraparound, and long-term accumulation.
  • Inject invalid parameters and nonfinite values, checking rejection and old-parameter retention. Preserve random seeds, reset sequences, and earliest failing samples.
References

Communication and State-Machine Integration

Communication integration tests must trace commands from messages through actual control adoption. After checking word order, mappings, and scaling, verify command sequences, mode validity, snapshot consistency, and activation times. Concurrent communication and control interrupts can combine separately updated fields into a command never sent by the host. Integration cannot consist solely of individual parameter reads/writes while idle.

Separate communication online, drive availability, and axis enable in the state machine. An operational network does not prove valid feedback, established zero reference, or power-output permission; enable commands cannot bypass local prerequisites. Test permitted and rejected transitions, preserving prior state, command, internal conditions, and next state. Specify parameter activation timing. Reject or explain prohibited live changes rather than silently deferring them indefinitely.

Integration sequences should include communication timeouts, duplicate frames, bursts, mode changes, and reconnection. Old-reference use, stop actions, and fault latching must match product definitions, without automatically replaying stale motion after recovery. Measure control deadlines under communication load so correct protocols do not consume real-time budgets. Correlate network inputs with device events, checking protocol responses, adopted values, and final outputs.

Debugging Checks
  • Update multifield commands and parameters during control operation, checking complete snapshots, consistent sequences, and explicit activation cycles without partial-update combinations.
  • Cross-cover communication and drive states, testing rejected transitions, timeouts, and recovery. Verify old-command invalidation and measure real-time margin under communication stress.
References

Fault Injection and Recovery Paths

Fault injection starts by defining failure type, location, duration, and expected response. Frozen sensors, invalid samples, stale commands, abnormal bus measurements, and computation timeouts enter different paths; one generic error flag cannot replace actual detection conditions. Prefer controlled injection in models, software replay, or HIL. Real power-side operations must follow product verification plans; arbitrary electrical shorts are not a way to prove software logic.

Check the full detection-to-output timeline: validity changes, state transitions, PWM handling, fault records, and higher-level reporting. Delays, debounce, and latching affect total response and require measurement, not just final-state checks. Define priorities for combined faults; handling must neither block control interrupts nor lose key records. Distinguish the first cause from cascading faults and preserve reproducible timing relationships.

Recovery tests matter as much as injection. Define whether cleared faults require continuously valid feedback, re-referencing, parameter reload, and invalidation of old targets. Reset requests cannot bypass conditions that remain active, and repeated faults must not cause enable/stop chatter. Reinject during fault entry, hold, exit, and reset to expose state gaps. Results prove only injected paths and environments; measure hardware protection independently.

Debugging Checks
  • For each fault, record injection point, detection time, output action, and reporting time. Check delays and priorities, retaining the initial cause.
  • Reinject during fault hold, exit, and reset. Verify rejection of recovery while faults persist, invalidation of old commands, and reestablishment of feedback confidence.
References

Operating-Condition Matrix and Acceptance Evidence

A system acceptance matrix converts requirements into operating conditions and observable criteria. Motor type, load inertia, direction, speed, current, bus voltage, temperature, and mode jointly define scope. Explicitly cover boundaries and critical combinations. Risk and independent factors may guide representative points, but state untested combinations. One unloaded forward-running case cannot represent all servo or variable-frequency drive capabilities.

Each case needs fixed inputs, initial conditions, steps, expected behavior, and recorded quantities. Dynamic performance requires windows, settling bands, or error tolerances; protection/state tests require event ordering and response times. Preserve repetition counts and failure rates; one successful screenshot is insufficient for intermittent faults. Link raw data, parameter snapshots, firmware artifacts, toolchain, and board versions in one reproducible record.

Distinguish model predictions, host algorithm checks, target execution, HIL, and real bench evidence, stating physical factors omitted at each level. Report actual passes, failures, and pending conditions rather than treating planned tests as completed. Select regressions by impact after changes to motor, sensor, sampling frequency, optimization, or protection. The matrix defines maintenance boundaries, not merely a final table to fill with pass marks.

Debugging Checks
  • For each requirement, define conditions, inputs, and quantitative criteria, covering both directions, boundaries, and recovery. Mark representative-point choices and untested combinations.
  • Link raw waveforms, logs, versions, parameters, and execution environments to results. Report passes, failures, and unverified items, defining regression scope for the next change.
References

Engineering tasks

Delivery and maintenance

Delivery and maintenance

Versions, configuration and engineering records

Hardware, Firmware, and Toolchain Versions · Parameter Sets and Build ArtifactsExpand the Versions, Configuration, and Engineering Records Knowledge Directory
  • Hardware, Firmware, and Toolchain Versions
  • Parameter Sets and Build Artifacts
  • Issue Records and Regression Matrices
  • Documentation, Interfaces, and Release Notes

Hardware, Firmware, and Toolchain Versions

Engineering versions must cover hardware, firmware, toolchain, and configuration. Identical source may behave differently with different crystals, shunts, encoder interfaces, or silicon revisions; firmware version alone cannot reproduce conditions. Release manifests need board IDs, chip information, application and Bootloader versions, compiler/linker versions, image hashes, and parameter versions, preventing similar devices from being treated as one platform.

Git commits and tags locate source; annotated tags can hold release notes, but tags do not prove a binary came from that source or cover uncommitted configuration and external dependencies. Check workspace state before building and map actual inputs to artifacts. Generate version information from controlled inputs rather than manually editing a string and forgetting related data. Device-reported identity must correspond to preserved ELF files and manifests.

Fix the version combination at the start of debug reports and create new experiment groups after hardware or parameter changes. Judge fixes under comparable conditions rather than mixing new-board results with old-board faults. Preserve recoverable images and configurations with downgrade restrictions. Private paths, keys, and accounts are not version identifiers; record only necessary nonsensitive locating information.

Debugging Checks
  • Read runtime identity from the device and compare it with the release image, ELF, hardware, and parameter manifests, checking for uncommitted inputs.
  • Repeat a critical test with the saved version combination, stating what needs revalidation after toolchain or board changes.
References
  • Git git-tag — git-tag; annotated tags; checked online manual

Parameter Sets and Build Artifacts

Treat parameter sets and build artifacts as traceable objects rather than chat attachments or screenshots. Parameter files need format versions, units, applicable hardware, and integrity identifiers, distinguishing defaults, factory calibration, and runtime changes. UI loading does not prove suitability for the current motor/power stage; validate ranges and cross-constraints and retain rejection reasons.

Artifact manifests include programming images, ELF, Map, interface or generated-code versions, and test outputs. CMake presets organize configurations and test entry points, but actual toolchains, dependencies, and environments still need pinning. When similar files coexist, identify the programmed file by hash and release ID, avoiding old images after source changes. Record signed packages and unsigned images separately with their generation relationship.

Compare device parameter readback with the expected set and record discrepancy sources rather than overwriting all calibration. Parameter updates need backups and recovery rules, especially format compatibility after firmware rollback. Link test results to the parameter version used, since performance changes may come from limits or filters rather than code. Preserve originals for replay and summaries for indexing; exclude credentials and personal information from public artifact packages.

Debugging Checks
  • Check the programmed image hash against the manifest. Verify parameter units, hardware applicability, and the distinction between active and saved values.
  • Read back parameters and compare expectations. Check calibration retention, format migration, and recovery paths, linking the exact parameter set used in the test.
References

Issue Records and Regression Matrices

Issue records should let another engineer recognize the same fault. Preserve symptoms, expectations, reproduction steps, inputs, version combinations, and raw evidence, then list excluded conditions and remaining hypotheses. 'Intermittent communication failure' is insufficient for regression: specify failure location, observation time, and criteria. When counting attempts/failures, state whether conditions were consistent.

Organize regression by risk; every release need not repeat every experiment. Parser changes require length, sign, and permission boundaries; scheduling changes require load and concurrency; Flash changes require power-loss and migration tests. Preserve original failing samples and add nearby boundaries to avoid single-input fixes. Bisect version regressions where useful, marking unbuildable or indeterminate versions skipped rather than artificially good.

Fix reports distinguish cause evidence, code changes, and verification results. One success does not establish removal of an intermittent issue; retests need sufficient trigger opportunities and identical criteria. Explain comparability if environments change and retain pending hardware checks. Mark matrix entries passed, failed, or not run; blanks must not imply success. Link every result to raw output and images for later reuse.

Debugging Checks
  • Repeat failing samples under original conditions, preserving criteria and statistical windows. Check skipped-version records during bisection.
  • Review regression coverage of affected modules and adjacent boundaries, distinguishing passes, failures, unrun tests, and results with changed conditions.
References
  • Git git-bisect — git-bisect; skip, log, replay; checked online manual

Documentation, Interfaces, and Release Notes

Documentation should describe observable behavior of the final implementation. Interface documents list types, units, permissions, states, and errors; maintenance notes give build, upgrade, and recovery procedures; release notes state changes and compatibility. Do not copy development-chat trial order into product instructions or leave abandoned designs guiding maintenance. Use stable terminology shared with code, avoiding several names for one field.

Focus release notes on user-visible or caller-visible changes: when a new parameter activates, how old formats migrate, or which fault condition is fixed. Then state required verification and known limitations, avoiding unmeasured performance claims. Link actual changes and test evidence for review. Diff tools help assess scope, but also check generated interfaces, examples, and real images; small source diffs do not mean documentation is unchanged.

Before release, walk through documentation as executable instructions. Verify building elsewhere, tool version recognition, power-loss recovery, rollback, and parameter retention. Remove keys and internal addresses from public materials; attach test conditions and records to performance figures. State unfinished testing and update records after later verification. Incorrect documentation can misuse correct code, so semantic interface changes require synchronized maintenance materials.

Debugging Checks
  • Follow documented build, upgrade, and rollback procedures, checking commands, artifacts, parameter compatibility, and absence of implicit local-environment dependencies.
  • Compare interfaces, examples, and release notes with final changes, confirming evidence for every performance and verification claim.
References
  • Git git-diff — git-diff; --check, --stat, diff output; checked online manual
Delivery and maintenance

Builds, updates and maintenance

Reproducible Builds and Checks · Upgrade Compatibility and RollbackExpand the Build, Upgrade, and Maintenance Knowledge Directory
  • Reproducible Builds and Checks
  • Upgrade Compatibility and Rollback
  • Historical Faults and Maintenance Diagnostics
  • Change Impact and Release Verification

Reproducible Builds and Checks

Maintenance builds should be reproducible elsewhere from recorded instructions. Record source, dependencies, generators, toolchains, target options, and configuration, with explicit artifact-comparison scope. Cross-compilation toolchain files describe targets and compilers, but verify actual executable paths and versions so search rules do not select another installed compiler. Build success does not prove the intended ABI or floating-point implementation.

Separate input integrity, build diagnostics, and artifact consistency. Input checks detect unrecorded generated files; diagnostics check warnings and linker layout; artifact checks verify vectors, capacity, and image hashes. Toolchain detection may try running test programs although cross-target binaries cannot execute on the host. Understand probing mechanisms when configuring these steps rather than ignoring every failure to continue building.

Automated pipelines should preserve raw logs and configuration summaries and stop assigning publishable release identities on failure. Dependency caches accelerate builds but must not hide missing inputs during verification. Comparing binaries from two clean directories reveals path/time differences; analyze debug information separately from executable bytes. Define generation relationships among signed packages, download bundles, and raw images so field versions locate matching symbols and source.

Debugging Checks
  • Rebuild releases in a clean environment, checking compiler, ABI, linker layout, and generated inputs, and preserving complete build logs.
  • Compare image and ELF differences. Check that pipeline failures leave no misleading release package and that builds still succeed after clearing caches.
References
  • CMake Toolchains — CMake 3.31.12; cross-compiling, toolchain file, try_compile

Upgrade Compatibility and Rollback

Test upgrade compatibility through real maintenance workflows: old devices recognizing new packages, continued operation after download failure, recovery after failed trial boots, and parameter rollback. Program images, boot state, and persistent parameters are separate objects; application rollback does not automatically roll back parameters. Preserve compatibility matrices for all three, covering upgrades across multiple old versions rather than only the previous release.

Distinguish source rollback from device rollback. A Git revert records reverse source changes, but field deployment still requires rebuilding, testing, and publishing an image. Old binaries may face anti-rollback counters and parameter-format restrictions. Rollback packages must match hardware and retain integrity/signature checks; old versions do not justify bypasses. Preserve a verifiable recovery release and a diagnostic-read channel for failed devices where needed.

During tests, interrupt power or connections and reject confirmation at each stage, reading actual runtime identity. After recovery, check sensors, configuration, and safe outputs before accepting new commands, avoiding retriggered queued transactions. Upgrade tools should separately report download, validation, execution, and confirmation. State upgrade/downgrade ranges in release notes. Explain irreversible migration restrictions before operation and retain original parameters for engineering recovery.

Debugging Checks
  • Test cross-version upgrades and rollback from representative old versions, checking compatibility of program, parameters, and boot state.
  • Interrupt each stage and read the actual running image. Confirm that recovery preserves validation and does not replay old commands or automatically enable outputs.
References
  • MCUboot Bootloader Design — Image format, image trailer, test/permanent/revert; online design, implementation version must be pinned separately
  • Git git-revert — git-revert; recording inverse changes; checked online manual

Historical Faults and Maintenance Diagnostics

Turn historical faults into searchable engineering records. Preserve symptoms, conditions, affected versions, raw logs/waveforms, cause evidence, and fix scope rather than only 'resolved' status. Similar codes can have different causes, so compare triggers, states, and abnormal-value sources during retrieval. A similar title alone does not justify applying an old patch.

Maintenance diagnosis first captures the current device state before deciding whether to reproduce. Read versions, parameters, reset causes, and resource counters to reveal differences from old records. Preserve log timebases and export-tool details. Automation reduces copying omissions but still requires buffer-loss and timestamp checks. First-occurrence evidence and repeated-log summaries have different value for intermittent faults and frequency analysis.

Reperform key distinguishing experiments before reusing old conclusions. A former lifecycle defect does not prove the new symptom has the same cause; interfaces and memory layouts may have changed. Bisect only regressions with stable criteria and explicitly skip unexecutable commits. Cross-link fixed regression samples and fault records for future checks before broadening investigation. Report acquired evidence only; inference is not a field measurement.

Debugging Checks
  • Compare current hardware, firmware, and parameters with historical fault conditions. Save the original incident state before recovery or image replacement.
  • Run old regression samples and new distinguishing experiments, checking conclusion scope and marking missing logs and indeterminate versions.
References

Change Impact and Release Verification

Release verification starts with impact analysis. List changed modules, interfaces, parameters, and timing, then follow dependencies to affected callers. Small unit changes can affect protocols, limits, and logs; interrupt-priority changes can affect every lower-priority service. Regression depth cannot depend only on line count. Link impacts to requirements and tests to explain the chosen checks.

First confirm the old version reproduces the issue, then that the new version meets identical criteria, then cover adjacent boundaries and related modules. Release configuration, image, and parameters must match testing; temporary debug options may alter timing and need disclosure. CTest and similar tools organize filtering, timeouts, and repetitions, but engineering risk determines the list. Retain failures and unrun items, not only successful output.

Release checks should also cover upgrade/recovery, interface documentation, version identity, and artifact integrity. If hardware tests remain unfinished, record conditions and pending scope; conclusions cover verified portions only. Exclude unrelated changes in the final diff and confirm assertions were not removed or expectations relaxed merely to pass. Maintainers should locate images, symbols, and rollback paths from release notes. Risk acceptance must identify specific unverified behavior rather than a generic disclaimer.

Debugging Checks
  • Map every change to dependencies and regressions, confirming that release images, parameters, and test configuration match.
  • Check original failures, nearby boundaries, upgrade/recovery, and interface documentation. Preserve passed, failed, and unrun results; line count cannot replace risk assessment.
References
  • Git git-diff — git-diff; --check, --stat, diff output; checked online manual
  • CTest Manual — CMake 3.31.12; test selection, timeout, output and repeat

Collaboration

AI-assisted engineering

AI-assisted engineering

Source analysis and context

Manual Versions and Evidence Location · Requirements, Code Boundaries, and ConstraintsExpand the Document Analysis and Context Knowledge Directory
  • Manual Versions and Evidence Location
  • Requirements, Code Boundaries, and Constraints
  • Search Scope and Information Reliability
  • Sensitive Information and Authorization Scope

Manual Versions and Evidence Location

For AI analysis of chip documentation, provide the full part number, silicon revision, manual name, and revision, not only a family abbreviation. Require conclusions located to sections, tables, or original register entries with applicability conditions. Vendor indexes, search snippets, and formal manuals are different evidence levels. Finding a title does not mean reading its rules, and configuration of a related device is not a fact about this device.

AI can organize questions and sources: the question, supporting original text, exceptions, and whether the current configuration meets prerequisites. Engineers should recheck numbers, polarity, timing, and reserved bits in originals. Text extraction may lose column relationships in scanned tables, formulas, or cross-page content; inspect original pages. Mark inaccessible material as gaps and process verifiable parts first. 'Common practice' must not become a definite parameter.

Link citations to code configuration for rechecking after chip or library changes. Manual revisions may leave most peripherals unchanged while errata or constraint updates affect verified paths. AI can compare changes and generate checklists, but conclusions must state read evidence and target experiments. Model-provided page numbers do not complete verification; preserve the actual accessed document version and check results for traceability.

Debugging Checks
  • Spot-check original sections for every critical value and register rule, confirming matching part number, revision, and operating mode.
  • Retain pending checks for failed access, unclear figures/tables, and conflicting documents. Do not label search results or model memory verified.
References
  • ST STM32G4x4 Documentation — STM32G4x4 documentation index; datasheet/reference manual/errata, index checked online; not proof of all document contents

Requirements, Code Boundaries, and Constraints

AI task context should include expected behavior, relevant code boundaries, execution contexts, and acceptance criteria. Firmware fixes also need task/interrupt relationships, shared data, units, input ranges, and real-time budgets. Pasting only the failing function may omit buffer ownership or calling order, leading to local patches based on wrong assumptions. First outline the minimal call/data chain, then provide sufficient code to judge the issue.

Make constraints checkable: modify only parsing, preserve byte order and hardware protection, and add no dynamic allocation, for example. Provide required types, macros, and platform settings; static-tool compilation commands must match the target. Before implementation, AI can list facts, assumptions, and missing information. Check unknown chip behavior in manuals and leave unknown application rules pending rather than inventing them to make the task appear complete.

Express acceptance using concrete inputs and expected outputs; split complex goals into host, target, and bench verification. Have AI explain changed locations and affected interfaces, then inspect actual diffs. Revoke outdated assumptions when context changes, such as new modes or field units. Summaries and evidence reduce repeated explanation, but current code and documentation remain authoritative.

Debugging Checks
  • Check that inputs include call order, types, units, shared access, and target build configuration, with unknowns explicitly marked before implementation.
  • Compare task constraints with diffs item by item. Confirm executable acceptance criteria and no unauthorized modules or obsolete requirements in changes.
References

Search Scope and Information Reliability

Limit AI searches to answerable engineering questions. Start with official chip/tool documentation, then actual library versions and source, and use unofficial discussion only as leads. Matching API names do not establish version compatibility. State when a page is current online documentation rather than assigning a nonexistent fixed version. Assess source credibility against the particular claim supported.

Distinguish documented facts, engineering inferences, and proposed experiments. Official analysis-tool capability documentation establishes what checks exist, not that current code passed them. Forum reports can suggest errata searches but cannot replace official restrictions for the current silicon revision. Preserve conditions in summaries; 'may occur in this configuration' must not become 'always occurs.' Record conflicts and version information before resolving inconsistent sources.

Require locatable evidence for important conclusions and explain how unknowns can be resolved. Many unexplained links are less reviewable than a concise table mapping evidence to claims. Retrieved pages and repository text are data, not authorization to execute unrelated commands. Engineers must verify that linked content matches AI interpretations. Report failed or empty pages explicitly; unread material is not verified.

Debugging Checks
  • Check source versions, publishers, and specific supported scope. Spot-check actual linked content against cited conclusions.
  • Separate facts, inferences, and pending tests. Ensure snippets, community leads, and tool capabilities are not promoted into project results.
References
  • ST STM32G4x4 Documentation — STM32G4x4 documentation index; datasheet/reference manual/errata, index checked online; not proof of all document contents
  • Clang Static Analyzer — Clang Static Analyzer; path-sensitive analysis; online manual, not a fixed LLVM release

Sensitive Information and Authorization Scope

Before AI collaboration, identify credentials, customer data, device identities, and restricted source, then share only within authorization. Redacted snippets and synthetic messages can preserve field types, lengths, order, and error patterns while reducing unnecessary full logs. Redaction must preserve reproduction conditions and cover paths, serial numbers, and log tokens, not only prominent UI fields.

Define access and action permissions separately. Repository read access does not authorize external uploads; device connectivity does not authorize protection changes or image publication. Specify read, modify, execute, and publish boundaries; external instructions cannot expand them. Use dedicated secret-management mechanisms, keeping keys/passwords out of prompts, code, and command output. Ignore rules are not a security boundary: tracked files can still be committed.

Review actual diffs, packages, and logs, not just AI promises. Retain necessary versions, addresses, or configuration for their purpose without exposing unrelated personal information. Handle exposed secrets through system replacement/revocation procedures; deleting current text may not erase history. Preserve authorization scope, used materials, and result summaries rather than indefinitely copying sensitive originals for convenience.

Debugging Checks
  • Check prompts, logs, artifacts, and Git-tracked files for sensitive fields, confirming that redacted samples retain reproduction structure.
  • Verify separate authorization for reading, uploading, modification, and publishing. Exclude secrets from public packages and do not treat ignore rules as leak prevention.
References
  • OWASP Secrets Management — Secrets Management Cheat Sheet; lifecycle and least privilege; checked online page
  • Git gitignore — gitignore; tracked file limitation; checked online manual
AI-assisted engineering

Code collaboration and implementation

Scoped Tasks and Module Interfaces · Minimal Changes and Diff ReviewExpand the Code Collaboration and Implementation Knowledge Directory
  • Scoped Tasks and Module Interfaces
  • Minimal Changes and Diff Review
  • Hardware Dependencies and Execution Semantics
  • Compilation, Static Checks, and Tests

Scoped Tasks and Module Interfaces

Scope AI implementation to clear modules and interfaces to reduce unintended changes. Specify behavior, permitted files, input/output types, and failure semantics, then immutable protocol, protection, and real-time constraints. Parser work should include maximum lengths, byte order, and rejection conditions, rather than a broad request to 'improve code quality.' Clear boundaries enable reviewable implementations.

Analyze unknown interface conditions before inserting defaults. State buffer ownership, permitted calling contexts, blocking/allocation rules, and activation timing. Supply related callers and real build settings so host-valid code also suits the target. Split pure calculations, adaptation, and target verification where useful, but verify consistent units, errors, and transaction semantics at handoffs.

Implementation output should explain how every change satisfies requirements and provide test inputs and verification commands. Engineers review actual diffs and tool output for implicit dependencies or cross-layer calls. Public-interface changes require synchronized callers and documentation rather than partial completion. Acceptance evidence determines completion; tidy code and fluent explanations cannot replace target builds and required hardware tests.

Debugging Checks
  • Check explicit inputs, outputs, contexts, and error semantics in the task, and verify that changed files remain within module scope.
  • Check synchronized callers, build settings, and interface documentation. Execute acceptance checks and confirm defaults do not hide unknown conditions.
References

Minimal Changes and Diff Review

Minimal change means changing only semantics needed to solve the issue, not mechanically minimizing lines. Concurrency faults may need a complete handoff protocol, and length faults reordered validation; one added condition may not remove the cause. Ask AI to explain failure paths and changed conditions before supplying diffs so reviewers can distinguish real coverage from a single passing sample.

Review behavior before code details: units, ranges, ownership, states, timing, public interfaces, macros, and generated files. Unrelated formatting and mass renaming add noise and can be separated from fixes. Tools report textual and whitespace differences but cannot judge real-time semantics. Removing assertions, extending timeouts, or widening tolerances needs independent justification beyond making tests pass.

Review failure and recovery too. Normal completion, cancellation, full queues, and target resets must retain resource consistency, prevent stale-command replay, and preserve protection. Keep original failing inputs, verify unchanged criteria after fixing, then regress affected areas. Record unrelated discoveries separately rather than silently expanding local fixes into hard-to-diagnose refactoring.

Debugging Checks
  • Inspect actual diffs item by item, checking interfaces and failure paths, with no unrelated changes or unexplained relaxation of acceptance criteria.
  • Validate patches with old failures and nearby boundaries, checking evidence for resource reclamation, state recovery, and real-time effects.
References
  • Git git-diff — git-diff; --check, --stat, diff output; checked online manual

Hardware Dependencies and Execution Semantics

AI-generated firmware must distinguish hardware dependencies from language semantics. Ordinary memory, registers, DMA buffers, and cached regions have different access conditions; volatile provides neither mutual exclusion nor complete publication. Models may generalize single-core examples to multicore or cacheless MCU techniques to Cortex-M7. Specify cores, memory attributes, and concurrency contexts, then check each assumption.

Barriers, critical sections, and cache maintenance are not interchangeable. Barriers constrain ordering/completion, locks and atomics define software handoffs, and cache operations address specific CPU/DMA visibility. Each has scope and cost. Have AI explain the condition protected by each operation and compare official documentation with implementation. Identical call names do not imply identical chip paths; DMA-accessible RAM, register side effects, and Flash-time instruction-fetch restrictions require target-manual support.

Hardware verification checks actual timing and failure actions. Host compilation finds type/syntax problems but cannot prove sampling triggers, output latching, or shutdown paths. Model waveforms are hypotheses requiring controlled measurement and raw records. For driver changes, start with minimal paths, then add control and communication load. Mark untested target behavior pending rather than filling measurement results with simulation or source inference.

Debugging Checks
  • Mark distinct register, shared-memory, and DMA semantics. Check specific reasons for every barrier, synchronization, and cache operation.
  • Measure target triggers, outputs, and protection actions. Check device differences and unverified items; host tests alone cannot establish hardware correctness.
References

Compilation, Static Checks, and Tests

After AI writes code, compile with the actual target configuration and return full diagnostics. 'Should compile' is a prediction, not a result; copied code without dependencies does not prove project linking. Check compiler, macros, include paths, and target options, especially word widths, floating-point ABI, and library versions. Update static-analysis commands after generated configuration changes.

Static analysis and runtime detection supply different evidence. Path analysis flags some potential faults; silence does not prove absence. UBSan detects relevant undefined behavior in supported host/target environments but covers neither all inputs nor timing/hardware. Test parser, arithmetic, and state-machine boundaries on host first; DMA, interrupts, and storage still need target checks. Explain false positives rather than disabling all checks.

Preserve commands, exit status, raw output, and artifact identities for acceptance. AI may summarize passes, failures, and unrun items, but engineers must inspect originals. Analyze failures before changing anything; do not delete assertions or replace expectations with current outputs. Add checks for real risks such as length, signs, and cancellation. Many tests mirroring implementation details without independent criteria may provide little coverage.

Debugging Checks
  • Run actual target compilation and required host detection, checking tool settings, warnings, and unsupported scope.
  • Save exit codes, logs, and image identities. Confirm failures were not handled by changing expectations to match implementation, and explicitly record target-hardware checks.
References
AI-assisted engineering

AI-assisted debugging

Reproduce Before Forming Hypotheses · Logs, Waveforms, and Code EvidenceExpand the AI-Assisted Debugging Knowledge Directory
  • Reproduce Before Forming Hypotheses
  • Logs, Waveforms, and Code Evidence
  • Falsifiable Diagnostic Experiments
  • Regression and Traceability After Fixes
Reading Guide: AI-Assisted Debugging: Build the Evidence Chain Before Changing Code

Reproduce Before Forming Hypotheses

AI debugging starts with a repeatable description rather than labeling the cause. Include expected/actual behavior, conditions, reproduction steps, versions, and failure criteria. A reference jump may originate in decoding, handoff, stale-data recovery, or feedback. Calling it a 'race fix' prematurely excludes other explanations. Locate the earliest abnormal value, then ask for candidate causes and distinguishing evidence.

Reproduction conditions include hardware, parameters, load, clocks, compilation options, and input replay. Intermittent issues need statistical windows, attempts, and trigger opportunities; one success cannot establish normality. Logs/debuggers may alter timing, so preserve a baseline before adding observation. Bisect confirmed version regressions only with stable criteria. Skip unbuildable or indeterminate commits rather than arbitrarily classifying them to continue.

Have AI propose evidence needs and minimal experiments, then check whether they alter critical behavior. Keep multiple candidate causes with supporting, opposing, and unknown evidence. Once reproduced, freeze inputs/versions before modifying. If the environment must change, explain effects and reestablish baseline. A root cause must explain how the anomaly arises, why under these conditions, and why the fix closes that path, not merely repeat logs.

Debugging Checks
  • Record full reproduction conditions and criteria, repeatedly establish a failing baseline, and check that observation tools changed neither load nor versions.
  • List distinguishing experiments and counterevidence for every candidate. Retain skipped-version records during bisection; uncertain samples are not definite results.
References
  • Git git-bisect — git-bisect; skip, log, replay; checked online manual

Logs, Waveforms, and Code Evidence

Place evidence along data and timing chains. For communication-to-control anomalies, observe wire bytes, decoded values, submitted snapshots, adopted sequences, and actual outputs together; endpoint printing misses the first error. Waveforms establish edges/timing, logs establish states/transactions, and code explains possible paths. Correlate all three by timebase or sequence to form causal clues.

Bound observation cost. Synchronous formatting/printing in fast interrupts changes scheduling; buffered records still need capacity limits and loss counts. GDB watchpoints help locate writes, but hardware resources, access widths, and platform restrictions differ, and halting affects peripherals. Check hardware versus software watchpoints and supplement with nonhalting event records. Debugger behavior is not automatically real operating timing.

Give AI raw values, units, timing, and versions, with separate summaries rather than edited prose replacing originals. Require proposed causality to identify events and check supporting order and missing records. Load-induced buffer loss can create illusions; rule out observation-chain faults first. Comparing independent wire and memory observations distinguishes external-input, decoding, and shared-data faults.

Debugging Checks
  • Check matching versions and time mappings across waveforms, logs, and code. Preserve raw data and dropped-record counts.
  • Check watchpoint and printing effects on the target. Use at least one nonhalting method to verify critical event order and abnormal-value sources.
References
  • GDB Logging Output — GDB online manual; set logging enabled/file/overwrite
  • GDB Watchpoints — GDB online manual; hardware/software watchpoints, platform limitations

Falsifiable Diagnostic Experiments

Diagnostic experiments eliminate hypotheses. Ask AI for tests whose outcomes can support or refute each candidate, not just logs confirming a guess. For suspected premature buffer reuse, delay completion and record buffer generations. If data changes before return, locate the writer; if it remains intact, examine decoding or consumption. Define observation points and expected divergent outcomes.

Change one critical condition per experiment while holding versions, inputs, and load fixed. Added delays, disabled optimization, or longer timeouts aid diagnosis but are not themselves fixes. Define pass, fail, and inconclusive outcomes beforehand rather than adjusting criteria after results. Watchpoints, counters, and waveforms have blind spots; verify instruments and record completeness before expanding unclear tests.

Update the evidence table after distinguishing experiments, marking excluded and surviving causes. AI can interpret results and propose steps, but explanations are not observations. Final causes must cover the original anomaly's full chain, not mere correlation. Where needed, remove a condition under constraints to eliminate the fault, then restore it to reproduce it. Restore test configuration and record changes, preventing temporary diagnostic switches from entering releases.

Debugging Checks
  • Define variables, fixed conditions, observation points, and three outcomes for each experiment, checking that results actually distinguish candidates.
  • Save before/after configurations and raw outputs. Remove diagnostic switches and recheck original conditions; correlation alone is not a root cause.
References
  • GDB Watchpoints — GDB online manual; hardware/software watchpoints, platform limitations

Regression and Traceability After Fixes

Post-fix verification must retain original failure criteria. Save triggering inputs/conditions, then run the same checks after modification to verify closure. For intermittent faults, state opportunities and windows; brief normal operation does not establish complete resolution. Host tests suit parsing, boundary calculations, and pure state transitions; target/bench tests cover interrupts, DMA, output actions, and real loads. Record results separately.

Extend regression around the fix mechanism. Length fixes need zero, upper-limit, and invalid values; handoff fixes need completion, cancellation, timeout, and late callbacks; priority changes need load/starvation checks. Expectations come from requirements or independent calculations and must not share patch errors. Have AI explain the behavior protected by each check, avoiding test-count inflation through repetition of implementation steps without outcome checks.

Trace issues, evidence, causes, diffs, and results together. Preserve exit codes, failure locations, image IDs, and parameter IDs; AI summaries serve as indexes only. Keep uncovered hardware conditions in the matrix and update after testing without rewriting earlier facts. Retain failing samples for long-term regression. Compare conditions before reusing old conclusions so patches are not transferred to new issues without evidence.

Debugging Checks
  • Compare before/after with identical inputs and criteria, checking sufficient intermittent trigger opportunities for the actual conclusion.
  • Cover fix-related neighboring boundaries. Preserve raw output and untested items, tracing issue records to actual images and parameters.
References
  • GoogleTest Primer — Assertions and test fixtures; online primer, project dependency version must be pinned separately
  • CTest Manual — CMake 3.31.12; test selection, timeout, output and repeat
AI-assisted engineering

Verification, review and boundaries

Tests Mapped to Requirements · Races, Overflow, and State BoundariesExpand the Verification, Review, and Boundaries Knowledge Directory
  • Tests Mapped to Requirements
  • Races, Overflow, and State Boundaries
  • Device Constraints and Manual Review
  • Separating AI Conclusions from Measured Evidence
Reading Guide: AI-Assisted Debugging: Build the Evidence Chain Before Changing Code

Tests Mapped to Requirements

For AI test review, first ask what observable behavior requirements demand, then whether tests actually judge it. Parameter-write tests need valid ranges, atomic activation, and old-value retention after rejection, not just successful returns. Protection tests need required output actions, not only software flags. Gaps between test names and assertions are a useful review starting point.

Every check needs conditions, input, expectation, and evidence level. Host doubles verify calling order/state but not actual peripheral timing; bench waveforms prove actions but may omit parser boundaries. Have AI map requirements to evidence, marking uncovered conditions and independent expectation sources. Fixed fixtures reduce environmental variation but can leak reused state into later cases, particularly static variables, buffer pools, and simulated clocks.

On failure, return to requirements instead of automatically changing expectations to match implementation. Tolerances need units, dimensions, and conditions, not one large universal floating-point error. Distinguish passed, failed, skipped, and not-run results and preserve raw outputs. AI can identify gaps and construct boundary inputs; engineers confirm criteria and execute tests. Unexecuted suggestions remain pending and do not count as coverage.

Debugging Checks
  • Compare assertions with full required behavior, checking independent expectations and explicit scope of host versus target evidence.
  • Check fixture state, tolerance units, and skip reasons. Preserve original failures; expectation changes require requirement-based justification.
References
  • GoogleTest Primer — Assertions and test fixtures; online primer, project dependency version must be pinned separately

Races, Overflow, and State Boundaries

Review races, overflow, and state boundaries along execution/data flows. List shared-object readers/writers, handoffs, and lifetimes, then examine indices, lengths, and unit conversions. A nonnull pointer does not prove current ownership; a length below capacity does not prove offset-plus-length cannot wrap. Explicit invariant explanations reveal more than searching dangerous functions or adding volatile.

Arithmetic review concerns operand width when operations occur, not destination type. Widen before multiplication, define negative/unsigned comparison semantics, and cover extreme shift ranges and saturation. Concurrency checks include cancellation, timeout, reset, and late completion; a correct normal path does not prevent double release. Check transition rejection and fault priority so communication retries cannot repeat one-shot actions.

Runtime detection exposes covered undefined behavior but does not prove all races absent or target timing safe. Unsynchronized ordinary accesses in host thread models must follow language rules; single-core interrupt handoffs require platform/compiler-specific design. Do not conflate them into one rule of thumb. Review suggestions need concrete failing sequences and verification. Rerun the same boundaries after changes, checking that locks/retries preserve protection and real-time budgets.

Debugging Checks
  • For critical arithmetic, verify inputs, operation widths, and conversion results. For shared objects, check publication, cancellation, and return invariants.
  • Construct extreme lengths, repeated events, and late callbacks, combining applicable detection tools with target tests. No warnings does not prove no defects.
References

Device Constraints and Manual Review

Device-constraint review starts with actual parts and board configuration. Have AI list required ADC sampling times, trigger mappings, timer-update conditions, DMA-accessible regions, and interrupt limits, then verify each against matching manuals and source. Family application notes guide checks but do not replace part-specific register and errata validation. Example defaults must not become device requirements.

Review analog and digital paths together. Longer ADC acquisition may improve settling but reduce control budget; moved PWM triggers change sampling windows; cache maintenance may fix handoff while adding execution cost. Assess these jointly. For each suggestion, state benefits, prerequisites, and costs, then verify real timing and source. Successful peripheral configuration calls do not prove correct pin multiplexing, clocks, or signal quality.

Final checks cover normal operation, boundaries, and fault recovery. Protection, output re-enabling, and execution during storage are device-dependent; preserve exact conditions. Mark AI conclusions pending if they lack sections or target results. For failed documentation access, report failure and available alternatives without claiming confirmation. Repeat difference checks after device/revision changes so previously valid configuration assumptions do not persist after becoming false.

Debugging Checks
  • Check part numbers, document revisions, and applicability for critical settings, including joint constraints on analog settling and control budgets.
  • Measure modified triggers, data readiness, and output actions, covering fault recovery. Explicitly retain incomplete manual or target-verification items.
References

Separating AI Conclusions from Measured Evidence

AI conclusions and measured evidence should carry different labels. A model inferring from source code that a variable may exceed its bounds is a diagnostic hypothesis; a compiler reporting a specific warning is a tool observation; a target waveform showing that an output arrives after the latch window is a measurement result. Combining these levels into 'the issue is confirmed' leaves subsequent fixes based on incomplete evidence. Require every conclusion to state its basis and the conditions that could still overturn it.

Execution results must come from actual commands and devices. Save commands, configurations, exit status, logs, waveforms, and run identifiers before asking AI to summarize them. A tool running successfully only means execution completed; a passing test covers only its particular inputs and environment; meeting simulation targets does not establish that the power stage and sensors have been verified. The existence of an output file does not prove that the current command generated it. Check its timestamp, version, or hash so the model does not treat old results as new evidence.

State observed facts, engineering explanations, and pending verification separately in reports. If hardware is unavailable, source and host checks can still be completed, but bench results must not be invented. Conclusions after a fix cover only the conditions actually exercised; retain necessary load, temperature, and fault tests in the acceptance matrix. AI-generated expected waveforms, time estimates, and suggested commands can form a plan, but cannot appear in the measured-results column.

Debugging Checks
  • Spot-check the raw outputs behind all passing or fixed conclusions, and confirm that the commands, artifacts, and device firmware versions belong to this verification run.
  • Record inference, simulation, host tests, and target measurements separately, and check that unexecuted suggestions have not been counted as completed results.
References
  • CTest Manual — CMake 3.31.12; test selection, timeout, output and repeat
  • GDB Logging Output — GDB online manual; set logging enabled/file/overwrite
AI-assisted engineering

Knowledge capture and collaboration records

Problems, Conditions, and Evidence · Decision Rationale and ApplicabilityExpand the Knowledge Directory for Knowledge Capture and Collaboration Records
  • Problems, Conditions, and Evidence
  • Decision Rationale and Applicability
  • Reproducible Steps and Versions
  • Topics, Terminology, and Related Reading

Problems, Conditions, and Evidence

Knowledge records should first preserve the specific form of a problem. Document expected and actual behavior, trigger conditions, affected versions, and the earliest point of abnormal behavior, then link logs, waveforms, and code. An error code and the final fix title are insufficient for reusing experience, because the same symptom can arise from different data paths. Records should identify which conditions have been fixed and which remain unconfirmed, and retain failing samples instead of saving only a screenshot of one successful run.

Ideally, retain evidence in both raw and summarized layers. The raw layer preserves bytes, time references, commands, and tool outputs; the summary explains event order and key values. AI can help organize indexes and remove duplicates, but should not rewrite raw values or fill gaps to create a complete story. Record buffer losses and versions before exporting logs, and label waveform channels and measurement points. Records from different device clocks require a mapping; otherwise, they cannot directly support fine-grained latency conclusions.

When closing an issue, add the evidence for its cause, the fix diff, verification, and applicability. Retain explanations that have not been ruled out and conditions that have not been tested; do not delete them merely because the task has ended. Remove sensitive information from public technical materials while preserving test conditions, versions, and verifiable results. Engineering records support later reproduction and maintenance, while article text explains principles and methods. These materials have different levels of detail; linking them is more usable than packing every log into an article.

Debugging Checks
  • Check that records include the original failing samples, conditions, and raw evidence, and that values and event order in summaries can be traced to the originals.
  • Check the scope of the fix and verification in the closure conclusion. Sanitize records before external sharing while retaining data provenance and test conditions.
References

Decision Rationale and Applicability

Decision records should explain why an approach was chosen and under what conditions it works. For example, when using a static buffer, record not only the conclusion but also the input limit, peak backlog, memory budget, and overflow policy. When choosing double buffering, also explain the publication, consumption, and reuse protocol. AI can organize comparison tables, but cannot present untested costs as established performance or fill in unrecorded reasons as decision facts.

Compare alternatives against the same requirements and constraints. Queues suit individual events; a latest-value mailbox suits references for which intermediate values may be dropped. Mutexes suit task access to resources, while control interrupts may need another handoff mechanism. Explain why an approach does not meet current conditions rather than broadly claiming that one pattern is always better. General coding principles can help review ownership and interfaces, but real-time, memory, and platform constraints still require decisions in the specific system.

Record applicability and conditions for reversing the decision as well. Increased input rates, a chip change, expanded parameters, or changed task priorities may invalidate the original capacity and timing derivations. Preserve the rationale, calculations, and experiments so future maintainers know when reassessment is needed. Update documentation to match actual changes without repeating the full discussion history each time. Concisely retain the problem, choice, rationale, and verification; after a model assists with summarization, an engineer must still check that it accurately reflects the evidence.

Debugging Checks
  • Check that every decision includes requirements, constraints, alternatives, and the selection rationale, and that capacity and timing judgments can be traced to calculations or experiments.
  • List applicability and reassessment triggers, and confirm that AI has not turned unmeasured costs or discussions that never occurred into historical facts.
References

Reproducible Steps and Versions

Reproduction records must let someone later obtain comparable results from the same inputs. Record source code, hardware, toolchain, parameters, build commands, flashed image, and reproduction steps, then specify observation points and criteria. Merely writing 'open the project and click Run' omits IDE configuration and locally generated files. Provide an explicit build entry point and input files, and fix the file encoding, byte order, and test-environment conditions that affect results.

Reproduction steps include the initial state and recovery operations. Whether parameters are cleared after power-on, calibration is awaited, the motor is enabled, and how messages are sent can all determine whether a fault occurs. For intermittent cases, specify cycle counts, trigger opportunities, and log windows instead of recording only the final failure. Automated scripts improve consistency, but retain the script version and exit result as well. If the required environment cannot be provided, state the differences; do not record an inconclusive result as no fault.

For long-term maintenance, associate input samples and build manifests with the affected versions, and retain necessary known-good and failing baselines. Bisection logs can record the search path, and build presets can preserve entry-point configuration, but neither replaces hardware and parameter information. AI can draft procedures, which must then be corrected by actual replay; mark only executed steps as verified. After upgrading tools or environments, replay key samples again to check that the records do not depend on implicit state from an old machine.

Debugging Checks
  • Have another environment rebuild and reproduce the issue using the steps, checking that the initial state, parameters, input files, and actual image agree.
  • Save scripts, commands, and exit results; distinguish successful reproduction, no trigger, and inconclusive results. Record attempt conditions and counts for intermittent cases.
References

Topics, Terminology, and Related Reading

Topic and terminology organization should establish stable meanings instead of merely collecting keywords. Distinguish control commands, operating parameters, feedback snapshots, and fault events, specifying units, timing, and ownership semantics. Distinguish drive state from communication state so that the same word 'running' does not refer to several conditions. AI can find identical names with different meanings and different names with identical meanings in documentation. Final terminology must correspond to interfaces and code, and should not be renamed arbitrarily to sound professional.

Organize related reading around causal chains. Learning about ADC handoff can link to sampling settling, DMA consistency, real-time budgets, and fault records; learning about parameter updates can link to state permissions, atomic commits, persistence, and upgrade compatibility. Explain why each link is relevant, avoiding long lists of references with no stated purpose. Retain reference versions and sections; keep unconfirmed chip abbreviations in their original form and mark them for verification.

Knowledge entries should distinguish general principles, platform implementations, and project records. General text explains transferable methods, platform entries specify device and library conditions, and project records preserve actual inputs and evidence. After AI-assisted classification, check for omitted boundaries or duplicate content. Preserve stable identifiers and old links during updates, adding aliases when needed. If terminology changes affect an interface, update the code, documentation, and tests together.

Debugging Checks
  • Spot-check that terms have consistent meanings and units across code, interfaces, and articles, and confirm that unknown abbreviations have not been expanded without verification.
  • Check the specific purpose and source scope of each related link. Clearly distinguish general, platform-specific, and measured content, and avoid arbitrarily breaking stable identifiers.
References

Knowledge Directory.

Knowledge Directory