⚠️ Third-Party Educational Content

The motor control examples and algorithms presented in this guide are provided by the ctrl-elec project, an educational initiative from INSA Lyon (France).

Attribution:

  • Project: ctrl-elec - Real-time Control & Embedded Systems Education
  • Institution: Institut National des Sciences Appliquées de Lyon (INSA Lyon)
  • Website:[https://www.ctrl-elec.fr/]
  • GitHub Repository:[https://github.com/rdelpoux/ctrl-elec]
  • RCP Platform:[http://rcp.ctrl-elec.fr/]

License: Educational use - Please refer to the ctrl-elec website for specific licensing terms.

This content is included in the MPLAB Device Blocks for Simulink documentation to demonstrate real-world motor control applications. Microchip Technology and the MPLAB Device Blocks toolbox are separate from the ctrl-elec project.

Introduction

This guide demonstrates how to use the MPLAB Device Blocks for Simulink toolbox for motor control applications, using examples and educational materials from the ctrl-elec project (INSA Lyon).

The examples showcase:

  • Field-Oriented Control (FOC) for Permanent Magnet Synchronous Motors (PMSM)
  • Sensorless control using position and speed observers
  • Field weakening for extended speed range operation
  • Real-time parameter tuning using External Mode
  • Hardware-in-the-loop testing with dsPIC33 and PIC32 devices

Prerequisites:

        Understanding of motor control theory (vector control, Park/Clarke transforms)
        Familiarity with Simulink and Model-Based Design
        Microchip development hardware (e.g., MCLV-2, dsPICDEM MCLV)

Example 1: Field-Oriented Control (FOC) for PMSM

Overview

Field-Oriented Control (FOC) provides precise control of PMSM torque and speed by independently controlling flux and torque-producing currents in the rotating reference frame (d-q frame).

Control Algorithm Components

ComponentFunctionMPLAB Blocks Used
Clarke TransformConverts 3-phase currents (a,b,c) to stationary frame (α,β)Math blocks (Simulink standard)
Park TransformConverts stationary frame (α,β) to rotating frame (d,q)Math blocks with rotor position input
PI ControllersRegulate d-axis and q-axis currents independentlyDiscrete PID blocks with anti-windup
Inverse ParkConverts voltage commands (Vd, Vq) to stationary frameMath blocks with angle input
Space Vector ModulationGenerates 3-phase PWM duty cyclesMCHP_PWM_HS or MCHP_PWM_HS_FEP
Current SensingMeasures motor phase currentsMCHP_ADC with PWM-synchronized sampling
Position/Speed EstimationEncoder or sensorless observerMCHP_QEI (encoder) or observer algorithm

Implementation Steps

  • Hardware Configuration

  • Configure PWM outputs using MCHP_PWM_HS_FEP block

  • Set PWM frequency (typically 10-20 kHz)

  • Enable complementary mode with dead-time insertion

  • Configure center-aligned PWM for reduced harmonics

  • ADC Setup

  • Use MCHP_ADC block for current sensing

  • Trigger ADC from PWM for synchronous sampling

  • Sample at PWM valley or peak for accurate measurements

  • Enable ADC interrupt for time-critical control loop

  • Control Loop Structure

  • Outer loop: Speed controller (lower rate, e.g., 1 kHz)

  • Inner loop: Current controller (higher rate, e.g., 10 kHz)

  • Use multi-rate model with appropriate task priorities

  • Parameter Tuning

  • Enable External Mode for real-time tuning

  • Use picgui for lightweight data visualization

  • Adjust PI gains using Ziegler-Nichols or model-based methods

Key Peripheral Blocks

Block NameConfigurationPurpose in FOC
MCHP_MasterSelect target device, enable multi-taskingSystem configuration and scheduler
MCHP_PWM_HS_FEP3-phase complementary, center-aligned, 10 kHzDrive motor inverter (6 IGBTs/MOSFETs)
MCHP_ADC2 channels (phase currents), PWM-triggeredMeasure Ia, Ib (Ic calculated)
MCHP_QEIQuadrature encoder interface, 1024 PPRRotor position and speed feedback
MCHP_UART_Config115200 baud, XCP protocolExternal Mode communication
MCHP_InterruptTimer or ADC interrupt, highest priorityTrigger fast current control loop

Safety Considerations:

        Implement overcurrent protection using ADC limits and emergency shutdown
        Add dead-time compensation to prevent shoot-through
        Test control algorithm in simulation before hardware deployment
        Use current limiting during startup and parameter tuning
        Monitor MCU load to prevent scheduler overruns

Example 2: Sensorless Control with Sliding Mode Observer

Overview

Sensorless control eliminates the need for mechanical position sensors by estimating rotor position and speed from electrical measurements (voltages and currents). This example uses a Sliding Mode Observer (SMO) for robust position estimation.

Observer Algorithm Components

ComponentFunctionImplementation Notes
Current ObserverEstimates stator currents using motor modelUses measured voltages and motor parameters (Rs, Ls)
Back-EMF EstimationExtracts back-EMF from current errorSliding mode function with adaptive gain
Position CalculationComputes rotor angle from back-EMF (α,β)Arctangent function with phase compensation
Speed EstimationDifferentiates position or uses PLLLow-pass filter to reduce noise
Startup StrategyOpen-loop alignment then transition to sensorlessForced angle ramp until sufficient back-EMF

MPLAB Blocks Configuration

Block NameConfigurationPurpose in Sensorless Control
MCHP_ADC4 channels: Ia, Ib, Vdc, temperatureMeasure currents and DC bus voltage
MCHP_PWM_HS_FEPSame as FOC exampleMotor drive PWM generation
Observer SubsystemFixed-point or floating-point mathSliding mode observer implementation
MCHP_InterruptADC interrupt at PWM frequencyExecute observer at high rate (10-20 kHz)

Key Tuning Parameters

  • Observer Gain (k_smo): Trade-off between convergence speed and noise sensitivity
  • Low-Pass Filter Cutoff: Filter back-EMF signals without excessive phase delay
  • Transition Speed: Minimum speed for sensorless operation (typically 5-10% rated speed)
  • Startup Ramp Rate: Balance between fast startup and smooth transition

Advantages of Sensorless Control:

        Reduced hardware cost (no encoder)
        Higher reliability (no mechanical sensor to fail)
        Simplified wiring and installation
        Suitable for harsh environments
    
    Limitations:
    
        Poor performance at zero/low speed
        Requires accurate motor parameters
        Sensitive to parameter variations (temperature, saturation)
        More complex tuning process

Example 3: Field Weakening Control

Overview

Field weakening extends the speed range of PMSM beyond the base speed by injecting negative d-axis current. This reduces the flux linkage, allowing higher speeds while maintaining voltage within DC bus limits.

Field Weakening Strategy

Operating RegionControl StrategyId CommandIq Command
Constant Torque (ω < ωbase)Maximum torque per ampere (MTPA)0 A (or slightly negative), Limited by max current
Field Weakening (ωbase < ω < ωmax)Voltage-limited operationNegative (increases with speed)Adjusted to maintain voltage limit
Constant Power (ω ≈ ωmax)Maximum speed operationMaximum negative IdReduced for voltage constraint

Implementation with MPLAB Blocks

  • Voltage Limit Calculation

  • Measure DC bus voltage using MCHP_ADC

  • Calculate maximum voltage: Vmax = Vdc / √3 (for SVPWM)

  • Account for voltage drops and modulation overhead

  • Field Weakening Controller

  • Input: Speed feedback, voltage magnitude, current limits

  • Output: Id_ref (d-axis current command)

  • Algorithm: PI controller on voltage error or lookup table

  • Current Limiting

  • Enforce circular current limit: √(Id² + Iq²) ≤ Imax

  • Priority given to Id (flux control) at high speeds

  • Reduce Iq if total current exceeds limit

Tuning Guidelines

ParameterTypical RangeEffect
Base Speed (ωbase)Rated speed or design speedTransition point to field weakening
Max Id Current50-80% of rated currentMaximum field weakening capability
Voltage Margin5-10% below VmaxSafety buffer for control headroom
FW Controller GainTuned for stabilityResponse speed vs. oscillations

Field Weakening Considerations:

        Increased copper losses due to higher total current
        Reduced efficiency at high speeds
        Risk of demagnetization with excessive negative Id
        Requires precise voltage and current limiting
        Test carefully with thermal monitoring

Development Workflow with MPLAB Blocks

Step 1: Model Development

  • Start from MCHP template for target device (e.g., dsPIC33CK Curiosity Board)
  • Add peripheral blocks: PWM, ADC, QEI, UART
  • Implement control algorithm using Simulink blocks
  • Configure multi-rate model: Fast loop (current) + Slow loop (speed)

Step 2: Simulation and Validation

  • Test algorithm with motor model in Simulink
  • Verify control stability and transient response
  • Check for numerical issues (saturation, overflow)
  • Optimize fixed-point data types for embedded implementation

Step 3: Code Generation and Deployment

  • Configure Embedded Coder settings in MCHP Master block
  • Generate C code and compile for target device
  • Program device using MPLAB X IPE or ICD
  • Use picgui or MPLAB Data Visualizer for initial debugging

Step 4: Real-Time Tuning

  • Enable External Mode in MCHP Master block
  • Connect via UART or USB to development PC
  • Adjust controller gains and parameters in real-time
  • Log data for post-processing and analysis

Step 5: Performance Optimization

  • Run PIL (Processor-in-the-Loop) test for execution time analysis
  • Optimize code with dsPIC assembly replacements (if needed)
  • Monitor CPU load using MCHP_MCULoad block
  • Verify scheduler timing with MCHP_TasksState block

Accessing ctrl-elec Resources

Educational Materials

  • Website:[https://www.ctrl-elec.fr/]

  • Comprehensive tutorials on motor control theory

  • Detailed explanations of FOC, sensorless control, and field weakening

  • Step-by-step lab exercises with MATLAB/Simulink

  • GitHub Repository:[https://github.com/rdelpoux/ctrl-elec]

  • Complete Simulink models for motor control examples

  • Reference implementations and test cases

  • Documentation and supplementary materials

  • RCP Platform:[http://rcp.ctrl-elec.fr/]

  • Rapid Control Prototyping platform documentation

  • Hardware setup guides for various development boards

  • Application notes and best practices

Adapting ctrl-elec Examples for MPLAB Blocks

The ctrl-elec examples can be adapted to use MPLAB Device Blocks by:

  • Replace generic peripheral blocks with MCHP-specific blocks:

  • Generic PWM → MCHP_PWM_HS_FEP

  • Generic ADC → MCHP_ADC

  • Generic encoder → MCHP_QEI

  • Configure MCHP Master block for target device and enable multi-tasking

  • Adjust sample times to match MCHP scheduler rates

  • Enable External Mode using MCHP UART blocks for real-time tuning

  • Leverage MCHP-specific features:

  • PWM-triggered ADC for precise current sampling

  • DMA transfers for high-performance data movement

  • Assembly code replacement for optimized math operations


Integration Tip: The control algorithms (Clarke/Park transforms, PI controllers, observers) remain identical. Only the peripheral interface blocks need to be replaced with MPLAB-specific blocks. The ctrl-elec documentation provides excellent theoretical background that complements the MPLAB blocks hardware implementation.

Additional Resources

MPLAB Blockset Documentation

  • [Scheduler and Multitasking] - Configure multi-rate control loops
  • [External Mode and PIL Testing] - Real-time tuning and verification
  • [PWM Block Reference] - Motor drive PWM configuration
  • [ADC Block Reference] - Current and voltage sensing setup
  • [QEI Block Reference] - Encoder interface for position feedback

Microchip Application Notes

  • [AN1078] - Sensorless Field-Oriented Control (FOC) for PMSM
  • [AN1292] - Sensorless Field-Oriented Control of Three-Phase PMSMs
  • [AN1160] - Sensorless Field-Oriented Control of PMSM Motors
  • [AN2520] - Field Weakening for PMSM Motor Control

Summary

This guide demonstrated how to implement advanced motor control algorithms using the MPLAB Device Blocks for Simulink, leveraging educational resources from the ctrl-elec project (INSA Lyon).

Key Takeaways:

  • MPLAB blocks provide hardware-optimized peripheral interfaces for motor control
  • Field-Oriented Control (FOC) can be implemented using standard Simulink blocks + MCHP PWM/ADC
  • Sensorless control eliminates encoders using observers, with trade-offs in low-speed performance
  • Field weakening extends speed range beyond base speed using negative d-axis current
  • External Mode and PIL testing enable efficient tuning and verification
  • Multi-rate scheduling optimizes CPU usage for nested control loops

Next Steps:

  • Visit [ctrl-elec website] for motor control theory tutorials
  • Download example models from [ctrl-elec GitHub]
  • Adapt examples using MCHP peripheral blocks for your target device
  • Use picgui and External Mode for real-time development
  • Refer to MPLAB blockset documentation for block-specific configuration details

Attribution

Motor control algorithms, theory, and examples presented in this guide are provided by:

ctrl-elec project - Real-time Control & Embedded Systems EducationINSA Lyon (Institut National des Sciences Appliquées de Lyon), France

Website:[https://www.ctrl-elec.fr/]GitHub:[https://github.com/rdelpoux/ctrl-elec]RCP Platform:[http://rcp.ctrl-elec.fr/]

This documentation is part of the MPLAB Device Blocks for Simulink toolbox. The ctrl-elec project and INSA Lyon are independent educational initiatives. Microchip Technology provides the MPLAB blocks hardware interface, while ctrl-elec provides motor control algorithms and educational materials.

MPLAB Device Blocks for Simulink © Microchip Technology Inc. All rights reserved.

See Also

Application Notes

GitHub

ctrl-elec