matlab-deploy-embedded-code

$npx mdskill add matlab/matlab-agentic-toolkit/matlab-deploy-embedded-code

Deploy MATLAB-generated code to embedded hardware with Embedded Coder.

  • Configures code generation for microcontrollers and embedded Linux boards.
  • Depends on MATLAB Coder, Embedded Coder, and hardware support packages.
  • Selects ERT-based configs, disables dynamic memory, sets hardware target.
  • Generates production C/C++ code and sets up PIL/SIL verification.

SKILL.md

.github/skills/matlab-deploy-embedded-codeView on GitHub ↗
---
name: matlab-deploy-embedded-code
description: >
  Deploy MATLAB-generated code to embedded hardware using Embedded Coder. Use when
  configuring code generation for microcontrollers (STM32, Raspberry Pi, ARM Cortex),
  setting up PIL/SIL verification, disabling dynamic memory allocation, or configuring
  hardware-specific code generation settings. Covers ERT-based configurations,
  processor-in-the-loop testing, memory constraints, and the MEX→SIL→PIL verification
  progression.
license: MathWorks BSD-3-Clause
metadata:
  author: MathWorks
  version: "1.0"
---

# Deploy Embedded Code

Configure MATLAB Coder with Embedded Coder for production-quality code generation
targeting embedded hardware, and verify correctness with processor-in-the-loop (PIL)
testing.

## When to Use

- Generating C/C++ code for a microcontroller or embedded Linux board
- Setting up PIL or SIL verification for generated code
- Configuring code generation with no dynamic memory allocation
- Deploying deep learning models to resource-constrained hardware
- Selecting a hardware target board (STM32, Raspberry Pi)

## When NOT to Use

- Generating MEX or desktop libraries — use standard `codegen` workflows
- Simulink-based deployment — use Simulink Coder / Embedded Coder workflows directly
- GPU code generation (CUDA) — use GPU Coder

## Workflow

### 1. Create an ERT-Based Configuration

```matlab
cfg = coder.config("lib", "ecoder", true);
```

The `"ecoder", true` flag creates an ERT-based (Embedded Real-Time) configuration
that generates production-quality code with no OS dependencies.

### 2. Select Target Hardware

With `coder.hardware`:

```matlab
cfg.Hardware = coder.hardware("STM32F746G-Discovery");
```

Without the support package, configure hardware manually:

```matlab
cfg.HardwareImplementation.ProdHWDeviceType = 'ARM Compatible->ARM Cortex-M';
cfg.HardwareImplementation.ProdBitPerFloat = 32;
cfg.HardwareImplementation.ProdBitPerDouble = 64;
```

See `references/supported-hardware.md` for the full list of supported boards and
their constraints.

### 3. Configure Memory for Bare-Metal Targets

```matlab
cfg.EnableDynamicMemoryAllocation = false;
cfg.StackUsageMax = 512;
```

- `EnableDynamicMemoryAllocation = false` — disables `malloc`/`free` for targets
  where heap is unavailable or non-deterministic. All arrays must be bounded at
  compile time.
- `StackUsageMax` — set based on target SRAM. The code generation report shows
  actual usage after compilation.

For entry-points that use deep learning inference (`invoke`, `predict`):

```matlab
cfg.DeepLearningConfig = coder.DeepLearningConfig('none');
cfg.LargeConstantGeneration = "KeepInSourceFiles";
```

- `DeepLearningConfig('none')` — generates C with no external DL library dependencies
  (MKL-DNN, cuDNN, TensorRT). Required for bare-metal targets. Without this, codegen
  may attempt to link an unavailable library and fail.
- `LargeConstantGeneration = "KeepInSourceFiles"` — keeps weight constants in source
  files rather than separate data files. Needed for bare-metal targets where external
  data file linking is unsupported.

### 4. Configure Performance (SIMD and OpenMP)

**SIMD vectorization** — generates vectorized code for the target ISA:

```matlab
cfg.InstructionSetExtensions = 'Neon v7';  % ARM Cortex-A (128-bit, 4x float32)
```

| Target | Value | Notes |
|--------|-------|-------|
| ARM Cortex-A (Raspberry Pi) | `'Neon v7'` | 128-bit SIMD |
| Intel x86-64 | `'SSE'`, `'SSE4.1'`, `'AVX'`, `'AVX2'`, `'AVX512F'` | Match target CPU |
| ARM Cortex-M | Do not set — use `CodeReplacementLibrary` instead | Different mechanism |

**OpenMP multi-threading** — enables parallel loops in generated code:

```matlab
cfg.EnableOpenMP = true;   % multi-core targets (Cortex-A, x86)
cfg.EnableOpenMP = false;  % single-core targets (Cortex-M) — no OS/threading support, won't compile
```

### 5. Set Up PIL Verification

PIL compiles the generated code, deploys it to the physical board, sends test
vectors, and compares outputs against MATLAB. This catches precision differences,
stack overflows, and memory issues that SIL cannot detect.

**Cortex-M (serial transport):**

```matlab
cfg.VerificationMode = "PIL";
cfg.Hardware.PILInterface = "Serial";
cfg.Hardware.PILCOMPort = "COM4";  % adjust to your system
```

**Cortex-A / Raspberry Pi (SSH transport):**

```matlab
cfg.VerificationMode = "PIL";
cfg.Hardware = coder.hardware("Raspberry Pi");
cfg.Hardware.DeviceAddress = "192.168.1.10";
cfg.Hardware.Username = "<your-pi-username>";
cfg.Hardware.Password = "<your-pi-password>";
cfg.Hardware.BuildDir = "/home/pi/mymodel";  % optional: defaults to /home/pi/MATLAB_ws/<release>
```

Pi PIL runs over SSH (not serial). The support package uses `DeviceAddress`,
`Username`, and `Password` to establish the SSH connection. `BuildDir` specifies
where the compiled binary is deployed on the target; if omitted, defaults to
`/home/pi/MATLAB_ws/<release>/`. Do not set `PILInterface` or `PILCOMPort` — those
are for serial-connected bare-metal boards only.

### 6. Generate Code

```matlab
cfg.TargetLang = "C";
codegen -config cfg -args {inputArgs} myEntryPoint
```

### 7. Verify with the MEX → SIL → PIL Progression

For confidence in deployment, follow this sequence:

1. **MEX** — verify on host, fast iteration
2. **SIL** (Software-in-the-Loop) — run generated code on host, compare to MATLAB
3. **PIL** (Processor-in-the-Loop) — run on actual hardware, compare to MATLAB

```matlab
cfgSil = coder.config("lib", "ecoder", true);
cfgSil.VerificationMode = "SIL";
codegen -config cfgSil -args {inputArgs} myEntryPoint
```

## Key Properties

| Property | Values | Purpose |
|----------|--------|---------|
| `VerificationMode` | `"PIL"`, `"SIL"`, `"None"` | Enable in-the-loop verification |
| `Hardware` | `coder.hardware(boardName)` | Select target board |
| `Hardware.PILInterface` | `"Serial"` | PIL communication type |
| `Hardware.PILCOMPort` | `"COM4"`, `"/dev/ttyACM0"` | Serial port |
| `EnableDynamicMemoryAllocation` | `true` (default), `false` | Master switch for heap |
| `DynamicMemoryAllocationThreshold` | numeric (bytes), default 65536 | Arrays above this use heap |
| `LargeConstantGeneration` | `"KeepInSourceFiles"`, `"WriteOnlyDNNConstantsToDataFiles"` | Where to put large constants |
| `StackUsageMax` | numeric (bytes) | Stack limit for generated code |
| `TargetLang` | `"C"`, `"C++"` | Output language |

## Common Mistakes

| Mistake | Why It's Wrong | Correct Approach |
|---------|---------------|-----------------|
| `DynamicMemoryAllocation = "Off"` | Wrong property name and type | `EnableDynamicMemoryAllocation = false` (boolean) |
| Skipping SIL before PIL | PIL failures on hardware are harder to debug | Always validate with SIL first |
| Not setting `StackUsageMax` | Default may exceed target SRAM | Set explicitly based on hardware constraints |
| Using `cfg = coder.config("lib")` without `"ecoder", true` | Creates a generic config, not ERT-based | Always pass `"ecoder", true` for embedded targets |

## Conventions

- Always: use `coder.config("lib", "ecoder", true)` for embedded targets
- Always: disable dynamic memory for bare-metal Cortex-M targets
- Always: follow MEX → SIL → PIL verification order
- Never: use `DynamicMemoryAllocation` (wrong property name — it's `EnableDynamicMemoryAllocation`)
- Prefer: `TargetLang = "C"` for Cortex-M targets (smaller code footprint)

## References

- `references/supported-hardware.md` — board specs, support packages, and PIL interface details

## See Also

- `matlab-deploy-ai-model` — full AI model codegen pipeline (load, verify, generate MEX/lib)

----

Copyright 2026 The MathWorks, Inc.

----

More from matlab/matlab-agentic-toolkit

SkillDescription
matlab-access-datafeed>
matlab-add-awgnRead BEFORE writing any code that adds Additive White Gaussian Noise (AWGN) to signals and converts between SNR, Eb/No, Es/No, and per-subcarrier SNR for communications simulations, using awgn(), convertSNR(), berawgn(). The default MATLAB patterns for AWGN (e.g., 'measured' option, manual SNR formulas) produce subtly incorrect results. This skill specifies the correct calling conventions, required function usage, and critical anti-patterns that must be avoided.
matlab-analyze-ams-waveformAnalyze AMS waveform data using Mixed-Signal Blockset utilities: phase noise measurement, clock jitter, anti-aliased resampling, timing measurements, lock time, INL/DNL, ADC/DAC calibration, HSpice import. Use when analyzing time-domain voltage from PLL/VCO/clock simulations, measuring phase noise from variable-step solver output, computing jitter, or resampling non-uniform data.
matlab-analyze-dataAnalyze data using MATLAB. Use when the task involves tables, timetables, time-series data, numeric arrays, sensor matrices, or gridded data — including but not limited to exploring, filtering, sorting, cleaning, transforming, aggregating, smoothing, padding, trimming, and answering questions about data. MATLAB provides extensive, easy-to-use built-in functions for these workflows with no additional products required.
matlab-analyze-dependenciesAnalyze the effective toolbox file set to produce a Dependency Manifest — classify all transitive dependencies as included, product, add-on, or external-unresolved, then present resolution options with tradeoffs. Use after matlab-define-toolbox-api when the spec is approved.
matlab-analyze-emS-parameters, insertion loss, fields, currents, mesh control, and solver selection for RF PCB performance validation. TRIGGER: user asks to compute S-parameters, analyze insertion/return loss, extract fields or currents, compare MoM vs FEM, or control mesh for any RF PCB component. Invoke BEFORE writing sparameters() or solver code — API is non-obvious. SKIP: designing or creating components (use the specific matlab-design-pcb-* skill), material/stackup setup only (use matlab-manage-pcb-material), optimization sweeps (use matlab-optimize-pcb-design), PDN/IR-drop analysis (use matlab-analyze-pcb-pdn).
matlab-analyze-installed-antennaAnalyze antennas installed on electrically large conducting platforms using MATLAB Antenna Toolbox. Loads platform geometry from STL/STEP/IGES, installs antenna elements, selects electromagnetic solvers (MoM-PO, FMM, MoM), and computes patterns, impedance, coupling, and efficiency. Use when the user wants to model an antenna on a vehicle, aircraft, ship, satellite, or other large structure.
matlab-analyze-pcb-pdnPDN DC voltage/current analysis, IR drop, design rule checking, and multi-net batch analysis on imported PCB layouts. TRIGGER: user asks about power integrity, PDN analysis, IR drop, voltage distribution, current density, power nets, or design rule checking on a PCB. Invoke BEFORE writing code — the PDN API chain is specialized and non-obvious. SKIP: importing a PCB file (use matlab-read-pcb-layout), EM field/S-parameter extraction (use matlab-analyze-em), material/stackup setup only (use matlab-manage-pcb-material), transmission line design (use matlab-design-pcb-txline).
matlab-analyze-rcsCalculate and visualize monostatic and bistatic radar cross section (RCS) using MATLAB Antenna Toolbox. Computes RCS of platforms, antennas, and arrays with PO, MoM, and FMM solvers, supporting HH/VV/HV/VH polarization, GPU acceleration, and near-field observation. Use when the user wants to compute, plot, or analyze radar cross section.
matlab-analyze-rf-propagationAnalyze RF propagation and plan wireless sites using MATLAB Antenna Toolbox. Creates transmitter/receiver sites, computes signal strength, coverage maps, SINR, line-of-sight, and ray tracing in geographic or indoor environments. Supports multiple propagation models (free-space, close-in, Longley-Rice, ray tracing, rain/gas/fog), custom terrain, building data, and directional antennas. Use when the user wants to compute coverage, signal strength, path loss, SINR, ray tracing, or plan a wireless network.