The MPLAB Device Blocks for Simulink provides two powerful tools for testing and validating embedded algorithms:
This guide explains both tools, their use cases, setup procedures, and best practices.
External Mode creates a bidirectional communication link between Simulink and your embedded target while the code is running. This enables:
The toolbox provides MathWorks External Mode for real-time parameter tuning and signal monitoring.
MathWorks External Mode provides tight integration with Simulink, enabling parameter tuning and signal monitoring directly from the Simulink model interface.
External Mode uses the industry-standard XCP protocol, which provides:
1. Open Model Configuration Parameters (Ctrl+E)
2. Navigate to: Code Generation → Interface
3. Check "External mode"
4. Configure transport layer:
- Transport: "XCP on Serial" (for UART)
- Transport: "XCP on TCP/IP" (for Ethernet)
5. Set baud rate (serial) or IP address (TCP/IP)
For Serial (UART):
- Baud rate: 115200 (or higher)
- COM port: Detected automatically or set manually
- Data bits: 8
- Stop bits: 1
- Parity: None
For TCP/IP (Ethernet):
- Target IP address: e.g., 192.168.1.100
- Port: 17725 (default XCP port)
1. Build model (Ctrl+B)
- External Mode code is automatically included
2. Program microcontroller via ICD/PICkit
3. In Simulink:
- Click "Connect to Target" button (or Ctrl+K)
- Wait for connection confirmation
4. Click "Start Real-Time Code" (or Ctrl+T)
5. Observe signals in Simulink scopes
6. Modify tunable parameters in real-time
To allow real-time tuning of a parameter:
1. Right-click the block parameter or constant block
2. Select "Tune Parameter..."
3. Check "Tunable" checkbox
4. Optional: Set min/max limits for safety
5. Rebuild model
During External Mode:
- Double-click parameter to open slider
- Adjust value while code runs
- Observe effect immediately
⚠️ Safety Warning: When tuning parameters in real-time for motor control or other safety-critical applications:
Set appropriate min/max limits on tunable parameters
Have emergency stop mechanism ready
Start with safe operating conditions
Monitor system behavior continuously
| Aspect | Impact | Recommendation |
|---|---|---|
| CPU Overhead | 5-15% depending on logged signals | Minimize number of logged signals |
| Communication Latency | 10-100ms depending on transport | Use TCP/IP for lower latency than Serial |
| Maximum Sample Rate | Limited by baud rate / network speed | Serial: ~10 kHz max, Ethernet: ~100 kHz max |
| Buffer Size | Limits burst logging capability | Configure in External Mode settings |
PIL runs your generated code on the actual target hardware and compares the results to a reference simulation. This provides two critical types of verification:
Why PIL is Important: PIL catches errors that simulation alone cannot detect:
Fixed-point quantization errors
Compiler optimization side effects
Hardware-specific behavior
Performance bottlenecks
Figure 2: PIL test model structure. The algorithm under test runs on hardware (PIL block), while a reference model runs in simulation. Results are compared to verify correctness.
Model components:
Figure 3: PIL numerical verification results. Blue line (simulation) vs. Orange line (hardware execution). In this test, the outputs match exactly, confirming code generation accuracy.
What to verify:
Figure 4: PIL timing analysis results showing actual execution time on target hardware. Statistics include minimum, maximum, and average execution times in CPU cycles and microseconds.
Timing metrics provided:
| Metric | Description | Use |
|---|---|---|
| Minimum Time | Fastest execution (best-case path) | Understand base performance |
| Maximum Time | Slowest execution (worst-case path) | Verify meets deadline |
| Average Time | Typical execution time | Calculate CPU utilization |
| Stack Usage | Peak stack depth | Ensure no stack overflow |
| Code Size | Flash memory used | Check fits in device |
1. Create new Simulink model
2. Add test signal sources (sine, step, etc.)
3. Add your algorithm as a subsystem or reference model
4. Add reference implementation for comparison
5. Add comparison logic (subtraction + assertion)
1. Right-click subsystem/model block
2. Select "C/C++ Code" → "Build"
3. In build dialog:
- Set "Build action" to "Software-in-the-Loop (SIL)"
or "Processor-in-the-Loop (PIL)"
- Select PIL for hardware testing
4. Choose hardware connection:
- ICD3/ICD4/ICD5
- PICkit 3/4/5
- MPLAB SNAP
5. Click "Build"
1. Click "Run" in Simulink (Ctrl+T)
2. Code is automatically:
- Generated
- Compiled
- Programmed to hardware
- Executed with test inputs
3. Results compared to reference
4. Report generated with timing data
| Data Type | Acceptable Error | Notes |
|---|---|---|
| double (64-bit) | < 1e-14 (rounding) | Should match exactly |
| single (32-bit) | < 1e-6 (rounding) | Should match exactly |
| int32 / uint32 | 0 (exact) | Must match exactly |
| int16 / uint16 | 0 or ±1 (rounding) | Check quantization |
| Fixed-point | Application-dependent | Verify against requirements |
Example Timing Report:
Function: ControlLoop
Min time: 45 μs (2,250 cycles @ 50 MHz)
Max time: 67 μs (3,350 cycles @ 50 MHz)
Avg time: 52 μs (2,600 cycles @ 50 MHz)
Analysis:
• Sample period: 100 μs (10 kHz control loop)
• Worst case: 67 μs < 100 μs ✅ PASS
• CPU load: 52 / 100 = 52% average
• Safety margin: 100 - 67 = 33 μs (33% margin) ✅ GOOD
Timing Failure: If maximum execution time exceeds sample period:
| Aspect | External Mode | PIL |
|---|---|---|
| Purpose | Real-time tuning & debugging | Verification & performance analysis |
| When to use | During development & commissioning | Before production release |
| Code modification | Adds communication code | No modification (tests production code) |
| Performance impact | 5-15% overhead | None (measured without overhead) |
| Hardware connection | Serial/Ethernet required during run | Programmer (ICD/PICkit) required |
| Results | Real-time plots, tuned parameters | Pass/fail verification, timing data |
| Automation | Manual interaction | Fully automated test |
Development Phase:
1. Develop algorithm in Simulink (pure simulation)
2. Test with PIL for numerical verification
3. Optimize if timing fails
4. Deploy to hardware
5. Use External Mode for tuning
6. Final PIL test with tuned parameters
Production Phase:
7. Disable External Mode (remove overhead)
8. Build production code
9. Final verification with PIL
10. Program production units
Problem: Cannot connect to target
Solutions:
Problem: Numerical mismatch between simulation and hardware
Possible causes:
Problem: Timing exceeds sample period
Solutions: