A cross-platform field-oriented control method for permanent magnet synchronous motor

CN123019546APending Publication Date: 2026-10-30XIJING UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611296176.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-25
Publication Date
2026-10-30

AI Technical Summary

Technical Problem

[0005]针对现有技术的不足,本发明提供了一种永磁同步电机的跨平台磁场定向控制方法,具备控制时序跨平台一致性继承、死区补偿平滑无跳变、多平台统一代码分支维护及快速平台迁移的优点,解决了现有FOC控制方法在跨平台移植时控制时序失效、死区补偿过零点占空比抖动、多平台维护成本高及迁移周期长的问题

Benefits of technology

[0043]1、本发明通过编译阶段注入的三层递进式硬件兼容映射层(类型等价映射→位域符号映射→指令级等价替换),将FOC控制算法中全部外设寄存器访问操作在编译期等价变换为目标微控制器的寄存器操作指令(LDR/ORR/STR三指令序列),使同一套控制算法在不同微控制器平台上产生完全等价的PWM输出时序和ADC采样时序,达到了已调优的控制参数(PI增益、时序偏移、死区补偿值)在不同平台间直接继承的技术效果,无需重新调参,消除了跨平台移植后控制性能衰减的问题。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123019546A_ABST
    Figure CN123019546A_ABST
Patent Text Reader

Abstract

The application relates to the technical field of permanent magnet synchronous motor control, and discloses a cross-platform magnetic field oriented control method for a permanent magnet synchronous motor, which injects three-layer progressive hardware compatible mapping layers of type equivalent mapping, bit field symbol mapping and instruction level equivalent replacement in the compiling stage, equivalently transforms all peripheral register access operations in the FOC control algorithm into LDR / ORR / STR register operation instruction of a target microcontroller in the compiling period, makes the same set of control algorithms produce completely equivalent PWM output time sequences and ADC sampling time sequences on different microcontroller platforms, thereby realizing direct inheritance of the optimized control parameters among different platforms, and finally eliminating the problem of control performance attenuation after cross-platform transplantation; meanwhile, the traditional phase current symbol hard switching in the dead zone compensation link is replaced by a segmented continuous compensation function with a linear transition zone, so that the compensation quantity continuously changes in the whole real number domain, and the double-value step jump of the compensation quantity caused by ADC noise near the zero point of the phase current is eliminated.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of permanent magnet synchronous motor control technology, specifically a cross-platform field-oriented control method for permanent magnet synchronous motors. Background Technology

[0002] Field-oriented control (FOC) of permanent magnet synchronous motors (PMSMs) is a core technology for high-precision motor control, achieving precise torque and speed regulation through coordinate transformation and dual closed-loop PI control. However, existing FOC methods face four major technical bottlenecks when migrating across platforms: First, differences in peripheral register access methods lead to control timing offsets, compromising the effectiveness of optimized parameters; second, dead-time compensation strategies cause PWM duty cycle jitter due to sign transitions at current zero-crossing points, exacerbating torque ripple; third, multi-platform adaptation requires maintaining independent code branches, with development costs increasing exponentially with the number of platforms; and fourth, manual porting takes 2-4 weeks, making it difficult to meet the needs of rapid product iteration.

[0003] To address these issues, existing technologies attempt to achieve platform migration by replacing the entire hardware abstraction layer. However, differences in the underlying instruction sequence still lead to timing mismatches, and the hard switching defects of dead-time compensation cannot be avoided. Furthermore, traditional solutions lack a compile-time hardware behavior equivalence mapping mechanism, relying on manual line-by-line code modification, which is inefficient and prone to introducing human error. Summary of the Invention

[0004] (a) Technical problems to be solved

[0005] To address the shortcomings of existing technologies, this invention provides a cross-platform field-oriented control method for permanent magnet synchronous motors. It has the advantages of consistent inheritance of control timing across platforms, smooth dead-zone compensation without jumps, unified code branch maintenance across multiple platforms, and rapid platform migration. It solves the problems of control timing failure, dead-zone compensation zero-crossing duty cycle jitter, high maintenance cost across multiple platforms, and long migration cycle of existing FOC control methods when ported to multiple platforms.

[0006] (II) Technical Solution

[0007] To achieve the above objectives, the present invention provides the following technical solution: a cross-platform field-oriented control method for a permanent magnet synchronous motor, comprising the following steps:

[0008] S1. Construct type equivalence mapping for register access: During the compilation phase, in the hardware-compatible mapping header file, the data type of the peripheral base address of the target microcontroller is uniformly defined as the same type name as that of the source microcontroller, and the peripheral base address is remapped using preprocessing macros;

[0009] S2. Construct symbolic mapping of register bit control domains: During the compilation phase, all register bit control macro names of the first microcontroller referenced in the field orientation control algorithm are mapped one by one to the macro names of the corresponding register bits of the target microcontroller using the #define preprocessing directive, and the three-line conditional compilation protection mode of #ifndef...#define...#endif is adopted.

[0010] S3. Constructing instruction-level equivalent replacements for peripheral driver interfaces: During the compilation phase, each call to the hardware abstraction layer driver interface in the FOC control algorithm is mapped one-to-one to a compile-time inline function that directly operates the peripheral registers of the target microcontroller using a static inline function. At optimization levels of -O1 and above, the compiler expands the inline function body of each call point into a three-instruction sequence of load / bit OR / store, and the number of cycles is exactly the same as the number of assembly instructions generated by the native code of the target microcontroller directly operating the PWM timer register.

[0011] S4. Configure the target platform's control peripherals: Create a new peripheral initialization source file and strictly configure the various peripheral parameters of the target microcontroller according to the control timing sequence;

[0012] S5. Associate the hardware compatibility mapping layer and compile the environment: In the compilation configuration, change the C compiler's header file search path from pointing to the source microcontroller hardware abstraction layer to pointing to the hardware compatibility mapping layer and the target microcontroller standard peripheral library;

[0013] S6. Compilation Verification and Ordered Error Correction: During the compilation process, errors are checked and corrected in the order of step S1 type layer → step S2 bit macro layer → step S3 function layer.

[0014] S7. Burn and run control: Burn the compiled target firmware to the target microcontroller. After powering on, first execute the startup diagnosis in step S4. After confirming that the system is normal, start the motor and execute the FOC control cycle according to the set timing.

[0015] Preferably, the type equivalence mapping construction process for register accesses in S1 is as follows:

[0016] S1.1, For the target microcontroller in uint3 Integer macros represent peripheral base addresses, while the source microcontroller accesses them via structure pointers, using the C language typedef uint3. TIM_ Define the peripheral register type as uint3 ;

[0017] S1.2 Then, by using #define TIM1, the numerical base address of the target microcontroller is forcibly converted to a type name compatible with the source microcontroller, so that the register access expression in the style of the source microcontroller is equivalently transformed into an access instruction to the actual hardware register address in the compilation environment of the target microcontroller.

[0018] Preferably, the correctness of the equivalent transformation in S1 is based on the following hardware fact: the base address and offset address layout of the registers of the pulse width modulation timer, analog-to-digital converter, and motor control-related peripherals of the general-purpose input / output port of the first microcontroller and the second microcontroller are completely consistent, which is guaranteed by the register-level interface compatibility design of the GD32F4xx product.

[0019] Preferably, the formal semantics of the protection mode in S2 is:

[0020] (1) When a macro name is already defined in the target microcontroller's native header file, the Shim layer skips the definition;

[0021] (2) When the macro name exists only in the namespace of the source microcontroller, the Shim layer provides the definition as a supplement.

[0022] Preferably, each compile-time inline function in S3 satisfies the function signature equality constraint, that is, the function name, parameter types and number, and return value type are identical to the original driver function of the source microcontroller word by word, and the function body directly operates on the register bits of the target microcontroller.

[0023] Preferably, the configuration of the control peripheral parameters of the target platform in S4 includes:

[0024] (a) Configure the system clock tree: The external high-speed crystal oscillator is multiplied to a 168MHz system clock via a phase-locked loop, of which the high-performance bus clock is 168MHz, the peripheral bus 2 clock is 84MHz, and the analog-to-digital converter clock is 21MHz;

[0025] (b) Configure the multiplexing function of control-related pins: Configure PA8 / PA9 / PA10 and PB13 / PB14 / PB15 as PWM output, configure PC6 / PC7 / PC8 as encoder input, configure PC0 / PC1 / PC2 as analog-to-digital converter current sampling input, and configure PB6 / PB7 as serial communication.

[0026] (c) Enable the clocks for the PWM timer, analog-to-digital converter, encoder timer, serial port and universal serial bus peripheral modules;

[0027] (d) Perform interrupt vector name mapping: map the interrupt vector name of the source microcontroller to the corresponding interrupt vector name of the target microcontroller;

[0028] (e) Start-up diagnostics: After power-on, check the phase-locked loop lock status, external high-speed crystal oscillator start-up status, PWM timer clock, analog-to-digital converter clock, and general-purpose input / output port clock in sequence, and return an 8-bit bit-encoded fault code.

[0029] Preferably, the code in all source files of the FOC control algorithm layer in S5 is not modified in any way, and the original peripheral register access expressions and driver interface calls remain unchanged.

[0030] Preferably, the compilation verification and ordered error correction in S6 are implemented as follows:

[0031] (1) After the first round of compilation, check for type layer errors and supplement the missing typedef definitions;

[0032] (2) After the second round of compilation, check for errors in the bit macro layer and supplement the missing #define register bit mappings;

[0033] (3) After the third round of compilation, check for errors in the function layer and supplement the missing static inline function definitions.

[0034] Preferably, the firmware is burned and a magnetic field orientation control loop with dead-zone compensation is executed in step S7:

[0035] (I) Overview of interrupt scheduling and timing guarantee mechanism: The nested vector interrupt controller with ARM Cortex-M4F core is adopted. The priority group is NVIC_PRIGROUP_PRE3_SUB1. The 7 interrupt sources are arranged in order of preemption priority from high to low: PWM overflow update interrupt → ADC injection group conversion end interrupt → encoder overflow / serial communication interrupt → PWM brake / USB interrupt → SysTick interrupt;

[0036] (ii) Deterministic guarantee of worst-case execution time of the current loop: Item by item, the total instruction cycle from interrupt response to PWM register write is accumulated: NVIC response delay 12 cycles + ADC data reading and preprocessing 80 cycles + Clarke transform 120 cycles + Park transform 180 cycles + d-axis PI control 150 cycles + q-axis PI control 150 cycles + inverse Park transform 180 cycles + space vector pulse width modulation calculation 200 cycles + PWM compare register write and interrupt return 60 cycles = 1132 CPU cycles;

[0037] (III) Execution sequence of the magnetic field orientation control calculation process: Executed once every 62.5 microseconds: The PWM timer overflow event triggers the ADC injection group hardware automatic conversion to complete the three-phase current synchronous sampling; After the ADC conversion ends and the interrupt is triggered, Clarke transformation, Park transformation, d-axis PI control, q-axis PI control, inverse Park transformation and SVPWM calculation are executed in sequence. Finally, the three-phase duty cycle is written to the PWM comparison register through the inline function in step S3. Every 500 microseconds, the speed loop PI calculation is executed in the SysTick interrupt to update the q-axis current setpoint, forming a double closed-loop cascaded control structure of speed outer loop and current inner loop;

[0038] (iv) Dead-zone compensation control method with linear transition region: The traditional hard-switching compensation based on phase current sign is replaced with a piecewise continuous compensation function:

[0039]

[0040] in, This represents the PWM comparison value compensation amount in the k-th PWM cycle, and DTCompCnt represents the dead-time compensation full-count value. This represents the phase current ADC sample value. The threshold for the transition region, when > The time compensation amount is +DTCompCnt; when <- When it is -DTCompCnt; when | |≤ The time is (DTCompCnt / )× .

[0041] Preferably, the threshold of the transition region in the S7 piecewise continuous compensation function satisfies the upper limit. ≤¼ × and lower limit > × The dual constraints, which add 20 CPU cycles of computation, satisfy the design constraints by no more than 5%.

[0042] Compared with the prior art, the present invention provides a cross-platform field-oriented control method for permanent magnet synchronous motors, which has the following beneficial effects:

[0043] 1. This invention uses a three-layer progressive hardware compatibility mapping layer (type equivalence mapping → bit field symbol mapping → instruction-level equivalence replacement) injected during the compilation stage to equivalently transform all peripheral register access operations in the FOC control algorithm into register operation instructions (LDR / ORR / STR three-instruction sequence) of the target microcontroller at compile time. This enables the same control algorithm to produce completely equivalent PWM output timing and ADC sampling timing on different microcontroller platforms, achieving the technical effect of direct inheritance of optimized control parameters (PI gain, timing offset, dead zone compensation value) between different platforms without the need for re-tuning, thus eliminating the problem of control performance degradation after cross-platform porting.

[0044] 2. This invention replaces the traditional hard switching of the phase current sign in the dead-zone compensation stage with a piecewise continuous compensation function with a linear transition region, so that the compensation amount changes continuously throughout the real number domain. This achieves the technical effect of eliminating the double-value step jump of the compensation amount caused by ADC noise near the zero-crossing point of the phase current, fundamentally suppressing PWM duty cycle jitter and zero-current clamping effect, improving the current waveform quality and reducing torque ripple. At the same time, the additional calculation amount accounts for only 1.8% of the current loop WCET, and does not affect the real-time performance of the 16kHz control cycle.

[0045] 3. This invention, by modifying only the compiler's header file search path (from the source microcontroller's HAL / LL library to the Shim layer and the target microcontroller's standard peripheral library), keeps all 120 source files (120 files) of the FOC control algorithm layer unchanged. This achieves cross-platform deployment by eliminating the need to replace the hardware abstraction layer and modify the code piecemeal in traditional solutions, transforming it into a modular architecture of a control algorithm + M mapping header files. This results in a reduction of the maintenance and migration cycle of unified code branches across multiple platforms from 2-4 weeks to approximately 8 hours, thus meeting the rapid iteration needs of motor control products. Attached Figure Description

[0046] Figure 1 This is a flowchart illustrating the control process of the method of the present invention. Detailed Implementation

[0047] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0048] Please see Figure 1 A cross-platform field-oriented control method for a permanent magnet synchronous motor includes the following steps:

[0049] S1. Construct type equivalence mapping for register access (first-level hardware compatibility mapping): During the compilation phase, in the hardware compatibility mapping header file (Shim layer), the data type of the peripheral base address of the target microcontroller (such as GigaDevice GD32F405) is uniformly defined as the same type name as that of the source microcontroller (such as STMicroelectronics STM32F407), and the peripheral base address is remapped using preprocessing macros;

[0050] S1 register access type equivalence mapping construction process:

[0051] S1.1, For the target microcontroller in uint3 Integer macros represent peripheral base addresses (e.g., #define TIMER0 (0x40010000U)), while the source microcontroller accesses them via structure pointers (e.g., TIM_TypeDef*). This is achieved using the C language typedef uint3. TI Define the peripheral register type as uint3 ;

[0052] S1.2 Then, by using #define TIM1 ((TIM)TIMER0), the numerical base address of the target microcontroller is forcibly converted to a type name compatible with the source microcontroller, so that the register access expression in the style of the source microcontroller (such as TIM1->CR1) is equivalently transformed into an access instruction to the actual hardware register address in the compilation environment of the target microcontroller.

[0053] The following is an example of mapping in this step (#define remapping peripheral base address):

[0054] Typedef uint3 ADC_TypeDef, TIM_TypeDef, GPIO_TypeDef, USART_TypeDef, DAC_TypeDef;

[0055] typedef uint3 DMA_Stream_TypeDef;

[0056] typedef uint FunctionalState;

[0057] #define ADC1 ((ADC_TypeDef)ADC0) / / Analog-to-digital converter base address mapping;

[0058] #define ADC2 ((ADC_TypeDef)ADC1);

[0059] #define TIM1 ((TIM_TypeDef)TIMER0) / / PWM timer base address mapping;

[0060] #define TIM2 ((TIM_TypeDef)TIMER1) / / Encoder timer base address mapping;

[0061] #define USART1 ((USART_TypeDef)USART0) / / Serial port base address mapping;

[0062] The correctness of this equivalent transformation is based on the following hardware fact: the register base address and offset address layout of motor control-related peripherals such as the Pulse Width Modulation (PWM) timer, Analog-to-Digital Converter (ADC), and General Purpose Input / Output (GPIO) ports of the first microcontroller (STM32F407) and the second microcontroller (GD32F405) are completely identical (e.g., the PWM timer base address is 0x40010000, and the control register offset is 0x00), guaranteed by the register-level interface compatibility design of the GD32F4xx products. It should be noted that the -> operator operates on uint3. Integer operands are strictly a constraint violation according to the C99 standard, but they are supported as compiler extensions in mainstream C compilers for embedded systems (ARMCompiler 5 / 6, GCC for ARM). This extension is explicitly described in the ARM Architecture Procedure Call Standard (AAPCS).

[0063] The advantages are: by unifying the data type name of the peripheral base address and forcibly converting the numerical base address to a structure pointer compatible type, the register access expression of the source microcontroller style can be correctly parsed in the target compilation environment. This helps to eliminate compilation errors caused by differences in peripheral access syntax between the two platforms, and at the same time, it enables zero-modification porting of the control algorithm source code, thus laying the type foundation for the subsequent instruction-level timing equivalence of this invention.

[0064] S2. Constructing the symbolic mapping of register bit control domains (second-level hardware compatibility mapping): During the compilation phase, all register bit control macro names of the first microcontroller referenced in the Field-Oriented Control (FOC) algorithm are mapped one by one to the corresponding register bit macro names of the target microcontroller using the #define preprocessing directive. A three-line conditional compilation protection mode (#ifndef ... #define ... #endif) is then used. The formal semantics of this protection mode are:

[0065] (1) When a macro name is already defined in the native header file of the target microcontroller, the Shim layer skips the definition (native library takes precedence).

[0066] (2) When the macro name exists only in the namespace of the source microcontroller, the Shim layer provides the definition as a supplement;

[0067] This mechanism ensures that every reference to a peripheral control bit or status bit in the control algorithm (such as the PWM enable bit or the ADC injection group conversion completion flag) is correctly parsed into an equivalent hardware register bit operation in the target microcontroller compilation environment.

[0068] This addresses the issue of duplicate macro definitions with the same name among multiple peripheral header files in the target microcontroller's standard peripheral library (e.g., BIT macros in gd32f4x). and gd32f4x (Both are defined in the code), #ifndef protection ensures the safe coexistence of the Shim layer and the target native library without introducing new conflicts.

[0069] The mapping example for this step (mapping approximately 160 register bit macros in total) uses the #ifndef / #define / #endif pattern:

[0070] #ifndef TIM_CR1_CEN;

[0071] #define TIM_CR1_CEN TIMER_CTL0_CEN / / PWM timer counter enable bit;

[0072] #endif;

[0073] #ifndef TIM_BDTR_MOE;

[0074] #define TIM_BDTR_MOE TIMER_CTL0_CEN / / Enable PWM main output;

[0075] #endif;

[0076] #ifndef BIT;

[0077] #define BIT(x) ((uint3 )(1U<<(x))) / / General bit manipulation macro (#ifndef protected);

[0078] #endif;

[0079] / / ...more than 160 items in total;

[0080] The advantages are: by using #ifndef conditional compilation protection to map the register bit macro names of the source microcontroller to the corresponding bit macro names of the target microcontroller, it is helpful to solve the compilation errors caused by the difference in register bit definition naming between the two platforms, and at the same time avoid the conflict of duplicate definition with the target native library, thereby ensuring that each operation in the control algorithm is correctly resolved into the equivalent hardware register bit operation when the target platform is compiled, and finally provides bit field symbol support for the third-level instruction-level replacement.

[0081] S3. Constructing instruction-level equivalent replacements for peripheral driver interfaces (third-layer hardware compatibility mapping): During the compilation phase, each call to the hardware abstraction layer driver interface in the FOC control algorithm is mapped one-to-one to a compile-time inline function that directly operates on the target microcontroller's peripheral registers using a static inline function.

[0082] In S3, each compile-time inline function satisfies the Function Signature Identity Constraint, meaning that the function name, parameter types and number, and return value type are identical to the original driver function of the source microcontroller, and the function body directly manipulates the register bits of the target microcontroller.

[0083] This step covers over 90 inline functions, including PWM timer classes (approximately 35), analog-to-digital converter classes (approximately 12), general-purpose input / output port classes (approximately 15), reset and clock unit (RCU) classes (approximately 8), digital-to-analog converter classes (approximately 5), and miscellaneous classes (approximately 15). Examples of key functions are as follows:

[0084] / * PWM timer control * /

[0085] static inline void LL_TIM_EnableCounter(TIM_TypeDef* TIMx)

[0086] {((uint3 )TIMx)->CTL0|= TIMER_CTL0_CEN;}static inline void LL_TIM_EnableAllOutputs(TIM_TypeDef* TIMx)

[0087] {((uint3 )TIMx)->SWWEVT |= TIMER_SWWEVT_SWEN;}static inline void LL_TIM_SetCompareCH1(TIM_TypeDef* TIMx,uint3 v)

[0088] {((uint3 )TIMx)->CH0CV=v;} / * Analog-to-digital converter injection group (current sampling)* /

[0089] static inline uint3 LL_ADC_IsActiveFlag_JEOS(ADC_TypeDef* ADCx)

[0090] {return ((uint3 )ADCx)->STAT & ADC_STAT_JEOS;}static inline uint3 LL_ADC_INJ_ReadConversionData12(ADC_TypeDef* ADCx)

[0091] {return ((uint3 )ADCx)->IDATA0;} / * General input / output port bit operations* / staticinline void LL_GPIO_SetOutputPin(GPIO_TypeDef* GPIOx, uint32_t m)

[0092] {((uint3 )GPIOx)->BOP=m;}static inline void LL_GPIO_ResetOutputPin(GPIO_TypeDef* GPIOx, uint32_t m) { ((uint3 )GPIOx)->BOP=(m<<16);}

[0093] / * Clock control * /

[0094] static inline void LL_APB1_GRP1_EnableClock(uint32_t Periphs)

[0095] {RC |= (Periphs & 0xFFFFFFFF);}

[0096] At optimization levels of -O1 and above, the compiler expands the inline function body at each call point into a three-instruction sequence of Load (LDR), Bitwise OR (ORR), and Store (STR) (approximately 6 CPU cycles), which is exactly the same as the number of assembly instruction cycles generated by the target microcontroller's native code directly manipulating the PWM timer register.

[0097] The execution of the three-layer mapping activities—type equivalence (typedef), bit field mapping (#define), and instruction substitution (staticinline)—is all completed at compile time by the C preprocessor and compiler optimizer. No independent code segments for any mapping layer are retained in the firmware during motor operation, achieving zero runtime overhead. There is a strict unidirectional dependency between the three layers: the inline function body of the third layer uses the type name (TI) defined in the first layer. ) and the second-level defined bit macro name (TI) This dictates that compilation error correction must proceed in the order of first level → second level → third level, consistent with the natural progression of register address → register bit → register operation instruction;

[0098] The advantages are: by using static inline functions, the hardware abstraction layer driver interface of the source platform is mapped one-to-one to the register direct operation of the target platform, and expanded at compile time into the LDR / ORR / STR three instruction sequence that is exactly the same as the target native code. This helps to ensure that the number of instruction cycles for accessing the underlying peripherals is strictly consistent across different platforms, thereby achieving cross-platform equivalence of PWM output timing and ADC sampling timing. At the same time, all mappings are completed at compile time, with no additional function call overhead at runtime, and do not affect the real-time performance of the current loop.

[0099] S4. Configure the target platform's control peripherals: Create a new peripheral initialization source file and strictly configure the various peripheral parameters of the target microcontroller according to the control timing sequence;

[0100] S4. The target platform's control peripheral parameter configuration includes:

[0101] (a) Configure the system clock tree: The external high-speed crystal oscillator (8MHz) is multiplied to a system clock of 168MHz via a phase-locked loop (PLL), of which the Advanced High-performance Bus (AHB) clock is 168MHz, the Advanced Peripheral Bus 2 (APB2) clock is 84MHz, and the analog-to-digital converter (ADC) clock is 21MHz;

[0102] (b) Configure the multiplexing function of control-related pins: Configure PA8 / PA9 / PA10 and PB13 / PB14 / PB15 as PWM output (multiplexing function AF1), configure PC6 / PC7 / PC8 as encoder input (multiplexing function AF2), configure PC0 / PC1 / PC2 as analog-to-digital converter (ADC) current sampling input, and configure PB6 / PB7 as serial communication (multiplexing function AF7).

[0103] (c) Enable the clocks of peripheral modules such as PWM timers, analog-to-digital converters (ADCs), encoder timers, serial ports (USART), and Universal Serial Bus (USB);

[0104] (d) Perform interrupt vector name mapping: Map the interrupt vector name of the source microcontroller (e.g., TIM). ) is mapped to the corresponding interrupt vector name of the target microcontroller (e.g., TIMER) );

[0105] (e) Start-up diagnostics: After power-on, check the phase-locked loop lock status, external high-speed crystal oscillator start-up status, PWM timer clock, analog-to-digital converter clock, and general-purpose input / output port clock in sequence, and return an 8-bit bit-coded fault code (0x00 indicates all passes);

[0106] The advantages are: by mapping the clock tree configuration, pin multiplexing, peripheral clock enable, and interrupt vector name of the source platform to the corresponding configuration of the target platform according to the control timing requirements, it is beneficial to establish a hardware operating environment on the target platform that is consistent with the source platform, ensuring that the timing conditions of the subsequent FOC control loop are the same as those of the source platform, and supporting the direct inheritance of control parameters at the system level.

[0107] S5. Associate the Hardware Compatibility Mapping Layer (Shim Layer) and Compilation Environment: In the compilation configuration, change the C compiler's header file search path from pointing to the source microcontroller's Hardware Abstraction Layer (HAL / LL library) to pointing to the Hardware Compatibility Mapping Layer (Shim Layer) and the target microcontroller's standard peripheral library; leave all source files (120 in total) of the FOC control algorithm layer unchanged, maintaining the original peripheral register access expressions (e.g., TIM1->CR1|=TI). ) and driver interface calls (such as L (TIM1) remains unchanged;

[0108] The advantages are: by modifying only the compiler's header file search path instead of the control algorithm source code, it is beneficial to redirect all peripheral accesses to the Shim layer while keeping the FOC control algorithm layer code completely unchanged. This allows a set of control algorithm source code to be reused across different platforms, completely eliminating the need for M independent code branches required for multi-platform maintenance and reducing the maintenance cost from O(N×M) to O(M).

[0109] S6. Compilation Verification and Ordered Error Correction: During the compilation process, compilation errors are checked and corrected in the order of S1 (type layer) → S2 (bit macro layer) → S3 (function layer). Due to the strict unidirectional dependency between the three layers, this order ensures the ordered iterative convergence of the control method when deployed on multiple platforms. The specific implementation of this step is as follows: After the 0th round of compilation, there are 68 errors. After the 1st round of compilation, type layer errors are checked and missing typedef definitions are added. After the 2nd round of compilation, bit macro layer errors are checked and missing #define register bit mappings are added. After the 3rd round of compilation, function layer errors are checked and missing static inline function definitions are added. All compilation errors can be eliminated in three iterations, generating executable firmware for the target platform.

[0110] The advantages are: by iteratively compiling and correcting errors in a unidirectional dependency order of type layer → bit macro layer → function layer, it is beneficial to converge compilation errors in cross-platform porting into a deterministic process that can be completely eliminated in just three rounds, which greatly shortens the debugging cycle of platform migration (from 2-4 weeks in the traditional solution to about 8 hours), thereby avoiding the efficiency loss caused by blind modifications.

[0111] S7. Flash firmware and execute the field-oriented control loop with dead-time compensation: Flash the compiled target firmware to the target microcontroller. After power-on, first execute the startup diagnosis in step S4. After confirming that the system is normal (returning to 0x00), start the motor and execute the FOC control loop according to the following timing sequence (control parameters are: current loop 16kHz, speed loop 2kHz, center-aligned complementary PWM, dead time about 900ns (DRV8301 dead-time register (DTC) and software compensation dual-layer collaboration), speed loop PI gain Kp=2200 / Ki=150, current loop PI gain Kp=800 / Ki=16 (Id and Iq are the same)):

[0112] (I) Interrupt Scheduling and Real-Time Timing Guarantee Mechanism: This control method adopts a Nested Vectored Interrupt Controller (NVIC) with an ARM Cortex-M4F core. The priority grouping is NVIC_PRIGROUP_PRE3_SUB1 (3-bit preemption priority, value range 0-7). The allocation of the 7 interrupt sources within the control cycle is as follows: PWM timer overflow update interrupt (preemption priority 0, triggers ADC injection group hardware conversion) → ADC injection group conversion end interrupt (preemption priority 2, current loop FOC calculation entry) → encoder overflow interrupt (preemption priority 3, sub-priority 0) / serial communication interrupt (preemption priority 3, sub-priority 1) → PWM brake interrupt (preemption priority 4, sub-priority 0) / USB interrupt (preemption priority 4, sub-priority 1) → system metronome (SysTick) interrupt (preemption priority 5, speed loop calculation). The PWM period is 62.5 microseconds (16kHz), and the speed loop period is 500 microseconds (2kHz). This hierarchical scheduling mechanism ensures that current loop calculations are executed with the highest real-time response priority, unaffected by slow communication or diagnostic tasks.

[0113] The formal analysis of the worst-case execution time (WCET) for current loop control calculation is as follows: Nested vector interrupt controller response delay 12 cycles + ADC data read and preprocessing 80 cycles + Clarke transform 120 cycles + Park transform 180 cycles + d-axis proportional-integral (PI) control 150 cycles + q-axis PI control 150 cycles + inverse Park transform 180 cycles + Space vector pulse width modulation (SVPWM) calculation 200 cycles + PWM compare register write and interrupt return 60 cycles = approximately 1132 CPU cycles. At a 168MHz clock frequency, the worst-case execution time is... =1132 / (168×10 6 The time margin of the PWM cycle (62.5μs) is 55.76μs, and the current loop CPU load rate is only 10.78%; with a safety factor of 3 (20.22μs), it still accounts for only 32.35% of the PWM cycle. From the ADC sampling time (about 3μs after PWM overflow) to the writing of the new PWM comparison value to the shadow register (about 11μs), the total delay is about 8μs, which is within half a PWM cycle (31.25μs), meeting the intra-cycle update requirement.

[0114] (II) PWM Timer Overflow Trigger for Synchronous Sampling of Three-Phase Current in ADC Injection Group: The PWM timer operates in center-aligned counting mode. When the timer count register (CNT) increments to the set value of the period register (ARR) and generates an overflow update event, this event serves as a hardware trigger signal (TRGO signal) to directly initiate the synchronous conversion of the ADC injection group. The differential voltage across the three-phase current sampling resistors is conditioned by the AD8418AWBRZ-RL current sense amplifier (gain 16.5V / V) and then sent to the ADC module injection group channels (PC0, PC1, PC2) of the target microcontroller GD32F405. Under hardware triggering, the Successive Approximation Register (SAR) conversion begins without CPU intervention. The conversion time for each channel is set to 21 ADC clock cycles (approximately 1μs at a 21MHz ADC clock), with a total of approximately 3μs for all three phases. This hardware-based automatic triggering mechanism avoids the interrupt response delay and instruction execution jitter caused by software-initiated ADC conversion in traditional solutions. It ensures that the offset of the sampling time relative to the PWM center alignment point is strictly locked within ±1 ADC clock cycle (approximately 47.6ns), thus guaranteeing the consistency and repeatability of the current sampling phase from the source.

[0115] (III) Execution sequence of the field-oriented control calculation process: After the ADC injection group conversion end flag (JEOS, Injected End Of Sampling) is set, an injection group conversion end interrupt is triggered. After the CPU responds to the interrupt, it immediately enters the current loop FOC calculation process, and performs the following operation sequence:

[0116] (1) ADC data reading and preprocessing: using the inline function L constructed in step S3 (ADCx) Reads the raw ADC count values ​​(12-bit resolution) of the three-phase currents respectively, and subtracts the offset (Offset Calibration Value) to obtain the signed instantaneous values ​​of the phase currents. , , ;

[0117] (2) Clarke transformation (three-phase → two-phase stationary coordinate system): transforms the three-phase stator current into a two-phase stationary coordinate system. , , Mapping to the two-phase stationary α-β coordinate system, we obtain and The transformation matrix is = , =( +2 ) / √3 (or equivalent) =( - (√3), This embodiment uses equal magnitude transformation to ensure that the vector magnitude remains unchanged before and after the transformation;

[0118] (3) Park transformation (two-phase stationary → two-phase rotating dq coordinate system): combined with the electrical angle feedback from the rotor position sensor (2500-line incremental photoelectric encoder, electrical angle resolution of 0.18° after 4 times frequency multiplication). ,Will and Transform to the rotating dq coordinate system to obtain the excitation current component. and torque current component The transformation formula is: = cos + ·sin , =- ·sin + cos ;

[0119] (4) Parallel calculation of d-axis and q-axis PI controllers: The d-axis PI controller (adjusting the excitation current component Id, with a setpoint of 0 to achieve maximum torque-current ratio control) and the q-axis PI controller (adjusting the torque current component Iq, with the setpoint provided by the speed loop output) are executed respectively. Each PI controller performs accumulation and anti-windup processing of the proportional term and integral term, and outputs the d-axis voltage command. and q-axis voltage command ;

[0120] (5) Inverse Park transformation (dq → two-phase stationary): and Combined with electrical angle Inverse transformation back to the two-phase stationary α-β coordinate system, we obtain and The transformation formula is: = cos - ·sin , = ·sin + cos ;

[0121] (6) Space Vector Pulse Width Modulation (SVPWM) Calculation: Based on and The duty cycle comparison values ​​(Ta, Tb, Tc) of the three-phase bridge arms are calculated, including sub-steps such as sector determination, vector action time calculation (such as intermediate variables X, Y, Z), and duty cycle synthesis. A seven-segment symmetrical space vector modulation strategy is adopted to reduce harmonic content.

[0122] (7) PWM Comparator Register Write and Update: After adding the dead-time compensation amount to the comparison value calculated by SVPWM, the L value in step S3 is updated. L L The inline functions are written to the compare registers (CH0CV, CH1CV, CH2CV) of the PWM timer's channels 1, 2, and 3, respectively, and take effect in the next PWM cycle (the shadow register is loaded during the update event). The entire FOC calculation process is completed in approximately 6.74 μs (WCET), which is much shorter than the PWM cycle of 62.5 μs.

[0123] Every 500 microseconds, a speed loop PI calculation is performed in the SysTick interrupt: the actual speed is calculated based on encoder feedback, and the deviation from the target speed is calculated by the speed loop PI controller (Kp=2200 / Ki=150) and outputs the q-axis current setpoint. The reference input of the q-axis PI controller of the current loop is updated, forming a double closed-loop cascaded control structure of speed outer loop and current inner loop.

[0124] (iv) Dead-zone compensation control method with linear transition region: In the dead-zone compensation stage, the traditional hard-switching compensation based on the phase current sign is replaced with a piecewise continuous compensation function to eliminate the double-value jump in compensation caused by ADC noise near the zero-crossing point of the phase current. Let... This is the ADC sample value of the current phase current (containing noise from peak-to-peak and 2-3 least significant bits). Given a preset transition current threshold (20 counts in this embodiment, corresponding to approximately 100mA phase current), and DTCompCnt being the dead-time compensation full-count value (approximately 80 counts, determined by the DRV8301 hardware DTC register and software compensation dual-layer collaboration, an empirically tuned value), the comparison value compensation amount for the current PWM cycle is... Defined as a piecewise continuous function as follows:

[0125]

[0126] when > hour, =+DTCompCnt (Full positive compensation is implemented during the positive half-cycle of the phase current).

[0127] when <- hour, =-DTCompCnt (Full negative compensation is implemented during the negative half-cycle of the phase current).

[0128] When | |≤ hour, =(DTCompCnt / )× (Linear continuous transition within the neighborhood of zero, smoothly changing from -DTCompCnt to +DTCompCnt).

[0129] The compensation function has the following mathematical and physical properties:

[0130] (a) Continuity: at the breakpoint = At, the left limit (DTCompCnt / )× =DTCompCnt is equal to the right limit +DTCompCnt; in =- At this point, the left limit -DTCompCnt and the right limit (DTCompCnt / )×(- The values ​​of -DTCompCnt and ) are equal. Therefore, the compensation function is continuous throughout the real number domain and has no discontinuities.

[0131] (b) Noise suppression: Even with the fluctuation of phase current sampling value caused by ADC noise (peak-to-peak value 2-3 LSB), the compensation amount is an analog quantity that changes continuously within the range of -DTCompCnt to +DTCompCnt. There will be no step jump from +DTCompCnt to -DTCompCnt (the peak-to-peak value under the hard switching scheme is about 2×DTCompCnt≈160 count jitter level), thereby eliminating the unwanted jitter of PWM duty cycle and the "zero-current clamping" effect.

[0132] (c) Dual constraints on the transition zone threshold: upper limit constraint ≤¼× ( (The ADC count value corresponding to the rated current) ensures full dead-zone compensation is still implemented in the linear region above 75% of the rated current; lower limit constraint > × ( This represents the peak-to-peak count of the ADC noise. For safety, this embodiment uses a factor of 2 to ensure that the width of the transition zone is sufficient to cover the noise fluctuation range and to avoid the compensation state from repeatedly crossing the boundary of the transition zone due to noise.

[0133] (d) Physical Rationality: The Shockley IV characteristic of the body diode in a Metal-Oxide-Semiconductor Field-Effect Transistor (MOSFET) shows that when the current approaches zero, the forward voltage drop of the body diode also approaches zero, and the dead-time error voltage is a continuous function of the current rather than a step function. The piecewise linear function is a first-order Taylor approximation of the logarithmic IV curve in the neighborhood of zero, which is consistent with the physical nature of the inverter dead-time effect.

[0134] (e) Computational overhead is controllable: The additional computational cost added in this step is approximately 20 CPU cycles (multiplication MUL instruction calculates (DTCompCnt / I_th)×I_dq[k] and division SDIV instruction calculates the slope), which accounts for about 1.8% of the worst-case execution time of the current loop (1132 cycles), meeting the design constraint of no more than 5%, and ensuring that all control calculations are reliably completed within the PWM cycle of the 16kHz current loop.

[0135] Ultimately, the value written to the PWM comparator register is the theoretical duty cycle count calculated by SVPWM, plus the aforementioned dead-time compensation amount. CM =CM + The final value is written to the PWM timer's compare shadow register within a defined timing window (before the ADC interrupt service routine ends) via the inline function in step S3, and takes effect in the next PWM cycle.

[0136] Verified by actual measurements (no load, target speed 900 RPM, VOFA + telemetry 50Hz sampling): Start-up rise time 27ms; speed overshoot 6-12 RPM (0.7%-1.3%); steady-state deviation 6 RPM (0.67%); Id steady-state fluctuation ±0.076A; Iq steady-state 0.04-0.075A; electrical angle 0-360° continuous sawtooth wave. The PI parameters pre-tuned on the source microcontroller (STM32F407) were directly applied to the target microcontroller (GD32F405) without any performance degradation.

[0137] The advantages are: the three-layer hardware compatibility mapping layer ensures that the instruction cycle number of the underlying peripheral access is consistent across platforms; combined with interrupt priority hierarchical scheduling and WCET formal verification, the timing validity of the optimized PI gain, timing offset, dead-time compensation value and other control parameters can be directly inherited between different platforms without re-tuning; at the same time, the piecewise continuous dead-time compensation function eliminates the step jump of the compensation amount near the zero crossing point, suppresses PWM duty cycle jitter and zero current clamping effect from the root, improves the current waveform quality and reduces torque ripple.

[0138] This invention can be widely applied in the following fields:

[0139] (1) Industrial servo drive field: Applied to FOC drivers that replace imported microcontrollers (such as STM32F407) with domestic microcontrollers such as the GD32 series, covering industrial servo applications of 200W-2kW permanent magnet synchronous motors, including CNC machine tool feed drive, industrial robot joint drive, automated production line conveyor belt control, textile machinery spindle drive, injection molding machine servo pump control and other scenarios. This invention eliminates the need to readjust PI parameters after cross-platform porting, allowing the optimized control performance to be directly inherited between different microcontroller platforms, significantly shortening the development cycle of industrial servo drivers switching from imported chips to domestic chips, and reducing the supply chain risk and R&D costs of enterprises.

[0140] (2) Electric vehicle and automated guided vehicle (AGV) drive control: Applied to electric vehicles and AGVs driven by low-voltage (24V / 48V / 72V) permanent magnet synchronous motors, including electric forklifts, electric pallet trucks, service robot chassis, unmanned delivery vehicles, and AGV drive wheels. This invention, in conjunction with CAN bus communication, enables multi-motor collaborative control. Furthermore, because control parameters can be directly inherited, it eliminates the need to re-match motor control parameters when using different microcontrollers for the same vehicle model in different batches, effectively shortening the product iteration cycle of the vehicle controller.

[0141] (3) Robot joint motor servo control: Applied to joint servo drives in collaborative robots, humanoid robots, quadruped robots and exoskeleton robots, etc., and used with high-precision encoders (2500-line incremental or 17 / 23-bit absolute encoders) to achieve closed-loop control of position / velocity / torque. The piecewise continuous function introduced in the dead zone compensation stage of this invention makes the compensation amount change continuously, eliminating torque pulsation, and is especially suitable for robot joint application scenarios with strict requirements for low-speed stability and torque control accuracy.

[0142] (4) In the field of variable frequency drive for home appliances and commercial applications: It is applied to variable frequency drives for air conditioner compressors and outdoor fans, variable frequency drives for refrigerator compressors, variable frequency control for direct drive motors (DDM) in washing machines, high-speed brushless motor drives for vacuum cleaners (speeds can reach over 100,000 RPM), and variable frequency energy-saving control for industrial exhaust fans / fans / pumps, etc. This invention enables the same FOC algorithm to be quickly adapted to the microcontroller selection of different home appliances through a three-layer hardware compatibility mapping. At the same time, the segmented continuous dead zone compensation has significant advantages under the requirements of low noise and low torque pulsation, which helps to improve the energy efficiency level of home appliances (such as reaching the first-level energy efficiency standard).

[0143] (5) Cross-platform motor control general methodology: The core method of this invention—the three-layer progressive hardware-compatible mapping at compile time—can be extended to the entire GD32 series (including the GD32F3xx series based on Cortex-M3, the GD32F4xx series based on Cortex-M4, the GD32E5xx series based on Cortex-M3, etc.), the AT32 series from Arteli Technology, the MM32 series from Lingdong Microelectronics, and other domestic ARM Cortex-M microcontroller platforms. For microcontrollers whose register base address and offset address layout are compatible with the source platform, the three-layer mapping layer can be directly reused or only needs fine-tuning; for platforms with large differences in register layout, the Shim layer can also be reconstructed with reference to the mapping architecture of this invention, and the same technical effects such as control timing consistency and parameter inheritance can still be obtained. The mapping architecture of this invention can also be extended to other motor control methods based on coordinate transformation (such as direct torque control (DTC) of permanent magnet synchronous motors and vector control of asynchronous motors), and has broad applicability.

[0144] (6) Embedded System Teaching and Electronic Competition Platform in Universities: The mapping mechanism of this invention enables the same set of FOC teaching example code to be compiled and run on different development boards (STM32F407 development board, GD32F405 development board, AT32F407 development board, etc.) without modifying the control algorithm source code, significantly reducing the teaching preparation cost of embedded system courses and motor control experiments in universities. At the same time, the GD32+DRV8301 solution has the advantages of low cost, easy setup, and convenient debugging (the hardware cost of the entire driver board is about 40% of that of imported solutions), and is especially suitable for the motor control track in competitions such as the National Undergraduate Intelligent Vehicle Competition, the China Postgraduate Electronic Design Competition, and the National Undergraduate Electronic Design Competition, lowering the entry threshold. In addition, students can gain a deeper understanding of FOC control principles and cross-platform embedded software development methods through this platform, which is in line with the direction of the new engineering education reform.

[0145] (7) Aerospace and Military Special Motor Drive Field: This invention is applicable to low-power (hundred-watt) aerospace servo systems (such as UAV servo control and satellite attitude control flywheel drive) and military special motor drive scenarios. Its advantages in timing determinism and control consistency—PWM output timing deviation reduced from "uncertainty" in traditional solutions to "zero" (instruction-level equivalence), and dead-zone compensation without zero-crossing jitter—provide technical support for applications with high reliability requirements. At the same time, the demand for domestic microcontrollers to replace imported chips is particularly urgent in the above-mentioned fields. This invention provides a feasible technical path for the domestic substitution of microcontrollers in such high-safety-level applications.

[0146] (8) New energy and energy storage system auxiliary drive field: Applied to solar tracking system (daily trajectory tracking motor drive of photovoltaic panel), wind power generation pitch control system, energy storage system cooling fan frequency conversion drive, hydrogen fuel cell system air compressor high speed motor drive (speed is usually 30000-100000RPM) and other new energy fields, the control timing consistency and dead zone compensation smoothness of the present invention help to improve system efficiency and reduce mechanical vibration noise.

[0147] Finally, alternative implementation variants (replaceable solutions for different platforms and computing power conditions) are added.

[0148] As a supplement to this method, the following alternative implementation schemes are allowed for different hardware platform characteristics and computing power conditions, all of which do not depart from the core compile-time mapping concept of this invention:

[0149] (1) When the target microcontroller and the source microcontroller both access peripherals using structure pointers (e.g., both are different models from the same ST series), the type equivalence mapping layer in step S1 will be simplified to direct structure remapping (i.e., only the peripheral base address pointer is redefined), while the bit field mapping layer in step S2 and the instruction substitution layer in step S3 remain unchanged.

[0150] (2) For the transition region of dead zone compensation, when the target microcontroller is equipped with a stronger floating-point unit (such as Cortex-M7 or M55 core), the linear interpolation function in step S7 can be replaced by a quadratic curve or arctan function to obtain higher smoothness (the compensation amount and its first derivative are continuous), but the central processing unit overhead increases accordingly (the constraint of not exceeding 5% of the current loop needs to be evaluated).

[0151] (3) The type equivalence mapping layer of the present invention can also be implemented using C++ template specialization or Rust trait generic programming. In essence, they are all zero-cost abstractions at compile time, and are still equivalent replacements of the present invention.

[0152] Example

[0153] The embodiments of the method of the present invention are executed through the following hardware system: The hardware configuration of the control system is shown in Table 1 below:

[0154] Table 1 Hardware configuration of the control system

[0155] Components Model / Specification Control function Target microcontroller GD32F405RGT6 LQFP-64, 168MHz Cortex-M4F, 1MB Flash / 192KB SRAM Source microcontroller STM32F407VGT6 LQFP-100, 168MHz Cortex-M4F Gate driver chip TI DRV8301DCA Three-phase drive + dual current sensing op-amp + Buck converter + SPI, HTSSOP-56 power switching transistors HYG025N06LS2C2 ×6 MOSFET, 60V / 160A / 4.5mΩ, DFN package Current sensor AD8418AWBRZ-RL ×3 0.01Ω sampling resistor, Kelvin four-wire connection, equivalent gain 16.5V / V Rotor position sensor 2500-line incremental photoelectric encoder A / B / Z differential signal, 4x frequency harmonics = 10000 edges / revolution, electrical angular resolution 0.18° Controlled motor Surface-mounted permanent magnet synchronous motor 5 pole pairs, 24V / 200W / 3000RPM / 0.64N·m, Rs≈0.06Ω, Ls≈80μH DC bus power supply SDM XT-DY-300W-24V AC180-264V input, DC24V / 12.5A output compilation environment Keil MDK-ARM v5.38 + ARMCompiler 5 Optimization Level - O2, GD32 DFP Pack v3.5.0 Control parameters Current loop 16kHz / Speed ​​loop 2kHz Center-aligned complementary PWM with a dead time of approximately 900ns (DRV8301 DTC + software dual-layer). PI control parameters Speed ​​loop Kp=2200 / Ki=150 Current loop Kp = 800 / Ki = 16 (Id and Iq are the same)

[0156] The experimental conditions for this embodiment are as follows: Source microcontroller = STM32F407VGT6 (STM32CubeF4 HAL / LL library + MCSDK v5.4.3), Target microcontroller = GD32F405RGT6 (GD32F4xx standard peripheral library v3.5.0), Keil MDK-ARM v5.38 + ARM Compiler 5 -O2, Controlled motor = 5-pole surface-mount permanent magnet synchronous motor (24V / 200W), Inverter = DRV8301 + HYG025N06LS2C2×6, Current sensor = three resistors at the low end + AD8418AWBRZ-RL (Kelvin connection), Rotor position sensor = 2500-line incremental encoder, PWM = 16kHz center-aligned complementary.

[0157] Compilation verification: Hardware compatibility mapping layer (1033 lines) + initialization (approximately 300 lines). After three rounds of orderly correction: Round 0: 68 Errors → Round 1 (adding 3 typedefs): 23 Errors → Round 2 (adding approximately 40 #defines): 0 Errors / 78 Warnings (all from the GD32 library, non-functional) → Round 3 verification passed. Target firmware successfully generated, 0 errors.

[0158] Control function verification: Burn to GD32F405RGT6 → Power-on diagnostics passed → USB CDC connection to VOFA+ host computer → Start motor → Speed ​​control is normal, id≈0 decoupling is normal, encoder feedback is normal.

[0159] Quantitative control performance data (900RPM no-load, VOFA + telemetry 50Hz sampling): Startup rise time 27ms (0→90% of target value) / Speed ​​overshoot 6-12RPM (0.7%-1.3%) / Steady-state deviation 6RPM / Id steady-state ripple ±0.076A / Current loop measured execution time approximately 5.3μs (measured with GPIO toggling + oscilloscope; worst-case execution time of 6.74μs is a conservative estimate including safety margin). Source platform PI parameters are directly applied without any performance degradation.

[0160] Dead zone compensation control experiment: Control group A (hard switching) showed occasional jumps in the PWM comparison value with ±80 counts near the zero crossing point. Experimental group B (smooth transition, DT_SMOOTH_TH=20) showed continuous transition of the compensation amount at the zero crossing point, with no step jump in the PWM comparison value. The additional CPU overhead is approximately 20 cycles.

[0161] The above experiments have verified that the method of the present invention can effectively realize the seamless migration of the field orientation control method of permanent magnet synchronous motor on the GD32F405 platform. The control performance is equivalent to that of the source platform (STM32F407), and the dead zone compensation effect is significantly better than the traditional hard switching scheme.

[0162] The technical effects of the present invention are shown in Table 2 below:

[0163] Table 2

[0164] Effect Dimension Existing overall hardware abstraction layer replacement solution Control method of the present invention Quantitative improvement PWM output timing consistency There are differences between different platforms (different numbers of underlying instructions). Completely equivalent (inline expansion at compile time results in the same sequence of instructions) Timing bias reduced from uncertainty to zero Inheritability of control parameters The PI parameters need to be readjusted (it will take several days). Direct inheritance; the motor starts operating normally immediately upon startup. Re-optimization and elimination of requirements Dead-time compensation PWM duty cycle jitter Peak-to-peak value 2 × DTCompCnt (≈160 counts) Jitter elimination (continuous convergence of compensation amount within the transition zone) Zero-crossing jitter elimination Worst-case execution time of the current loop Depends on the new platform HAL implementation 6.74 μs (WCET formal verification) Deterministic real-time guarantees Cross-platform deployment time of control algorithms Approximately 2-4 weeks Approximately 8 hours (including compilation verification and hardware integration testing) Efficiency increased by approximately 20-40 times Multi-platform control algorithm maintenance M independent branches 1 control algorithm + M mapping header files O(N×M)→O(M)

[0165] Measured control performance (no load, target speed 900 RPM, VOFA + telemetry 50Hz sampling): Start-up rise time 27ms; speed overshoot 6-12 RPM (0.7%-1.3%); steady-state deviation 6 RPM (0.67%); Id steady-state ripple ±0.076A; Iq steady-state 0.04-0.075A; electrical angle 0-360° continuous sawtooth wave. The PI parameters pre-tuned on the source microcontroller (STM32F407) were directly applied to the target microcontroller (GD32F405) without any performance degradation.

[0166] The causal chain of technical effects:

[0167] (1) PWM timing consistency ← Inline functions are expanded into a three-instruction sequence of LDR / ORR / STR at compile time, with the number of cycles equivalent to the original function of the source platform;

[0168] (2) Control parameters can be inherited ← Timing consistency ensures that the timing conditions on which parameters depend remain unchanged;

[0169] (3) Dead zone compensation smoothness ← The piecewise continuous function changes linearly in the transition region, and the PWM comparison value correction does not produce a step;

[0170] (4) Cross-platform deployment efficiency: Zero modification to the control algorithm layer, only replacement of compilation include paths;

[0171] (5) Zero runtime overhead ← typedef / #define is expanded during the preprocessing stage, static inline is inlined during the optimization stage, and the runtime firmware is no different from the target microcontroller's native code;

[0172] The keywords of this invention are shown in Table 3 below:

[0173] Table 3

[0174] Chinese terminology English terminology Chinese terminology English terminology Permanent magnet synchronous motor Permanent MagnetSynchronous Motor (PMSM) Hardware compatibility mapping layer Hardware Compatibility MappingLayer (Shim Layer) Magnetic field orientation control Field-Oriented Control (FOC) Compile-time equivalent transformations Compile-Time EquivalentTransformation Space Vector Pulse Width Modulation Space Vector Pulse WidthModulation (SVPWM) Function signature equality constraint Function Signature IdentityConstraint Dead zone compensation Dead-Time Compensation Conditional compilation protection Conditional CompilationGuarding Current loop / velocity loop Current Loop / Speed ​​Loop Zero-overhead abstraction Zero-Overhead Abstraction Peripheral Registers Peripheral Register Register-level interface compatibility Register-Level InterfaceCompatibility Injection group conversion Injected Conversion Worst case execution time Worst-Case Execution Time(WCET) Proportional-integral controller Proportional-Integral (PI)Controller Motor control software development kit Motor Control Software Development Kit (MCSDK)

[0175] Although embodiments of the invention have been shown and described, it will be understood by those skilled in the art that various changes, modifications, substitutions and alterations can be made to these embodiments without departing from the principles and spirit of the invention, the scope of which is defined by the appended claims and their equivalents.

Claims

1. A cross-platform field-oriented control method for a permanent magnet synchronous motor, characterized in that, Includes the following steps: S1. Construct type equivalence mapping for register access: During the compilation phase, in the hardware-compatible mapping header file, the data type of the peripheral base address of the target microcontroller is uniformly defined as the same type name as that of the source microcontroller, and the peripheral base address is remapped using preprocessing macros; S2. Constructing the symbolic mapping of register bit control domains: During the compilation phase, all register bit control macro names of the first microcontroller referenced in the field orientation control algorithm are mapped one by one to the macro names of the corresponding register bits of the target microcontroller using the #define preprocessing directive, and a three-line conditional compilation protection mode of #ifndef... #define... #endif is adopted. S3. Constructing instruction-level equivalent replacements for peripheral driver interfaces: During the compilation phase, each call to the hardware abstraction layer driver interface in the FOC control algorithm is mapped one-to-one to a compile-time inline function that directly operates the peripheral registers of the target microcontroller using a static inline function. At optimization levels of -O1 and above, the compiler expands the inline function body of each call point into a three-instruction sequence of load / bit OR / store, and the number of cycles is exactly the same as the number of assembly instructions generated by the native code of the target microcontroller directly operating the PWM timer register. S4. Configure the target platform's control peripherals: Create a new peripheral initialization source file and strictly configure the various peripheral parameters of the target microcontroller according to the control timing sequence; S5. Associate the hardware compatibility mapping layer and compile the environment: In the compilation configuration, change the C compiler's header file search path from pointing to the source microcontroller hardware abstraction layer to pointing to the hardware compatibility mapping layer and the target microcontroller standard peripheral library; S6. Compilation Verification and Ordered Error Correction: During the compilation process, errors are checked and corrected in the order of step S1 type layer → step S2 bit macro layer → step S3 function layer. S7. Burn and run control: Burn the compiled target firmware to the target microcontroller. After powering on, first execute the startup diagnosis in step S4. After confirming that the system is normal, start the motor and execute the FOC control cycle according to the set timing.

2. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The process for constructing the type equivalence mapping of register accesses in S1 is as follows: S1.1, For the target microcontroller in uint3 Integer macros represent peripheral base addresses, while the source microcontroller accesses them via structure pointers, using the C language typedef uint3. TIM_ Define the peripheral register type as uint3 ; S1.2 Then, by using #define TIM1, the numerical base address of the target microcontroller is forcibly converted to a type name compatible with the source microcontroller, so that the register access expression in the style of the source microcontroller is equivalently transformed into an access instruction to the actual hardware register address in the compilation environment of the target microcontroller.

3. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The correctness of the equivalent transformation in S1 is based on the following hardware fact: the base address and offset address layout of the registers of the pulse width modulation timer, analog-to-digital converter, and motor control peripherals of the general-purpose input / output port of the first microcontroller and the second microcontroller are completely consistent, which is guaranteed by the register-level interface compatibility design of the GD32F4xx product.

4. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The formal semantics of the protection mode in S2 are: (1) When a macro name is already defined in the target microcontroller's native header file, the Shim layer skips the definition; (2) When the macro name exists only in the namespace of the source microcontroller, the Shim layer provides the definition as a supplement.

5. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, In S3, each compile-time inline function satisfies the function signature equality constraint, that is, the function name, parameter types and number, and return value type are identical to the original driver function of the source microcontroller word by word, and the function body directly operates on the register bits of the target microcontroller.

6. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The control peripheral parameter configuration of the target platform in S4 includes: (a) Configure the system clock tree: The external high-speed crystal oscillator is multiplied to a 168MHz system clock via a phase-locked loop, of which the high-performance bus clock is 168MHz, the peripheral bus 2 clock is 84MHz, and the analog-to-digital converter clock is 21MHz; (b) Configure the multiplexing function of control-related pins: Configure PA8 / PA9 / PA10 and PB13 / PB14 / PB15 as PWM output, configure PC6 / PC7 / PC8 as encoder input, configure PC0 / PC1 / PC2 as analog-to-digital converter current sampling input, and configure PB6 / PB7 as serial communication. (c) Enable the clocks for the PWM timer, analog-to-digital converter, encoder timer, serial port and universal serial bus peripheral modules; (d) Perform interrupt vector name mapping: map the interrupt vector name of the source microcontroller to the corresponding interrupt vector name of the target microcontroller; (e) Start-up diagnostics: After power-on, check the phase-locked loop lock status, external high-speed crystal oscillator start-up status, PWM timer clock, analog-to-digital converter clock, and general-purpose input / output port clock in sequence, and return an 8-bit bit-encoded fault code.

7. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The code in all source files of the FOC control algorithm layer in S5 remains unchanged, and the original peripheral register access expressions and driver interface calls are kept unchanged.

8. The cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The compilation verification and ordered error correction in S6 are implemented as follows: (1) After the first round of compilation, check for type layer errors and supplement the missing typedef definitions; (2) After the second round of compilation, check for errors in the bit macro layer and supplement the missing #define register bit mappings; (3) After the third round of compilation, check for errors in the function layer and supplement the missing static inline function definitions.

9. A cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The S7 process involves burning firmware and executing a magnetic field orientation control loop with dead-zone compensation. (I) Overview of interrupt scheduling and timing guarantee mechanism: The nested vector interrupt controller with ARM Cortex-M4F core is adopted. The priority group is NVIC_PRIGROUP_PRE3_SUB1. The 7 interrupt sources are arranged in order of preemption priority from high to low: PWM overflow update interrupt → ADC injection group conversion end interrupt → encoder overflow / serial communication interrupt → PWM brake / USB interrupt → SysTick interrupt; (ii) Deterministic guarantee of worst-case execution time of the current loop: Item by item, the total instruction cycle from interrupt response to PWM register write is accumulated: NVIC response delay 12 cycles + ADC data reading and preprocessing 80 cycles + Clarke transform 120 cycles + Park transform 180 cycles + d-axis PI control 150 cycles + q-axis PI control 150 cycles + inverse Park transform 180 cycles + space vector pulse width modulation calculation 200 cycles + PWM compare register write and interrupt return 60 cycles = 1132 CPU cycles; (III) Execution sequence of the magnetic field orientation control calculation process: Executed once every 62.5 microseconds: The PWM timer overflow event triggers the ADC injection group hardware automatic conversion to complete the three-phase current synchronous sampling; After the ADC conversion ends and the interrupt is triggered, Clarke transformation, Park transformation, d-axis PI control, q-axis PI control, inverse Park transformation and SVPWM calculation are executed in sequence. Finally, the three-phase duty cycle is written to the PWM comparison register through the inline function in step S3. Every 500 microseconds, the speed loop PI calculation is executed in the SysTick interrupt to update the q-axis current setpoint, forming a double closed-loop cascaded control structure of speed outer loop and current inner loop; (iv) Dead-zone compensation control method with linear transition region: The traditional hard-switching compensation based on phase current sign is replaced with a piecewise continuous compensation function: in, This represents the PWM comparison value compensation amount in the k-th PWM cycle, and DTCompCnt represents the dead-time compensation full-count value. This represents the phase current ADC sample value. The threshold for the transition region, when > The time compensation amount is +DTCompCnt; when <- When it is -DTCompCnt; when | |≤ The time is (DTCompCnt / )× .

10. A cross-platform field-oriented control method for a permanent magnet synchronous motor according to claim 1, characterized in that, The transition region threshold in the S7 piecewise continuous compensation function satisfies the upper limit. ≤¼ × and lower limit > × The dual constraints, which add 20 CPU cycles of computation, satisfy the design constraints by no more than 5%.