matlab-vehicle-network-communication

$npx mdskill add matlab/matlab-agentic-toolkit/matlab-vehicle-network-communication

Establish vehicle network communication in MATLAB using Vehicle Network Toolbox

  • User needs to send or receive messages on a vehicle network.
  • Depends on MATLAB R2021a and Vehicle Network Toolbox, along with vendor-specific drivers for physical hardware.
  • Decides based on user requirements and supported protocols (CAN/CAN FD, J1939, XCP) across various vendors.
  • Delivers by configuring channels, setting up buses, encoding/decoding messages, and analyzing communication results.

SKILL.md

.github/skills/matlab-vehicle-network-communicationView on GitHub ↗
---
name: matlab-vehicle-network-communication
description: Use when setting up vehicle network communication in MATLAB using Vehicle Network Toolbox. Covers CAN/CAN FD (fully implemented), with architecture for J1939, XCP, and future protocols. Handles hardware discovery, channel creation, bus configuration, message exchange, signal encoding/decoding, and analysis across all supported vendors (Vector, Kvaser, PEAK-System, NI, SocketCAN, MathWorks Virtual).
license: MathWorks BSD-3-Clause
metadata:
  author: MathWorks
  version: "1.0"
---

# MATLAB Vehicle Network Communication

## Prerequisites

- MATLAB R2021a or later
- Vehicle Network Toolbox installed (`ver('vnt')` to verify)
- For physical hardware: vendor-specific drivers installed (Vector CANlib, Kvaser CANlib, NI-XNET, PEAK PCAN driver)
- For testing without hardware: MathWorks Virtual channels are always available

## Overview

Guide Claude through helping users establish vehicle network communication using MATLAB Vehicle Network Toolbox. This skill covers the full workflow from hardware discovery to message exchange across all supported protocols and vendors.

**Implemented protocols:**
- CAN / CAN FD — fully documented

**Planned protocols (architecture ready, not yet documented):**
- J1939 — parameter groups, transport protocol, address claiming
- XCP — measurement, calibration, A2L file handling
- Additional protocols as VNT adds support

## When to Use

- User wants to send/receive messages on a vehicle network bus in MATLAB
- User is setting up a communication test bench or loopback verification
- User asks about Vehicle Network Toolbox channel configuration
- User encounters channel errors (initialization access, bus speed, no acknowledgment)
- User wants to filter, decode, or analyze vehicle network messages
- User asks which hardware works on their platform
- User wants passive bus monitoring without affecting traffic
- User needs to encode/decode signal data from messages

## When NOT to Use

- User wants to log/replay BLF files without live communication — use a BLF logging skill
- User is building Simulink vehicle network blocks — use Simulink-specific skills
- User needs CAN database file (DBC/LDF/A2L) creation or editing — this skill covers using existing files only
- User is working with a protocol not yet documented in this skill (check protocol sections below)

## Protocol Router

Use this decision tree to identify which protocol the user needs:

| User's Goal | Protocol | Reference Section |
|-------------|----------|-------------------|
| Send/receive CAN or CAN FD messages | CAN/CAN FD | `references/can/` |
| Work with SAE J1939 parameter groups | J1939 | *Not yet documented* |
| ECU measurement or calibration via XCP/CCP | XCP | *Not yet documented* |
| General hardware discovery (any protocol) | Shared | `references/shared/` |

If the user asks about a protocol not yet documented, inform them which protocols are currently covered and offer to help with those.

## Shared Concepts (All Protocols)

### Hardware Discovery

```matlab
t = canChannelList;  % CAN/CAN FD/J1939 devices
```

All VNT protocols share the same hardware discovery mechanism. See [references/shared/hardware-discovery.md](references/shared/hardware-discovery.md).

### Channel Lifecycle

All protocols follow the same lifecycle pattern:

```
Create Channel → Configure → Start → Operate → Stop/Cleanup
```

Key rules:
- Configuration (bus speed, filters) must happen BEFORE `start`
- `clear ch` releases the channel (equivalent to stop + destroy)
- Use `onCleanup(@() stop(ch))` for error-safe cleanup
- Running channels hold InitializationAccess — blocking new channel creation

See [references/shared/channel-lifecycle.md](references/shared/channel-lifecycle.md).

### Vendor / Platform Matrix

| Vendor | Windows | Linux | Notes |
|--------|:-------:|:-----:|-------|
| Vector | Yes | No | Virtual channels if driver installed |
| NI | Yes | No | No channel index in constructor |
| Kvaser | Yes | Yes | Restart MATLAB after connecting hardware |
| PEAK-System | Yes | Yes | 10-arg clock-based configBusSpeed |
| SocketCAN | No | Yes | Configure speed at OS level via `ip link` |
| MathWorks Virtual | Yes | Yes | Always available, no driver needed |

---

## CAN / CAN FD

### Core Workflow

```dot
digraph can_workflow {
    rankdir=TB;
    node [shape=box];

    discover [label="1. Discover Hardware\ncanChannelList"];
    decide [label="CAN Classic or CAN FD?" shape=diamond];
    create_classic [label="2a. Create Channel\ncanChannel(vendor, device, ch)"];
    create_fd [label="2b. Create FD Channel\ncanChannel(..., ProtocolMode='CAN FD')\nor canFDChannel(...)"];
    config [label="3. Configure Bus Speed\nconfigBusSpeed (vendor-specific syntax)"];
    start [label="4. Start Channel\nstart(ch)"];
    operate [label="5. Transmit / Receive\ntransmit, receive\ntransmitPeriodic, transmitEvent, replay"];
    cleanup [label="6. Cleanup\nstop(ch) or clear ch"];

    discover -> decide;
    decide -> create_classic [label="Classic"];
    decide -> create_fd [label="CAN FD"];
    create_classic -> config;
    create_fd -> config;
    config -> start;
    start -> operate;
    operate -> cleanup;
}
```

### CAN Classic vs CAN FD Decision

| Aspect | CAN Classic | CAN FD |
|--------|-------------|--------|
| Max payload | 8 bytes | 64 bytes |
| Message constructor | `canMessage(id, ext, dlc)` | `canFDMessage(id, ext, dlc)` or `canMessage(..., ProtocolMode="CAN FD")` |
| Channel creation | `canChannel(vendor, device, ch)` | Add `'ProtocolMode', 'CAN FD'` or use `canFDChannel` |
| Bus speed config | Single speed | Arbitration + Data phase (vendor-specific syntax) |
| `receive` output | Objects or timetable | Always timetable |
| Valid DLCs | 0–8 | 0, 8, 12, 16, 20, 24, 32, 48, 64 |

### Critical Patterns (Non-Obvious API Behavior)

These patterns are where the API behaves differently than expected. Follow these exactly.

#### attachDatabase operates on MESSAGES, not channels

```matlab
% WRONG — will error
attachDatabase(ch, db);
ch.Database = db;  % only valid for name-based filterAllowOnly

% CORRECT — attach to received message object
rxMsg = receive(ch, 1);
attachDatabase(rxMsg, db);
speed = rxMsg.Signals.EngineSpeed;
```

#### transmitPeriodic + pack for live signal updates

```matlab
% WRONG — manual loop blocks MATLAB, timing is inaccurate
while running
    pack(msg, newValue, 0, 16, 'LittleEndian');
    transmit(ch, msg);
    pause(0.1);
end

% CORRECT — hardware-timed, non-blocking
transmitPeriodic(ch, msg, 'On', 0.1);
start(ch);
pack(msg, newValue, 0, 16, 'LittleEndian');  % next cycle sends updated data
```

#### filterAllowOnly REQUIRES type argument for numeric IDs

```matlab
% WRONG — errors with "Expected NAME to be one of these types: char, cell"
filterAllowOnly(ch, [0x180 0x181]);

% CORRECT — must specify 'Standard' or 'Extended'
filterAllowOnly(ch, [0x180 0x181], 'Standard');
filterAllowOnly(ch, [0x18FEF100], 'Extended');
```

#### CAN FD configBusSpeed is vendor-specific

```matlab
% MathWorks Virtual / NI — simple 3-arg form works
configBusSpeed(ch, 500000, 2000000);

% Vector / Kvaser — REQUIRES 9-arg advanced timing form
configBusSpeed(ch, 500000, 2, 6, 3, 2000000, 2, 6, 3);

% PEAK-System — REQUIRES 10-arg clock-based form
configBusSpeed(ch, 20, 5, 1, 2, 1, 2, 1, 3, 1);
```

#### CAN FD receive ALWAYS returns timetable

```matlab
% CAN FD channels ignore OutputFormat — always timetable
msgs = receive(fdCh, Inf);       % returns timetable
msgs.ID                          % numeric vector of IDs
msgs.Data{1}                     % uint8 vector for first message
% WRONG: msgs(1).Data, msgs.Data(1) — these error on timetable
```

#### transmitEvent fires on ANY .Data write (including pack)

```matlab
transmitEvent(ch, msg, 'On');
start(ch);
pack(msg, value, 0, 16, 'LittleEndian');  % this auto-transmits!
% No explicit transmit() call needed — pack triggers it
```

### Common Pitfalls

| Pitfall | Symptom | Fix |
|---------|---------|-----|
| Stale channel object | "lacks initialization access" | `clear` the variable or `stop` prior channel |
| `canMessage` for FD payload | "DATALENGTH must be <= 8" | Use `canFDMessage` or add `ProtocolMode="CAN FD"` |
| No acknowledging node | Transmit retries continuously | Ensure another node/channel is started on the bus |
| Bus speed mismatch | Transmit succeeds, receive empty | All nodes must share same speed |
| `configBusSpeed` after `start` | Error | Must configure while channel is offline |
| Reusing variable | Error on creation | `clear` variable before creating new channel |
| `configBusSpeed` on SocketCAN | Not supported | Configure speed at OS level via `ip link` |
| CAN FD on PEAK-System Linux | Self-receive not supported | Use SocketCAN as workaround |
| `unpack` on timetable | "Incorrect number or types of inputs" | CAN FD always returns timetable; use `typecast(data(1:2), 'int16')` on raw bytes |

### CAN References

Detailed API documentation (load on demand):
- [references/can/channel-creation.md](references/can/channel-creation.md) — `canChannel`, `canFDChannel`, vendor-specific syntax
- [references/can/bus-speed-config.md](references/can/bus-speed-config.md) — `configBusSpeed`, vendor-specific argument counts
- [references/can/message-creation.md](references/can/message-creation.md) — `canMessage`, `canFDMessage`, valid FD DLCs
- [references/can/transmit.md](references/can/transmit.md) — `transmit`, `transmitPeriodic`, `transmitEvent`, `replay`
- [references/can/receive.md](references/can/receive.md) — `receive`, `SilentMode`, timetable output, FIFO behavior
- [references/can/filters.md](references/can/filters.md) — `filterAllowOnly`, `filterBlockAll`, `filterAllowAll`
- [references/can/database.md](references/can/database.md) — `canDatabase`, `attachDatabase`, signal-level decode/encode
- [references/can/pack-unpack.md](references/can/pack-unpack.md) — `pack`, `unpack`, signal extraction, byte-order
- [references/can/message-extraction.md](references/can/message-extraction.md) — `extractAll`, `extractRecent`, `extractTime`, `discard`

---

## Shared References

- [references/shared/hardware-discovery.md](references/shared/hardware-discovery.md) — `canChannelList`, platform constraints
- [references/shared/channel-lifecycle.md](references/shared/channel-lifecycle.md) — `start`, `stop`, `onCleanup`, channel release
- [references/shared/limitations.md](references/shared/limitations.md) — Vendor/platform-specific constraints

---

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.