The MPLAB Device Blocks for Simulink provides two powerful tools for testing and validating embedded algorithms:

  • External Mode: Real-time parameter tuning and data visualization during code execution
  • PIL (Processor-in-the-Loop): Verification of code generation accuracy and performance analysis

This guide explains both tools, their use cases, setup procedures, and best practices.

External Mode: Real-Time Parameter Tuning

What is External Mode?

External Mode creates a bidirectional communication link between Simulink and your embedded target while the code is running. This enables:

  • Upload parameters to running code without rebuilding (e.g., tune PID gains in real-time)
  • Download signals from embedded hardware for real-time plotting in Simulink
  • Start/stop execution from Simulink interface
  • Trigger data capture based on signal conditions
 Typical Use Case: A motor control engineer uses External Mode to tune PID controller gains while the motor is running, observing the effect of each change immediately on Simulink scopes without stopping the motor or rebuilding code.

External Mode Variants

The toolbox provides MathWorks External Mode for real-time parameter tuning and signal monitoring.

 Related Tool - PIC GUI: For simplified data visualization without parameter tuning capabilities, see Data Visualization with PIC GUI. PIC GUI provides lightweight data logging over UART with custom MATLAB visualization scripts.

MathWorks External Mode

Overview

MathWorks External Mode provides tight integration with Simulink, enabling parameter tuning and signal monitoring directly from the Simulink model interface.

Protocol: XCP (Universal Measurement and Calibration Protocol)

External Mode uses the industry-standard XCP protocol, which provides:

  • Standardized communication protocol
  • Support for multiple transport layers (Serial, TCP/IP, CAN)
  • Efficient binary data format
  • Synchronization with model execution

External Mode Setup Procedure

Step 1: Enable External Mode in Model

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)

Step 2: Configure Communication Parameters

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)

Step 3: Build and Program with External Mode

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

Making Parameters Tunable

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

External Mode Performance Considerations

AspectImpactRecommendation
CPU Overhead5-15% depending on logged signalsMinimize number of logged signals
Communication Latency10-100ms depending on transportUse TCP/IP for lower latency than Serial
Maximum Sample RateLimited by baud rate / network speedSerial: ~10 kHz max, Ethernet: ~100 kHz max
Buffer SizeLimits burst logging capabilityConfigure in External Mode settings

Processor-in-the-Loop (PIL) Testing

What is PIL?

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:

  • Numerical Verification: Confirms code generation produces bit-accurate results
  • Timing Analysis: Measures actual execution time and resource usage on hardware

 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

PIL Test Model Structure

PIL test model structure

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:

  • Test Inputs: Signal sources (sine waves, steps, ramps)
  • PIL Block: Algorithm running on hardware
  • Reference Model: Same algorithm in Simulink
  • Comparison: Subtract outputs to check for differences
  • Assertion: Fail test if error exceeds threshold

PIL Numerical Verification

PIL numerical comparison results

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:

  • Floating-point algorithms: Should match simulation exactly (within rounding tolerance)
  • Fixed-point algorithms: May have quantization differences - verify they’re acceptable
  • Lookup tables: Check interpolation accuracy
  • State machines: Verify state transitions

PIL Timing Analysis

PIL timing analysis results

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:

MetricDescriptionUse
Minimum TimeFastest execution (best-case path)Understand base performance
Maximum TimeSlowest execution (worst-case path)Verify meets deadline
Average TimeTypical execution timeCalculate CPU utilization
Stack UsagePeak stack depthEnsure no stack overflow
Code SizeFlash memory usedCheck fits in device

PIL Setup Procedure

Step 1: Create PIL Test Model

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)

Step 2: Configure Subsystem for PIL

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"

Step 3: Run PIL Test

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

Interpreting PIL Results

Numerical Verification Pass Criteria

Data TypeAcceptable ErrorNotes
double (64-bit)< 1e-14 (rounding)Should match exactly
single (32-bit)< 1e-6 (rounding)Should match exactly
int32 / uint320 (exact)Must match exactly
int16 / uint160 or ±1 (rounding)Check quantization
Fixed-pointApplication-dependentVerify against requirements

Timing Analysis Guidelines

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:

  • Optimize code: Use PIL profiling to find bottlenecks
  • Enable optimizations: Check compiler settings (-O1/-O2/-O3)
  • Use code replacement: Enable assembly optimizations for dsPIC
  • Reduce sample rate: Increase sample period if possible
  • Upgrade hardware: Consider faster microcontroller

External Mode vs PIL Comparison

AspectExternal ModePIL
PurposeReal-time tuning & debuggingVerification & performance analysis
When to useDuring development & commissioningBefore production release
Code modificationAdds communication codeNo modification (tests production code)
Performance impact5-15% overheadNone (measured without overhead)
Hardware connectionSerial/Ethernet required during runProgrammer (ICD/PICkit) required
ResultsReal-time plots, tuned parametersPass/fail verification, timing data
AutomationManual interactionFully automated test

Best Practices

External Mode Best Practices

  • Minimize logged signals: Only log signals you need to observe
  • Use appropriate sample rates: Don’t oversample slow signals
  • Set parameter limits: Prevent accidental unsafe values
  • Document tuned values: Record final parameter values in model
  • Test without External Mode: Verify performance without communication overhead

PIL Best Practices

  • Test early and often: Run PIL after major algorithm changes
  • Use realistic test inputs: Cover full operating range
  • Check worst-case timing: Verify maximum execution time
  • Test with optimizations: PIL with same settings as production
  • Automate PIL tests: Integrate into CI/CD pipeline
  • Document results: Keep timing reports for reference

Workflow Recommendation

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

Troubleshooting

External Mode Connection Issues

Problem: Cannot connect to target

Solutions:

  • Verify COM port or IP address is correct
  • Check baud rate matches between model and hardware
  • Ensure target code is running (toggle LED test)
  • Check cable connections
  • Disable Windows firewall (for TCP/IP mode)
  • Try different USB port (for Serial mode)

PIL Test Failures

Problem: Numerical mismatch between simulation and hardware

Possible causes:

  • Fixed-point quantization: Check word lengths and scaling
  • Compiler optimization: May reorder operations (usually safe)
  • Uninitialized variables: Hardware vs simulation default values differ
  • Timing-dependent logic: Sample time mismatch

Problem: Timing exceeds sample period

Solutions:

  • Enable compiler optimizations (-O2 or -O3)
  • Enable code replacement library (assembly optimizations)
  • Profile code to find bottleneck functions
  • Simplify algorithm or increase sample period

See Also

Other