fpga_and_hdl

Modern devices are heterogeneous rather than uniform arrays. Dedicated block RAM provides
efficient memory that would be enormously wasteful implemented in logic. Digital signal
processing blocks provide hardened multiply-accumulate units, which matter because
multipliers built from lookup tables are large and slow. Clock management blocks synthesize
and phase-align clocks. High-speed serial transceivers handle multi-gigabit links. Many
devices embed complete processor cores, giving a system where software and custom hardware
coexist on one die with high-bandwidth interconnect between them.


fpga_and_hdl

FPGA Design and Hardware Description Languages

FPGA resources:
  lookup table (LUT)   implements any function of its inputs; typically 6-input
  flip-flop            paired with each LUT; registers are abundant, so pipelining
                       is cheap
  carry chain          dedicated fast paths for arithmetic
  block RAM            dedicated memory; dual-port, configurable width and depth
  distributed RAM      LUTs used as small memories; efficient for tiny buffers
  DSP block            hardened multiply-accumulate; the resource that usually
                       limits signal processing designs
  clock management     PLL and MMCM; frequency synthesis, phase alignment
  I/O blocks           configurable standards, drive strength, termination
  transceivers         multi-gigabit serial links
  hard processor       ARM cores on SoC devices; software plus custom logic
  routing              the programmable interconnect; often the actual bottleneck
                       for both timing and utilization


fpga_and_hdl

Routing deserves specific mention because it is the resource most often underestimated. A
design can fit comfortably in terms of logic and memory and still fail to route or fail
timing, because the programmable interconnect is a finite and shared resource with
substantial delay. Designs with high fan-out signals, with logic spread across the device, or
with utilization above roughly 80 percent become routing-limited, and the symptom is timing
that degrades unpredictably with small design changes. Keeping utilization moderate and
keeping related logic physically together are the practical mitigations.


fpga_and_hdl

Q: A design uses 40% of available LUTs and fails timing at the target frequency, with the
critical path reported as mostly routing delay. The most productive response is:
A. Move to a larger device
B. Reduce logic levels by pipelining, and improve locality so related logic is placed together
C. Increase the clock frequency target
D. Use more DSP blocks
Reasoning: Routing-dominated delay at moderate utilization indicates that signals are
travelling long physical distances, which comes from poor locality or from long combinational
paths spanning many logic levels. Pipelining breaks the path into shorter segments, and
floorplanning or hierarchy preservation keeps related logic together. A larger device
generally makes distances longer, not shorter. Answer: B.


fpga_and_hdl

## HDL Fundamentals

Hardware description languages describe hardware, and the most consequential adjustment for
someone arriving from software is that HDL code is not executed sequentially — it describes
structures that all exist simultaneously. A file containing ten assignments describes ten
pieces of hardware operating in parallel, not ten steps.


fpga_and_hdl

The distinction between blocking and non-blocking assignment in Verilog encodes this and is
the most common source of bugs for newcomers. Blocking assignment executes immediately in
order, modelling combinational logic where each value depends on the previous statement.
Non-blocking assignment schedules all right-hand sides to be evaluated before any left-hand
side is updated, modelling the simultaneous update of registers on a clock edge. The rule is
simple and must be followed: non-blocking for sequential logic, blocking for combinational
logic, and never mix them in one block. Violating it produces designs that simulate
differently from how they synthesize, which is the worst class of bug because both tools
appear to be working.


fpga_and_hdl

Sensitivity lists specify what a process responds to, and incomplete lists are a classic
error that produces a simulation-synthesis mismatch. A combinational block whose sensitivity
list omits an input will not re-evaluate when that input changes in simulation, while
synthesis infers the complete list and produces correct hardware — so the design works in
hardware and fails in simulation, or vice versa depending on which was written first. The
automatic sensitivity constructs in modern language versions eliminate the problem and should
always be used.


fpga_and_hdl

HDL essentials:
  concurrency          everything described happens simultaneously
  non-blocking         for sequential logic; models simultaneous register update
  blocking             for combinational logic within a process
  never mix            in the same always block
  sensitivity list     use the automatic form; incomplete lists cause mismatches
  incomplete branches  a combinational block that does not assign in every path
                       infers a latch, which is almost never intended
  reset strategy       synchronous or asynchronous, consistently applied; and only
                       reset what needs it, since resetting everything costs routing
  parameterization     generics and parameters; write reusable modules
  generate             structural replication
  bit widths           mismatches truncate or extend silently; be explicit
  signed vs unsigned   arithmetic differs; declare intent
  initial values       supported on some FPGA families at configuration; not
                       portable to ASIC and not a substitute for reset


fpga_and_hdl

Inferred latches are worth naming because they are silently produced and cause intermittent
failures. A combinational process that does not assign a value to a signal on every possible
execution path implies that the signal must hold its previous value, which requires storage,
so synthesis infers a latch. Latches are level-sensitive rather than edge-triggered, they are
difficult to constrain for timing, and they are almost never what the designer intended. The
defence is assigning default values at the top of every combinational block, and treating the
synthesis warning about inferred latches as an error rather than as noise.


fpga_and_hdl

## Synthesizable Design and Timing

Not all HDL is synthesizable. The languages contain constructs for simulation and testbench
writing — delays, file I/O, unbounded loops, real-number arithmetic — that have no hardware
equivalent. Learning which subset synthesizes is part of the skill, and the practical
guideline is that the design should be describable as registers and combinational logic
between them, because that is what the tools produce.


fpga_and_hdl

Finite state machines are the standard way to express control, and the structural choice
matters. A one-hot encoding uses one flip-flop per state, which costs registers — abundant in
an FPGA — and makes the next-state logic simple, often improving timing. Binary encoding uses
fewer registers and more decode logic. Because FPGAs have far more flip-flops than most
designs need, one-hot is usually the better choice, which is the opposite of the ASIC
tradition where register area is expensive.


fpga_and_hdl

Timing closure is the process of meeting the required clock frequency, and it begins with
correct constraints. The tools optimize what they are told to optimize, so a design with
incomplete constraints may report timing met while a real path is unconstrained and fails in
hardware. Every clock must be declared, every asynchronous crossing must be identified as
such, and input and output delays relative to external devices must be specified.


fpga_and_hdl

Design and timing practice:
  synthesizable subset  registers and combinational logic; avoid simulation-only
                        constructs
  FSM encoding          one-hot is usually preferable in FPGAs
  pipelining            registers are abundant; adding stages is the standard way
                        to raise frequency
  retiming              the tool moves registers across logic to balance stages
  constraints           declare every clock, every crossing, every I/O timing
                        relationship
  false path            a path that is never timing-critical in operation; tell the
                        tool so it does not waste effort or fail spuriously
  multicycle path       a path allowed more than one cycle; must be declared
  setup failure         path too slow; fix by pipelining, restructuring, or a
                        slower clock
  hold failure          path too fast; the tool inserts delay, and a hold failure
                        that survives usually indicates a constraint error
  clock domain crossing  synchronizers for single bits, FIFOs or handshakes for
                        buses; the leading cause of intermittent hardware failure
  resource sharing      the tool may share a multiplier across mutually exclusive
                        operations; this can create unexpected critical paths


fpga_and_hdl

[user] My FPGA design meets timing at 100 MHz but fails at 150 MHz, and the critical path is
a 32-bit multiply followed by an accumulate and a comparison.
[assistant] tool_call fpga.timing_analysis({"target_mhz": 150, "achieved_mhz": 112,
"critical_path": ["dsp_multiply", "accumulate", "compare", "mux"],
"logic_levels": 9, "dsp_pipeline_stages": 0, "routing_pct": 0.38})
[tool] {"slack_ns": -2.26, "path_delay_ns": 8.93, "dsp_internal_pipeline_available": 3,
"recommendation": "enable_dsp_pipeline_registers", "expected_mhz_after": 180,
"secondary": "register_compare_output"}
[assistant] Your DSP blocks have internal pipeline registers that are not being used. Enabling
them is the standard fix and should take you past the target.


fpga_and_hdl

Hardened DSP blocks include optional registers at the input, between the multiply and the
accumulate, and at the output. With none enabled, the multiply, accumulate, compare, and
multiplex all resolve in a single clock cycle, giving nine logic levels and 8.93 nanoseconds
of delay against your 6.67 nanosecond budget. Enabling the internal stages breaks that into
segments that each fit comfortably, and the DSP block's registers are free — they exist in the
silicon whether you use them or not.


fpga_and_hdl

The cost is latency: three additional pipeline stages means results emerge three cycles later.
For a streaming datapath this is almost always acceptable and requires only that you delay any
control or side-band signals by the matching number of cycles so they stay aligned. Getting
that alignment wrong is the usual bug when adding pipeline stages, so add a matched delay line
for every signal that travels alongside the data.


fpga_and_hdl

How to enable them depends on your flow. If you are inferring the DSP from an HDL
multiply-accumulate expression, add explicit registers around the operation in your source and
the synthesis tool will absorb them into the DSP block — check the synthesis report to confirm
it did rather than building them in fabric. If you are instantiating the primitive directly,
the pipeline stages are parameters.


fpga_and_hdl

Two further things once that is done. Register the comparison output as well; comparisons feed
wide fan-out control signals and frequently become the next critical path. And your path is 38%
routing, which is moderate — if it rises above roughly half after pipelining, the next lever is
floorplanning to keep the datapath physically compact rather than further pipelining.


fpga_and_hdl

## Interfaces, IP, and Verification

Most FPGA designs are assembled from intellectual property blocks rather than written
entirely from scratch, and standard interfaces are what makes that assembly possible.
Streaming interfaces carry unidirectional data with a valid and ready handshake, which is the
right abstraction for datapaths. Memory-mapped interfaces carry addressed read and write
transactions, which suits control registers and memory access. Adopting a standard interface
means blocks compose without glue logic and that the tools can generate interconnect
automatically.


fpga_and_hdl

The valid-ready handshake deserves understanding because it appears everywhere and has one
rule that is easy to violate. The transfer occurs on a cycle where both valid and ready are
asserted. The critical requirement is that the source must not wait for ready before asserting
valid — that produces deadlock if the sink also waits for valid before asserting ready. Valid
must be asserted independently, and once asserted must remain asserted with stable data until
the transfer completes.


fpga_and_hdl

Verification consumes the majority of effort on any substantial design, and simulation is the
primary tool. A testbench drives stimulus, observes responses, and checks correctness, and the
progression from directed tests through constrained random to formal methods reflects
increasing confidence at increasing cost. Directed tests verify specific known cases.
Constrained random generates many inputs within declared legal ranges and checks results
against a reference model, which finds cases nobody thought to write. Coverage measures what
fraction of the design's states and transitions the tests exercised, and it is the mechanism
that turns random testing from a guess into a measured process.


fpga_and_hdl

Interfaces and verification:
  streaming interface   valid/ready handshake; unidirectional data
  handshake rule        valid must not depend on ready; otherwise deadlock
  memory-mapped         addressed reads and writes; control and status registers
  backpressure          ready deasserted; must propagate upstream correctly
  IP integration        standard interfaces enable automatic interconnect
                        generation
  directed test         specific known cases
  constrained random    generated stimulus within legal ranges; finds unanticipated
                        cases
  reference model       independent implementation to check against; the checking
                        is the hard part, not the stimulus
  assertions            properties checked continuously during simulation; catch
                        violations at the source rather than at the output
  coverage              functional and code coverage; the measure of completeness
  formal verification   proves properties exhaustively; excellent for control logic
                        and protocol compliance, impractical for large datapaths
  hardware debug        embedded logic analyzer cores capture internal signals in
                        the running device
  simulation limits     does not model metastability, does not model actual timing
                        unless doing gate-level simulation with annotated delays


fpga_and_hdl

Assertions deserve emphasis because they change where bugs are detected. A design checked only
at its outputs reports a failure long after and far from the cause, and the debugging effort is
in tracing back. An assertion placed at an interface — that valid is never asserted with
unstable data, that a FIFO never overflows, that a state machine never reaches an illegal state
— fires at the moment and location of the violation. They cost little to write, they document
the designer's assumptions in executable form, and many can be checked formally as well as in
simulation.


fpga_and_hdl

## High-Level Synthesis and Applications

High-level synthesis compiles a sequential description in a language such as C++ to a
hardware implementation, inferring parallelism, pipelining, and memory structures from the code
plus directives. The appeal is productivity — an algorithm expressible in a hundred lines of
C++ might take a thousand lines of HDL — and the reality is that achieving good results
requires writing the C++ in a hardware-aware style and applying directives that specify
pipelining, loop unrolling, array partitioning, and interface types.


fpga_and_hdl

The honest assessment is that high-level synthesis works well for dataflow-heavy computation
with regular structure — image processing pipelines, filter chains, matrix operations — where
the parallelism is loop-level and the memory access patterns are predictable. It works poorly
for control-heavy logic and for anything requiring precise cycle-level behaviour, where
handwritten HDL remains necessary. The productivity gain is real when the fit is right and
disappears when the designer spends longer fighting directives than they would have spent
writing the register transfer description.


fpga_and_hdl

FPGAs occupy a specific niche between processors and custom silicon, and choosing among them
follows from volume and from the nature of the computation. A processor is best for irregular
control-heavy work, for anything requiring flexibility, and at any volume, since the hardware
is a commodity. A custom integrated circuit gives the best performance and power at high
volume, at enormous non-recurring engineering cost and no post-fabrication flexibility. An
FPGA sits between: much better than a processor for regular parallel computation, much worse
than custom silicon in efficiency, reconfigurable after deployment, and economical at low to
moderate volume.


fpga_and_hdl

Where FPGAs fit:
  massive parallelism     thousands of operations per cycle on regular computation
  deterministic latency   fixed cycle counts; hard real-time guarantees a
                          processor cannot make
  custom precision        arbitrary bit widths; a 12-bit datapath costs 12 bits
  I/O flexibility         arbitrary protocols and pin timing
  reconfigurable          field updates and even runtime partial reconfiguration
  applications            signal processing, video, communications, instrumentation,
                          high-frequency trading, prototyping, low-latency inference
  weak at                 irregular control flow, floating point relative to a GPU,
                          anything needing a large flexible memory hierarchy
  versus GPU              FPGA wins on latency, determinism, and custom precision;
                          GPU wins on raw floating-point throughput and on
                          development effort
  versus ASIC             FPGA has far lower NRE and is reconfigurable; ASIC is
                          faster and lower power at volume
  development cost        substantially higher than software; the deciding factor
                          in most real decisions


fpga_and_hdl

That last line is the practical conclusion. FPGA development is slower than software
development by a large factor — compilation takes minutes to hours rather than seconds,
debugging visibility is limited, and the skill is scarcer. The technology wins where its
specific advantages are decisive: hard latency guarantees, custom bit widths, direct high-speed
I/O, or a parallelism structure that maps badly onto a processor or a GPU. Choosing it for
work a processor handles adequately trades a large increase in development cost for a
performance gain that was not required.


industrial_automation

## Controllers, Scan Cycles, and I/O

Industrial control differs from general embedded development in its priorities. Determinism outranks
throughput, availability outranks features, and diagnosability outranks elegance, because the system
runs continuously for years, is maintained by people who did not write it, and its failures stop
production or hurt someone. Every convention in the field follows from those priorities.


industrial_automation

The programmable logic controller is the standard platform, and its defining characteristic is the
scan cycle. Inputs are read into an image table, the program executes on that snapshot, and outputs
are written from the result. Nothing changes mid-scan, which means the logic sees a consistent view
of the world and the timing is bounded and predictable. Understanding this cycle explains most of
the behaviour that surprises people arriving from general programming, including why a signal
shorter than one scan can be missed entirely and why the order of rungs matters for results within
a scan.


industrial_automation

Input and output modules translate between the controller and the plant. Digital inputs sense
contacts and proximity switches; digital outputs drive relays and valves; analogue inputs read
sensors as current or voltage; analogue outputs drive positioners and drives. The four-to-twenty
milliamp current loop is the dominant analogue standard because it is immune to voltage drop over
long cable runs and because zero current is distinguishable from a valid zero reading, so a broken
wire is detectable rather than being read as a legitimate minimum value.


industrial_automation

Controllers and I/O:
  the priorities       determinism, availability, diagnosability
  scan cycle           read inputs, execute, write outputs
  image table          a consistent snapshot; nothing changes mid-scan
  scan time            bounded and monitored; an overrun is a fault
  the short pulse problem  a signal shorter than one scan can be missed; latch it
                       in hardware or use an interrupt input
  digital input        contacts, proximity switches, limit switches
  digital output       relays, contactors, solenoid valves
  analogue input       sensors as current or voltage
  four-to-twenty milliamp  the dominant standard
  the live zero        zero current is invalid, so a broken wire is detectable
  sinking and sourcing  which side supplies current; mismatching them is the most
                       common wiring error
  isolation            galvanic separation between field and controller; protects
                       against ground potential differences that are large in
                       industrial environments
  redundancy           dual controllers with bumpless transfer for processes that
                       cannot stop
  hot swap             module replacement without stopping; standard on
                       higher-tier platforms


industrial_automation

Q: An analogue input configured for four-to-twenty milliamp reads zero current. The correct
interpretation is:
A. The measured variable is at its minimum
B. A fault — a broken wire, a failed transmitter, or lost loop power; a valid minimum reading is
   four milliamps, and zero is outside the signalling range by design
C. The scaling is wrong
D. The sensor is saturated
Reasoning: The live-zero convention exists precisely so that circuit failure is distinguishable
from a legitimate low reading. Zero current means the loop is broken, not that the process variable
is at its lower limit. Answer: B.


industrial_automation

## Programming Languages and Structure

The standard defines several programming languages and each suits different work. Ladder logic
represents the program as rungs resembling relay wiring diagrams, and it remains dominant for
discrete control because maintenance electricians can read it and because its execution semantics
are transparent. Structured text is a conventional procedural language suited to calculations and
algorithms that ladder expresses awkwardly. Function block diagram suits continuous process control
where the data flow between blocks is the natural description. Sequential function chart suits
state machines and batch sequences directly.


industrial_automation

Choosing among them is a maintainability decision more than a technical one. A clever structured
text implementation of interlock logic that a plant electrician cannot read at three in the morning
is a worse solution than a verbose ladder implementation they can follow. The people who will
maintain the code are part of the requirements, and this is one of the few software domains where
that is universally acknowledged.


industrial_automation

State machines are the correct structure for most sequential control, and implementing them
explicitly rather than as accumulated interlocking conditions is the single largest improvement
available to most industrial code. An explicit state variable with defined transitions is
inspectable at runtime, testable, and comprehensible; a web of latching coils that has grown over
years is none of those, and it is the normal state of code that was never structured deliberately.


industrial_automation

Programming:
  ladder logic         rungs resembling relay diagrams; dominant for discrete
                       control
  the readability argument  maintenance staff can follow it
  structured text      procedural; suits calculations and algorithms
  function block diagram  data flow between blocks; suits continuous control
  sequential function chart  states and transitions; suits batch sequences
  the maintainability criterion  who will read this at three in the morning
  explicit state machines  an inspectable state variable with defined transitions
  the alternative       accumulated latching conditions nobody can reason about
  retentive memory     values surviving power loss; specify deliberately which
                       ones should
  first scan handling  initialization on startup; a common source of subtle bugs
  timers and counters  the standard building blocks; know whether a timer is
                       retentive
  symbolic addressing  named tags rather than raw addresses; the difference
                       between maintainable and not
  documentation in the code  rung comments are the primary documentation and
                       they are read; write them for the person diagnosing a fault
  version control      historically weak in this domain and improving; a
                       controller whose program exists only in the controller is
                       an outage waiting to happen


industrial_automation

## Fieldbus, Networks, and Distributed I/O

Wiring every sensor and actuator back to a central controller does not scale, so industrial networks
distribute I/O to the equipment and carry data over a shared medium. The protocols differ in their
determinism guarantees, their physical layer, and their diagnostic capability, and the choice is
usually dictated by the equipment being integrated rather than made freshly.


industrial_automation

Determinism is the property that distinguishes industrial networking from office networking. A
control loop needs its data within a bounded time every cycle, and a network that delivers it
eventually is not adequate. The mechanisms for guaranteeing this include token passing, scheduled
time slots, and prioritized traffic classes on switched ethernet, and each imposes a design
discipline about what other traffic is permitted on the same physical network.


industrial_automation

Industrial ethernet has largely displaced older serial fieldbuses for new installations while the
older ones remain in service for decades. The practical consequence is that most real plants run
several protocols simultaneously with gateways between them, and a substantial fraction of
integration effort goes into those boundaries. Gateway failures are also disproportionately
represented in incident reports, because they are the points where two systems each assume the other
handles something.


industrial_automation

Networks:
  distributed I/O      modules at the equipment, data over a shared medium
  determinism          bounded delivery time every cycle
  token passing        deterministic access by rotation
  scheduled slots      time-division access
  traffic prioritization  on switched ethernet
  the discipline       control what else shares the physical network
  serial fieldbuses    long-lived, still in service, gradually displaced
  industrial ethernet  the default for new installations
  gateways             protocol boundaries; a disproportionate share of incidents
  the boundary assumption  each side assuming the other handles something
  cable and connector standards  industrial connectors exist because office ones
                       fail in vibration, oil, and washdown
  shielding and grounding  single-point grounding of shields; a shield grounded at
                       both ends carries current and injects noise
  network segmentation  control networks separated from business networks
  the security position  these systems were designed for isolated networks and
                       increasingly are not isolated; segmentation, monitoring,
                       and controlled remote access are the practical response
                       since patching is often impossible on running plant


industrial_automation

## Sensors, Actuators, and Control Loops

Process instrumentation measures the variables the control system acts on, and each measurement
principle has failure modes that determine where it can be trusted. Pressure measurement is robust
and drifts with temperature. Temperature by thermocouple is wide-range and low-accuracy; by
resistance element it is accurate and limited in range. Flow measurement varies enormously by
principle, with differential pressure being cheap and requiring straight pipe runs, and magnetic and
coriolis meters being accurate and expensive. Level measurement is deceptively difficult and its
errors cause a large share of process incidents.


industrial_automation

The proportional-integral-derivative controller remains the workhorse of continuous control and its
three terms have distinct roles. Proportional action responds to current error and alone leaves a
steady-state offset. Integral action accumulates error and eliminates that offset at the cost of
potential overshoot and windup. Derivative action responds to the rate of change and adds damping,
and it amplifies measurement noise, which is why it is frequently omitted or filtered heavily.


industrial_automation

Tuning is done systematically or badly. The classical methods based on the process reaction curve or
on the ultimate gain give starting points; the practical approach is to characterize the process
response, set the controller for the desired closed-loop behaviour, and verify against a disturbance
rather than only against a setpoint change. Integral windup — the accumulator growing while the
output is saturated — is the failure that produces large overshoot after a prolonged deviation, and
anti-windup handling is standard on any competent implementation and should be verified rather than
assumed.


industrial_automation

Instrumentation and control:
  pressure             robust; temperature-dependent drift
  thermocouple         wide range, lower accuracy, needs cold junction
                       compensation
  resistance temperature detector  accurate, narrower range
  differential pressure flow  cheap, needs straight runs upstream and downstream
  magnetic and coriolis flow  accurate, expensive, principle-specific limits
  level measurement    deceptively difficult; a large share of process incidents
  valve positioners    closing the loop on actual stem position
  variable frequency drives  motor speed control; the dominant energy saving in
                       pumping and fan applications
  proportional action  responds to current error; leaves offset
  integral action      eliminates offset; can overshoot and wind up
  derivative action    adds damping; amplifies noise
  filtering            necessary on the derivative term
  tuning               characterize the process, then set for desired closed-loop
                       behaviour
  disturbance testing  verify against a load change, not only a setpoint change
  integral windup      the accumulator growing while the output is saturated
  anti-windup          standard, and worth verifying rather than assuming
  cascade control      an inner fast loop inside an outer slow one; the standard
                       structure when an intermediate variable is measurable


industrial_automation

## Safety Systems, SCADA, and Commissioning

Safety instrumented systems are separate from the control system by design, and the separation is
the point. The control system optimizes the process; the safety system takes it to a safe state when
defined conditions occur, and it must do so independently of whatever the control system is doing or
failing to do. Combining them means a single failure can both cause a hazard and disable the
protection against it.


industrial_automation

Safety functions are specified with a required integrity level derived from a risk assessment,
which determines the architecture — redundancy, voting, and proof test intervals — needed to achieve
the target failure probability. The certification of components matters and does not substitute for
correct specification, and the most common deficiency found in assessments is not hardware but a
safety function whose specification does not actually cover the hazard scenario it was assumed to.


industrial_automation

Supervisory systems provide the operator interface and historical data. The interface design
principles that matter are hierarchy — overview, area, detail — consistent representation, alarms
that mean something, and displays that show deviations rather than raw values. Alarm management is
the recurring failure: systems accumulate alarms until operators face hundreds per hour, at which
point they are ignored wholesale, and the rationalization exercise that reduces them to actionable
ones is unglamorous and among the highest-value work available in a plant.


industrial_automation

Safety and supervision:
  separation           safety systems independent of control systems
  the reason           a single failure must not both cause and unprotect a hazard
  hazard analysis      the systematic identification of what can go wrong
  integrity level      derived from risk; determines required architecture
  redundancy and voting  two-out-of-three and similar arrangements
  proof testing        periodic verification that a dormant function still works
  the common deficiency  specification gaps rather than hardware failures
  fail-safe design     the de-energized state is the safe state
  emergency stop       hardwired, independent of software, and it must be
                       verifiable
  supervisory interface  overview, area, and detail hierarchy
  deviation display    show departure from normal rather than raw values
  alarm rationalization  every alarm actionable, prioritized, and unique
  alarm flood          hundreds per hour; results in wholesale ignoring
  historian            time series storage for analysis and incident
                       reconstruction
  commissioning        loop checks, function tests, and documented sign-off
  factory and site acceptance testing  catch what simulation cannot
  the operational reality  the plant runs for decades, the original engineers
                       leave, and the drawings, tags, and comments are what the
                       next person has; producing them well is not overhead, it
                       is the deliverable


mechanical_design

## Materials and Their Properties

Mechanical design selects materials and geometry to carry loads, maintain dimensions, resist the
environment, and be manufacturable at the required cost. The properties that drive selection are few
and it is worth being precise about what each one means, because they are routinely confused in
casual discussion.


mechanical_design

Stiffness and strength are independent properties. Stiffness — the elastic modulus — governs how much
a part deflects under load and is essentially fixed for a given material family, so heat-treating
steel does not make it stiffer. Strength governs when it yields or breaks and varies enormously with
alloy and treatment. A part that flexes too much needs more material or better geometry, not a
stronger alloy, and this distinction resolves a large fraction of the design mistakes made by people
approaching mechanics from other fields.


mechanical_design

Toughness is a third independent property: the energy absorbed before fracture. A material can be
strong and brittle, failing suddenly at high load with no warning, or weaker and tough, deforming
substantially first. For anything that might be dropped, impacted, or overloaded, toughness usually
matters more than peak strength, because the failure mode determines whether the product degrades or
shatters.


mechanical_design

Material properties:
  elastic modulus      stiffness; nearly fixed within a material family
  the common error     treating a stronger alloy as a stiffer one
  yield strength       where permanent deformation begins
  ultimate strength    where it breaks
  toughness            energy absorbed before fracture; independent of strength
  ductile failure      deformation before fracture; gives warning
  brittle failure      sudden, at high load, no warning
  fatigue strength     the stress survivable for many cycles; far below the
                       static strength
  the fatigue reality  most mechanical failures in service are fatigue, not
                       overload
  creep                slow deformation under sustained load; significant for
                       plastics at room temperature
  thermal expansion    dimensional change with temperature; mismatch between
                       joined materials generates stress
  aluminium            light, stiff for its weight, easily machined, conducts heat
  steel                stiff and strong, heavy, and inexpensive
  stainless            corrosion resistance at higher cost and lower machinability
  engineering plastics  cheap in volume, insulating, dimensionally less stable,
                       and each has a distinct chemical and temperature tolerance
  the selection method  identify the governing requirement first, since a
                       material chosen for the wrong property is a common and
                       expensive mistake


mechanical_design

Q: A bracket deflects more than acceptable under load, though it is nowhere near yielding. The
correct response is:
A. Use a higher-strength alloy
B. Change the geometry or the material family — deflection is governed by stiffness, which is
   essentially fixed for a material family, so a stronger alloy of the same metal will deflect
   identically
C. Reduce the load
D. Add a safety factor
Reasoning: Elastic deflection depends on the elastic modulus and the section geometry. Heat treating
or alloying steel changes its strength by large factors and its modulus barely at all. Increasing
the section's moment of inertia, shortening the span, or adding a support are the effective
remedies. Answer: B.


mechanical_design

## Stress, Deflection, and Section Geometry

Simple loading cases cover most practical design and are worth knowing quantitatively. Axial
loading distributes stress over the cross-sectional area. Bending produces stress varying linearly
across the section, maximum at the outer fibres and zero at the neutral axis. Torsion produces shear
stress increasing with radius. Each has a corresponding section property that geometry can be
optimized against.


mechanical_design

Bending is where geometry matters most and the leverage is large. The relevant property is the
second moment of area, which scales with the cube of the depth in the loading direction. Doubling a
beam's depth increases its bending stiffness eightfold while doubling its mass, which is why
structural sections put material far from the neutral axis — the I-beam, the box section, the ribbed
plate. A flat plate stiffened with a few ribs is dramatically stiffer than the same mass distributed
uniformly.


mechanical_design

Stress concentration is the most consequential effect for durability. Any abrupt change in section —
a sharp internal corner, a hole, a notch, a thread root — locally multiplies the stress, often by a
factor of two or three, and fatigue cracks start there. Generous fillet radii at internal corners are
nearly free and are among the highest-value details in a mechanical drawing, and a sharp internal
corner in a part that sees cyclic load is a defect regardless of what the nominal stress calculation
says.


mechanical_design

Stress and geometry:
  axial loading        stress over the cross-sectional area
  bending              stress linear across the section, maximum at the outer
                       fibres
  neutral axis         zero stress; material there contributes little to bending
                       resistance
  second moment of area  the bending section property; scales with depth cubed
  the practical implication  depth is worth far more than width or thickness
  structural sections  material placed far from the neutral axis
  ribbing              stiffening a plate at small mass cost
  torsion              shear increasing with radius; closed sections vastly
                       outperform open ones
  buckling             instability of slender members under compression;
                       independent of strength and governed by geometry and end
                       conditions
  the buckling surprise  a column can fail far below its material's compressive
                       strength
  stress concentration  abrupt section changes multiplying local stress
  fillet radii         generous internal radii; nearly free and highly effective
  the fatigue connection  cracks start at stress concentrations
  safety factor        the ratio of capacity to expected load; chosen by
                       consequence of failure and by confidence in the load
                       estimate, and stating both is more useful than quoting a
                       number


mechanical_design

## Fasteners, Joints, and Tolerances

A bolted joint works by clamping, not by shear on the bolt. Tightening stretches the bolt elastically
and the resulting tension clamps the parts, so the joint carries load through friction between the
clamped faces while the bolt sees a nearly constant tension. This is why preload matters so much: a
properly preloaded joint sees very little cyclic stress in the bolt and survives indefinitely, and
an under-preloaded one lets the parts separate slightly under load, cycling the bolt and failing by
fatigue.


mechanical_design

Thread engagement should be at least one diameter in steel and more in softer materials, because
insufficient engagement strips the female thread rather than breaking the bolt. Threading directly
into aluminium or plastic in a joint that will be disassembled repeatedly is a common design
mistake; threaded inserts solve it cheaply. And locking features exist because vibration loosens
fasteners through transverse micro-motion, not through rotation from vibration directly — which is
why locking compounds and prevailing-torque features work while lock washers largely do not.


mechanical_design

Tolerances specify how much dimensions may vary, and they drive cost steeply. Every tolerance should
be as loose as the function permits, because tight tolerances require better processes, more
inspection, and higher scrap rates. Tolerance stackup — the accumulation of individual variations
across a chain of parts — is what determines whether an assembly fits, and analysing it before
manufacture rather than discovering it afterward is standard practice that is nonetheless skipped
regularly.


mechanical_design

Fasteners and tolerances:
  bolted joints clamp  load carried by friction, not by shear on the bolt
  preload              the bolt tension from tightening
  the fatigue mechanism  insufficient preload allows separation and cycles the
                       bolt
  torque as a proxy    torque relates to preload through friction, which varies
                       widely; it is an imprecise control and the usual one
  thread engagement    at least one diameter in steel, more in soft materials
  threaded inserts     for repeated assembly into soft materials
  loosening mechanism  transverse micro-motion, not rotational vibration
  effective locking    prevailing-torque features, adhesives, and adequate preload
  tolerance            permitted dimensional variation
  the cost relationship  tightening tolerances raises cost steeply
  the design rule      as loose as function permits
  tolerance stackup    accumulated variation across a chain
  worst case versus statistical  worst-case stackup is conservative and
                       statistical is realistic for high volume
  fits                 clearance, transition, and interference; specified by the
                       function of the mating pair
  datum scheme         which surfaces the dimensions reference; an unclear datum
                       scheme makes a drawing ambiguous even when every number is
                       correct


mechanical_design

## Manufacturing Processes and Design for Them

Every process imposes constraints, and designing without knowing them produces parts that are
expensive or impossible to make. Machining removes material and can produce almost any external
geometry, with the constraints being tool access, internal corner radii limited by tool diameter, and
cost proportional to material removed and to setup count. Reducing the number of setups — the
reorientations needed to reach every feature — often saves more than optimizing any individual
operation.


mechanical_design

Injection moulding is the volume process for plastics and its constraints are strict. Wall thickness
must be uniform, because thick sections cool more slowly and shrink, producing sink marks and
warping. Draft angles are required so the part releases from the mould. Undercuts require moving
mould components at substantial cost. Ribs stiffen without thickening walls and must themselves be
thinner than the wall they attach to. These rules are not preferences; violating them produces parts
with visible defects.


mechanical_design

Sheet metal is inexpensive and highly capable within its constraints. Bends require a minimum radius
related to thickness, features must stand clear of bend zones by a minimum distance, and the flat
pattern must account for material stretching at bends. Additive processes remove most geometric
constraints and introduce their own — anisotropic strength along the build direction, surface finish
determined by layer height and orientation, and support requirements on overhangs — and their
economics favour low volume and high complexity, which is the reverse of the traditional processes.


mechanical_design

Manufacturing:
  machining            subtractive; almost any external geometry
  tool access          the primary geometric constraint
  internal corner radii  limited by tool diameter; a sharp internal corner cannot
                       be milled
  setup count          reorientations; often the dominant cost driver
  injection moulding   volume plastics; strict geometric rules
  uniform wall thickness  the first rule; violations cause sink and warp
  draft angle          required for release
  undercuts            moving mould components; expensive
  ribs                 thinner than the wall they stiffen
  sheet metal          inexpensive within its constraints
  bend radius          minimum related to thickness
  bend relief          features must clear the bend zone
  bend allowance       material stretch accounted for in the flat pattern
  casting              complex shapes at volume; draft, uniform sections, and
                       machined datum surfaces where precision is needed
  additive             geometric freedom, anisotropic properties, support
                       requirements
  the economics inversion  additive favours low volume and high complexity
  design for assembly  fewer parts, self-locating features, one direction of
                       assembly, no fixturing required; consistently a larger
                       cost lever than optimizing individual part manufacture


mechanical_design

## Enclosures, Sealing, and Vibration

An enclosure protects the electronics from the environment and often provides the thermal path,
structural support, and user interface simultaneously. Its material and construction follow from
which of those functions dominates, and the conflicts between them — sealing against airflow, thermal
conduction against electrical isolation, access for service against ingress protection — are decided
early and are expensive to revisit.


mechanical_design

Sealing requires a designed gland. A gasket needs a defined compression, achieved by a groove of
controlled depth and a fastener pattern close enough that the flange does not bow between fasteners,
which is the usual cause of leaks in an otherwise correct design. Ingress protection ratings specify
tested resistance to dust and water, and they are tested conditions rather than general guarantees —
a rating for temporary immersion says nothing about sustained pressure or about chemical exposure.


mechanical_design

Vibration and shock are where mechanical and electronic design meet most directly. A circuit board
has a natural frequency determined by its dimensions, thickness, and mounting points, and excitation
near it produces amplified deflection that fatigues solder joints and cracks components. The remedies
are raising the natural frequency by adding mounting points near the centre and supporting heavy
components, or isolating the assembly on mounts tuned well below the excitation. Heavy components on
long leads are the classic failure — the mass at the end of a flexible support is a resonator, and
staking it to the board is the standard and effective fix.


mechanical_design

Enclosures and vibration:
  competing functions  protection, thermal path, structure, interface
  the early decisions  conflicts between them are expensive to revisit
  gasket compression   a groove of controlled depth, not a squeezed pad
  flange bowing        fasteners too far apart; the usual leak cause
  ingress ratings      tested conditions, not general guarantees
  pressure equalization  a vent membrane preventing a sealed enclosure from
                       pumping moisture in as it thermally cycles
  the sealed enclosure surprise  a perfectly sealed box breathes through any
                       imperfection and accumulates condensation
  natural frequency    determined by dimensions, thickness, and mounting
  resonance            excitation near the natural frequency; amplified
                       deflection
  the failure          fatigued solder joints and cracked components
  raising the frequency  mounting points near the centre, supporting heavy parts
  isolation            mounts tuned well below the excitation frequency
  heavy components on leads  a mass on a flexible support; stake them
  connector strain relief  cable movement transmitted to the joint is a leading
                       field failure and is prevented by a fixing point on the
                       cable rather than on the connector
  drop and shock       specified as a pulse; the design question is the peak
                       acceleration transmitted to the most fragile component,
                       which is a chain calculation from the impact through
                       every compliant element between it and that component


microcontrollers

## Microcontroller Architecture

A microcontroller integrates a CPU core, flash for program storage, SRAM for working
memory, and a set of peripherals onto one die. The defining difference from an
application processor is the absence of external DRAM and usually of a memory
management unit: code executes in place from flash, data lives in a few kilobytes to a
few hundred kilobytes of on-chip SRAM, and there is no virtual memory, no process
isolation by default, and no operating system unless you put one there. That
constraint shapes everything downstream — you count bytes, you avoid dynamic
allocation, and a wild pointer corrupts whatever it happens to hit rather than
producing a clean segmentation fault.


microcontrollers

The ARM Cortex-M family dominates the 32-bit space. Cortex-M0 and M0+ are minimal
two- and three-stage pipelines targeting the lowest cost and power, with a reduced
Thumb instruction set and no hardware divide on M0. Cortex-M3 adds hardware divide,
bit-banding, and the full Thumb-2 set. Cortex-M4 adds DSP instructions — single-cycle
multiply-accumulate, SIMD on packed 8- and 16-bit data, saturating arithmetic — and
optionally a single-precision floating-point unit, which is why it is the default for
motor control and audio. Cortex-M7 adds caches, a superscalar pipeline, and
double-precision floating point, running at several hundred megahertz. Cortex-M33
adds TrustZone security extensions. RISC-V cores (the ESP32-C series, various
open-source implementations) now occupy the same niches with an open instruction set.


microcontrollers

Two architectural facts drive most firmware design decisions. First, flash is slower
than the core at high clock speeds, so the flash controller inserts wait states, and
above a threshold frequency the CPU stalls on instruction fetch unless a prefetch
buffer or cache absorbs it — this is why moving a hot interrupt handler into RAM can
measurably reduce latency and jitter. Second, on Cortex-M the entire address space is
memory-mapped, including every peripheral register, so configuring hardware is a
matter of writing to specific addresses, and those addresses must be declared
`volatile` so the compiler does not optimize away reads and writes it believes are
redundant. Omitting `volatile` on a peripheral pointer is a classic bug that
disappears at -O0 and reappears at -O2.


microcontrollers

The Cortex-M memory map, fixed by the architecture:
  0x0000_0000 - 0x1FFF_FFFF   Code       flash, execute here, vector table at base
  0x2000_0000 - 0x3FFF_FFFF   SRAM       data, bit-band region on M3/M4
  0x4000_0000 - 0x5FFF_FFFF   Peripheral vendor peripheral registers
  0x6000_0000 - 0x9FFF_FFFF   External RAM
  0xA000_0000 - 0xDFFF_FFFF   External device
  0xE000_0000 - 0xE00F_FFFF   Private Peripheral Bus: NVIC, SysTick, SCB, debug
  0xE000_E010                 SysTick control and status
  0xE000_E100                 NVIC interrupt set-enable registers
  0xE000_ED08                 VTOR, vector table offset register


microcontrollers

Reset behaviour follows directly from that map. On power-up the core reads the initial
stack pointer from address 0x0000_0000 and the reset vector — the address of the
startup code — from 0x0000_0004, then begins executing. The startup code copies
initialized data from flash to RAM, zeroes the .bss section, optionally configures the
clock tree and external memory, runs C++ static constructors, and calls main. If main
returns there is nowhere to return to, so the startup code traps in an infinite loop.
Understanding this sequence is what lets you debug a board that appears dead before
the first line of your code runs.


microcontrollers

Q: A peripheral status register is polled in a loop and the loop never exits, though a
debugger shows the bit is set. The most likely cause is:
A. The clock to the peripheral is disabled
B. The pointer to the register is not declared volatile
C. The interrupt priority is wrong
D. The flash wait states are misconfigured
Reasoning: The debugger reads the register directly from hardware and sees the true
value, while the compiled loop reads it once, caches it in a register, and spins on
that stale copy — the classic symptom of a missing `volatile`. A disabled peripheral
clock would show the register reading as zero or faulting in the debugger too.
Answer: B.


microcontrollers

## Memory, Linking, and the Build

An embedded binary is divided into sections that the linker script places at specific
addresses. `.text` holds executable code and lives in flash. `.rodata` holds string
literals and const data, also in flash. `.data` holds initialized globals: the values
live in flash but the variables live in RAM, so startup code copies them across.
`.bss` holds zero-initialized globals, occupying RAM but no flash, and startup zeroes
it. The heap grows up from the end of .bss, and the stack grows down from the top of
RAM. When they meet, you have a stack overflow, and on a device with no MMU there is
nothing to catch it — the stack silently overwrites your heap or globals and the
failure manifests somewhere completely unrelated.


microcontrollers

Stack depth is therefore a design parameter to be measured rather than hoped for. The
standard technique is painting: fill the stack region with a known pattern such as
0xDEADBEEF at startup, run the worst-case workload, and inspect how far the pattern
has been eroded. Static analysis tools can compute worst-case stack depth from the
call graph, which is exact for code without recursion or function pointers and is one
reason both are discouraged in safety-critical firmware. On Cortex-M with the memory
protection unit available, placing an unmapped guard region below the stack turns
silent corruption into an immediate, debuggable fault.


microcontrollers

Dynamic allocation is avoided in most production firmware for three reasons: malloc
can fail and much embedded code has no sensible failure path, allocation time is not
bounded which breaks real-time guarantees, and long-running heaps fragment until a
request fails despite sufficient total free memory. The alternatives are static
allocation of everything at compile time, fixed-size block pools where each pool
serves one object size so fragmentation is impossible, and stack allocation for
short-lived buffers. When a heap is genuinely required, it is typically a single
allocation phase during initialization followed by no further allocation.


microcontrollers

A minimal linker script, annotated:
  MEMORY {
    FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 512K
    RAM   (rwx) : ORIGIN = 0x20000000, LENGTH = 128K
  }
  SECTIONS {
    .isr_vector : { KEEP(*(.isr_vector)) } > FLASH
    .text   : { *(.text*) *(.rodata*) } > FLASH
    _sidata = LOADADDR(.data);
    .data   : { _sdata = .; *(.data*) _edata = .; } > RAM AT> FLASH
    .bss    : { _sbss = .; *(.bss*) *(COMMON) _ebss = .; } > RAM
    ._stack : { . = . + 0x1000; } > RAM
  }


microcontrollers

The `KEEP` on the vector table prevents the linker from garbage-collecting a section
nothing appears to reference — the hardware references it, and the linker cannot know
that. The `AT> FLASH` on `.data` is the load-address versus run-address distinction:
the section is stored in flash but linked to run from RAM, and the symbols `_sidata`,
`_sdata`, and `_edata` are what the startup copy loop uses. Getting this wrong
produces a board where global variables have garbage initial values, which is
bewildering until you know where to look.


microcontrollers

Firmware size discipline is mostly about knowing what pulls in bulk. Calling `printf`
with a floating-point conversion links the full formatting machinery and can add 20-40
kilobytes; the newlib-nano variants and dedicated tiny printf implementations exist
for this reason. C++ exceptions and RTTI add both code size and unpredictable timing,
and are conventionally disabled with `-fno-exceptions -fno-rtti`. Building with
`-ffunction-sections -fdata-sections` and linking with `--gc-sections` lets the linker
discard unreferenced functions individually rather than whole object files, typically
recovering a significant fraction. `-Os` optimizes for size and is the usual default;
`arm-none-eabi-size` and a map file tell you where the bytes actually went.


microcontrollers

[user] My STM32 firmware works in debug builds but hangs immediately in release builds.
[assistant] tool_call firmware.build_diff({"target": "stm32f411", "debug": "-Og -g",
"release": "-O2 -DNDEBUG"})
[tool] {"text_bytes": {"debug": 41208, "release": 24960}, "bss_bytes": 18432,
"stack_size": 4096, "ram_total": 131072, "warnings": ["assert() compiled out under
NDEBUG in 3 translation units", "2 volatile-qualified reads removed at -O2"]}
[assistant] Two strong candidates, and both are classic release-only failures.


microcontrollers

The most likely is a missing `volatile`. The build log shows two volatile-qualified
reads eliminated at -O2, which means somewhere you are polling a hardware register or
a variable modified by an interrupt handler through a non-volatile access. At -Og the
compiler re-reads memory each iteration and the code appears to work; at -O2 it hoists
the read out of the loop and you spin forever on a stale value. Audit every peripheral
register pointer and every global shared with an ISR — the latter need `volatile` and,
if wider than a single word or read as a multi-field group, also need interrupt
masking or an atomic access, because `volatile` guarantees the access happens but
guarantees nothing about atomicity.


microcontrollers

The second is that `NDEBUG` compiled out your asserts, and three of them contain side
effects. `assert(init_peripheral() == OK)` is a bug that only bites in release,
because the call itself disappears with the assert. Grep for function calls inside
assert expressions.


microcontrollers

To isolate quickly: build release with `-O2 -UNDEBUG` first. If it works, the problem
is in the asserts. If it still hangs, rebuild with `-O2 -fno-strict-aliasing` — a
third possibility is a type-punned pointer that only breaks once the optimizer trusts
the aliasing rules. Then attach the debugger, break on the hang, and read the program
counter and the fault status registers.


microcontrollers

## Interrupts and Concurrency

An interrupt suspends normal execution to run a handler in response to a hardware
event. On Cortex-M the Nested Vectored Interrupt Controller handles priority
arbitration, automatic stacking of caller-saved registers, and tail-chaining between
back-to-back interrupts without a full unstack-restack cycle. Interrupt latency on
these cores is deterministic and low, around twelve cycles to the first instruction of
the handler, which is what makes them suitable for hard real-time control.


microcontrollers

Priority on Cortex-M is inverted from intuition: lower numerical value means higher
priority, and a higher-priority interrupt preempts a lower-priority handler already in
progress. Priority values are split into preemption bits and sub-priority bits by the
priority grouping configuration, where sub-priority only breaks ties among
simultaneously pending interrupts and does not permit preemption. The number of
implemented priority bits is vendor-specific — typically four, giving sixteen levels,
stored in the upper bits of the byte — so writing priority 1 without shifting sets a
completely different level than intended, a frequent and confusing bug.


microcontrollers

Handlers should be short. The discipline is to do the minimum in the interrupt —
read the hardware register that clears the flag, push the data into a queue, set a
flag — and defer the real work to the main loop or a task. Long handlers block
everything at lower priority and destroy the timing guarantees that motivated using an
interrupt at all. Never block inside an ISR: no delays, no waiting on a semaphore that
another ISR must give, and generally no printf, which is slow, often not reentrant,
and may itself use interrupts.


microcontrollers

Sharing data between an ISR and main code is the core concurrency problem, and
`volatile` alone is insufficient. `volatile` prevents the compiler from caching or
reordering the access, but it provides no atomicity: a 32-bit aligned read or write is
atomic on Cortex-M, but a 64-bit value, a multi-field struct, or a read-modify-write
such as `counter++` is not. The remedies, in order of preference: make the shared
datum a single aligned word and accept that reads and writes are atomic; use a
lock-free single-producer single-consumer ring buffer where the producer only advances
the head and the consumer only the tail; or, as a last resort, briefly disable
interrupts around the critical section, saving and restoring the previous mask rather
than unconditionally re-enabling.


microcontrollers

A critical section done correctly:
  uint32_t primask = __get_PRIMASK();   // save current mask state
  __disable_irq();
  shared_struct.a = x;                  // the indivisible update
  shared_struct.b = y;
  __set_PRIMASK(primask);               // restore, do NOT just __enable_irq()


microcontrollers

The distinction in that last line matters: unconditionally enabling interrupts at the
end of a critical section will enable them even if the caller had deliberately
disabled them, silently breaking nesting. Keep critical sections to a handful of
instructions, because every cycle spent with interrupts disabled adds directly to the
worst-case latency of every interrupt in the system.


microcontrollers

The memory barrier instructions `__DSB()` and `__ISB()` are occasionally necessary
even on a single core. Writes to peripheral registers may be buffered, so a write that
disables an interrupt source may not have taken effect before the next instruction
executes, allowing a spurious interrupt to fire after you believed it was masked. A
`__DSB()` after such a write, and an `__ISB()` after operations that change execution
context such as writing the vector table offset register or reconfiguring the MPU,
prevent this class of race.


microcontrollers

Q: Two interrupts on a Cortex-M have priorities 2 and 5. Interrupt 5 is executing when
interrupt 2 arrives. What happens?
A. Interrupt 2 waits until interrupt 5 completes
B. Interrupt 2 preempts interrupt 5 immediately
C. Both are serviced simultaneously
D. Interrupt 2 is discarded
Reasoning: On Cortex-M, numerically lower priority values are higher priority.
Interrupt 2 outranks interrupt 5, and the NVIC supports nesting, so it preempts the
running handler. Interrupt 5 resumes when 2 completes. The mistake this question
targets is assuming higher numbers mean higher priority. Answer: B.


microcontrollers

Q: A 32-bit counter is incremented in an ISR and read in the main loop. It is declared
volatile. Is this correct?
A. Yes, volatile makes it fully safe
B. Yes for the read, but the increment is a read-modify-write and can be lost if the
   main loop also writes it
C. No, volatile does nothing here
D. Only if the counter is 8-bit
Reasoning: An aligned 32-bit read is atomic on Cortex-M, so the main loop reads a
coherent value, and volatile correctly forces the re-read. The remaining hazard is
that `count++` is load-modify-store; if only the ISR ever writes it, that is safe
because the ISR is not itself preempted by another writer. If the main loop also
modifies it, an interrupt landing mid-sequence loses an update. Answer: B.


microcontrollers

## Serial Protocols

UART is asynchronous point-to-point serial with no clock line, so both ends must agree
on the baud rate in advance and each side resynchronizes on the start bit of every
frame. A frame is a start bit, five to nine data bits, an optional parity bit, and one
or two stop bits — the ubiquitous "8N1" being eight data bits, no parity, one stop bit.
Because the receiver samples using its own clock, accumulated error over a frame must
stay under roughly half a bit period, which in practice means clock mismatch below
about 2%. This is why a device running from an imprecise internal RC oscillator
produces garbage at high baud rates while working fine at 9600, and why UART bootloaders
usually require an external crystal.


microcontrollers

SPI is synchronous, full-duplex, and fast, using four lines: clock, master-out
slave-in, master-in slave-out, and an active-low chip select per peripheral. The master
generates the clock, so there is no baud rate agreement problem and tens of megahertz
is routine. The configuration trap is clock polarity and phase: CPOL sets the idle
level of the clock and CPHA selects whether data is sampled on the leading or trailing
edge, giving four modes. Mode 0 (CPOL 0, CPHA 0) is by far the most common, but
datasheets specify the required mode per device, and a mismatch produces data shifted
by one bit or read at the wrong edge — often appearing as values that are plausible
but consistently wrong, which is harder to diagnose than pure garbage.


microcontrollers

I2C is synchronous, half-duplex, and multi-drop, using only two lines — serial data
and serial clock — both open-drain with pull-up resistors, so any device can hold a
line low and the pull-ups provide the high level. Each device has a 7-bit address
(10-bit addressing exists and is rare), transactions begin with a start condition and
the address plus a read/write bit, and each byte is acknowledged. Standard speeds are
100 kHz, 400 kHz fast mode, and 1 MHz fast mode plus. Pull-up sizing is the recurring
practical issue: too large and the rise time exceeds the specification so edges are
sloppy and communication fails at speed, too small and devices cannot pull the line
low within the specified voltage. Typical values are 4.7 kilohms at 100 kHz and 2.2
kilohms at 400 kHz, adjusted for total bus capacitance, which is the sum of every
device's pin capacitance plus trace capacitance and must stay under 400 picofarads.


microcontrollers

Protocol comparison for board-level interconnect:
  UART   2 wires, async, point-to-point, ~115200 baud typical, no addressing,
         simplest to debug with a scope or logic analyzer
  SPI    4+ wires, sync, full duplex, 10-50 MHz, one chip select per device,
         no acknowledgement so errors are silent
  I2C    2 wires, sync, half duplex, 100k-1M Hz, 7-bit addressing, per-byte ACK,
         open-drain with pull-ups, clock stretching by slow slaves
  CAN    2 wires differential, multi-master, arbitration by message priority,
         robust to noise, automotive and industrial standard
  1-Wire 1 wire plus ground, parasitic power, very slow, sensor niche
  USB    differential pair, host-centric, complex stack, enumeration required


microcontrollers

I2C's failure modes are worth knowing because it fails in ways the other buses do not.
A slave that was reset mid-transaction can hold the data line low indefinitely,
hanging the entire bus; the recovery procedure is to bit-bang up to nine clock pulses
manually to let the slave finish its byte, then issue a stop condition. Clock
stretching, where a slow slave holds the clock low to delay the master, is legal and
some master implementations handle it poorly. And because addressing is only 7 bits
and many sensor families use the same fixed address, two identical sensors cannot share
a bus without an address-select pin or a multiplexer.


microcontrollers

## Timers, PWM, and Analog

A timer is a counter driven by a clock, with a prescaler dividing the input and an
auto-reload value setting the period. When the counter reaches the reload value it
wraps and optionally raises an interrupt. From these primitives come periodic
interrupts, output compare (toggle a pin when the counter matches a value), input
capture (record the counter value when a pin changes, for measuring frequency or pulse
width), and quadrature decoding for rotary encoders.


microcontrollers

Pulse width modulation generates an analog-like average by switching a pin between
full on and full off at fixed frequency, varying the fraction of time spent high — the
duty cycle. It is the standard way to dim LEDs, drive motors, and control heaters,
because switching elements dissipate almost no power in either saturated state, unlike
a linear regulator burning the difference as heat. The frequency choice is governed by
the load: LEDs need above roughly 200 Hz to avoid visible flicker and above 1 kHz to
avoid artifacts on camera, motors typically want 20 kHz to push switching noise above
the audible range, and heaters can run at a fraction of a hertz.


microcontrollers

The arithmetic is simple and worth doing carefully. With a timer clock of f_tim, a
prescaler PSC, and an auto-reload ARR, the PWM frequency is f_tim / ((PSC + 1) *
(ARR + 1)) and the duty resolution is ARR + 1 steps. There is a direct tradeoff:
raising the frequency for a fixed timer clock reduces the number of distinct duty
levels available. At a 84 MHz timer clock, 20 kHz PWM with no prescaling gives ARR =
4199, so about 4,200 steps — over 12 bits of resolution, comfortable. At 1 MHz PWM the
same clock gives only 84 steps, under 7 bits, and the quantization becomes visible in
the controlled quantity.


microcontrollers

Worked timer configuration:
  goal: 20 kHz PWM, 50% duty, timer clock 84 MHz
  choose PSC = 0            -> counter clock = 84 MHz
  ARR = 84e6 / 20e3 - 1     = 4199
  CCR = (ARR + 1) * 0.50    = 2100
  resolution = ARR + 1      = 4200 steps, ~12.0 bits
  check: 84e6 / (1 * 4200)  = 20000 Hz exactly


microcontrollers

Analog-to-digital conversion samples a voltage into a digital code. The successive
approximation converters typical of microcontrollers binary-search the input against a
reference over N clock cycles for N bits, giving 12-bit resolution at up to a few
million samples per second. Resolution is not accuracy: a 12-bit ADC has 4,096 codes,
but integral and differential nonlinearity, reference drift, and noise commonly mean
only nine or ten of those bits are trustworthy. Effective number of bits is the honest
specification.


microcontrollers

Three analog practicalities cause most field problems. Sampling time must be long
enough for the internal sample-and-hold capacitor to charge through the source
impedance; a high-impedance sensor into a short sampling window reads systematically
low, and the fix is either a longer sample time or an op-amp buffer. Aliasing folds
any frequency content above half the sampling rate down into the band of interest and
is not removable afterward, so an analog low-pass filter before the converter is
mandatory rather than optional whenever the signal may contain high-frequency content.
And the reference voltage sets the absolute accuracy of every reading, so an ADC
referenced to a noisy supply rail inherits that noise directly — which is why
precision measurement uses a dedicated reference and why averaging many samples helps
with random noise but does nothing for a systematically wrong reference.


microcontrollers

[user] My 12-bit ADC readings from a thermistor divider jump around by 30 counts and
read about 4% low compared to a multimeter.
[assistant] tool_call adc.diagnose({"bits": 12, "vref": 3.3, "noise_counts": 30,
"source_impedance_ohms": 47000, "sample_cycles": 3, "adc_clock_hz": 21000000})
[tool] {"sample_time_us": 0.143, "required_time_us": 2.1, "settling_ratio": 0.068,
"expected_error_pct": -4.3, "noise_lsb_equivalent_mv": 24, "verdict":
"insufficient_sampling_time"}
[assistant] Both symptoms have the same root cause: your sampling time is about
fifteen times too short for the source impedance.


microcontrollers

At 47 kilohms source impedance the internal sample-and-hold capacitor needs roughly
2.1 microseconds to settle to within half an LSB. You are giving it 0.143
microseconds, so the capacitor never fully charges and every reading lands low — the
predicted error is 4.3%, which matches your measured 4% almost exactly. The jitter has
the same origin: an incompletely settled sample is sensitive to whatever the previous
conversion left on the capacitor, so readings depend on the channel sequence and on
noise in a way a settled sample would not.


microcontrollers

Two fixes, and the first is free. Increase the sampling time in the ADC channel
configuration to the longest setting available — on STM32 that is typically 480 cycles
— which at your 21 MHz ADC clock gives about 23 microseconds, comfortably sufficient.
Verify against the multimeter afterward; the 4% offset should vanish.


microcontrollers

If you need faster conversions than that allows, lower the source impedance instead:
either use smaller resistors in the divider (a 4.7 k / 4.7 k divider instead of 47 k
costs a little more standby current but settles in a tenth the time) or add a
unity-gain op-amp buffer between the divider and the ADC pin. Also add a 100 nF
capacitor from the ADC input to ground, which provides local charge for the
sample-and-hold and low-pass filters the input.


microcontrollers

Once settling is fixed, average 16 samples to knock down the remaining random noise by
a factor of four. That will not correct any reference error, so if absolute accuracy
matters, measure the internal reference channel and calibrate against it.


microcontrollers

## Power Management and Low-Power Design

Battery-powered devices live or die by average current, and average current is
dominated by whatever the device does while nominally idle. A design that draws 20
milliamps active for 10 milliseconds per second and 2 microamps the rest of the time
averages about 202 microamps; the same design failing to enter its low-power state and
idling at 5 milliamps averages 5.2 milliamps, a twenty-five-fold difference in battery
life from a single configuration error. The discipline is to measure current with the
device in each state rather than to reason about it.


microcontrollers

Cortex-M devices offer a ladder of sleep modes. Sleep stops the core clock while
peripherals continue and any interrupt wakes it, with negligible wake latency — this
is what a well-written main loop should enter on every pass with nothing to do, via
the wait-for-interrupt instruction. Stop modes additionally halt most clocks and
optionally the main regulator, retaining SRAM contents, waking on external interrupts
or a low-power timer, with wake latency in microseconds. Standby powers down nearly
everything including SRAM, retaining only a small backup domain and the real-time
clock, with current in the hundreds of nanoamperes and a wake that is effectively a
reset. Choosing among them is a tradeoff between current, retained state, and wake
latency.


microcontrollers

The peripherals, not the core, usually dominate. An unused GPIO left floating as an
input can oscillate around the logic threshold and burn current in the input buffer,
which is why the standard practice is to configure every unused pin as analog input or
as an output driven low. Peripheral clocks are individually gateable and cost current
whenever enabled even if the peripheral is idle. Pull-up resistors on an I2C bus draw
current continuously whenever the bus is held low. An LED at 10 milliamps dwarfs
everything else the microcontroller does. And the voltage regulator's own quiescent
current sets a floor: a regulator with 50 microamps of quiescent draw makes a
2-microampere standby mode irrelevant.


microcontrollers

Low-power checklist:
  enter WFI in the idle loop            never spin-wait
  gate clocks to unused peripherals     RCC enable bits default off, keep them off
  configure unused GPIO as analog       eliminates floating-input current
  use DMA instead of CPU polling        the core sleeps while data moves
  wake on RTC or low-power timer        not a busy-wait or a fast timer tick
  choose a low-Iq regulator             quiescent current sets the floor
  batch radio transmissions             transmit is orders of magnitude costlier
  measure with a current probe          per state, not a datasheet estimate


microcontrollers

Direct memory access deserves emphasis as a power technique as much as a performance
one. A DMA controller moves data between a peripheral and memory without the CPU,
so a block of ADC samples, a UART transmission, or an SPI transfer to a display can
proceed while the core sits in a sleep state, waking only on the transfer-complete
interrupt. Replacing a polling loop with DMA plus sleep frequently cuts the energy per
operation by an order of magnitude, and it simultaneously removes the jitter that
polling introduces into everything else the system is trying to do on time.


microcontrollers

## Real-Time Operating Systems

An RTOS provides preemptive multitasking with priority-based scheduling, so
independent activities can be written as sequential tasks rather than as a hand-woven
state machine in a superloop. The defining property is not speed but determinism: the
highest-priority ready task runs, and the worst-case time from an event to the
corresponding task running is bounded and calculable. FreeRTOS, Zephyr, ThreadX, and
RT-Thread are the common choices on Cortex-M, with kernel footprints from a few
kilobytes upward.


microcontrollers

Each task owns a stack, and that is the main memory cost — a system with twelve tasks
at one kilobyte each has spent twelve kilobytes before any application data. Task
stacks must be sized for the worst case including the interrupt frame, and RTOS stack
overflow checking (writing a known pattern and validating it at each context switch)
catches the common failures at modest cost and should be enabled during development.


microcontrollers

Priority inversion is the classic RTOS hazard: a high-priority task blocks on a mutex
held by a low-priority task, which is itself preempted by an unrelated medium-priority
task, so the high-priority task waits on the medium one indefinitely. This is what
delayed the Mars Pathfinder mission in 1997. The standard remedy is priority
inheritance, where a task holding a mutex temporarily inherits the priority of the
highest-priority task waiting on it, and it is why an RTOS mutex differs from a binary
semaphore — the mutex has an owner and can implement inheritance, the semaphore does
not and cannot.


microcontrollers

Inter-task communication primitives and their proper uses:
  queue                  pass data between tasks; copies by value, thread-safe
  mutex                  mutual exclusion with an owner and priority inheritance
  binary semaphore       signalling from ISR to task; no owner, no inheritance
  counting semaphore     managing a pool of N identical resources
  event group / flags    a task waiting on any or all of several conditions
  stream/message buffer  single-producer single-consumer byte or message stream
  task notification      lightest-weight direct signal, far cheaper than a
                         semaphore when there is exactly one waiting task


microcontrollers

The ISR-safe variants matter and are easy to get wrong. Most RTOS APIs provide
separate functions for calls from interrupt context — in FreeRTOS the `FromISR`
suffix — which do not block and which return a flag indicating whether a higher-priority
task was woken, so the ISR can request a context switch on exit. Calling the ordinary
blocking API from an ISR corrupts the scheduler state, and the resulting failure is
usually delayed and baffling. Equally, the interrupt priority of any ISR that calls
RTOS functions must be at or below the kernel's maximum syscall priority, since the
kernel masks interrupts up to that level to protect its critical sections; an ISR
above it can preempt the kernel mid-update and calls from it are unsafe.


microcontrollers

Whether an RTOS is warranted at all is a real design question. A superloop with
interrupt-driven peripherals is simpler, has no scheduler overhead, uses far less RAM,
and is easier to reason about exhaustively — for a device that reads a sensor,
processes it, and transmits, that is the right architecture. An RTOS earns its cost
when there are several activities with genuinely different timing requirements,
particularly when some must block on I/O for indeterminate periods, or when a
communications stack (TCP/IP, BLE, USB) demands it. Adopting one for a simple device
adds complexity, memory cost, and an entire category of concurrency bugs in exchange
for structure that the application did not need.


motor_drives

## Motor Types and Selection

An electric motor converts electrical energy into mechanical motion through the interaction of
magnetic fields, and the types differ in how those fields are produced and switched. The choice
determines the drive electronics, the control complexity, the sensing requirement, and the
achievable performance, so it is the decision that constrains everything downstream.


motor_drives

Brushed DC motors use mechanical commutation: brushes contacting a rotating commutator switch the
current through the windings as the rotor turns, so the torque remains in one direction without any
electronics. This makes the drive trivially simple — apply voltage and it turns — and it makes the
brushes a wear item that limits life, generates electrical noise, and produces dust. Torque is
proportional to current and speed is proportional to voltage, which makes the control intuitive.


motor_drives

Brushless motors move the commutation into electronics, which eliminates the wear and permits far
higher efficiency, speed, and power density. The cost is that the drive must know the rotor
position to energize the correct windings, which requires either position sensors or an estimation
scheme. Two variants exist and are frequently confused: trapezoidal motors have concentrated
windings and are driven with block commutation, while sinusoidal motors have distributed windings
and are driven with sinusoidal currents, giving smoother torque at the cost of more complex
control.


motor_drives

Stepper motors move in discrete steps determined by the winding energization sequence, which
permits open-loop position control with no feedback at all. This is their entire appeal and their
central weakness: if the load exceeds the available torque, the motor loses steps silently and the
controller's position estimate is wrong with no indication. They also produce full holding current
regardless of load, so they run hot and consume power even when stationary.


motor_drives

Motor types:
  brushed DC           mechanical commutation; simple drive, brush wear, noise
  torque and speed     torque proportional to current, speed to voltage
  brushless DC         electronic commutation; needs rotor position
  trapezoidal BLDC     concentrated windings, block commutation, torque ripple
  PMSM                 sinusoidal windings and drive; smooth torque, more complex
                       control
  induction motor      no rotor magnets; rugged, cheap, and requires slip so the
                       rotor never matches the field speed
  stepper              discrete steps, open loop; loses steps silently under
                       overload
  microstepping        intermediate positions by proportioning phase currents;
                       smoother and does not increase the reliable positioning
                       accuracy proportionally
  servo                a motor with position feedback and closed-loop control; a
                       system rather than a motor type
  linear motor         direct linear force; no transmission backlash, low force
                       density
  torque constant      newton metres per amp; with the back EMF constant, the same
                       number in SI units
  back EMF             voltage generated proportional to speed; limits the
                       achievable speed at a given supply voltage
  thermal limit        continuous torque is limited by heat rather than by
                       magnetics; peak torque can far exceed it briefly


motor_drives

Q: A stepper motor system positions correctly at low speed and accumulates error at high
acceleration. The most likely cause is:
A. Encoder failure
B. The motor is losing steps because the required torque exceeds what is available at that speed,
   and open-loop stepping has no way to detect it
C. Incorrect microstepping
D. Supply voltage too high
Reasoning: A stepper's available torque falls with speed because back EMF opposes the drive
voltage and the winding inductance limits current rise. If the acceleration demands more torque
than is available, the rotor falls behind and steps are lost, with no feedback to indicate it. The
remedies are a gentler acceleration profile, a higher supply voltage to force current faster, a
larger motor, or closed-loop operation. Answer: B.


motor_drives

## Drive Electronics

The power stage converts the supply into controlled current in the motor windings, and the
half-bridge is the fundamental building block: two switches in series across the supply with the
motor connected at their midpoint. Switching the upper device connects the winding to the supply
and the lower connects it to ground, so the average voltage is controlled by the duty ratio.


motor_drives

Three half-bridges form the three-phase inverter that drives brushless and induction motors, and
one or two form the arrangements driving brushed motors — a single half-bridge gives one direction
with braking, and a full bridge of two gives both directions.


motor_drives

The dead time between switching one device off and the other on is what prevents shoot-through,
where both conduct simultaneously and short the supply. It must be long enough for the first
device to turn off fully under all conditions and short enough that the resulting voltage
distortion is tolerable. Too little destroys the devices; too much distorts the output waveform and
degrades low-speed performance, which is why dead-time compensation is implemented in
performance-oriented drives.


motor_drives

Current measurement is required for any torque control and the placement determines what is
measurable. A shunt in each phase gives direct measurement of every phase at the cost of level
shifting from the switching node. A shunt in the low side of each leg is easier to measure and is
valid only while the low-side device conducts, which constrains the timing. A single shunt in the
supply return is cheapest and requires reconstruction of the phase currents from the switching
state, which fails at extreme duty ratios.


motor_drives

Drive electronics:
  half bridge          two switches; duty ratio sets the average voltage
  full bridge          two half bridges; bidirectional
  three-phase inverter  three half bridges; brushless and induction
  dead time            prevents shoot-through; too little destroys, too much
                       distorts
  dead-time compensation  correct the resulting distortion in software
  bootstrap            supplies the high-side gate drive; requires the low side to
                       conduct periodically to recharge, which constrains
                       hundred-percent duty operation
  gate driver          supplies peak current to switch quickly; an underpowered
                       driver raises switching loss quadratically
  shoot-through        both devices conducting; a short across the supply
  current sensing      phase shunts, low-side shunts, or a single supply shunt;
                       each trades cost against what is measurable and when
  regeneration         a decelerating motor returns energy; the supply must absorb
                       it or the bus voltage rises
  brake resistor       dissipates regenerated energy where the supply cannot
                       absorb it; required for high-inertia decelerating loads
  bus capacitance      absorbs switching ripple and regenerated energy; sized for
                       ripple current as much as for capacitance
  PWM frequency        above audibility if noise matters; higher costs switching
                       loss and permits lower current ripple


motor_drives

Regeneration deserves emphasis because it produces a failure that surprises people. A motor
decelerating a load acts as a generator and returns energy to the supply, raising the bus voltage.
A battery absorbs it, a supply with a diode input cannot, and the voltage rises until something
fails — typically the bus capacitors or the switches. Any system decelerating a substantial inertia
from a rectified supply needs either a brake resistor switched in when the bus rises or a control
strategy that limits the deceleration rate, and discovering this after the first hard stop is a
common experience.


motor_drives

## Commutation and Control

Commutation is the sequencing of winding currents to maintain torque as the rotor turns, and its
sophistication determines the torque quality. Six-step or trapezoidal commutation energizes two of
three phases at a time in a sequence determined by the rotor sector, which requires only coarse
position information — three Hall sensors give sixty-degree resolution, which is sufficient. Its
cost is torque ripple, since the torque varies within each sector, producing audible noise and
speed variation at low speed.


motor_drives

Field oriented control drives all three phases with sinusoidal currents whose phase is
continuously matched to the rotor position, which gives smooth torque and the best efficiency. It
works by transforming the three phase currents into a rotating reference frame where they become
two direct-current quantities — one producing torque and one producing flux — which can then be
controlled independently by ordinary regulators. This transformation is what makes the control
tractable, and it requires accurate continuous rotor position rather than sector information.


motor_drives

The control structure is a cascade of nested loops, and the ordering follows from their
bandwidths. The innermost current loop is fastest, running at the switching frequency or a
submultiple, and it regulates torque. The velocity loop is roughly a decade slower and commands
current. The position loop is slower again and commands velocity. Each loop must be substantially
faster than the one enclosing it, or they interact and the system oscillates.


motor_drives

Commutation and control:
  six-step commutation  two phases at a time; coarse position sufficient, torque
                       ripple
  Hall sensors         sixty-degree resolution; enough for six-step
  sinusoidal commutation  smooth torque; needs continuous position
  field oriented control  transform to a rotating frame; independent torque and
                       flux control
  Clarke and Park transforms  three phase to two axis, then to the rotor frame
  direct and quadrature currents  flux-producing and torque-producing
  field weakening      negative direct-axis current reduces the effective flux,
                       permitting speed above the back-EMF limit at reduced torque
  cascaded loops       current inside velocity inside position
  bandwidth separation  each loop roughly a decade faster than the one enclosing
                       it
  feedforward          command the expected current from the desired acceleration;
                       the feedback then corrects only the error, which
                       substantially improves tracking
  anti-windup          on every integrator that can saturate
  torque ripple        from commutation, cogging, and sensor error; audible and
                       visible at low speed
  cogging torque       from magnetic attraction between magnets and stator teeth;
                       present with no current, and reduced by skewing


motor_drives

Feedforward deserves emphasis because it is the single most effective addition to a motion
control loop and is frequently omitted. A feedback-only loop must first observe an error before
correcting it, so it necessarily lags the command. Computing the current required to produce the
commanded acceleration from the known inertia, and adding it directly, means the feedback loop
handles only the discrepancy between the model and reality. Tracking error typically falls by an
order of magnitude, and the addition requires only an inertia estimate.


motor_drives

## Sensing, Motion Profiles, and Transmission

Position sensing determines what control is possible. Hall sensors give sector information
adequate for six-step commutation and inadequate for smooth control. Incremental encoders give
high-resolution relative position and require a homing operation at startup to establish the
absolute reference. Absolute encoders give position immediately at power-on. Resolvers are rugged
analogue devices suited to harsh environments. Sensorless schemes estimate position from the back
EMF or from the winding inductance variation, which works well at speed and poorly or not at all
near zero, where the back EMF vanishes.


motor_drives

Motion profiles determine how a move is executed, and the choice affects the mechanical stress and
the settling behaviour. A trapezoidal velocity profile accelerates at a constant rate, cruises, and
decelerates, which is simple and produces a step change in acceleration at each transition —
infinite jerk, which excites structural resonances and produces audible knocking and vibration. An
S-curve profile limits the rate of change of acceleration, which lengthens the move slightly and
substantially reduces the excitation.


motor_drives

Mechanical transmission couples the motor to the load and its properties dominate the achievable
performance more than the motor's do. A gearbox multiplies torque by the ratio and divides speed,
and it multiplies the reflected inertia by the square of the ratio — which is usually beneficial,
since it makes the motor's own inertia dominant and the load easy to control, and it is why high
reduction systems are not backdrivable.


motor_drives

Sensing, profiles, and transmission:
  Hall sensors         sector information; six-step only
  incremental encoder  high resolution, relative; requires homing
  absolute encoder     position at power-on; single or multi-turn
  resolver             rugged analogue; harsh environments
  sensorless           back EMF or inductance based; fails near zero speed
  quadrature           two channels ninety degrees apart; direction and four times
                       the resolution
  trapezoidal profile  constant acceleration; infinite jerk at the transitions
  S-curve profile      limited jerk; less excitation of resonances
  jerk                 the rate of change of acceleration; what excites structural
                       modes
  gear reduction       multiplies torque, divides speed, multiplies reflected
                       inertia by the ratio squared
  inertia matching     the classical rule of a load-to-motor inertia ratio near
                       one; a guideline rather than an optimum, and ratios far
                       from it work with appropriate control
  backlash             lost motion on reversal; the dominant limit on positioning
                       accuracy in geared systems, and it destabilizes a
                       high-gain loop
  compliance           transmission flexibility; produces a resonance between the
                       motor and load inertias that bounds the achievable
                       bandwidth
  belt drive           compliant and quiet; the compliance sets the resonance
  harmonic drive       high ratio, near-zero backlash, some compliance
  direct drive         no transmission; no backlash, backdrivable, needs a large
                       motor