Motor control is a topic that engineers cannot avoid. Qualified engineers must have rich experience in the entire motor control before designing. This article will sort out the process and composition of motor control in detail from the three aspects of synchronization, timing and software, and share the experience of engineers in actual work.
Synchronization and Timing
Proper timing, synchronization, and deterministic system response are top priorities for every real-time application, and special attention must be paid to these aspects when designing motor control software. In essence, the process sounds simple: the system reads sensor values, processes the control algorithm, monitors system safety, and manages the output stage by adjusting the duty cycle of the PWM output.Minor timing errors can lead to serious system response errors, unstable operation and poor performance. In order to ensure that everything runs as expected, it is crucial to maintain synchronization and ensure the determinism of the system. Here, I want to emphasize that we are dealing with a "hard real-time system" and it is absolutely critical to meet strict deadlines.Motor controller software can be implemented as a bare-metal solution without an operating system using a suitable RTOS (Real-Time Operating System), or as a multi-core hybrid solution where some CPU cores run in bare-metal mode while others use an operating system. Bare-metal solutions are always based on interrupt-driven designs where interrupts handle time-critical tasks, ensuring that everything happens at precise intervals.Whether it is a bare metal, RTOS, or hybrid solution, timing analysis, task prioritization, and safety analysis must be performed to ensure efficient and reliable system performance.Timing analysis ensures that all tasks are completed on time. This includes considering the worst-case execution time for each task. Some of the main critical tasks in motor control include sensor data acquisition, execution of control algorithms through PWM signal generation, fault detection and handling, emergency stop and safety functions, real-time communication with other system components, and synchronization with external systems.As mentioned earlier, phase-locked loops (PLLs), whether integrated into MCU/DSP hardware or implemented as IP cores in FPGAs, are essential for synchronizing critical events. The primary function of a PLL is to synchronize the internal clock of the MCU/DSP/FPGA with an external clock source or signal. This is critical for maintaining timing accuracy in real-time applications. PLLs help reduce clock jitter, which is critical for precise timing, especially important when controlling the speed and position of a motor. PLLs ensure precise timing alignment between the sampling of feedback signals (such as rotor position and current measurement) and the execution of the control algorithm, ensuring optimal synchronization and accuracy. In a multi-core system, PLLs can be used to synchronize the operation of these cores.Synchronizing pulse width modulation (PWM) with current measurement and analog-to-digital conversion (ADC) via a phase-locked loop (PLL) is critical to ensuring accurate and efficient system performance in motor control applications. By synchronizing the clock, the PLL ensures that all system components, including the PWM generator, ADC, and other processing elements, run on a synchronized clock. The PWM signals that control the power delivered to the motor are generated based on this synchronized clock. The timing of these signals directly affects motor performance. Current sensors measure the current in the motor. The timing of these measurements is critical, especially in systems such as field-oriented control (FOC), where current feedback is used to control motor torque and speed. The analog signals from the current sensors are converted to digital values using an ADC. The PLL helps synchronize the ADC sampling with the PWM cycle. This synchronization ensures that the ADC samples the current at the optimal time relative to the PWM signal (usually at a point where the PWM is neither fully on nor fully off) to obtain accurate current. The digitized current measurement is then fed into the control algorithm. The PLL ensures that the measurements are taken at consistent intervals relative to the PWM signal, allowing the control algorithm to accurately modify the PWM duty cycle based on changes in state variables, ensuring optimal motor performance. By synchronizing ADC sampling with PWM, the effects of switching noise and distortion can be minimized. This is especially important in high-power motor control applications, where PWM signals can have significant noise.
Current and position measurement
It is critical to accurately measure the current and synchronize it with the PWM pulses. Techniques such as periodic sampling, current oversampling, and averaging are used to improve accuracy.The frequency of periodic sampling is the same as the frequency of the PWM, so the challenge is to determine the appropriate sampling time. This involves setting the appropriate delay between the start of the PWM cycle and the analog-to-digital conversion.Current oversampling involves sampling at a higher frequency than the PWM frequency (sometimes 8-32 times higher) and averaging the measurements. The ADC interrupt service routine (ISR) frequency can be much higher than the PWM frequency, allowing detailed data to be collected.Oversampling is limited by the bandwidth of the current sensor. For example, most Hall sensors commonly used in motor control have a bandwidth between 50 kHz and 160 kHz. Proper timing and synchronization are key to dealing with the high frequency oscillations that affect the phase currents.
Figure 1: Synchronous PWM and current measurement
Figure 1 shows the timing in one processing cycle. The analog-to-digital converter (ADC) can be configured to sample at a high frequency. This requires setting the ADC clock and adjusting its sampling rate. After sampling is completed, the MCU or DSP processes these samples to calculate their average. This calculation is usually performed after accumulating a specific number of samples. The main processing interrupt service routine (ISR) must be configured to trigger when the average calculation is completed. In addition, the PWM module needs to be set up in a way that ensures synchronization between ADC sampling, ISR, and PWM timing. Modern MCUs and DSPs are good at handling these tasks simultaneously due to their high processing power, real-time operation capabilities, and a variety of peripherals designed to manage ADC, PWM, and ISR tasks.It is critical that the sampling of the position sensor data is synchronized with the main processing interrupt service routine. Also, any delays caused by the data transmission are taken into account and these delays can be calculated to maintain timing accuracy. When applying any filter, it is important to consider the effect of phase delay. In the case of using a resolver to measure angular velocity, the processing of the resolver data must be synchronized and the point where the amplitude of the sine and cosine signals is minimal must be selected to ensure accurate readings. In addition, the resolver signal is oversampled and a bandpass filter with a cutoff frequency that matches the PWM frequency is applied. This approach helps to filter out unwanted frequencies while maintaining the integrity of the signal.In high-speed systems, position must be inferred to ensure rotor accuracy so that the stator field is properly aligned relative to the rotor field. Accurate angle measurement ensures the right amount of power is delivered to the motor at any given time, reducing energy losses, torque ripple, vibration, and heat.This discussion focuses primarily on field-oriented control (FOC) applications that utilize direct rotor position measurement. It does not delve into sensorless FOC applications, where the rotor position is not measured directly but estimated through indirect methods.
Some common safety features often seen in motor control applications include:Safe Torque Off (STO): This feature immediately removes power to the motor drive, causing the motor to stop producing torque. This is a critical feature in emergency situations when the motor needs to be stopped as quickly as possible to prevent injury.Safe Direction Indicator (SDI): Prevents the motor from running in unintended directions.Safe Operating Stop (SOS): This function keeps the motor at a stop without removing power.Safe Speed Range (SSR) or Safely Limited Speed (SLS): Ensures that the motor operates within the safe speed range or below the safe maximum speed.Overcurrent protection: This feature protects motors and electronic devices from damage due to overcurrent caused by faults such as short circuit or overload.Overvoltage and undervoltage protection: These features prevent voltage from being too high or too low, which could damage the motor or control electronics.Thermal protection: Monitors the temperature of the motor and drive, and if the temperature exceeds safe limits, the system can shut down to prevent overheating.Speed monitoring and limiting: Ensuring that the motor does not exceed predefined speed limits is critical in applications where exceeding a certain speed could be dangerous.Emergency Stop: A physical button or switch that can immediately stop the motor. This is a standard feature that is required in industrial applications.Safe Brake Control: For motors equipped with brakes, this feature safely engages the brake to stop the motor, especially in applications that move vertically under gravity. Before activating the Safe Brake function, the system first attempts to stop the motor using electrical braking (if feasible), during which the energy flow is reversed to slow the motor.Safety functions can be implemented in hardware (HW), software (SW) or a combination of both, depending on the specific requirements and constraints of the application. Safety functions such as overvoltage and undervoltage protection, overcurrent protection, thermal protection and emergency stop are often implemented in hardware to ensure strong, fast and reliable system protection.Speed monitoring and limiting, fault detection algorithms and safe operating stop (SOS) are implemented in software.Functions such as safe torque off (STO), safe direction (SDI), safe speed range (SSR)/safe limited speed (SLS) and safe brake control are often implemented through a combination of hardware and software. This hybrid approach typically involves software commands for actuation and control, while relying on hardware components for effective execution and execution.The topic of safe design and functional safety in motor control, including standards such as SIL3, is another dedicated topic.Various manufacturers in the embedded systems and motor control space offer comprehensive design packages and tools designed to facilitate and accelerate the design and certification process in key areas such as industrial, transportation, energy, and medical. These packages often include pre-certified software libraries, detailed safety manuals, and hardware modules designed to comply with stringent safety standards such as IEC 61508, ISO 13849, etc. In addition, they often provide extensive documentation and support to achieve certifications such as SIL (Safety Integrity Level) ratings, which are essential for high-reliability and safety-critical applications. This assistance not only simplifies the development process, but also significantly reduces the time and effort required for compliance and certification in these highly regulated industries.
Real-time operating system (RTOS)
Choosing the right RTOS for motor control applications is critical to ensuring high performance, reliability, and safety. Key considerations include the RTOS's real-time performance, resource efficiency (including memory footprint and CPU utilization), and priority-based preemptive scheduling. Efficient and fast interrupts, as well as the reliability and robustness of the system are also key factors. Vendor support and documentation, compatibility with hardware, and the availability of development tools (such as IDEs, debuggers, and profilers) and ecosystems (including libraries and code examples) play an important role. Finally, the licensing terms and cost of the RTOS should also be considered.Considering the various factors and specific requirements of motor control applications, FreeRTOS, a widely acclaimed open source real-time operating system known for its efficiency and versatility, becomes an excellent choice. This choice is particularly beneficial in scenarios where cost-effectiveness, operational efficiency, system flexibility, reliability and robustness, ease of use, broad hardware support, and resource efficiency are key considerations.
Figure 2: Overview of motor control system architectureThe architecture of a motor control application consists of several layers and modules:Hardware Abstraction Layer (HAL): Provides standardized interfaces for accessing hardware peripherals (including ADC, PWM controllers, and communication interfaces), promoting portability and scalability. It also contains the Board Support Package (BSP) and drivers for various hardware peripherals, enabling seamless hardware-software integration.Core real-time runtime layer: This layer contains the real-time operating system (RTOS) for efficient task scheduling and system resource management. It also includes specialized memory management with a real-time heap allocator designed to optimize memory allocation in time-critical applications. In addition, this layer integrates powerful inter-core and inter-process communication (IPC) mechanisms to facilitate seamless data exchange and synchronization between different cores and processes within the system. This layer serves as the backbone of core operating functions, ensuring smooth and efficient runtime performance.Middleware layer: This layer integrates the following key functions:
-
Communication interfaces: Manage interactions with external systems or devices using various communication protocols.
-
Tracking and Data Logging: Focus on tracking and logging specific signals and events, capable of real-time data output via DAC, IO, Ethernet, UART, USB and other channels.
-
Software Upload: Oversee the upload of new software versions or updates to ensure seamless integration and system continuity.
-
Configuration Management: Deals with the optimization and operational adjustments of the customer's system configuration settings.
-
Diagnostics and Monitoring: Provides system diagnostics and ongoing monitoring tools, which are critical to maintaining system health and performance.
-
Built-in Test (BIT): Includes self-test functions to check the status and functionality of hardware and software components.
Motor Control Application Layer: Sitting on top of all layers is the motor control application, which is the key component for executing application-specific workflows. This layer encapsulates:
-
Control and signal processing algorithms: This includes core control algorithms such as PID control and field-oriented control (FOC), as well as signal processing algorithms designed to optimize motor performance.
-
Safety Logic: This component is dedicated to the safety aspects of the system, implementing the necessary protocols for emergency situations and routine safety checks to ensure that the system operates within safety parameters.
-
Application-specific workflows: This layer also integrates additional, unique workflows tailored to the specific requirements of motor control applications, ensuring comprehensive functionality and performance.
The application workflow typically involves several key steps:First-stage bootloader (FSBL): This important component is responsible for the initial stages of the boot process, including low-level hardware initialization and loading major software components. A key part of its role is to load and start the user application. The FSBL runs separately from the application layer and is usually provided by the MCU or DSP in its SDK. Customization of the BSP is often required, such as adding additional memory checks or diagnostic functions, to ensure that the FSBL meets specific system requirements and enhances overall reliability.Platform Setup: Initialization of hardware components: This includes setting up the ADC (Analog to Digital Converter), system interrupts, PWM (Pulse Width Modulation) modules, communication interfaces (such as SPI, I2C, UART), watchdog timer, and any other necessary hardware peripherals. Set up interrupt handling mechanisms to respond to events such as timer overflow/input changes or communication. Configure system clocks, power modes, and ensure efficient power management for controllers and motors.Application Configuration: This step contains the critical task of defining operating parameters, which is usually achieved by reading configuration files. These files specify essential details such as motor characteristics, control parameters, and operating limits. In addition, configuration settings can be adjusted in a variety of ways, including digital inputs, DIP switches, or dynamically through the communication interface of an external PC or host device. This multifaceted approach ensures flexible and adaptable configuration management to meet a wide range of application needs.This phase also includes:
-
Define tasks: Create tasks such as the main control task, communication tasks, health monitoring tasks, etc., which are critical to the functionality of the application.
-
Set Priority: Assign priorities to these tasks based on their importance and role in the application. This is essential to ensure that critical tasks, such as main control tasks, receive the necessary CPU response before less critical tasks.
-
Configure task properties: This can include setting the stack size, specifying task parameters, and configuring any task-specific properties.
-
Establish inter-task communication: Establish a mechanism for inter-task communication, such as queues, semaphores, or shared data structures.
Sensor Calibration: In applications where sensors are integrated, their calibration is critical to ensure accurate readings. Specifically, commonly used Hall Effect sensors exhibit initial offsets that must be accounted for. During the calibration phase, these initial offsets are identified and subsequently subtracted from the current measurement to correct the sensor output. This step is critical to guaranteeing the accuracy of the sensor data.Communications and Monitoring: Handles communications with external devices or systems for command and control, diagnostics, or remote monitoring.
Human Machine Interface (HMI)
In motor control applications, the HMI can mean simple physical controls and indicators (such as buttons, LEDs, or displays) or a remote control interface.This part of the workflow includes:Sensor Data Acquisition: Reading and processing data from sensors in real time, which is required for control loop feedback.
-
Real-time control loop execution: This is where the main control algorithm (such as PID control or FOC) is executed, usually in the main controller. Responds to timer interrupts to achieve consistent timing.
-
Actuator Command Generation: Generates commands for actuators such as motor drives based on the output of the control algorithm. It usually involves setting up specific digital outputs and PWM signal generation.
-
Safety and emergency handling: To ensure an immediate response to safety and emergency events (e.g., emergency shutdowns), these events should be handled sequentially and with high priority in this dedicated phase. This approach not only minimizes delays in handling critical events, but also enhances the overall safety and reliability of the system. In addition, this phase also includes detecting and responding to various types of faults, including overcurrent, overvoltage, and hardware failures. By prioritizing these tasks, the system is better able to address and mitigate potential risks in a timely manner, ensuring a safer operating environment.
The key principle is to maintain a concise interrupt service routine (ISR) that is mainly used to notify the main control task when further processing is required. Its main role is not to execute the entire control logic within the ISR, but to notify higher priority tasks about the occurrence of events. For this purpose, FreeRTOS provides various notification methods, such as binary semaphores, task notifications, or queues. The master control task is an RTOS task that is responsible for the main control algorithm. Once notified by the ISR, the task is activated (or unlocked) and performs all the necessary steps described previously. It is crucial to assign an appropriate priority to the main control task to ensure that the control algorithm is processed in a timely manner after the ISR.A watchdog timer should be used to ensure operation of the main task, which is designed to reset the watchdog timer periodically, demonstrating its correct operation and preventing the timer from expiring and triggering a system reset or error routine.System health monitoring: Continuously monitors the system for faults such as overheating or other anomalies, and takes appropriate action if any issues are detected.Logging and data logging: Record important events, errors, and system performance metrics for future analysis or troubleshooting.
Figure 3: Data journey: from motor controller recording to PC analysisGraceful shutdown: Ensures that the motor and controller shut down safely when the application stops.If the application runs on a multicore MCU/DSP/FPGA, appropriate inter-core communication mechanisms must be ensured. This can be achieved using on-chip shared RAM and software interrupts, but the approach may vary from platform to platform. Other possibilities include message passing interfaces, direct memory access (DMA) channels, or the use of architecture-specific dedicated hardware communication blocks.A common approach is to have one core dedicated to communication tasks and another core for the main control loop. An RTOS is often used on both cores for efficient task management, but the main control core is often run in a bare-metal environment for simplified low-level control. Products including Texas Instruments' CLA, ARM's Cortex-M DSP extensions, STMicroelectronics' ART accelerators, Microchip's dsPIC, NXP's motor control coprocessors, and Infineon's XMC digital coprocessors all offer specialized processing units to enhance performance for specific embedded system applications. Such extensions increase overall computational bandwidth and free up the CPU to perform other tasks, such as communications, monitoring, and diagnostics.