← Back
Home › Systems › Energy, industry and public infrastructure

solar-inverter

Converts the direct current of a solar array into alternating current in step with the utility grid, safely and unattended for years, and reports its status through monitoring.

SMA, SolarEdge, Enphase

Open the solar-inverter pagesolar-inverter Maximum power point trackingcontrol: Hunt the PV maximum power point by perturb-and-observe or incremental conductance adjusting the operating voltageHdr histogramdata-structures: Log-linear bucketed histograms with bounded relative error for latency percentilesDeterministic simulationtestingdistributed: Run the whole system in one thread under a seeded scheduler with simulated network, disk and clock, so every failure replays from its seed.›Primary-backup replicationdistributed: One node orders all writes and ships them to standbys; the acknowledgement rule (none, one, all) sets what a crash loses, and an external arbiter decides who takes over.›A/B partition updatesembedded: Two bootable slots and a small atomic metadata block: write the new image to the idle slot, try it once, and fall back by itself unless it reports healthy.›Anti islanding detectionembedded: Detect loss of grid with passive voltage/frequency windows and active frequency or impedance shift, then trip within required timeCan bus framingembedded: CAN / CAN FD frames, bitwise arbitration, bit stuffing, CRC and error confinementDma transfersembedded: DMA controllers: descriptors, circular buffers, cache coherence for zero-CPU data movementDroop controlembedded: Frequency/voltage droop: proportional power response that lets inverters share load without communicationFault detection isolationrecoveryembedded: Monitor/response tables, fault isolation and safe-mode recovery hierarchies for autonomous systemsFixed-rate control loopembedded: Run a controller at an exact period using absolute deadlines and a fixed dt, so jitter never accumulates and the math stays valid.›Gate drive desat protectionembedded: Detect IGBT/MOSFET short circuit by watching Vce/Vds while on (desaturation), blank briefly, then soft turn-off and latch a faultModbus protocolembedded: Modbus RTU/TCP registers and function codes with polling and CRCPWM generationembedded: A timer's counter, period and compare registers draw the pulse train; preload, dead time and DMA make duty changes glitch-free, shoot-through-free and cheap.›Rms power metering dspembedded: Sample voltage and current to compute RMS, active/reactive power and energy accumulationSafety-critical codingstandardsembedded: Which rule sets (MISRA C, CERT C, JPL Power of Ten, Rust lint subsets) apply when software must not fail, what they forbid, and how to enforce them in CI.›Safety monitor architectureembedded: Independent doer/checker safety monitor that forces a safe state when the main channel misbehavesWatchdog timerembedded: A hardware down-counter that resets the chip unless software proves, in time and in a plausible pattern, that it is still healthy.›Deterministic fixed-point mathgame-networking: Bit-identical simulation math across CPUs, compilers and builds: integer fixed-point formats, the float traps (FMA, x87, fast-math, libm), deterministic trig, sqrt and RNG.›Interrupt handlinghardware-os: How a device signal reaches a CPU handler through an interrupt controller and vector table, and how top/bottom halves, polling switch-over and coalescing keep load bounded.›Process supervisionhardware-os: A parent process starts services, reaps their exits and restarts them under a delay and burst-limit policy, then stops them with SIGTERM before SIGKILL.›Mqtt protocolnetworking: MQTT pub/sub: topics, QoS 0/1/2, retained messages, sessions and keepalivePID controllerrobotics: Drive a measured value to a setpoint with three terms on the error: proportional, integral, derivative. The default feedback loop for motors, heaters, drones and gimbals.›Coverage-guided fuzzingsecurity: Mutate inputs, run an instrumented target, and keep any input that reaches a new code edge; feedback turns blind guessing into incremental search.›Mutual TLSsecurity: TLS where the client also proves a certificate key, so every connection carries a verified, rotatable machine identity.›IIR and FIR filterssignal-processing: Two ways to shape a sampled signal's spectrum: FIR (finite taps, always stable, exact linear phase) or IIR (feedback, a few coefficients, cheap but phase-distorting).›Phase-locked loop (digital)signal-processing: Feedback loop that locks a local oscillator to the phase and frequency of an input tone; the core of carrier recovery, clock recovery and GNSS tracking.›Point-in-time recoverystorage: Periodic base backups plus a continuously archived change log let you rebuild the state as of any instant, then branch from there.›Graceful drainingsystems: On a termination signal, stop taking new work, finish in-flight work until a deadline, tell clients to reconnect elsewhere, then exit; clients resume from a token.›Cooperative schedulingconcurrency: Green threads/coroutines yielding at await points on a user-space schedulerFault injectiondistributed: Inject latency, errors, kills and partitions via proxies, netem or hooksRecord replaydistributed: Record every nondeterministic input (time, randomness, I/O, model and tool outputs, per-tick player input) and re-execute deterministically for debugging, replays and state rebuildLeasesdistributed: A lock that expires on its own: bounded-time ownership that survives crashes and partitions, given bounded clock drift and fencing tokens on writes.›Health checkingsystems: Decide per backend whether to route to it using probes and real-traffic errors, with consecutive-count hysteresis, capped ejection and a panic fallback.›Binary delta diffcompression: Bsdiff, VCDIFF and xdelta-style binary patches between file versionsCRC32C checksumshardware-os: The Castagnoli CRC-32 with dedicated instructions on x86 (SSE4.2) and ARMv8. It is the standard fast integrity check for storage blocks, logs and network frames.›Secure boot chainsecurity: Each boot stage verifies the signature of the next before running it, anchored in an immutable ROM key hash, with version counters against downgrade and a TPM log of what ran.›Signed update metadata (TUF)security: Separate signing roles with thresholds sign small metadata pinning file hashes, versions and expiry, so clients detect rollback, freeze and mix-and-match and recover by rotating the root.›Hierarchical state machinesystems: Nest states so a substate inherits its parent's reactions and only overrides what differs, with ordered entry and exit actions along the path.›Redundancy votingembedded: N-modular redundancy and MooN voting (2oo3, TMR) with discrepancy detectionPRNGs (PCG, xoshiro)numerics: Small, fast, statistically strong non-cryptographic generators: PCG32 and xoshiro256**, with seeding, parallel streams and unbiased ranges.›+ 12 moreTransparent interceptionnetworking: Redirect traffic to a local proxy (iptables TPROXY/REDIRECT, eBPF) without app changesSyscall interceptionsecurity: Intercept syscalls via ptrace, seccomp user notify or a user-space kernelFencing tokensdistributed: A number that grows with every lock grant and is checked by the protected resource, so a paused ex-holder's late write is rejected.›Delta encodingcompression: Store differences between consecutive values instead of the values, turning sorted IDs, timestamps and counters into small numbers that pack into few bits.›LZ77compression: Replace repeated byte strings with (distance, length) back-references into a sliding window; the parsing stage of gzip, LZ4, zstd, Brotli and xz.›Rolling hashdata-structures: Rabin-Karp polynomial rolling hashes and winnowing for substring fingerprints and document matchingSuffix arraysearch-sort: Sorted array of all suffix start positions of a text; finds every occurrence of any substring by binary search, at 4-5 bytes per text byte.›SIMD programminghardware-os: Process 4-16 lanes per instruction with AVX2, AVX-512 or NEON via Rust std::arch, with runtime dispatch and a portable fallback.›Deterministic serializationfinance: Canonical byte encodings (RLP, SSZ, canonical CBOR) so every node hashes identical bytesCryptographic hashes (SHA-2,BLAKE3)security: Collision-resistant fingerprints of data; SHA-256 for interoperability, BLAKE3 for speed, HMAC/HKDF for keyed uses.›Digital signatures (Ed25519)security: Small, fast, deterministic public-key signatures that prove who produced a message; the default for tokens, releases and protocols.›Key rotationsecurity: Rotating keys without downtime: key ids, overlap windows, re-wrapping, JWKS publication, revocation+ 6 moreEbpfhardware-os: Verified in-kernel programs on hooks (kprobes, XDP, tc) with mapsPtrace process controlhardware-os: Ptrace: attach, read and write registers and memory, single-step, intercept signalsSeccomp bpfsecurity: Syscall filtering with seccomp BPF programsBit packing and PFORcompression: Store blocks of integers with exactly b bits each and patch rare outliers separately (PFOR); the fastest integer codec family, billions of values per second.›Varint (LEB128)compression: Variable-length integers in 7-bit groups with a continuation bit; small numbers take 1 byte, the wire format of Protobuf, WebAssembly and DWARF.›Radix sortsearch-sort: Non-comparison sort that distributes keys by 8-bit digits; several times faster than comparison sorts on large arrays of integers, floats or fixed-size keys.›Envelope encryptionsecurity: Encrypt each object with its own data key and wrap that key under a KMS-held key, so rotation re-wraps 60 bytes and deleting a key shreds data.›Secrets managementsecurity: Keep keys and passwords out of code and logs, give workloads short-lived identity instead of static keys, and make rotation routine.›Cron schedulingsystems: Cron expression parsing and next-fire-time computation, with catch-up and time-zone rules+ 5 moreAes key wrapsecurity: AES Key Wrap (RFC 3394/5649) and AES-GCM-SIV for deterministic, authenticated wrapping of key materialCsprngsecurity: OS-backed cryptographically secure random numbers (getrandom), and when a fast PRNG is not enoughAEAD (AES-GCM,ChaCha20-Poly1305)security: Authenticated encryption that encrypts and detects tampering in one call; the only kind of symmetric encryption you should use.›OAuth 2 and OpenID Connectsecurity: Delegated authorization (OAuth 2) and login on top of it (OIDC); use authorization code + PKCE for every user-facing client.›+ 1 moreConstant time codesecurity: Writing secret-dependent code without branches or memory lookups on secrets; constant-time compare and selectJSON Web Token (JWT)security: A signed, URL-safe token carrying claims; the verifier's job is the checklist (pinned algorithm, key by kid, exp, aud, iss), not the format.›

How it is built

Architecture overview

A grid-tied solar inverter converts the direct current of a PV array into alternating current that is in step with the utility grid, and keeps doing so safely for ten or more years without a technician. Inside it are two worlds. The power stage (a switching bridge, a DC link capacitor, a filter and a relay to the grid) moves the energy; a microcontroller or DSP closes several control loops around it at fixed rates, thousands to tens of thousands of times per second, and decides when it must stop. Around that sits a communications and update path (a local fieldbus for installers and an uplink to a cloud monitoring service), and behind the uplink a backend that stores the telemetry of a whole fleet.

The idea that holds it together is a hard real-time control core with a protective shell. The control loops run from a timer interrupt on a fixed schedule, using integer or fixed-point maths so that behaviour is identical on every unit. Independent protections (hardware trips, a safety monitor, a watchdog) sit beside the loops and can force the inverter off without asking the software that might be at fault. Grid codes (IEEE 1547 in the US; UL 1741 and IEC 62109 for product safety; European codes such as VDE-AR-N 4105) define what the inverter must do when the grid misbehaves, and these rules shape the architecture more than efficiency does.

Product families differ in where the power conversion sits: string inverters (one box per string group), microinverters (one small inverter per panel, as Enphase builds) and optimiser-plus-central-inverter systems (as SolarEdge builds). The blocks below are the same; the number of control cores and the communication topology differ.

Parts:

  PV array ─► DC input (MPPT) ─► DC link ─► inverter bridge ─► filter ─► relay ─► grid
                  ▲                 ▲            ▲   gate drive            ▲
                  │ V, I            │ V          │ PWM                     │ V, I
  ┌───────────────┴─────────────────┴────────────┴─────────────────────────┴─────────┐
  │ MCU / DSP                                                                         │
  │  ADC ─DMA─► filter ─► [ISR @ fixed rate: PLL ─► current loop ─► PWM compare]     │
  │                       [slower task: DC-link loop, MPPT, ride-through, droop]     │
  │  safety monitor + watchdog ──► hardware trip / relay open     (independent path) │
  │  Modbus / CAN ◄──► installer, meter, battery        TLS + MQTT ──► cloud         │
  └───────────────────────────────────────────────────────────────────┬──────────────┘
                                                                       ▼
        fleet backend: ingest ─► time-series store (replicated, PITR) ─► dashboards, alerts, OTA

How the parts fit together

Power stage drive

PWM generation is the actuator: a timer compares a carrier counter with a duty value and drives the bridge's gates, with dead time so the upper and lower switches of a leg never conduct together. A new duty value takes effect at a defined point of the carrier (shadow registers), so the control loop and the output stay in step. The gate driver adds protection that does not depend on firmware: desaturation detection turns a switch off when its collector-emitter voltage shows a short circuit (gate-drive-desat-protection, no page yet and not in the graph). The contract is that firmware can request a duty, but a hardware path can always override it.

Sensing chain

The loops need clean voltages and currents. The ADC is triggered from the PWM timer so that it samples at a repeatable point of the switching cycle, away from switching edges. Results move by DMA into memory (DMA transfers, no page yet), so the processor is interrupted once per block or once per cycle and not once per sample. IIR and FIR filters remove switching noise and offset; grid-frequency quantities (RMS voltage, active and reactive power, THD) come from RMS power metering DSP (no page yet). All of this runs in Deterministic fixed-point math where the processor lacks a floating-point unit: the same input then gives the same output on every unit, which also makes firmware testable bit-for-bit.

Control loops

The core is a Fixed-rate control loop started from a timer interrupt, commonly in the same period as the PWM (switching frequencies for inverters of this type are of the order of 10 to 20 kHz, order of). In a grid-tied inverter the loops are nested:

  • Inner current loop (fastest): controls the current injected into the grid so that it follows a sinusoidal reference; a PID controller (usually PI or proportional-resonant) closes it. Bandwidth of the order of a kilohertz, an order of magnitude below the switching frequency.
  • Outer DC-link voltage loop (slower): keeps the DC link at its setpoint; the power it demands from the grid side is what the array supplies, so this loop sets the amplitude of the inner loop's reference.
  • Maximum power point tracking (slowest): perturbs the array operating voltage and keeps the point of highest power; the common algorithms are perturb-and-observe and incremental conductance (survey: Esram and Chapman 2007). This is the block maximum-power-point-tracking (no page yet, not in the graph).

Each loop must finish before the next one starts; the nesting ratio (each outer loop about ten times slower than the loop inside it) keeps them from fighting. Priorities follow the same order: the current loop's interrupt preempts everything, and communications run in the background.

Grid interface

The current reference must be in phase with the grid voltage, which has to be measured and tracked even when it is distorted. A Phase-locked loop (digital) does this: it estimates the grid phase and frequency from the sampled voltage and feeds the phase into the current reference (Teodorescu et al.; Blaabjerg et al. 2006). Three things build on that estimate:

  • Fault ride-through and protection: under- and over-voltage and frequency windows decide when the inverter must stay connected, ride through, or disconnect; these windows come from the grid code.
  • Anti-islanding: if the grid disappears but local load and generation roughly match, the inverter must notice and stop energising the line within a time limit set by the standard (IEEE 1547). Detection mixes passive checks (voltage and frequency limits, rate of change) with active methods (small injected perturbations). This is the block anti-islanding-detection (no page yet, not in the graph).
  • Grid support: modern codes ask inverters to help the grid, for example by reducing active power as frequency rises or by injecting reactive power with voltage. These characteristics are droop curves (Droop control, no page yet).

Safety shell

A fault should end in a known safe state: the relay open and the bridge off. Three layers do this. Safety monitor architecture (no page yet) covers the independent monitor that checks the main controller (a second processor or a redundant measurement channel that compares grid voltage and current with its own sensors, as product standards typically require for grid disconnection). The Watchdog timer forces a reset if the control interrupt or the main loop stops. Above both, Fault detection, isolation and recovery (no page yet) classifies faults (grid, array insulation, over-temperature, internal) and decides whether to retry after a delay or latch off. The code itself follows Safety-critical coding standards: no dynamic allocation, bounded loops, checked inputs, so the worst-case execution time of the control interrupt can be proven.

Local and cloud communications

Locally the inverter talks to installer tools, energy meters and batteries. Modbus protocol (no page yet) is the common register-based interface, and the SunSpec Alliance defines standard register maps for inverters and meters on top of Modbus, which is why generic monitoring tools can read inverters of different makers. Between several power units inside a system (optimisers, battery modules, multi-inverter clusters), CAN bus framing (no page yet) gives robust short-range messaging. To the cloud, inverters push telemetry on a schedule over MQTT (no page yet), a light publish/subscribe protocol that survives poor links, wrapped in Mutual TLS so both the device and the service prove who they are; a compromised inverter fleet is a grid-scale risk, so authenticated, signed control is not optional.

Firmware update

An inverter is updated in the field, often remotely, and a failed update at a remote roof has a high cost. A/B partition updates keep two firmware slots: the new image is written to the idle slot, tried once, and if it does not report healthy the bootloader falls back. The safety shell defines what "healthy" means: control loop running, grid sync achieved, relay test passed.

Monitoring backend

The fleet's telemetry arrives as many small time-series writes. The backend keeps them in a store with Primary-backup replication and Point-in-time recovery so a lost node or a bad deployment does not lose history. Process supervision restarts failed services and Graceful draining lets a node leave without dropping in-flight uploads. Latency of queries and ingestion is tracked in an HDR histogram (no page yet) so tail latency is visible. The ingest parsing is exposed to every device on the internet, so it is exercised with Coverage-guided fuzzing, and the fleet logic (retries, duplicate uploads, clock skew) is checked with Deterministic simulation testing.

Data and control flow

One control cycle (every PWM period, order of 50 to 100 microseconds):

  1. The PWM timer triggers the ADC; voltages and currents are sampled at the chosen point of the cycle.
  2. A DMA transfer or the ADC end-of-conversion interrupt hands the samples to the control ISR.
  3. The ISR filters the samples, updates the PLL (grid phase), computes the current error, runs the current controller and writes the new duty values to the PWM compare registers.
  4. The ISR kicks the watchdog only if its own sanity checks passed; every N cycles it signals the slower task.
  5. The slower task runs the DC-link loop, MPPT and protection windows, and updates the fault state.

A grid disturbance:

  1. The grid voltage leaves the allowed window. The ISR sees it within a few cycles, and the independent monitor sees it on its own channel.
  2. Depending on depth and duration the inverter rides through (keeps injecting within limits) or stops injecting.
  3. If the disturbance lasts longer than the code allows, the bridge is disabled and the relay opens; the fault is logged and a timer starts for the reconnection check.
  4. After the grid has been normal for the required time, the inverter re-synchronises with the PLL and ramps up its power in a controlled way.

Telemetry to the cloud:

  1. A slow task samples energy, power, temperatures and fault codes into a buffer.
  2. Every interval the device opens (or reuses) a mutually authenticated TLS session and publishes a batch via MQTT.
  3. The backend validates and stores it in the replicated time-series store; alerts run on top.
  4. Commands (a power limit, a firmware version to fetch) flow the other way, signed, and go through the update or configuration path above.

Scaling

The system scales along three different axes:

  1. Per device (control quality): faster processor and ADC, more loop bandwidth, better filtering, a second core for the safety monitor. Limit: the worst-case time of the control ISR inside one PWM period.
  2. Per site: many inverters on one feeder behave as a group. Limits: grid code requirements for the plant, and communication among units. Levers: a plant controller that distributes power limits, droop settings that are coordinated, and a field bus with deterministic latency.
  3. Per fleet (cloud): millions of devices pushing small messages. Limits: ingest rate and storage. Levers: batching on the device, partitioned time-series storage, tiered retention, horizontal ingest behind MQTT brokers. Update campaigns scale the other way: roll out in waves, watch health, stop on regression.

Failure modes

FailureSymptomCauseFix
Loop instabilityoutput current oscillates, audible noise, THD alarmsloop gain too high for the filter and grid impedance, delay not modelledtune with the real delay, add damping, limit bandwidth; test on weak grids
Control ISR overrunmissed PWM updates, watchdog resetstoo much work in the ISR, preemption by a lower taskbudget cycles, move work to the slow task, prove worst-case time
PLL loses lockwrong phase, current spikes at grid dipsdistorted or unbalanced grid, too fast PLLfiltered PLL, lock detector, trip on loss of lock
MPPT confusionpower well below the array's capabilitypartial shading with several power peaks, noise in the measurementperiodic scan of the curve, filtered perturbation
Failed anti-islanding detectioninverter keeps energising an isolated lineload and generation matched, detection method defeated by other inverterscombine passive and active methods; test with the standard's test circuit
Bridge shoot-throughswitch failure, fuse blowsdead time too short, noisy gate drivehardware desaturation trip, margin in dead time
Bad firmware updateunit does not return after rebootimage corrupt, config incompatibleA/B slots, health confirmation, staged rollout
Fleet sync stormcloud overload after an outageall devices reconnect and upload at oncejittered backoff, server-side admission, broker limits
Spoofed or replayed commandwrong power limit appliedweak authentication of the uplinkmutual TLS, signed commands, sequence numbers

Real implementations

namewhat it isrepolicencenotes
TI C2000 DigitalPower SDKfirmware, examples and tools for digital power on C2000 MCUs, including solarTI tool pageTI software licence (see page)reference control code for PWM, ADC, loops and compensator design
SunSpec modelsregister maps (information models) for inverters, meters and trackers over Modbussunspec/modelsApache-2.0generic monitoring tools use these
pysunspec2Python library for reading SunSpec-compliant devicessunspec/pysunspec2Apache-2.0useful for local probing and tests
OpenDTUopen firmware for an ESP32 gateway that talks to Hoymiles microinverters, replacing the vendor cloudtbnobody/OpenDTUGPL-2.0started by reverse engineering the vendor protocol
OpenEMSmodular open energy management platform for PV, storage and other devicesOpenEMS/openemsEPL-2.0 (a second licence file is present; see repo)monitoring and control above the inverter
SMA, SolarEdge, Enphasecommercial inverter and microinverter makers; each publishes interface documents on its own sitenoneproprietarynamed for the three product architectures; firmware is closed

Sources

  • IEEE, IEEE Std 1547-2018: Standard for Interconnection and Interoperability of Distributed Energy Resources with Associated Electric Power Systems Interfaces. standard
  • UL 1741 (Supplement SB) and IEC 62109-1/-2 (product safety of power converters for PV); named here as the governing standards, not summarised.
  • T. Esram, P. L. Chapman, Comparison of Photovoltaic Array Maximum Power Point Tracking Techniques, IEEE Transactions on Energy Conversion 22(2), 2007. DOI
  • F. Blaabjerg, R. Teodorescu, M. Liserre, A. V. Timbus, Overview of Control and Grid Synchronization for Distributed Power Generation Systems, IEEE Transactions on Industrial Electronics 53(5), 2006. DOI
  • R. Teodorescu, M. Liserre, P. Rodriguez, Grid Converters for Photovoltaic and Wind Power Systems, Wiley, 2011. DOI
  • Texas Instruments, C2000Ware DigitalPower SDK. tool page
  • SunSpec Alliance models and tools: models, pysunspec2

Similar systems

Share the most building blocks with this one.