battery_and_energy_storage

Q: An iron-phosphate pack reports wildly inaccurate state of charge from a voltage lookup table.
The cause is:
A. A faulty voltage sensor
B. The chemistry's discharge curve is nearly flat across most of its usable range, so small
   voltage measurement errors map to very large charge errors; coulomb counting with periodic
   endpoint correction is required instead
C. The pack is defective
D. The table is for the wrong temperature
Reasoning: A flat open-circuit voltage curve makes voltage a poor observable for charge state. The
standard approach is integrating current over time and correcting the accumulated drift at the
steep regions near full and empty, where voltage does become informative. Answer: B.


battery_and_energy_storage

## Charging and Degradation

The standard lithium-ion charge profile has two phases. Constant current brings the cell up to its
voltage limit at a controlled rate; constant voltage then holds at that limit while the current
tapers, and charging terminates when the current falls below a threshold. Most of the capacity
enters during the constant current phase, which is why fast charging to eighty percent is much
quicker than the remaining twenty.


battery_and_energy_storage

Charging outside the safe window causes damage that is often irreversible. Charging below freezing
plates metallic lithium on the anode rather than intercalating it, which permanently reduces
capacity and creates internal short-circuit risk; a correct charger refuses to charge a cold pack
and warms it first if it can. Overcharging drives the cathode beyond its stable range and can
initiate decomposition. Both failures are prevented by the same design principle: the charger
should treat temperature and voltage limits as hard interlocks rather than as advisory.


battery_and_energy_storage

Degradation proceeds through several mechanisms simultaneously, and the practical levers follow
from knowing which dominates. Growth of the interface layer on the anode consumes lithium and is
accelerated by high temperature and by time at high state of charge. Mechanical stress from
repeated expansion drives particle cracking, accelerated by deep cycling and high rates. Storing at
a mid state of charge in a cool place and avoiding both full charge and full discharge in routine
use addresses most of the controllable degradation.


battery_and_energy_storage

Charging and ageing:
  constant current phase  the bulk of the charge
  constant voltage phase  taper; slow and it completes the fill
  termination          current falling below a threshold
  fast charge to eighty  much of the time cost is in the last fifth
  cold charging        plates lithium; permanent damage and a short risk
  the interlock principle  temperature and voltage limits enforced in hardware
                       where possible
  balancing            equalizing cell voltages in a series string
  passive balancing    bleed the high cells through a resistor; simple, wasteful
  active balancing     transfer charge between cells; efficient, complex
  the weakest cell     determines pack capacity in series; balancing addresses
                       drift, not intrinsic mismatch
  interface layer growth  lithium consumed; driven by heat and high charge state
  particle cracking    mechanical; driven by deep cycles and high rates
  the practical levers  cool storage, mid state of charge, shallow cycles,
                       moderate rates
  depth of discharge   shallower cycles yield disproportionately more of them
  the throughput view  total energy delivered over life is often a better metric
                       than cycle count


battery_and_energy_storage

## Battery Management and State Estimation

A battery management system protects the pack, estimates its state, and reports to the system. The
protection function is safety-critical and should be simple, independent, and verifiable: overvoltage,
undervoltage, overcurrent, and over- and under-temperature cutoffs, ideally with a hardware
protection layer that operates even if the microcontroller has failed. Complexity belongs in the
estimation function, not the protection function.


battery_and_energy_storage

State of charge estimation combines two imperfect methods. Coulomb counting integrates current, which
is accurate in the short term and drifts without bound as sensor offset accumulates. Voltage-based
estimation uses the open-circuit voltage relationship, which does not drift but requires the cell to
rest before it is valid and is nearly useless on flat-curve chemistries. A Kalman filter or
equivalent combines them, trusting the integration over short intervals and correcting from voltage
when conditions allow.


battery_and_energy_storage

State of health is harder because the quantity of interest — remaining capacity relative to new —
is only directly measurable by a full discharge, which is rarely acceptable in service. Practical
estimators track internal resistance growth, partial-cycle capacity increments, and voltage
relaxation behaviour, and they are best understood as trended indicators rather than as
measurements. A state-of-health number that moves smoothly and monotonically is more likely to be
heavily filtered than accurate.


battery_and_energy_storage

Battery management:
  protection function  safety-critical; simple, independent, verifiable
  hardware protection  a second layer independent of firmware
  the design rule      complexity in estimation, never in protection
  coulomb counting     accurate short term, unbounded drift
  current sensor offset  the drift source; a small offset integrates to a large
                       error over a day
  open-circuit voltage  no drift, needs rest, useless on flat curves
  Kalman filtering     combining both with a cell model
  equivalent circuit model  resistance plus RC branches; enough for most
                       estimation
  state of health      capacity fade; not directly measurable in service
  resistance tracking  a usable proxy for ageing
  incremental capacity  differential analysis of partial charges; sensitive to
                       degradation mode
  cell-level monitoring  required in series strings; a single pack voltage hides
                       a failing cell entirely
  temperature sensing  multiple points; a pack has thermal gradients and the
                       hottest cell ages fastest
  logging              the data that makes a field failure diagnosable; log
                       current, voltage per cell, and temperature at a rate that
                       captures events rather than averages


battery_and_energy_storage

## Pack Design, Thermal, and Safety

A pack is cells in series for voltage and parallel for capacity, plus interconnects, sensing,
protection, thermal management, and enclosure. The series count sets the voltage and therefore the
insulation, isolation, and safety category; the parallel count sets capacity and the fault current
available, which is frequently underestimated. A modest lithium pack can deliver hundreds of amps
into a short circuit, and every design decision about conductors and fusing follows from that
number.


battery_and_energy_storage

Thermal management is a first-order concern rather than an afterthought. Heat generation scales
with current squared times internal resistance, so high-rate operation heats the pack rapidly.
Elevated temperature accelerates every degradation mechanism, and temperature non-uniformity across
the pack causes cells to age at different rates, which progressively worsens the imbalance the
balancing system is trying to correct. Designing for uniform temperature is as important as
designing for low temperature.


battery_and_energy_storage

Thermal runaway is the failure mode that governs safety design. A cell driven past its stability
limit by overcharge, internal short, mechanical damage, or external heat begins exothermic
decomposition, which raises the temperature, which accelerates the decomposition. Once initiated it
cannot be stopped, so the entire safety strategy is prevention and containment: prevent the
initiating conditions, and design the pack so that one cell in runaway does not propagate to its
neighbours.


battery_and_energy_storage

Pack design and safety:
  series count         sets voltage, insulation, and safety category
  parallel count       sets capacity and available fault current
  fault current        larger than intuition suggests; sizes conductors and fusing
  interconnect resistance  a source of imbalance and localized heating
  fusing               per-cell fusing limits the consequence of a single failure
  contactors           high-voltage disconnect; sequencing and pre-charge matter
  pre-charge           limits inrush into capacitive loads; skipping it welds
                       contactors
  isolation monitoring  detects insulation breakdown before it becomes a hazard
  heat generation      current squared times resistance
  thermal uniformity   as important as absolute temperature; gradients create
                       divergent ageing
  cooling approaches   passive, forced air, liquid, phase change; chosen by heat
                       flux and packaging
  thermal runaway      self-sustaining exothermic decomposition; unstoppable once
                       started
  propagation resistance  spacing, barriers, and venting so one cell does not
                       take the pack
  venting              directed away from occupants and electronics
  transport and regulation  lithium shipment is regulated; certification testing
                       is a schedule item, not a formality


battery_and_energy_storage

## Harvesting and Low-Power Design

Not every system carries a battery sized for its whole life. Energy harvesting extracts power from
the environment — light, vibration, thermal gradient, radio frequency — and the defining
characteristic is that the available power is small, intermittent, and highly variable. A harvesting
design is therefore an energy budget problem rather than a power supply problem, and it needs
storage to buffer between when energy arrives and when it is needed.


battery_and_energy_storage

The power extracted from most harvesters depends strongly on the load impedance, and maximum power
point tracking adjusts the operating point to keep it at the optimum. For a small photovoltaic cell
this can double or triple the harvested energy compared with directly charging a battery, which is
frequently the difference between a design that works and one that does not.


battery_and_energy_storage

Low-power firmware design follows a single principle: the processor should be asleep almost all of
the time. Average current is dominated by whatever runs continuously, so a design with a fifty
microamp sleep current and a brief twenty milliamp active burst is limited by the sleep current
entirely. The corollary is that peripherals left enabled, pins floating, and pull-ups fighting
external drives frequently consume more than the processor itself, and finding them requires
measuring rather than reasoning.


battery_and_energy_storage

Harvesting and low power:
  sources              light, vibration, thermal gradient, radio frequency
  the characteristic   small, intermittent, variable
  energy budget        the correct framing; joules per event, not watts
  storage buffer       supercapacitor for cycling, battery for density
  cold start           harvesting from zero stored energy; needs a dedicated
                       circuit
  maximum power point  the load impedance for peak extraction; tracking it can
                       multiply the yield
  duty cycling         the primary low-power technique
  sleep modes          retention versus wake latency versus current; know which
                       mode retains what
  wake sources         timer, pin, peripheral; the interrupt structure defines the
                       power profile
  average current      dominated by sleep current when the duty cycle is low
  the hidden consumers  enabled peripherals, floating inputs, pull-ups fighting
                       drives, unused regulators
  measurement          a current probe with sufficient dynamic range and
                       bandwidth; microamps and milliamps in one trace is the
                       requirement
  the practical method  measure the current profile of one full cycle, integrate
                       it, and multiply by the event rate; every low-power
                       estimate made without that measurement has been wrong in
                       my experience, usually by more than a factor of two


communication_buses

## Bus Fundamentals

A bus carries data between devices, and the design space is organized by a few orthogonal
choices whose consequences propagate through everything else. Serial transmission sends bits
sequentially over few conductors; parallel sends several simultaneously over many. Parallel was
faster historically and lost decisively as speeds rose, because skew between conductors — the
arrival time differences from unequal trace lengths and unequal propagation — becomes comparable
to the bit period and cannot be economically controlled. Modern high-speed interconnect is
serial, with parallelism achieved by multiple independent serial lanes rather than by
bit-parallel buses.


communication_buses

Synchronous buses transmit a clock alongside the data, so the receiver samples at known instants
and no clock recovery is needed. This is simple and requires a conductor for the clock and limits
the length over which the clock and data remain aligned. Asynchronous buses have no shared clock,
so both ends must agree on the rate in advance and the receiver resynchronizes on each frame's
start bit, which tolerates length and isolation at the cost of requiring clock accuracy on both
sides.


communication_buses

The topology determines how devices share the medium. Point-to-point connects exactly two
devices, which permits the highest speeds because the signal path is controlled and unbranched.
Multi-drop connects several devices to one shared medium, which is economical in conductors and
introduces the problems of arbitration, addressing, and signal integrity from the stubs each
device presents. Daisy chain passes through each device in turn, and a ring returns to the origin.


communication_buses

Bus fundamentals:
  serial               few conductors, sequential bits; wins at high speed
  parallel             many conductors; skew limits the achievable rate
  skew                 arrival time differences between conductors; why parallel
                       buses stopped scaling
  synchronous          a transmitted clock; simple, length-limited
  asynchronous         agreed rate, per-frame resynchronization; tolerates length
  source synchronous   the clock travels with the data over the same path, so
                       skew is common to both
  embedded clock       clock recovered from the data; requires transition density,
                       which is what line coding guarantees
  point to point       highest speed; two devices
  multi-drop           shared medium; needs arbitration and addressing
  master-slave         one initiator; simple and limits responsiveness
  multi-master         several initiators; requires arbitration
  arbitration          who transmits; by priority, by token, or by collision
                       detection
  full duplex          simultaneous both directions
  half duplex          one direction at a time; a shared medium or a shared pair
  single ended         one conductor referenced to ground; simple, noise-prone
  differential         two conductors carrying opposite signals; common-mode noise
                       cancels at the receiver, which is why every long or fast
                       interface is differential


communication_buses

Differential signalling deserves emphasis because it is the single technique making long or fast
links practical. Noise coupling into a cable affects both conductors of a pair nearly equally, and
the receiver responds to the difference between them, so the common-mode noise subtracts out. The
same mechanism rejects ground potential differences between the two ends, which for a
single-ended interface would appear directly as signal error. This is why RS-485, CAN, Ethernet,
USB, and every multi-gigabit interface use differential pairs.


communication_buses

Q: A parallel bus is upgraded from 50 MHz to 400 MHz and becomes unreliable despite adequate
signal quality on each individual line. The most likely cause is:
A. Insufficient drive strength
B. Skew between the conductors is now comparable to the bit period, so bits from one transfer
   arrive spread across the sampling window
C. Crosstalk only
D. Power supply noise
Reasoning: At 400 MHz the bit period is 2.5 nanoseconds, and trace length differences of even a
few centimetres produce delays that are a substantial fraction of that. Each line may look clean
individually while the set does not arrive together. This is why parallel buses stopped scaling
and why high-speed interfaces use independent serial lanes with per-lane clock recovery.
Answer: B.


communication_buses

## Board-Level Buses

The three buses connecting components on a board — UART, SPI, and I2C — cover most embedded
interconnect and differ in ways that determine which suits a given part.


communication_buses

UART is asynchronous point-to-point with no clock, so both ends must be configured to the same
rate and the receiver resynchronizes on each frame's start bit. The accumulated clock error over a
frame must stay under about half a bit period, which bounds the tolerable mismatch at roughly two
percent — which is why a device running from an imprecise internal oscillator communicates
reliably at low rates and produces garbage at high ones. Its simplicity and the ubiquity of
serial terminals make it the default debug interface.


communication_buses

SPI is synchronous, full duplex, and fast, using four lines with a separate chip select per
peripheral. The master provides the clock, so there is no rate agreement problem and tens of
megahertz is routine. Its configuration trap is clock polarity and phase, which together give four
modes, and a mismatch produces data that is shifted or sampled at the wrong edge — frequently
producing plausible but consistently wrong values, which is harder to diagnose than outright
garbage.


communication_buses

I2C is synchronous, half duplex, and multi-drop, using two open-drain lines with pull-up
resistors so any device can hold a line low. Addressing is seven bits, each byte is acknowledged,
and slow devices may stretch the clock by holding it low. The economy of two wires for many
devices is its advantage; the pull-up sizing, the limited bus capacitance, the address collisions
between identical parts, and the bus hang when a device is reset mid-transaction are its
practical costs.


communication_buses

Board-level buses:
  UART                 2 wires, async, point to point; ~2% clock tolerance
  UART use             debug console, GPS modules, simple modules; the default
                       serial interface
  SPI                  4+ wires, sync, full duplex, tens of MHz, one chip select
                       per device
  SPI modes            CPOL and CPHA give four; a mismatch gives plausible wrong
                       data
  SPI weakness         no acknowledgement; errors are silent
  I2C                  2 wires, sync, half duplex, 100k to 1M, 7-bit addressing,
                       per-byte acknowledgement
  pull-up sizing       4.7k at 100 kHz, 2.2k at 400 kHz; adjusted for bus
                       capacitance
  bus capacitance      under 400 pF total; the sum of every device and trace
  clock stretching     a slow device holds the clock low; legal and handled poorly
                       by some masters
  bus hang             a device reset mid-transaction holds the data line low;
                       recover by bit-banging up to nine clocks then a stop
  address collision    identical parts share a fixed address; needs an address pin
                       or a multiplexer
  1-Wire               one conductor plus ground, parasitic power; very slow,
                       sensor niche
  I3C                  the successor to I2C; higher speed, in-band interrupts,
                       dynamic addressing


communication_buses

The I2C bus hang deserves specific attention because it is a failure mode with a specific
recovery and no other. If a peripheral is reset or loses power partway through transmitting a
byte, it may leave the data line held low waiting to complete, and the master cannot issue a start
condition because the bus appears busy. No amount of resetting the master fixes it. The recovery
is to reconfigure the pins as general-purpose outputs and manually clock up to nine pulses,
allowing the peripheral to finish its byte, then issue a stop condition. Implementing this
recovery routine costs little and is the difference between a field failure requiring a power
cycle and one that self-corrects.


communication_buses

## Industrial and Automotive Buses

Industrial and automotive environments impose requirements that board-level buses do not meet:
long cable runs, high electrical noise, safety-relevant reliability, and operation across
temperature extremes for decades.


communication_buses

CAN was designed for automotive use and its arbitration mechanism is elegant. The bus is
differential with a dominant and a recessive state, where dominant overrides recessive, and nodes
transmit their identifier while monitoring the bus. A node transmitting recessive that reads
dominant has lost arbitration and stops, so the message with the numerically lowest identifier
wins without any collision and without retransmission. Arbitration is therefore
non-destructive and priority is inherent in the identifier.


communication_buses

CAN's other characteristic properties follow from its design goals. It is message-oriented rather
than address-oriented — a frame carries an identifier describing its content rather than a
destination, and any node interested receives it, which suits broadcasting sensor values.
Extensive error detection with automatic retransmission handles the electrical environment. And
error confinement progressively disconnects a node producing errors, so a faulty node cannot
disable the bus indefinitely.


communication_buses

RS-485 is a physical layer rather than a protocol, providing differential multi-drop signalling
over long distances — over a kilometre at low rates — with dozens of nodes. Modbus is the protocol
most commonly layered on it and is simple, widely supported, and lacks any security. Industrial
Ethernet variants add determinism to standard Ethernet through scheduling and hardware timestamping,
which is the direction industrial networking has moved.


communication_buses

Industrial and automotive:
  CAN                  differential, multi-master, message oriented, 1 Mbit
                       classic and higher with CAN FD
  dominant and recessive  dominant overrides; the basis of arbitration
  non-destructive arbitration  the lowest identifier wins without collision
  message oriented     identifiers describe content, not destination
  error confinement    a faulty node progressively disconnects itself
  CAN FD               larger payloads and a faster data phase
  LIN                  a cheap single-wire automotive subnetwork for low-speed
                       functions
  FlexRay              deterministic time-triggered automotive; safety-critical
  automotive Ethernet  single twisted pair; the direction vehicle networking is
                       moving as bandwidth demands rise
  RS-485               differential multi-drop physical layer; over a kilometre,
                       dozens of nodes
  termination          required at both ends of a long bus; reflections otherwise
  fail-safe biasing    resistors holding the idle state defined when no driver is
                       active
  Modbus               simple, ubiquitous, and has no security whatsoever
  industrial Ethernet  determinism through scheduling and hardware timestamping
  4-20 mA              analog current loop; noise immune, and a broken wire reads
                       as zero rather than as a valid value, which is why it
                       persists in safety contexts


communication_buses

The 4-20 milliamp current loop deserves mention despite being analog and old, because its design
property is one that digital systems frequently fail to match. The signal is a current rather than
a voltage, so it is immune to voltage drop along the cable and to induced noise. The live zero at
four milliamps means that a broken wire, a failed transmitter, or a lost supply reads as zero
current, which is outside the valid range and is therefore detectable as a fault rather than being
indistinguishable from a legitimate minimum reading. Designing so that a failure produces an
invalid value rather than a plausible one is a principle worth carrying into digital protocol
design.


communication_buses

[user] My CAN bus works on the bench with two nodes and gives constant errors with all eight
nodes connected in the vehicle.
[assistant] tool_call bus.can_diagnose({"nodes": 8, "bus_length_m": 12,
"bitrate_kbps": 500, "termination": "one_end_only", "stub_lengths_cm": [5, 8, 40, 12, 6, 30, 9],
"error_type": "bit_and_form_errors", "bench_config": "2_nodes_short_cable"})
[tool] {"issues": ["single_termination_causes_reflections", "two_long_stubs_exceed_guideline",
"reflections_worse_with_more_nodes_and_length"], "guideline_stub_max_cm": 30,
"recommendation": "terminate_both_ends_and_shorten_stubs"}
[assistant] Two problems, and the termination is almost certainly the dominant one.


communication_buses

You have termination at one end only. A CAN bus needs 120 ohms at each end of the trunk, and with
only one the signal reflects off the unterminated end and returns, arriving during the bit period
and corrupting the sampling. On the bench with two nodes and a short cable the round trip is fast
enough that the reflection settles before the sample point, which is why it works there and not in
the vehicle at twelve metres.


communication_buses

Your stub lengths are the second issue. Two of them are 40 and 30 centimetres, and the guideline
at 500 kbit is under 30. A stub is an unterminated branch, so it produces its own reflection, and
several stubs of significant length compound. Shorten those two, or if the physical layout does
not permit it, reduce the bitrate — at 250 kbit the bit period doubles and the same stubs become
acceptable.


communication_buses

Check three things while you are in there. Confirm you have exactly two 120 ohm terminators
rather than one or several — measure the resistance across the bus with everything powered off,
which should read 60 ohms for two in parallel. Confirm the stubs branch from the trunk rather than
the trunk passing through each node, since a daisy chain through the nodes has no stubs at all and
is the preferred topology. And confirm every node is configured for the same bitrate and sample
point, since a sample point mismatch produces exactly this error pattern and is easy to get wrong
when nodes use different microcontrollers with different bit timing calculations.


communication_buses

One diagnostic that will settle it quickly: put an oscilloscope across the bus and look at the
differential signal during a frame. Reflections appear as steps or ringing on the bit transitions,
and if the waveform is clean the problem is timing rather than signal integrity.


communication_buses

## High-Speed Serial and Wireless

High-speed serial interfaces above roughly a gigabit share a common set of techniques regardless
of the specific standard. Differential pairs with controlled impedance carry the signal. Line
coding guarantees transition density so the receiver can recover a clock from the data itself,
and it balances the direct-current content so the link can be capacitively coupled. Equalization
compensates for the frequency-dependent loss of the channel, at the transmitter by
pre-emphasizing the high frequencies and at the receiver by amplifying them. And a serializer and
deserializer convert between the parallel internal representation and the serial link.


communication_buses

Lane aggregation is how bandwidth scales beyond what one lane provides. Several independent serial
lanes operate in parallel with per-lane clock recovery, and the receiver deskews them using
periodic alignment markers rather than requiring them to arrive together. This is why modern
interfaces are described by a lane count and a per-lane rate, and it is what avoids the skew
problem that killed parallel buses.


communication_buses

Wireless protocols for embedded use trade range, data rate, power, and topology, and the choice
follows from which of those binds. Bluetooth Low Energy suits short-range, low-rate, battery-powered
devices communicating with a phone. Wi-Fi suits high rate with mains power or frequent charging.
Thread and Zigbee provide mesh networking so that range is extended by relaying. And the
low-power wide-area technologies trade data rate for kilometres of range at very low power.


communication_buses

High-speed serial and wireless:
  differential pairs   controlled impedance, matched length within the pair
  line coding          8b/10b, 64b/66b, or scrambling; transition density and DC
                       balance
  clock data recovery  extract the clock from the transitions
  equalization         pre-emphasis at the transmitter, amplification at the
                       receiver
  SerDes               serializer and deserializer
  lane aggregation     independent lanes with per-lane recovery and deskew
  eye diagram          overlaid bit periods; the standard signal quality view, and
                       the eye's opening is the margin
  BER                  bit error rate; the specification, typically 1e-12
  USB                  host-centric, enumeration, wide device class support
  PCIe                 lanes, packet based, the standard internal high-speed
                       interconnect
  Ethernet             ubiquitous, well-tooled, and increasingly used in embedded
                       and automotive
  BLE                  short range, low rate, low power; phone connectivity
  Wi-Fi                high rate, high power; mains or frequent charging
  Thread and Zigbee    mesh; range through relaying
  LoRa and NB-IoT      kilometres at very low rate and very low power
  the choice           determined by which of range, rate, power, and topology
                       binds


communication_buses

## Protocol Design and Debugging

Designing a protocol over any of these buses involves decisions that recur regardless of the
physical layer, and getting them wrong produces systems that work in the lab and fail in the
field.


communication_buses

Framing establishes where a message begins and ends, and the options are a length prefix, a
delimiter with escaping, or a fixed size. A length prefix is efficient and requires the length to
be received correctly, so a corrupted length desynchronizes the stream until some recovery
mechanism intervenes. A delimiter permits resynchronization by scanning for it and requires
escaping the delimiter within the payload. Including both a start delimiter and a length gives
efficient parsing with a resynchronization path.


communication_buses

Error detection must match the error model. A checksum detects random single-bit errors poorly and
is cheap. A cyclic redundancy check detects burst errors of up to its width and is what every
serious protocol uses. A cryptographic authentication code detects deliberate modification, which
a CRC does not — a CRC is an error detection code and provides no protection against an attacker
who can recompute it.


communication_buses

Debugging a bus problem benefits from working in a specific order. Establish that the physical
layer is correct before examining the protocol: check the signal on an oscilloscope for levels,
edges, ringing, and reflections. Then use a logic analyzer with protocol decoding to see the
transactions. Only then examine the application logic. Working the other way — starting with the
software — is how days are spent on a problem that a five-minute oscilloscope check would have
localized.


communication_buses

Protocol design and debugging:
  framing              length prefix, delimiter with escaping, or fixed size
  resynchronization    what happens after a corrupted frame; a length-only
                       protocol has no recovery path
  error detection      CRC for random and burst errors; a checksum is much weaker
  authentication       a CRC provides no protection against deliberate
                       modification
  sequence numbers     detect loss and duplication
  acknowledgement      and a retransmission timeout; and the timeout must exceed
                       the worst-case processing time or spurious retransmissions
                       compound the problem
  idempotency          makes retransmission safe
  versioning           a version field from the first release; retrofitting one is
                       far harder
  endianness           specify it; do not assume both ends match
  alignment and padding  specify the exact wire format rather than casting a
                       struct, since compilers pad differently
  timeouts             on every wait; a protocol that can block forever will
  state machine        write it explicitly, including the error transitions
  oscilloscope first   levels, edges, ringing, reflections
  logic analyzer       protocol decoding; transactions and timing
  bus monitor          a passive third device recording everything; the only way
                       to see what actually crossed the wire when both ends
                       disagree


communication_buses

The struct-casting pitfall deserves the closing emphasis because it is a portability failure that
testing on one platform never reveals. Defining a message as a C structure and transmitting its
bytes directly depends on the compiler's padding, alignment, and byte ordering, all of which differ
between architectures and can change with compiler flags. A protocol between two identical devices
works; the same protocol between a microcontroller and a host application on a different
architecture produces misaligned fields and byte-swapped values. Specifying the wire format
explicitly — field order, size, and byte order — and serializing to it field by field is more code
and is the only approach that survives a platform change.


digital_electronics

## Number Systems and Boolean Logic

Digital systems represent information in discrete levels, almost universally two, which
buys noise immunity: a signal need only be recognizably high or low rather than precisely at
a value, so small disturbances are rejected entirely at each stage rather than accumulating
as they do in analog chains. This regeneration at every gate is why complex digital systems
work at all and why analog signal chains degrade with length.


digital_electronics

Binary representation of signed integers has settled on two's complement for a specific
reason: it allows one adder circuit to handle both addition and subtraction, since
subtracting is adding the negation, and the negation is the bitwise complement plus one. It
also gives a unique representation of zero, unlike sign-magnitude or one's complement, both
of which have distinct positive and negative zeros and require extra logic to handle them.
The asymmetry of the range — one more negative value than positive — is the price, and it
produces the specific edge case that negating the most negative value overflows.


digital_electronics

Fixed-point representation places an implied binary point at a chosen position, giving
integer arithmetic with fractional interpretation. It is fast, exact within its range, and
requires the designer to manage scaling. Floating point trades a fixed absolute precision for
a fixed relative precision across a huge range, at substantially higher hardware cost — which
is why small microcontrollers omit floating-point hardware and why fixed-point implementation
remains standard in signal processing.


digital_electronics

Number representation:
  unsigned n bits      range 0 to 2^n - 1
  two's complement     range -2^(n-1) to 2^(n-1) - 1
  negation             invert all bits and add one
  sign extension       replicate the sign bit when widening
  overflow, signed     detected when the carry into and out of the sign bit differ
  overflow, unsigned   detected by the carry out
  fixed point Qm.n     m integer bits, n fractional; value = raw / 2^n
  BCD                  four bits per decimal digit; wasteful, avoids decimal
                       conversion error in displays and financial contexts
  Gray code            adjacent values differ in one bit; used in encoders so that
                       a transition never produces a spurious intermediate value
  hexadecimal          four bits per digit; the standard notation for bit patterns


digital_electronics

Gray code deserves its mention because it solves a real physical problem. In a binary
absolute encoder, transitioning from 0111 to 1000 requires four bits to change
simultaneously, and they never do — the sensor briefly reads an arbitrary intermediate value
which may be wildly wrong. Gray code guarantees exactly one bit changes per transition, so
any read during a transition returns either the old or the new value and never a spurious
third. The same reasoning applies to crossing clock domains with a multi-bit counter, where
Gray coding is the standard technique.


digital_electronics

Boolean algebra provides the rules for manipulating logic expressions, and De Morgan's laws
are the most used: the complement of a conjunction is the disjunction of complements and vice
versa. Practically, these let any circuit be rewritten in terms of NAND or NOR gates alone,
which matters because those are the natural primitives in CMOS — an inverting gate requires
fewer transistors than a non-inverting one, since the non-inverting version is the inverting
one followed by an inverter.


digital_electronics

Q: A 4-bit two's complement register holds 1000. Its value and the result of negating it are:
A. -8, and negation gives +8
B. -8, and negation overflows, returning -8
C. +8, and negation gives -8
D. -7, and negation gives +7
Reasoning: In 4-bit two's complement, 1000 is -8, the most negative value. Negating gives
invert (0111) plus one (1000), which is -8 again. The range is asymmetric, +8 is not
representable, and this edge case must be handled explicitly in any code performing absolute
value or negation. Answer: B.


digital_electronics

## Combinational Design

A combinational circuit's outputs depend only on its current inputs, with no memory. Design
proceeds from a truth table or a specification to a Boolean expression, which is then
minimized and mapped to gates. Karnaugh maps make minimization visual for up to about five
variables by arranging the truth table so that adjacent cells differ in one variable, making
simplifiable groupings visible as rectangles. Beyond that, algorithmic methods and synthesis
tools take over, and in practice the designer writes behaviour in a hardware description
language and lets synthesis handle minimization.


digital_electronics

The standard building blocks recur constantly and recognizing them shortens design
substantially. A multiplexer selects one of several inputs based on a select code and is the
hardware equivalent of a conditional. A decoder activates one of many outputs from a binary
code. An encoder does the reverse, with the priority variant resolving multiple simultaneous
inputs. Adders chain from full adders, with the ripple-carry version simple and slow because
the carry propagates serially, and carry-lookahead computing carries in parallel at the cost
of more logic — the classic area-versus-speed tradeoff.


digital_electronics

Combinational blocks:
  multiplexer        2^n inputs to 1 output under n select lines
  demultiplexer      1 to 2^n
  decoder            n-bit code to one-hot output
  priority encoder   resolves multiple asserted inputs by priority
  comparator         equality and magnitude
  full adder         sum and carry from three inputs
  ripple carry       simple, delay proportional to width
  carry lookahead    parallel carry computation; faster, more logic
  barrel shifter     arbitrary shift in one operation; a multiplexer tree
  ALU                arithmetic and logic under an operation select
  ROM as logic       any truth table implemented as a lookup; the principle behind
                     FPGA lookup tables
  don't care         unspecified outputs; exploit them for minimization


digital_electronics

Hazards are transient incorrect outputs arising from unequal propagation delays along
different paths, and they matter whenever a combinational output feeds something
edge-sensitive or asynchronous. A static hazard produces a brief glitch on an output that
should have remained constant; a dynamic hazard produces multiple transitions where one was
expected. They are eliminated by adding redundant terms that cover the transitions, or
avoided architecturally by registering outputs so that only the settled value is sampled —
which is why synchronous design is standard and why combinational outputs driving asynchronous
resets or clock inputs are a design review flag.


digital_electronics

## Sequential Logic and Timing

Sequential circuits have memory, so outputs depend on input history. The storage primitive is
the flip-flop, which captures its input on a clock edge and holds it until the next. The
latch, by contrast, is level-sensitive and transparent while its enable is asserted, which
makes it harder to reason about and is why edge-triggered flip-flops dominate synchronous
design.


digital_electronics

Timing constraints determine whether a design works at a given clock frequency. Setup time
requires the data input to be stable for some interval before the clock edge; hold time
requires it to remain stable for some interval after. A setup violation means the data
arrived too late and is fixed by slowing the clock or shortening the logic path. A hold
violation means the data arrived too early, changing before the flip-flop captured the
previous value, and it cannot be fixed by slowing the clock — it requires adding delay to the
path, which is why hold violations are more serious and are usually caught by the tools
inserting buffers.


digital_electronics

Maximum clock frequency follows from the longest combinational path between registers, the
critical path. The period must exceed the clock-to-output delay of the source register plus
the combinational delay plus the setup time of the destination register plus clock skew.
Pipelining raises throughput by inserting registers to break long paths into shorter stages,
increasing latency in cycles while raising the achievable frequency, which for
throughput-oriented designs is the correct trade.


digital_electronics

Sequential design and timing:
  D flip-flop        captures D on the clock edge; the standard element
  setup time         data stable before the edge; violation fixed by slowing the
                     clock
  hold time          data stable after the edge; violation needs added delay, not
                     a slower clock
  clock-to-Q         propagation delay from edge to output
  critical path      the longest register-to-register path; sets maximum frequency
  clock skew         arrival-time difference between registers; helps setup on one
                     path and hurts hold
  pipelining         more stages, higher frequency, higher latency
  metastability      a violated setup or hold can leave the output between levels
                     for an unbounded time
  synchronizer       two or more flip-flops in series to resolve metastability
                     probabilistically; mean time between failures grows
                     exponentially with stages
  FSM                Moore outputs depend on state only; Mealy on state and input,
                     giving faster response and combinational output paths
  one-hot encoding   one flip-flop per state; more registers, less decode logic,
                     often faster in an FPGA


digital_electronics

Clock domain crossing is where sequential designs most often fail in ways that are
intermittent and maddening to debug. A signal generated in one clock domain and sampled in
another can violate setup or hold on the receiving flip-flop, driving it metastable, and a
metastable output may resolve to either level or hover between them for an unbounded time. A
two-flip-flop synchronizer reduces the probability of an unresolved metastable state
propagating to a level that is negligible over any realistic operating life, and it works
only for a single-bit signal. Multi-bit values crossing domains need a handshake, an
asynchronous FIFO with Gray-coded pointers, or another structural mechanism, because
synchronizing each bit independently allows different bits to be captured on different cycles
and produces values that were never present at the source.


digital_electronics

[user] My FPGA design passes simulation but fails intermittently in hardware, roughly once
every few hours.
[assistant] tool_call fpga.diagnose({"simulation": "pass", "hardware": "intermittent",
"mtbf_hours": 3, "clock_domains": 3, "cdc_paths": 14, "synchronizers_found": 6,
"timing_met": true, "async_resets": true, "reset_synchronized": false})
[tool] {"likely_cause": "clock_domain_crossing", "unsynchronized_cdc_paths": 8,
"secondary": "async_reset_release_not_synchronized",
"note": "simulation_does_not_model_metastability"}
[assistant] Clock domain crossing, almost certainly. This has the exact signature: passes
simulation, fails randomly in hardware at long intervals, timing analysis clean.


digital_electronics

Simulation cannot find this. A simulator evaluates events at discrete times with idealized
zero-width setup and hold windows, so a signal crossing domains is captured cleanly every
time. Real flip-flops go metastable when their setup or hold is violated, and the probability
per crossing is low but nonzero — which is exactly why the failure interval is hours rather
than seconds.


digital_electronics

You have 14 crossing paths and 6 synchronizers, so 8 paths are unsynchronized. Find them
with a clock domain crossing report from your tool — most synthesis flows will generate one,
and there are lint tools specifically for this. For each path:


digital_electronics

Single-bit control signals need a two-flip-flop synchronizer in the destination domain. If the
pulse is shorter than a destination clock period it can be missed entirely, so a level signal
with handshake, or a pulse stretcher, is needed rather than a bare synchronizer.


digital_electronics

Multi-bit data must not be synchronized bit by bit. Each bit resolves independently, so
different bits can land on different cycles and the receiver sees a value that never existed
at the source. Use an asynchronous FIFO with Gray-coded pointers, or a handshake where the
source holds data stable and asserts a request, the destination synchronizes only the request
and then samples the already-stable data.


digital_electronics

Your asynchronous resets are the second issue and cause a similar class of failure. Asserting
a reset asynchronously is fine; releasing it asynchronously is not, because the release can
occur close to a clock edge and different flip-flops will exit reset on different cycles. Use
a reset synchronizer — assert asynchronously, release synchronously — one per clock domain.


digital_electronics

Once fixed, the failure should disappear entirely rather than becoming rarer. If it becomes
rarer but persists, there is another crossing path that was missed.


digital_electronics

## Memory and Logic Families

Memory technologies differ in volatility, density, speed, and endurance, and the choices
follow from the application. Static RAM stores each bit in a cross-coupled latch, is fast,
requires no refresh, and costs six transistors per bit, which makes it dense enough only for
caches and small on-chip memories. Dynamic RAM stores each bit as charge on a capacitor,
requires periodic refresh because the charge leaks, and costs roughly one transistor per bit,
which makes it the technology for main memory. Flash stores charge on a floating gate,
retains it without power, and wears out after a finite number of erase cycles.


digital_electronics

Flash endurance and its consequences are worth understanding because they shape system
design. NOR flash allows random read access and is used for code execution in place; NAND
flash is denser, reads and writes in pages and erases in larger blocks, and is used for bulk
storage. Both wear, with endurance from a hundred thousand cycles for single-level cells down
to a few thousand for multi-level cells, and both require wear levelling to spread erase
cycles across the device rather than concentrating them where a naive file system would.


digital_electronics

Logic families define the voltage levels, speed, and drive characteristics of gates. CMOS
dominates because its static power consumption is essentially zero — current flows only
during transitions — so power scales with switching activity and frequency rather than being
constant. This is why dynamic power in CMOS is proportional to capacitance times voltage
squared times frequency, and why reducing supply voltage is the most effective power
reduction available, since the dependence is quadratic.


digital_electronics

Memory and logic characteristics:
  SRAM              fast, no refresh, 6T per bit, volatile; caches
  DRAM              dense, needs refresh, 1T1C, volatile; main memory
  NOR flash         random read, execute in place, slower write; code storage
  NAND flash        page read/write, block erase, dense; bulk storage
  EEPROM            byte-erasable, limited endurance; configuration
  FRAM / MRAM       non-volatile with RAM-like endurance and speed; niche and
                    growing
  CMOS dynamic power P = C V^2 f;  voltage scaling is quadratic
  static power       leakage, increasingly significant at small process nodes
  logic levels       3.3 V and 1.8 V dominate; level shifting needed between
  open drain         requires a pull-up; permits wired-AND and bidirectional buses
  fan-out            how many inputs one output can drive
  propagation delay  rises with load capacitance


digital_electronics

## Signal Integrity, Buses, and Debug

At the edge rates of modern digital signals, interconnect must be treated as a transmission
line rather than as an ideal wire. The threshold is not the clock frequency but the edge rate:
if the propagation delay along a trace exceeds roughly a sixth of the signal's rise time, the
trace behaves as a transmission line and reflections matter. A 1 nanosecond edge on a
FR4 board reaches that threshold at about 25 millimetres, which means most traces on a
modern board qualify regardless of the nominal clock rate.


digital_electronics

Reflections occur wherever the impedance changes — at a stub, at a via, at an unterminated
end, at a connector. They produce overshoot, undershoot, and ringing that can exceed device
absolute maximum ratings and can cause double clocking when the ringing crosses the input
threshold repeatedly. Termination matches the impedance and absorbs the reflection: series
termination at the source is the common choice for point-to-point signals, and parallel
termination at the far end suits multi-drop buses at higher static power cost.


digital_electronics

Crosstalk is coupling between adjacent traces through mutual capacitance and inductance, and
it scales with the coupled length and inversely with separation. The standard mitigation is
spacing — a separation of three times the trace width reduces coupling substantially — plus
maintaining a continuous reference plane so that return currents flow directly beneath their
signals rather than detouring and coupling into neighbours.


digital_electronics

Signal integrity and debug:
  transmission line     when propagation delay exceeds ~1/6 of the rise time
  characteristic Z      set by geometry and dielectric; 50 ohm single-ended,
                        90-100 ohm differential are the conventions
  reflection            from any impedance discontinuity
  series termination    a resistor at the source summing with the driver impedance
  parallel termination  at the receiver; better for multi-drop, more static power
  crosstalk             reduce by spacing and by a continuous reference plane
  return path           follows the signal beneath it at high frequency; a split
                        plane under a trace forces a large loop
  ground bounce         simultaneous switching outputs disturbing the local
                        reference
  decoupling            local charge reservoirs; loop inductance matters more than
                        capacitance value
  differential signaling  common-mode rejection and lower emissions; the standard
                        above a few hundred megahertz
  logic analyzer        many channels, digital thresholds; for protocol and timing
  oscilloscope          analog detail; the only tool that shows signal integrity
  JTAG                  boundary scan and debug access
  built-in self test    on-chip pattern generation and checking


digital_electronics

The instrument choice deserves a closing note because it determines what can be seen. A logic
analyzer applies a threshold and reports ones and zeros, so a signal ringing violently around
the threshold appears as clean data or as inexplicable extra transitions, with no indication
of why. An oscilloscope shows the actual waveform and is the only way to diagnose overshoot,
slow edges, insufficient drive, and reflections. The standard sequence when a digital signal
misbehaves is to look at it on an oscilloscope with adequate bandwidth and a short-ground
probe connection first, because a signal that looks wrong analogically will never be explained
by more digital capture.


digital_signal_processing

## Sampling and Quantization

The Nyquist-Shannon sampling theorem states that a signal band-limited to B hertz is
perfectly reconstructible from samples taken at any rate above 2B. The theorem is exact
and its conditions are the part that matters in practice: the signal must be genuinely
band-limited, which no real signal is, and reconstruction requires an ideal sinc
interpolation of infinite extent, which no real system implements.


digital_signal_processing

Aliasing is what happens when the condition fails. Frequency components above half the
sampling rate fold back into the band as lower frequencies, indistinguishable from
genuine content once sampled. A 3 kHz tone sampled at 5 kHz appears as a 2 kHz tone, and
no amount of subsequent processing can separate them, because the information
distinguishing them was destroyed at the moment of sampling. This is why an analog
anti-aliasing filter before the converter is mandatory rather than optional: it is the
only place the fold-back can be prevented.


digital_signal_processing

Practical anti-alias filtering forces oversampling. A real analog filter has a finite
transition band, so a filter that passes 20 kHz and must reject 20 kHz-plus content
before folding cannot be built with a sharp enough skirt at a 44.1 kHz sample rate
without extreme order and terrible phase behaviour. The standard solution is to sample
well above Nyquist, use a gentle analog filter, and perform the sharp band-limiting
digitally where filters can be made arbitrarily steep with linear phase, then decimate.
This is why audio converters run at megahertz rates internally and output at 48 kHz.


digital_signal_processing

Sampling and quantization reference:
  Nyquist rate            f_s > 2B for a signal band-limited to B
  aliased frequency       |f - round(f/f_s) * f_s|
  quantization SNR        SNR_dB ≈ 6.02 N + 1.76 for N bits, full-scale sine
  effective bits          ENOB = (SNR_dB - 1.76) / 6.02;  what you actually get
  dynamic range           ratio of largest to smallest representable signal
  oversampling gain       2x oversampling then decimation gains 3 dB (0.5 bit)
  dither                  adds ~1 LSB of noise before quantization; decorrelates
                          quantization error from the signal, trading distortion
                          for benign noise
  noise shaping           pushes quantization noise out of the band of interest;
                          the basis of sigma-delta conversion


digital_signal_processing

The 6 dB per bit rule is the most useful number in the subject. Each additional bit
doubles the number of quantization levels, halving the error, which is a 6 dB
improvement in signal-to-noise ratio. A 12-bit converter has a theoretical 74 dB SNR, a
16-bit one 98 dB, a 24-bit one 146 dB — though the last is fictional, since no analog
front end has a noise floor that low, and real 24-bit converters deliver perhaps 20
effective bits. Always ask for ENOB rather than nominal resolution.


digital_signal_processing

Dither is counterintuitive and correct: deliberately adding noise improves the result.
Without it, quantization error is deterministically related to the signal, producing
harmonic distortion — a quiet sine wave quantized coarsely becomes a stepped waveform
with audible harmonics. Adding about one LSB of random noise before quantization
decorrelates the error, converting structured distortion into a flat noise floor that is
far less objectionable and, crucially, allows signals below the quantization step to
remain audible through the noise.


digital_signal_processing

Q: A signal containing energy at 7 kHz is sampled at 10 kHz with no anti-alias filter.
The 7 kHz component appears in the sampled data at:
A. 7 kHz   B. 3 kHz   C. 5 kHz   D. It is removed
Reasoning: Nyquist is 5 kHz. The component folds to |7 - 10| = 3 kHz. It is now
indistinguishable from genuine 3 kHz content and cannot be removed afterward, which is
precisely why the anti-alias filter must precede the sampler. Answer: B.


digital_signal_processing

## The Fourier Transform and Spectral Analysis

The Fourier transform decomposes a signal into sinusoidal components, and the discrete
Fourier transform does so for a finite sampled sequence. The fast Fourier transform is
an algorithm computing the DFT in O(N log N) rather than O(N^2) by recursively
exploiting symmetry — a change that turned spectral analysis from a research computation
into a real-time operation and is one of the most consequential algorithms ever devised.


digital_signal_processing

Interpreting a DFT requires knowing what its bins mean. An N-point DFT of a signal
sampled at f_s produces N bins spaced f_s/N apart, spanning zero to f_s. Bins above
N/2 correspond to negative frequencies and, for real input, are the complex conjugate
mirror of the lower half, carrying no additional information. Frequency resolution is
f_s/N and therefore depends only on the total observation duration, not on the sample
rate — observing for one second gives 1 Hz resolution whether sampled at 8 kHz or 8 MHz.
This is the fundamental time-frequency tradeoff, and it is why distinguishing two closely
spaced tones requires a long observation regardless of how fast you sample.


digital_signal_processing

Spectral leakage arises because the DFT implicitly assumes the finite record repeats
periodically. If the signal does not complete an integer number of cycles within the
window, the assumed periodic extension has a discontinuity at the boundary, and that
discontinuity spreads energy across all bins. A pure sine wave at a bin-centre frequency
produces one nonzero bin; the same sine offset by half a bin spreads across the whole
spectrum with a slowly decaying skirt that can bury weaker nearby components entirely.


digital_signal_processing

Windowing controls leakage by tapering the record to zero at both ends, removing the
discontinuity at the cost of widening the main lobe. Every window trades main-lobe width
against sidelobe level, and the choice depends on what the analysis must distinguish.


digital_signal_processing

Window functions:
  rectangular (none)   narrowest main lobe (2 bins), worst sidelobes (-13 dB);
                       correct only when the signal is exactly periodic in the window
  Hann                 4-bin main lobe, -31 dB sidelobes, fast -18 dB/octave rolloff;
                       the sensible general-purpose default
  Hamming              4-bin, -43 dB first sidelobe, slower rolloff
  Blackman             6-bin, -58 dB; use when a weak tone sits near a strong one
  Blackman-Harris      8-bin, -92 dB; extreme dynamic range applications
  flat-top             very wide main lobe, near-exact amplitude accuracy; use for
                       calibration where amplitude matters more than resolution
  Kaiser               parameterized family trading the two continuously


digital_signal_processing

Coherent gain and noise bandwidth corrections matter when the DFT is used for
measurement rather than display. A window attenuates the signal, so amplitude readings
must be scaled by the reciprocal of its coherent gain, and noise power estimates must
account for the window's equivalent noise bandwidth, which exceeds one bin. Omitting
these gives readings that are systematically low by several decibels, a common error in
homemade spectrum analyzers.


digital_signal_processing

The spectrogram extends spectral analysis to non-stationary signals by computing DFTs
over successive overlapping windows. Its resolution is governed by the same uncertainty
tradeoff: a short window localizes events in time and blurs them in frequency, a long
window does the reverse, and no choice does both. Overlapping windows by 50% or 75%
recovers information lost to the window taper and is standard. Wavelet transforms address
the same problem with a basis whose time-frequency tiling varies with scale, giving fine
time resolution at high frequency and fine frequency resolution at low — a better match
to how most natural signals are structured.


digital_signal_processing

## Digital Filters

A filter modifies a signal's frequency content. Digital filters divide into two families
with entirely different characteristics, and the choice between them is the first design
decision.


digital_signal_processing

Finite impulse response filters compute each output as a weighted sum of a finite number
of past inputs. They are unconditionally stable, since there is no feedback, and they can
be made exactly linear phase by choosing symmetric coefficients — meaning all frequencies
are delayed equally so the waveform shape is preserved, which matters enormously for
data communications, for medical waveforms, and for any application where the shape
rather than the spectrum carries the information. The cost is order: achieving a sharp
transition requires many taps, and the computational load and latency scale with that
count.


digital_signal_processing

Infinite impulse response filters include feedback, so the impulse response never fully
decays. They achieve a given frequency response with far fewer coefficients — often an
order of magnitude fewer than an equivalent FIR — which makes them attractive on
constrained hardware. The costs are that they can be unstable if poles move outside the
unit circle, that they have nonlinear phase which distorts waveform shape, and that they
are sensitive to coefficient quantization, especially at high order where a small
coefficient error can move a pole across the stability boundary.


digital_signal_processing

Filter design and structure:
  FIR design methods    windowed sinc (simple, suboptimal), Parks-McClellan
                        (equiripple, optimal for a given order), least squares,
                        frequency sampling
  IIR design methods    analog prototype plus bilinear transform; Butterworth
                        (maximally flat), Chebyshev I (passband ripple, sharper),
                        Chebyshev II (stopband ripple), elliptic (both, sharpest),
                        Bessel (maximally flat group delay)
  FIR order estimate    N ≈ (attenuation_dB - 8) / (2.285 * transition_width_rad)
  IIR implementation    cascade of second-order sections, never direct-form high
                        order — coefficient sensitivity makes high-order direct
                        forms unusable in fixed point
  group delay           FIR linear phase gives constant (N-1)/2 samples;
                        IIR varies with frequency
  minimum phase         non-symmetric FIR with lower delay for the same magnitude
                        response, when linear phase is not required


digital_signal_processing

The second-order-section rule is not a stylistic preference. A tenth-order IIR filter
implemented as a single direct-form structure has coefficients whose relationship to the
pole locations is extremely ill-conditioned; quantizing them to 16 bits can move poles
enough to destabilize the filter entirely. Factoring into five cascaded biquads makes
each section's coefficients directly related to a conjugate pole pair, so quantization
error moves each pole slightly rather than catastrophically. Every serious filter library
outputs second-order sections for this reason.


digital_signal_processing

Multirate processing changes the sample rate within a system and is often the largest
available efficiency gain. Decimation reduces the rate, requiring a low-pass filter first
to prevent aliasing; interpolation raises it by inserting zeros and filtering to remove
the resulting spectral images. Polyphase decomposition exploits the fact that in
decimation most filter outputs are discarded and in interpolation most inputs are zero,
restructuring the computation to avoid the wasted multiplies — a saving equal to the rate
change factor. A cascaded integrator-comb filter performs large rate changes with no
multipliers at all, using only adders and delays, which is why it is ubiquitous in the
front end of sigma-delta converters and software radios.


digital_signal_processing

[user] I need a 60 Hz notch on an ECG signal sampled at 500 Hz, but a simple notch is
distorting the QRS complexes.
[assistant] tool_call dsp.filter_design({"type": "notch", "f0": 60, "fs": 500,
"application": "ecg", "current": {"design": "iir_biquad", "q": 35},
"signal_bandwidth": [0.5, 40]})
[tool] {"current_group_delay_ms_at_qrs": 18.4, "group_delay_variation_ms": 14.2,
"ringing_duration_ms": 62, "qrs_duration_ms": 90, "recommendation":
"linear_phase_fir_or_notch_outside_band", "note": "60hz_above_diagnostic_band"}
[assistant] The distortion is phase, not magnitude — your IIR notch has 14 ms of group
delay variation across the QRS band, so different frequency components of the complex
arrive at different times and the shape smears. A high-Q IIR notch also rings for about
62 ms after a sharp transient, which is comparable to the 90 ms QRS duration itself.


digital_signal_processing

Two good options, and I would take the first.


digital_signal_processing

Your diagnostic band is 0.5 to 40 Hz and the interference is at 60 Hz — they do not
overlap. So you do not need a notch at all; you need a low-pass at 40 Hz. A linear-phase
FIR low-pass removes the 60 Hz entirely along with everything else above the diagnostic
band, and being linear phase it delays every component equally, preserving morphology
exactly. At 500 Hz sampling with a 40 Hz passband and 60 Hz stopband, an order of about
100 taps gives you 40 dB of rejection, which is 100 ms of constant delay — fine for
offline analysis, and correctable by compensating the known constant offset for
real-time display.


digital_signal_processing

If you must keep content above 40 Hz, use a linear-phase FIR notch instead of the
biquad. Higher order, but constant group delay so the QRS shape survives.


digital_signal_processing

A third technique worth knowing for mains interference specifically: adaptive
cancellation. Since 60 Hz is a known, nearly stationary frequency, you can estimate its
amplitude and phase over a window and subtract a synthesized sinusoid. This removes the
interference with essentially no effect on the signal band at all, and it tracks slow
drift in the mains frequency. It is more code than a filter but it is the cleanest
result.


digital_signal_processing

One thing to check regardless: if the 60 Hz is large enough to need aggressive removal,
look at the source. Better electrode preparation, shorter leads, driven-right-leg
circuitry, and proper shielding usually reduce mains pickup by 20-40 dB, which is more
than any filter buys you and costs no signal fidelity.


digital_signal_processing

## Fixed-Point Arithmetic

Embedded DSP frequently runs without a floating-point unit, so arithmetic uses integers
with an implied binary point. Q notation specifies the format: Q15 means one sign bit and
15 fractional bits in a 16-bit word, representing values in [-1, 1). Q31 is the 32-bit
equivalent. The representable range and the resolution are traded directly — every bit
moved from the fractional side to the integer side doubles the range and halves the
precision.


digital_signal_processing

Multiplication in Q format requires a shift. Multiplying two Q15 numbers yields a Q30
result in a 32-bit accumulator, which must be shifted left by one and taken from the high
half to return to Q15. Getting this wrong by one bit is a factor-of-two error that is
easy to introduce and easy to miss when the algorithm still roughly works. Many DSP
cores provide a fractional multiply mode performing the shift in hardware, which is worth
using precisely because it removes this error class.


digital_signal_processing

Overflow is the central hazard. Fixed-point addition of two full-scale values overflows,
and the behaviour on overflow determines whether the result is merely wrong or
catastrophic. Wraparound turns a large positive into a large negative, producing a
full-scale discontinuity — in audio, a loud click; in control, a violent transient.
Saturating arithmetic clamps to the maximum instead, which is a graceful degradation and
is why DSP instruction sets provide saturating add and multiply-accumulate instructions.
Use them.


digital_signal_processing

Fixed-point practice:
  Q15 range           [-1, 0.999969];  resolution 2^-15 ≈ 3.05e-5
  Q31 range           [-1, ~1);  resolution 2^-31 ≈ 4.66e-10
  multiply Q15 x Q15  32-bit product in Q30; shift left 1, take high 16 for Q15
  accumulate          use a wide accumulator (40-bit on many DSPs) with guard bits
                      so intermediate sums cannot overflow
  headroom            scale inputs down by the filter's gain so the output cannot
                      exceed full scale; the sum of |coefficients| bounds it
  saturation          prefer saturating instructions over wraparound
  rounding            round-to-nearest rather than truncation; truncation biases
                      results toward zero and that bias accumulates in feedback
  coefficient scaling normalize filter coefficients and track the scale separately


digital_signal_processing

Limit cycles are a fixed-point-specific pathology in IIR filters. Quantization inside the
feedback loop can sustain a small oscillation that never decays, so a filter given zero
input produces a persistent low-level output — audible as a tone in audio applications.
Increasing the internal word length, using round-to-nearest instead of truncation, and
adding a small dither to the feedback path all suppress it. It is a good example of a
problem that does not exist in the floating-point design and appears only in
implementation, which is why fixed-point implementations must be verified against the
reference rather than assumed equivalent.


digital_signal_processing

## Adaptive Filtering and Applications

An adaptive filter adjusts its own coefficients to minimize an error signal, learning the
correct response rather than having it designed in. The least mean squares algorithm is
the workhorse: it updates each coefficient by a step size times the error times the
corresponding input sample, which is stochastic gradient descent on the mean squared
error. Its appeal is extreme simplicity — one multiply-accumulate per coefficient per
sample — and robustness.


digital_signal_processing

Step size governs the fundamental tradeoff. Large steps adapt quickly and settle to a
noisier solution; small steps converge slowly to a more accurate one. Stability requires
the step size to be below a bound inversely proportional to the input power, which is why
normalized LMS divides by the current input energy — it makes the effective step size
independent of signal level, so a filter tuned on quiet input does not diverge when the
input gets loud. Recursive least squares converges far faster by maintaining an estimate
of the input correlation matrix inverse, at O(N^2) cost per sample instead of O(N) and
with numerical stability concerns that require care in fixed point.


digital_signal_processing

The four canonical adaptive configurations differ only in what is connected where, and
recognizing which one a problem is helps enormously. System identification places the
adaptive filter in parallel with an unknown system and drives both with the same input,
so the filter converges to a model of the system. Inverse modelling places it in series
and drives it toward reproducing a delayed input, so it converges to the system's
inverse — this is channel equalization. Noise cancellation subtracts a filtered version
of a reference noise input from a corrupted signal, requiring only that the reference
correlate with the noise and not with the signal. Linear prediction drives the filter to
predict the next sample from previous ones, and the prediction error is the innovation —
the basis of speech coding and of many compression schemes.


digital_signal_processing

Adaptive filter applications:
  echo cancellation      model the acoustic or hybrid echo path and subtract it;
                         the path changes when anyone moves, so adaptation must be
                         continuous
  active noise control   generate an anti-phase signal; limited by the acoustic
                         delay budget, which is why it works well for low-frequency
                         steady noise and poorly for transients
  channel equalization   invert the distortion of a communications channel
  adaptive beamforming   steer a null toward an interferer using a sensor array
  line enhancement       extract a narrowband signal from broadband noise
  biomedical             remove maternal ECG from fetal recordings, remove EOG
                         artifacts from EEG


digital_signal_processing

The practical constraint that governs adaptive systems is the correlation requirement. A
noise canceller needs a reference input containing the noise and none of the desired
signal; if the reference picks up any of the signal, the adaptation cancels part of the
signal too, and the result is a filter that quietly removes what you wanted to keep.
This is the most common failure in deployed adaptive cancellation, and the diagnostic is
to check whether the output degrades when the desired signal is present but the
interference is not.


digital_signal_processing

Embedded implementation brings its own constraints that shape algorithm choice. Memory
bandwidth often dominates over arithmetic, so a filter structure touching fewer
coefficients wins even at equal multiply count. Circular buffers avoid the cost of
shifting a delay line, and DSP cores provide modulo addressing to index them without
branches. Single-instruction multiple-data extensions on ARM Cortex-M4 and above process
several 16-bit samples per instruction, typically giving a two-to-fourfold speedup on
filter inner loops, and the CMSIS-DSP library provides tuned implementations that should
be preferred over hand-written loops. And the deepest optimization is usually algorithmic:
running the filter at a lower sample rate through decimation, or moving a convolution to
the frequency domain via FFT when the filter is long enough that N log N beats N^2 —
which for FIR filters happens somewhere around 64 taps, depending on the platform.


embedded_security

## Threat Models for Physical Devices

Embedded security differs from server security in one decisive respect: the attacker may have
physical possession of the device. Every assumption that holds when an attacker can only send
packets fails when they can desolder a chip, probe a bus, glitch a supply rail, or read a memory
directly. Designing without stating which of these are in scope produces protections that address
the wrong adversary.


embedded_security

The threat model should specify the attacker's access, capability, and motivation. A remote
attacker sends network traffic. A local attacker has the device on a bench with an oscilloscope
and a soldering iron. A well-resourced attacker has decapsulation equipment, a focused ion beam,
and the ability to read memory directly. And an attacker in the supply chain can modify the device
before it ever reaches the user. Each requires different defences and the costs differ by orders
of magnitude.


embedded_security

The motivation determines what protection is proportionate. An attacker extracting a shared
firmware signing key compromises every device of that model, so the value justifies substantial
effort and the protection must be correspondingly strong. An attacker extracting one device's
data compromises one device, and per-device keys are what limit the blast radius. This
distinction — whether a compromise scales — is the most useful question in prioritizing embedded
security work.


embedded_security

Threat model dimensions:
  remote attacker      network traffic only; the server security model
  local attacker       physical access; probing, glitching, chip removal
  invasive attacker    decapsulation, microprobing, focused ion beam; expensive
                       and available
  supply chain         modification before delivery; the hardest to detect
  insider              legitimate access misused
  does the compromise scale  a shared key compromises everything; a per-device key
                       compromises one device
  per-device keys      the single most effective architectural decision for
                       limiting blast radius
  asset identification  what actually needs protecting; frequently the firmware's
                       intellectual property, the user's data, and the ability to
                       impersonate the device, which need different protections
  security by obscurity  obfuscation raises cost and is not a foundation; assume
                       the design is known
  cost proportionality  protection should exceed the asset's value to the attacker
                       and not the defender's budget


embedded_security

Q: A product line uses one firmware signing key across all devices, and an attacker extracts it
from a single unit. The consequence is:
A. That unit is compromised
B. Every device of that model can be given attacker-signed firmware, so the compromise scales to
   the entire fleet
C. Only future devices are affected
D. Nothing, since the firmware is still signed
Reasoning: A shared secret means a single extraction compromises everything protected by it. This
is why signing keys belong in a hardware security module never present on the device, why devices
should hold only public keys for verification, and why per-device keys are used wherever a secret
must live on the device at all. Answer: B.


embedded_security

## Secure Boot and Root of Trust

Secure boot establishes that only authorized code runs, and it works by chaining trust from an
immutable starting point. A boot ROM that cannot be modified verifies the signature of the next
stage before executing it, that stage verifies the following one, and so on. The chain's security
rests entirely on the first link being genuinely immutable and on every stage verifying before
transferring control.


embedded_security

The root of trust is that immutable starting point plus the key material it uses. The public key
or its hash must be stored where it cannot be altered — mask ROM, one-time programmable fuses, or
write-protected flash with the protection irrevocably set. If an attacker can change the trusted
key, the entire chain is defeated regardless of how carefully the signatures are checked.


embedded_security

The distinction between secure boot and measured boot is worth keeping precise. Secure boot
refuses to execute code failing verification, which enforces a policy locally. Measured boot
records a hash of each stage into a tamper-resistant register and permits execution regardless,
so a remote party can later verify what actually ran through attestation. The two serve different
purposes and are frequently combined: local enforcement plus remote verification.


embedded_security

Secure boot and trust:
  chain of trust       each stage verifies the next before executing it
  root of trust        immutable code plus immutable key material
  immutable storage    mask ROM, OTP fuses, irrevocably locked flash
  verify before execute  the ordering is the whole security property
  secure boot          refuse to run unverified code
  measured boot        record what ran; enables remote attestation
  attestation          prove to a remote party what the device is running
  anti-rollback        a monotonic counter preventing downgrade to a version with
                       known vulnerabilities; without it, patching is defeated by
                       reinstalling the old firmware
  debug interface      JTAG and SWD must be disabled or authenticated in
                       production; an open debug port defeats everything above it
  lifecycle state      the device's stage from manufacturing through production to
                       decommissioned; transitions must be one-way
  secure element       a separate tamper-resistant chip for keys and crypto
  TEE                  a trusted execution environment isolated from the main
                       operating system; smaller attack surface, and it is not
                       equivalent to a separate chip


embedded_security

Anti-rollback protection deserves emphasis because its absence quietly defeats the entire
patching process. An attacker who can install an older signed firmware version installs one with a
known and published vulnerability, which is signed and therefore passes secure boot. A monotonic
counter incremented on each security-relevant release, checked at boot, prevents this — and it
must be genuinely monotonic and stored where it cannot be reset, which typically means fuses or a
dedicated counter in a secure element. Implementing secure boot without rollback protection is a
common and consequential gap.


embedded_security

## Key Storage and Cryptographic Implementation

Keys are the highest-value asset in most embedded systems and the hardest to protect on a device
an attacker holds. The ordering of storage options by strength is clear and the choice is
frequently made by cost rather than by threat model.


embedded_security

Keys in plain flash are readable by anyone who can dump the flash, which requires only a
programmer and an unlocked device. Keys encrypted in flash require the decryption key to be
somewhere, so the problem is relocated rather than solved unless that key is in hardware. Keys in
one-time programmable fuses, readable only by a hardware crypto engine and never exposed to
software, are substantially stronger. Keys in a secure element or a dedicated security chip,
generated on-chip and never leaving it, are stronger still, and the operations using them are
performed inside the chip so the key never exists outside it.


embedded_security

Physical unclonable functions derive a key from manufacturing variation rather than storing one.
Tiny random differences between nominally identical circuits produce a device-specific response
that is stable enough to reconstruct a key with error correction, and the key exists only while
powered — so there is nothing to read when the device is off. The technique is elegant and its
reliability across temperature and ageing requires careful engineering.


embedded_security

Cryptographic implementation on constrained devices has failure modes that the algorithm choice
does not address. Random number generation is the most common: a device with no good entropy
source at first boot generates predictable keys, and this has produced fleets of devices sharing
keys because they all seeded from the same initial state. A hardware random number generator with
proper health testing is the answer, and using a software pseudorandom generator seeded from a
device identifier is a recurring and severe failure.


embedded_security

Keys and crypto implementation:
  plain flash          readable with a programmer; not protection
  encrypted flash      relocates the problem unless the wrapping key is in hardware
  OTP fuses            hardware-only access via a crypto engine; substantially
                       stronger
  secure element       on-chip generation, never exported; the strongest common
                       option
  PUF                  derived from manufacturing variation; nothing stored to read
  key hierarchy        a device root key deriving purpose-specific keys; limits
                       what any one compromise yields
  key diversification  per-device keys derived from a master held only in the
                       factory HSM
  entropy at first boot  the classic failure; devices generating predictable keys
                       from an inadequate seed
  hardware RNG         with health tests; software PRNGs seeded from identifiers
                       are a severe and recurring failure
  constant time        cryptographic comparisons and operations must not branch on
                       secret data
  memcmp on a MAC      the canonical timing leak; returns early on the first
                       differing byte, revealing the correct value one byte at a
                       time
  nonce reuse          catastrophic in AES-GCM; must survive reboots, backups, and
                       cloning
  hardware acceleration  use the crypto engine; it is faster and typically
                       constant-time by construction
  do not implement crypto  use a vetted library; the failure modes are invisible
                       in testing


embedded_security

The constant-time requirement deserves elaboration because it is a correctness property that
ordinary testing cannot detect. A comparison that returns as soon as bytes differ takes a duration
depending on how many leading bytes matched, so an attacker submitting candidate values and
measuring the response time learns the correct value one byte at a time — turning an
exponential search into a linear one. The code is functionally correct, passes every test, and
leaks the secret. The remedy is comparing in constant time, which every cryptographic library
provides and which must actually be used.


embedded_security

[user] Our IoT device stores its TLS client certificate private key in internal flash with the
readout protection bit set. Is that adequate?
[assistant] tool_call sec.key_storage_audit({"storage": "internal_flash",
"protection": "readout_protection_level_1", "key_type": "tls_client_private",
"per_device": false, "mcu_family": "generic_cortex_m", "threat_model": "device_in_field"})
[tool] {"issues": ["shared_key_across_fleet", "rdp_level1_bypassable_by_glitching",
"key_in_flash_readable_after_bypass", "no_key_hierarchy"],
"known_attacks": ["voltage_glitch_rdp_downgrade", "cold_boot_ram_extraction"],
"recommendation": "per_device_keys_plus_secure_element_or_at_minimum_rdp_level2"}
[assistant] Two problems, and the first is more serious than the storage question.


embedded_security

The key is shared across the fleet. That means a single successful extraction from any device —
one bought on a marketplace, one recovered from a bin, one belonging to a curious owner — yields a
key that impersonates every device you have shipped. Whatever the storage strength, the value of
extracting it is the entire fleet rather than one unit, which justifies far more attacker effort
than you have budgeted against. Per-device keys, derived in the factory from a master held in a
hardware security module, is the change that matters most, and it also lets you revoke a single
compromised device rather than the whole product line.


embedded_security

On the storage: readout protection level 1 is not sufficient against a local attacker. It is
routinely bypassed by voltage or clock glitching during the boot sequence — the technique is
published, the equipment costs a few hundred pounds, and it is within reach of a hobbyist. Level 2
is substantially stronger because it permanently disables the debug interface, and the tradeoff is
that it also prevents your own debugging and field diagnostics, so it needs to be a deliberate
lifecycle decision rather than an afterthought.


embedded_security

The stronger option is a secure element. The key is generated on-chip, never leaves it, and the
TLS handshake's private key operation is performed inside the chip, so the key does not exist in
your microcontroller's memory at any point. This defeats both flash extraction and memory
scraping, and the parts cost around a dollar. For a device whose compromise matters, it is the
right answer.


embedded_security

Three things worth checking while you are here. Confirm the key is not also present in RAM longer
than necessary, since a cold boot or a debug halt can recover it. Confirm your provisioning
process does not log or transmit the key anywhere. And check whether the same key material is used
for both device identity and any firmware verification, since separating those means a compromise
of one does not yield the other.


embedded_security

## Physical and Side-Channel Attacks

Side-channel attacks recover secrets from a device's physical behaviour rather than from its
outputs. The device computes correctly and its power consumption, timing, electromagnetic
emission, or acoustic output varies with the data being processed, so an observer learns
something the interface does not expose.


embedded_security

Power analysis is the most developed. Simple power analysis reads a single trace and can reveal
the sequence of operations, which for a naive exponentiation implementation shows the key bits
directly because the square and multiply operations look different. Differential power analysis
correlates many traces with hypothesized intermediate values and extracts keys from
implementations where no single trace is informative, which makes it effective against
implementations that look adequate. Correlation power analysis refines this and is the standard
technique.


embedded_security

Fault injection perturbs the device to induce an error the attacker can exploit. A voltage
glitch, a clock glitch, an electromagnetic pulse, or a laser pulse causes an instruction to be
skipped or a value to be corrupted, and skipping a single comparison instruction can bypass a
signature check entirely. Some fault attacks are more subtle: a single faulty computation in an
RSA signature permits factoring the modulus from the correct and faulty outputs together.


embedded_security

Physical attacks:
  simple power analysis  a single trace; reveals operation sequences
  differential power analysis  many traces correlated with hypotheses; extracts
                       keys from implementations that look fine
  correlation power analysis  the refined standard technique
  electromagnetic analysis  the same, without electrical contact and with spatial
                       resolution
  timing attacks       execution duration varying with secret data
  cache timing         applicable where a cache exists
  voltage glitch       skip instructions or corrupt values
  clock glitch         the same via the clock
  EM fault injection   localized, no contact
  laser fault injection  precise, requires decapsulation
  differential fault analysis  compare correct and faulty outputs; a single fault
                       can break RSA
  countermeasures      masking randomizes intermediates, hiding equalizes the
                       signal, redundant computation detects faults, sensors
                       detect glitching conditions
  masking              split secrets into random shares so no intermediate
                       correlates with the secret; the principled defence
  random delays        raise the trace count needed; alignment techniques reduce
                       the benefit
  invasive attacks     decapsulation, microprobing, circuit editing; expensive and
                       available to a determined attacker
  tamper detection     meshes, sensors, and zeroization on detection


embedded_security

The instruction-skip fault deserves emphasis because it is so simple and so effective against
naive code. A signature verification ending with a conditional branch on a comparison result can
be defeated by glitching the processor at exactly that instruction, skipping the branch and
proceeding as though verification succeeded. The countermeasures are structural: perform the
check twice with different code paths, use a non-trivial success value rather than a boolean so
that a skipped instruction does not produce success, introduce random delays so the timing cannot
be predicted, and add a redundant check after the sensitive operation has begun.


embedded_security

## Firmware Update, Lifecycle, and Supply Chain

Firmware update is a security requirement rather than a feature, because vulnerabilities will be
found and a device that cannot be patched accumulates them for its service life. It is also an
attack surface of the first order, since the update mechanism by definition can replace all the
device's code.


embedded_security

A secure update requires several properties together. The image must be authenticated so that
only the vendor's firmware is accepted, which means signature verification against a key in the
root of trust. It must be versioned with rollback prevention. The update must be atomic, so that
an interruption leaves the device with a working image — dual-bank flash with an atomic pointer
switch, or a recovery image that cannot be overwritten. And the process must be resilient to
power loss at any point, which is the requirement that most implementations get wrong.


embedded_security

Encryption of the image is a separate question from authentication and protects different things.
Authentication prevents an attacker's firmware from running. Encryption prevents an observer from
reading the firmware, which protects intellectual property and makes vulnerability discovery
harder. The second is worth doing and is not a substitute for the first, and confusing them
produces designs that are encrypted and unauthenticated, where an attacker who obtains the
decryption key can also produce accepted images.


embedded_security

Update, lifecycle, and supply chain:
  authenticate         signature verified against a key in the root of trust
  version and rollback  monotonic counter; otherwise patching is defeated
  atomic update        dual bank or recovery image; survives interruption
  power loss resilience  at every point; the most commonly inadequate property
  encryption           protects the image's contents; not a substitute for
                       authentication
  delta updates        bandwidth savings; the patch application must be as robust
                       as a full update
  staged rollout       limit the blast radius of a bad update; the update
                       mechanism is itself a fleet-wide risk
  provisioning         inject unique identity and keys in a controlled facility;
                       the point where the fleet's security is established
  lifecycle states     manufacturing, provisioned, production, decommissioned;
                       transitions one-way
  debug lockout        before shipping; an open port defeats everything
  decommissioning      erase keys and data; a resold or discarded device with
                       intact credentials is a fleet exposure
  counterfeit parts    a substantial supply chain problem; authentication of
                       components where it matters
  hardware trojan      malicious modification during fabrication; extremely
                       difficult to detect and to defend against
  SBOM                 a bill of materials for firmware; required to know whether
                       a disclosed vulnerability affects the product
  vulnerability disclosure  a stated process; researchers will find issues and the
                       question is whether the report reaches someone who acts


embedded_security

The software bill of materials deserves the closing emphasis because it addresses a practical
problem most embedded organizations cannot currently answer. When a vulnerability is disclosed in
a widely used component — a TLS library, a networking stack, a compression routine — the immediate
question is which products contain the affected version. Without a recorded inventory of every
component and version in each firmware release, answering requires an audit per product, which
takes weeks during which the exposure is unknown. Generating the inventory automatically at build
time and retaining it per release converts that question into a database query, and it is
becoming a regulatory requirement in several jurisdictions rather than merely good practice.


fpga_and_hdl

FPGA Design and Hardware Description Languages

## FPGA Architecture

A field-programmable gate array is an array of configurable logic connected by a
programmable interconnect, so the same silicon can implement arbitrary digital circuits by
loading a configuration. This is a fundamentally different computational model from a
processor: rather than sequencing instructions through fixed hardware, the hardware itself is
shaped to the problem, and computation is spatial rather than temporal.


fpga_and_hdl

The basic logic element is a lookup table with an associated flip-flop. A lookup table with n
inputs stores the truth table of any n-input Boolean function, so a 6-input lookup table
implements any of the 2^64 possible functions of six variables by loading the appropriate
memory contents. Grouping several of these with carry chains, wide multiplexers, and
flip-flops gives the configurable logic block that synthesis targets.