S32M Knowledge Base

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

S32M Knowledge Base

Discussions

Sort by:
This document outlines the use of the eMIOS module on S32M27x and S32K3 series, detailing various operation modes and their implementations based on the RTD low level API to support diverse application needs.
View full article
[RTD200P04]S32M244 PWM ADC LLD demo 1. Abstract The S32M2XX series is an MCU series specially designed for motor control: S32M24X, a continuation of the S32K14X series MCU, adds an AE pre-driver module. S32M27X, a continuation of the S32K3 series MCU, adds an AE pre-driver module. NXP officially provides S32M24X and S32M27X series EVBs, which can be used with a three-phase PMSM/BLDC motor to achieve single-shunt current sampling motor control. The way to study motor control must need to understand how to control PWM, collect current and voltage signals at a specific time, and then control back PWM control after calculation. This article will be based on S32M24X-EVB: https://www.nxp.com/design/design-center/development-boards-and-designs/S32M24XEVB This document explains how to implement the complementary PWM with dead time output on S32M244, and use FTM_INT as the trigger signal, trigger ADC sampling through PDB delay, printf the ADC sampled value to the PC serial port through UART, and realize the interconnection of different modules, such as FTM and PDB, through the TRGMUX module, and output the signal through the TRGMUX_OUT pin. The block diagram structure of the implementation is as follows: (1)PWM+TRGMUX+PDB+ADC 1 ch     Attached demo code:S32M244_FTM_TRGMUX_PDB_ADC_RTD200_P04 Fig 1 (2)PWM+TRGMUX+PDB+ADC 2ch    Attached demo code:S32M244_FTM_TRGMUX_PDB_ADC2ch_RTD200_P04_20k    Fig 2 The demo here is mainly based on 2-channel ADC sampling, because the single-channel demo can be tailored based on the 2-channel. The principle of the single-channel is to share the code. In fact, the main purpose of this article is to share the demo made by the editor. If you are familiar with motor control, you can also directly refer to the official S32M244 motor control demo to do it yourself. 2. PWM+TRGMUX+PDB+ADC 2ch  configuration       2.1 Software and hardware platform Hardware:S32M244-EVB Software: S32DS : S32DS.3.5_b220726_win32.x86_64.exe Update 4 for S32DS:SW32_S32DS_3.5.4_D2307.zip Development package for S32K1XX: SW32K1_S32DS_3.5.4_D2307.zip Development package for S32M2XX: SW32M2xx_S32DS_3.5.0_D2303.zip RTD:      S32K1_S32M24X Real Time Drivers AUTOSAR 4.4 & R21-11 Version 2.0.0      S32K1_S32M24X Real Time Drivers AUTOSAR R21-11 Version 2.0.0 P04 S32M24x_AMMCLIB_RTM_1_1_39_BIN S32M24XEVB Evaluation Board Motor Control Application Software : S32M24XEVB-SW.exe FreeMASTER tool 3.2 : FMASTERSW32.exe The software platform here is the one that can make the motor demo run. If you don't need a motor, you only need to install S32DS, update, development, and RTD. For specific software links, it is recommended to go directly to the corresponding software download location on the official website to search and download the corresponding version. 2.2 Demo CT Module configuration First, create a new S32M244 S32DS project, and then configure the pins, clocks, and peripheral modules. For peripherals, we mainly design several modules:Adc_Ip, Ftm_Pwm, Pdb_Adc_Ip, Trgmux_Ip,Lpuart_Uart, Port_Ip 2.2.1 Pin configuration        The used pin is configured as follows:  Fig 3 The two FTM pins are used to output a pair of complementary PWM with dead zone. The ADC is used to collect the voltage of the onboard adjustable potentiometer, the LPUART is used to print information, and the TRGMUX related pins are used to output related test signals. 2.2.2 clock configuration The clocks that need to be paid attention to here are: main frequency clock, FTM clock, UART clock, and ADC clock.    Fig 4   Fig 5 2.2.3 Peripheral Configuration       The peripherals used are as follows:    Fig 6 (1)Port_Ip_1 When talking about port configuration, the main focus is on the setting principles of Pcr values.  Fig 7 PortPinPcr = PinId + PortId∗32 PortId:A=0,B=1,C=2,D=3,E=4; PinId is the port pin number In the above picture, FTM0_CH0 is PTC0, it means: PortPinPcr = PinId(0) + PortId(2)∗32=64 (2)Ftm_Pwm module configuration  Fig 8  Fig 9 (3)Adc_Ip Module configuration Fig 10 (4)Pdb_Adc_Ip    Fig 11 When configuring the PDB delay, it is important to consider the ADC conversion time. If one conversion is not completed and another is triggered, it will cause PDB trigger timing errors. (5)Trgmux_Ip  Fig 12 There are two parts to this: the FTM is connected to the PDB, and the test signal is connected to the TRGMUX_OUT output. (6)Lpuart_Uart Used to output signals to the PC serial terminal through printf    Fig 13 2.3 Main source code After the configuration is completed, you can call the following code in main to realize the situation where PWM triggers PDB to collect ADC dual channels. PWM can output complementary signals, and can also realize the output of related trigger signals through TRGMUX_OUT pin: #include "Mcal.h" #include "Port_Ci_Port_Ip.h" #include "Gpio_Dio_Ip.h" #include "Clock_Ip.h" #include "Lpuart_Uart_Ip.h" #include "string.h" #include "stdio.h" #include "retarget.h" #include "Ftm_Pwm_Ip.h" #include "Ftm_Pwm_Ip_HwAccess.h" #include "IntCtrl_Ip.h" #include "Adc_Ip.h" #include "Pdb_Adc_Ip.h" #include "Trgmux_Ip.h" #define PTD1_PORT IP_PTD #define PTD1_PIN 1U #define LED_PORT IP_PTE #define LED_PIN 15U #define INST_LPUART (0U) #define INST_FTM0 (0U) #define WELCOME_MSG_1 "Hello, This message is sent via Uart!\r\n" volatile Lpuart_Uart_Ip_StatusType lpuartStatus = LPUART_UART_IP_STATUS_ERROR; uint32 remainingBytes; uint32 T_timeout = 0xFFFFFF; uint16 pwmCycleCnt = 0,cntflag = 0,pwmCycleCnt1 = 0, ADCIsrDone = 0; volatile boolean notif_triggered = FALSE; volatile uint16 data; volatile uint16 data2ch[2]; volatile int exit_code = 0; /* User includes */ void TestDelay(uint32 delay); void TestDelay(uint32 delay) { static volatile uint32 DelayTimer = 0; while(DelayTimer<delay) { DelayTimer++; } DelayTimer=0; } __attribute__((section (".ramcode"))) void PDB1_SequenceErrorNotif(uint8 ChanIdx, uint16 SeqErrMask) { // Read ADCs Results registers to unlock PDB pre-triggers lock states if (Adc_Ip_GetConvActiveFlag(ADCHWUNIT_0_INSTANCE)){} Adc_Ip_GetConvData(ADCHWUNIT_0_INSTANCE, 0); Adc_Ip_GetConvData(ADCHWUNIT_0_INSTANCE, 1); Ftm_Pwm_Ip_SetInitTriggerCmd(IP_FTM0, true); /* Unused parameter */ (void)(ChanIdx); } __attribute__((section (".ramcode"))) void FTMReloadNotif(void) { pwmCycleCnt ++; } __attribute__((section (".ramcode"))) void ADC1_ConversionCompleteNotif(const uint8 ControlChanIdx) { (void)(ControlChanIdx); notif_triggered = TRUE; data2ch[0] = Adc_Ip_GetConvData(ADCHWUNIT_0_INSTANCE, 0); data2ch[1] = Adc_Ip_GetConvData(ADCHWUNIT_0_INSTANCE, 1); } int main(void) { Adc_Ip_StatusType adcStatus; Clock_Ip_Init(&Clock_Ip_aClockConfig[0]); Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); IntCtrl_Ip_Init(&IntCtrlConfig_0); Lpuart_Uart_Ip_Init(INST_LPUART, &Lpuart_Uart_Ip_xHwConfigPB_0); /**** Part 1: Start ADC software trigger conversions ****/ Adc_Ip_Init(ADCHWUNIT_0_INSTANCE, &AdcHwUnit_0); adcStatus = Adc_Ip_DoCalibration(ADCHWUNIT_0_INSTANCE); while (adcStatus != ADC_IP_STATUS_SUCCESS) { adcStatus = Adc_Ip_DoCalibration(ADCHWUNIT_0_INSTANCE); } #if 1 /* Start a software trigger conversion */ Adc_Ip_StartConversion(ADCHWUNIT_0_INSTANCE, ADC_IP_INPUTCHAN_EXT11, TRUE); /* Wait for the notification to be triggered and read the data */ while (notif_triggered != TRUE); notif_triggered = FALSE; /* Start a software trigger conversion */ Adc_Ip_StartConversion(ADCHWUNIT_0_INSTANCE, ADC_IP_INPUTCHAN_BANDGAP, TRUE); /* Wait for the notification to be triggered and read the data */ while (notif_triggered != TRUE); notif_triggered = FALSE; #endif if (Adc_Ip_GetConvActiveFlag(ADCHWUNIT_0_INSTANCE)){} Adc_Ip_GetConvData(ADCHWUNIT_0_INSTANCE, 0); Adc_Ip_GetConvData(ADCHWUNIT_0_INSTANCE, 1); /**** Part 2: Start ADC hardware trigger conversions ****/ Adc_Ip_SetTriggerMode(ADCHWUNIT_0_INSTANCE, ADC_IP_TRIGGER_HARDWARE); Trgmux_Ip_Init(&Trgmux_Ip_xTrgmuxInitPB); /* Initialize PWM driver */ Ftm_Pwm_Ip_DisableNotification(INST_FTM0, FTM_PWM_IP_OVERFLOW_NOTIFICATION); Ftm_Pwm_Ip_Init(INST_FTM0, &Ftm_Pwm_Ip_UserCfg0); Ftm_Pwm_Ip_EnableNotification(INST_FTM0, FTM_PWM_IP_RELOAD_POINT_NOTIFICATION); Pdb_Adc_Ip_Init(PDBHWUNIT_0_INSTANCE, &PdbHwUnit_0); Ftm_Pwm_Ip_SetInitTriggerCmd(IP_FTM0, true); printf("S32M244 FTM TRIGMUX ADC demo RTD200P04.\r\n"); for(;;) { printf("pwmCycleCnt = %d \r\n",(int)pwmCycleCnt); Gpio_Dio_Ip_WritePin(LED_PORT, LED_PIN, 1U); TestDelay(480000); Gpio_Dio_Ip_WritePin(LED_PORT, LED_PIN, 0U); TestDelay(480000); while (notif_triggered != TRUE); notif_triggered = FALSE; printf("adc1_bandGap = %d \r\n",(int)data2ch[0]); printf("adc1_SE11 = %d \r\n",(int)data2ch[1]); if((pwmCycleCnt > 30000) && (cntflag==0)) { cntflag = 1; Ftm_Pwm_Ip_UpdatePwmDutyCycleChannel(INST_FTM0,0,1000,TRUE); } else if((pwmCycleCnt < 30000) && (cntflag==1)) { cntflag = 0; Ftm_Pwm_Ip_UpdatePwmDutyCycleChannel(INST_FTM0,0,3000,TRUE); } } return (0U); } There is one point need to be noted: in the  C:\NXP\SW32K1_S32M24x_RTD_R21-11_2.0.0_P04\eclipse\plugins\Pwm_TS_T40D2M20I0R0\doc\RTD_PWM_UM.pdf The function Pwm_Init shall disable all notifications. The reason is that the users of these notifications may not be ready. They can call Pwm_EnableNotification to start notifications. So, need to call the Pwm_EnableNotification after the Pwm_Init.   3. Test result The test results include two parts: the printed results show the ADC sampling value, and the relationship between the PWM output and the PDB trigger position. The printed results are as follows, and you can see that the values ​​of the two ADC channels are correct:    Fig 14 The PWM waveform test is as follows: CH1: PTC0 CH2: PTC1 CH3: PTD0 CH4: PTD1 CH5: PTE11   Fig 15
View full article
[RTD200P04 MCAL] S32M244 PWM PDB ADC MCAL demo 1. Abstract     The S32M2XX series is an MCU series specially designed for motor control: S32M24X, a continuation of the S32K14X series MCU, adds an AE pre-driver module. S32M27X, a continuation of the S32K3 series MCU, adds an AE pre-driver module. NXP officially provides S32M24X and S32M27X series EVBs, which can be used with a three-phase PMSM/BLDC motor to achieve single-shunt current sampling motor control. The way to study motor control is must to understand how to control PWM, collect current and voltage signals at a specific time, and then back to do PWM control after calculation. This article will be based on S32M24X-EVB: https://www.nxp.com/design/design-center/development-boards-and-designs/S32M24XEVB This document explains how to implement complementary PWM with dead zone output on S32M244, and use FTM_INT as the trigger signal, trigger ADC sampling through PDB delay, print the value collected by ADC to PC serial port through UART, and realize the interconnection of different modules through TRGMUX module, such as FTM and PDB, and output the signal through TRGMUX_OUT pin. The block diagram structure of the implementation is as follows: PWM+TRGMUX+PDB+ADC dual channel. This article mainly uses MCAL to implement the function. Two supporting MCAL attachment codes is: S32DSMCAL: Mcal_PWMPDBADC_S32M244_RTD200P04.zip GCCMCAL: PWMPDBADC_TS_T40D2M20I0R0_kerry.zip GCCMCAL is compiled directly using the ARM GCC makefile method. You can refer to the vscode method in the tool section to compile and generate elf files for burning. S32DSMCAL is a method to integrate the EB MCAL project into the S32DS project.   Fig 1 The main purpose of this document is to share the S32M244 MCAL PWM PDB ADC demo made by the editor. There is no direct corresponding integrated M244 MCAL demo at present. If you are familiar with motor control, you can also refer to the official S32M244 motor control LLD demo to do it yourself, but there is no MCAL demo for M244 motor control at present. 2. PWM+TRGMUX+PDB+ADC 2ch configuration       2.1 HW and SW situation HW:S32M244-EVB SW: S32DS : S32DS.3.5_b220726_win32.x86_64.exe Update 4 for S32DS:SW32_S32DS_3.5.4_D2307.zip Development package for S32K1XX: SW32K1_S32DS_3.5.4_D2307.zip Development package for S32M2XX: SW32M2xx_S32DS_3.5.0_D2303.zip RTD:      S32K1_S32M24X Real Time Drivers AUTOSAR 4.4 & R21-11 Version 2.0.0      S32K1_S32M24X Real Time Drivers AUTOSAR R21-11 Version 2.0.0 P04 S32M24x_AMMCLIB_RTM_1_1_39_BIN S32M24XEVB Evaluation Board Motor Control Application Software : S32M24XEVB-SW.exe FreeMASTER tool 3.2 : FMASTERSW32.exe VSCode EB tresos studio 29.0 The software platform here is the one that can make the motor demo run. If you don't need a motor, you only need to install S32DS, update, development, RTD, and EB. VScode depends on your personal tool usage habits and can be installed as appropriate. For specific software links, it is recommended to go directly to the official website to search and download the corresponding version. 2.2 MCAL project and module configuration        This document related to two types of MCAL projects: (1) Copy the existing MCAL project in SW32K1_S32M24x_RTD_R21-11_2.0.0_P04, modify the EB MCAL configuration, add the code to main, compile and generate elf through makefile, and then program elf to chip. (2) Create a new S32DS project, integrate the SW32K1_S32M24x_RTD_R21-11_2.0.0_P04 driver and the code generated by EB, and then add the main code. This method can be directly compiled in S32DS and to program. For the compilation and construction of the two methods, there are some other corresponding tool articles for detailed explanation, you can refer to the following document. [S32K3 Tools Part] How to port RTD's existing MCAL demo to other K3 chips [S32K3 Tools Part] How to use VScode to compile EB MCAL project [S32K3 Tools Part]How to import RTD EB project into S32DS For EB projects, the relevant modules used in this example are as follows:   Fig 2 BaseNXP, Dem, EcuC modules are basic modules and do not require special configuration. The following is a detailed explanation of the key modules: 2.2.1 Dio module configuration     Dio mainly uses PTE15 as the LED pin. For PTE15, Port_Id=4, Dio Channel Id=15. Port_Id, A=0, B=1, C=2, D=3, E=4…, Dio Channel Id is the pin number in the corresponding port.   Fig 3 2.2.2 Adc module configuration     The Adc module needs to configure the ADC module, such as transmission type, division factor, calibration division factor, conversion resolution, PDB hardware module configuration, ADC channel, ADC group, pin trigger source, channel delay, etc. The specific configuration is as follows:      (1)AdcHwUnit AdcHwUnit_0->General   Fig 4 The main points are 12-bit resolution and a PDB cycle of 8000. Because the PDB uses a system clock of 80Mhz, it has a 10K cycle PDB counter. AdcHwUnit_0->AdcChannel   Fig 5 AdcChannel defines two channels, SE11_ADCH11, which is an external connection to the onboard adjustable potentiometer, and BANDGAP_ADCH27, which is the internal bandgap 1V. AdcHwUnit_0->AdcGroup There are several places in AdcGroup that need to be configured: AdcHwUnit_0->AdcGroup0->General: conversion mode, trigger mode, sampling time, etc.   Fig 6 AdcHwUnit_0->AdcGroup0->AdcChannelDelay: The time for defining the PDB trigger delay of the two channels must be sufficient for the single channel to complete the conversion, otherwise a PDB error will occur.   Fig 7 AdcHwUnit_0->AdcGroup0->AdcGroupDefinition: Define the channel status corresponding to the group   Fig 8   (2) AdcHwTrigger   Fig 9   (3) AdcInterrupt   Fig 10   2.2.3 Mcu module configuration    The Mcu module is mainly used to configure the MCU's related clock McuClockSettingConfig and the working mode McuModeSettingConf. McuClockSettingConfig has many clock configuration options, which are not expanded one by one. Please refer to the attached code.      Fig 11 Here need to configure McuclockReferencePoint   Fig 12 This involves the clock reference source of the FTM, ADC, PDB, and UART modules. 2.2.4 Platform module configuration       Platform configuration mainly involves the configuration of the Interrupt controller:   Fig 13 Add the interrupt number and interrupt Handler of the corresponding module. 2.2.5 Port module configuration Port configures the pin ports used, mainly the configuration of PortContainer. The current configuration is as follows:        Fig 14 2.2.6 Pwm module configuration       Pwm module configuration have two points: (1)PwmChannel   Fig 15 (2) PwmFtm PwmFtm_0->Ftm Modules   Fig 16 The edge alignment mode is configured here, and the dead time is 0.5us. PwmFtm_0->Ftm Sync   Fig 17 PwmFtm_0->PwmFtmCh   Fig 18 Configured as Combined Mode, complementary output, FTM0 channels 0 and 1. 2.2.7 Uart module configuration    Uart->UartChannel   Fig 19 2.3 Main code situation After the configuration is completed, you can call the following code in main to realize the situation where PWM triggers PDB to collect ADC dual channels. PWM can output complementary signals, and can also realize the output of related trigger signals through TRGMUX_­OUT pin: #ifdef __cplusplus extern "C" { #endif #include "Mcu.h" #include "Port.h" #include "Dio.h" #include "Pwm.h" #include "Platform.h" #include "Adc.h" #include "Mcl.h" #include "Lpuart_Uart_Ip_Irq.h" #include "CDD_Uart.h" #include <string.h> #include "stdio.h" #include "retarget.h" #include "check_example.h" #define RESULT_ADC_BANDGAP (1241U) /* Vbandgap ~ 1.0V at 3.3V reference */ #define NUM_RESULTS (4u) volatile uint32 VarNotification_0 = 0; volatile uint32 pdberrcnt = 0; extern ISR(Adc_0_Isr); Adc_ValueGroupType ResultBuffer[NUM_RESULTS] = {0xaaaa, 0xaaaa,0xaaaa, 0xaaaa}; /* Used for ReadGroup */ Adc_ValueGroupType AdcReadGroupBuffer[NUM_RESULTS] = {0xbbbb, 0xbbbb,0xbbbb, 0xbbbb}; //UART #define UART_LPUART_INTERNAL_CHANNEL 0U #define WELCOME_MSG "Helloworld for automotive with S32M244!\r\n" #define MSG_LEN 50U void AdcNotification(void) { VarNotification_0++; } void PDB_ADC_SEQ_ERR_NOTIFICATION() { pdberrcnt ++; } void TestDelay(uint32 delay); void TestDelay(uint32 delay) { static volatile uint32 DelayTimer = 0; while(DelayTimer<delay) { DelayTimer++; } DelayTimer=0; } int main(void) { uint8 count = 0U; Std_ReturnType StdReturn = E_NOT_OK; volatile boolean bStatus = TRUE; Adc_CalibrationStatusType CalibStatus; volatile Std_ReturnType T_Uart_Status1; /* Initialize the Mcu driver */ #if (MCU_PRECOMPILE_SUPPORT == STD_ON) Mcu_Init(NULL_PTR); #elif (MCU_PRECOMPILE_SUPPORT == STD_OFF) Mcu_Init(&Mcu_Config_VS_0); #endif /* (MCU_PRECOMPILE_SUPPORT == STD_ON) */ /* Initialize the clock tree and apply PLL as system clock */ Mcu_InitClock(McuClockSettingConfig_0); #if (MCU_NO_PLL == STD_OFF) while ( MCU_PLL_LOCKED != Mcu_GetPllStatus() ) { /* Busy wait until the System PLL is locked */ } Mcu_DistributePllClock(); #endif Mcu_SetMode(McuModeSettingConf_0); /* Initialize all pins using the Port driver */ Port_Init(NULL_PTR); Platform_Init(NULL_PTR); Platform_InstallIrqHandler(LPUART0_RxTx_IRQn, LPUART_UART_IP_0_IRQHandler, NULL_PTR); Pwm_Init(&Pwm_Config_VS_0); Mcl_Init(&Mcl_Config_VS_0); Adc_Init(&Adc_Config_VS_0); Uart_Init(NULL_PTR); /* Part 1: Example with SW Triggered One-Shot Conversion Mode, data conversion is updated by Interrupt.*/ /*******************************************************************************************************/ Adc_Calibrate(AdcHwUnit_0, &CalibStatus); if(CalibStatus.AdcUnitSelfTestStatus == E_NOT_OK) { bStatus = FALSE; } /* ResultBuffer is updated new data in Adc_0_Isr handler */ Adc_SetupResultBuffer(AdcGroup_0, ResultBuffer); Adc_EnableGroupNotification(AdcGroup_0); //for ADC hardware Adc_EnableHardwareTrigger(AdcHwUnit_0); Adc_StartGroupConversion(AdcHwUnit_0); printf("S32M244 FTM TRIGMUX ADC demo RTD200P04!\r\n"); while (1) { printf("===========New Round ADC sampling=========\r\n"); /* Get input level of channels */ Dio_WriteChannel(DioConf_DioChannel_DioChannel_LEDD20, STD_HIGH); TestDelay(2000000); TestDelay(2000000); Pwm_SetDutyCycle(PwmChannel_0, 0x2000); Dio_WriteChannel(DioConf_DioChannel_DioChannel_LEDD20, STD_LOW); TestDelay(2000000); TestDelay(2000000); Pwm_SetDutyCycle(PwmChannel_0, 0x6000); VarNotification_0 = 0; while(VarNotification_0 == 0) {} StdReturn = Adc_ReadGroup(AdcGroup_0, AdcReadGroupBuffer); printf("adc1_SE11 = %d \r\n",(int)AdcReadGroupBuffer[0]); printf("adc1_bandGap = %d \r\n",(int)AdcReadGroupBuffer[1]); } Exit_Example(TRUE); return (0U); } #ifdef __cplusplus } #endif 3. Test result The test results include two parts: the printed results show the ADC sampling value, and the relationship between the PWM output and the PDB trigger position. The printed results are as follows, and you can see that the values ​​of the two ADC channels are correct:   Fig 20 The PWM waveform test is as follows: CH1: PTC0 CH2: PTC1 CH3: PTD0 CH4: PTD1 CH5: PTE11     Fig 21
View full article
Example Description This application demonstrates the usage FlexTimer Module in Complementary mode and dead-time insertion. The application includes S32 Design Studio projects for both devices, that uses configurations for for the IP layer only (Clocks, Port_Ip_1 and Ftm_Pwm). For more details please refer to FlexTimer Module (FTM) Usage on S32M24x and S32K14x Series.   Installation steps Software installation      S32 Design Studio for S32 Platform v.3.5      RTD for S32K1 and S32M24x version 2.0.0 including patch P01 Hardware installation      Supported boards:           - S32M24xEVB-C064           - S32K144EVK      Connections to the scope in S32M24xEVB-C064/S32K144EVK:           - ftm0_ch0 -> PTD15 (J21-2/J2-2)           - ftm0_ch1  -> PTD16 (J21-1/J2-4)           - ftm0_ch2 -> PTD0  (J60-2/J2-6)           - ftm0_ch3 -> PTD1   (J60-3/J6-2)      Debugger in S32M24xEVB-C064/S32K144EVK           - Use the On-board Debug Interface in J32/J7 Open SDA connector.   S32 Configurations Tool      Clocks Tool S32M244 and S32K144 features a complex clocking sourcing, distribution. To run a core of the S32M244/S32K144 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal (meanwhile S32K144 is supplied externally by 8 MHz crystal). This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 in S32M244 (and by 40 in S32K144) and divides by 2 resulting 160 MHz frequency on output for both devices. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by 2 and 4 to supply bus clock (40 MHz) and flash clock (20 MHz), respectively (See next Figure). Figure 1. S32M244 Clocks Configuration        Pins Tool In Pins Tool are selected the signals to use the FTM0 module as follows: Figure 2. S32M244 Pins Configuration        Peripherals Tool Below is the FTM0 configuration (the default configuration of the tabs that are not shown is used): Figure 3: FTM Hardware instance Figure 4: FTM Clock Configuration Figure 5: FTM Global Channel Configuration Figure 6: FTM PwmFtmCh (for Ch0 and Ch1) Figure 7: FTM PwmFtmCh (for Ch2 and Ch3)   Software implementation The application software functionality perform the following instructions (see Example 1): - Initialize Clock driver. - Initialize Port driver - Initialize PWM driver - Update period for FTM0 - Update duty cycle to PWM signals Example 1. S32M244 FTM0 configured by S32 SDK int main(void) { /* Init clock */ Clock_Ip_Init(&Clock_Ip_aClockConfig[0]); /* Initialize all pins using the Port driver */ Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); /* Initialize PWM driver */ Ftm_Pwm_Ip_Init(FTM_INSTANCE_0, &Ftm_Pwm_Ip_UserCfg0); /* Set new period for PWM Signals*/ Ftm_Pwm_Ip_UpdatePwmPeriod(FTM_INSTANCE_0, 0x5000, TRUE); /* Setup new duty cycle to PWM signals */ Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_0, 0x4000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_2, 0x2000, 0x000, TRUE); … }     On the oscilloscope Figure 8 shows that the ftm0_ch0 (D0), ftm0_ch1 (D1), ftm0_ch2 (D2) and ftm0_ch3 (D3) signals on the oscilloscope. Such signals have the same period aligned in the center and with dead-time insertion. ftm0_ch1 is the complementary of ftm0_ch0 with inverted output. And ftm0_ch3 is the complementary of ftm0_ch2 with duplicated output. Figure 8: Complementary mode and dead-time insertion
View full article
Note: The example was designed on: S32M24 PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors C-project based example is a part of S32M24XEVB-SW application SW (the 6-step example has been the part of the application SW from release 1.1).  Application software contains:  S32M24xEVB_BLDC_6Step_Sensorless - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a 6-step sensorless application. Contents 1. Introduction 2. System concept 3. Sensorless BLDC control 3.1. Overview of the brushless DC motor 3.2. Output voltage actuation, PWM technique, current and BEMF measurement 3.3. Position estimation based on BEMF zero-crossing detection 3.4 States of the sensorless BLDC control based on BEMF zero-crossing detection 4. Software implementation on the S32M244 4.1. S32M244 – Key modules for BLDC 6-step control 4.2. S32M244 Device initialization 4.2.1. Clock configuration and power management 4.2.2. FlexTimer Module (FTM) 4.2.3. Trigger MUX Control (TRGMUX) 4.2.4. Programmable delay block (PDB) 4.2.5. Analog-to-digital converter (ADC) 4.2.6. Low Power Serial Peripheral Interface (LPSPI) 4.2.7. Low Power Universal Asynchronous Receiver/Transmitter (LPUART) 4.2.8. Port control and pin multiplexing 4.2.9. Interrupt configuration 4.2.10. Low Power Interrupt Timer (LPIT) configuration 4.2.11. Application Extension (AE) configuration 4.3. Software architecture 4.3.1. Introduction 4.3.2. Application data flow overview 4.3.3. State Machine  4.3.4  Application timing and interrupts 4.3.5  Zero crossing detection algorithm 4.3.6  Speed evaluation, motor current limitation and control 4.3.7. AMMCLIB Integration 5. FreeMASTER and MCAT user interface 6. Conclusion 7. References 1. Introduction This article describes the design of a 3-phase Brushless DC (BLDC) motor control drive using S32M244 NXP integrated solution. Following are the supported features: 3-phase BLDC speed control based on Six-step commutation control Shaft position obtained by BEMF (Back Electromotive Force) voltage zero-crossing detection technique DC-bus current, DC-bus voltage and BEMF voltage sensing Motor speed determined by BEMF zero-crossing period Application control user interface using FreeMASTER debugging tool Motor Control Application Tuning (MCAT) tool jump to top 2. System concept The system is designed to drive a 3-phase BLDC motor. The application meets the following performance specifications: Targeted at the S32M24xEVB-C064/L064 Evaluation Board (refer to dedicated user manual for S32M24xEVB available at www.nxp.com) See section References for more information. Control technique incorporating: Six-step commutation control of 3-phase brushless DC motor without position sensor Rotor position is obtained by BEMF voltage zero-crossing detection technique Closed-loop speed control with action period 1ms Bi-directional rotation Motor current limitation Alignment and start-up 50μs current sampling period Automotive Math and Motor Control Library (AMMCLIB) – Speed control loop built on blocks of precompiled SW library (see section References) FreeMASTER software control interface (motor start/stop, speed setup) FreeMASTER software monitor FreeMASTER Motor Control Application Tuning (MCAT) tool (motor parameters, speed loop, sensorless parameters) FreeMASTER software MCAT graphical control page (required speed, actual motor speed, start/stop status, DC-Bus voltage level, DC-Bus current, system status) FreeMASTER software speed scope (observes actual and desired speeds, DC-Bus voltage and DC-Bus current) FreeMASTER software high-speed recorder (six-step commutation control quantities) DC-Bus over-voltage and under-voltage, over-current, overload and start-up fail protection. jump to top 3. Sensorless BLDC control 3.1. Overview of the brushless DC motor The description of fundamental brushless DC motor principles, overview of electronic commutation control and speed/torque control of BLDC motor can be found in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapters 3.1., 3.1.1., 3.1.2. jump to top 3.2. Output voltage actuation, PWM technique, current and BEMF measurement The 3-phase voltage source inverter is shown on page 6 of S32M24xEVB schematics, see References. It uses single DC-bus shunt resistor (represented as R134 and R135 in parallel). DC-bus current which flows through the shunt resistor produces a voltage drop which is interfaced to the AD converter of microcontroller through the Digital Programmable Gain Amplifier (DPGA) integrated inside S32M244 . The BEMF voltage dividers for BEMF measurement (used for sensorless 6-step control) are integrated in S32M244. The description of the PWM technique used for BLDC motor control, is described in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapter 3.2. jump to top 3.3. Position estimation based on BEMF zero-crossing detection The position detection based on BEMF measurement and BEMF measurement are explained in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapter 3.3. The only difference in conditioning of BEMF voltages and DC Bus current - in case of S32M24x no external dividers for BEMF voltage are needed since these are integrated in S32M24x and voltage drop on shunt resistor is conditioned by S32M24x-integrated DPGA (Digital Programmable Gain Amplifier). 3.4. States of the sensorless BLDC control based on BEMF zero-crossing detection In order to start and run the BLDC motor, the control algorithm has to go through the following states: Initialization Calibration Alignment (initial position setting) Start-up (forced commutation or open-loop mode) Run (sensorless running with BEMF acquisition and zero-crossing detection 3.4.1. Initialization Initialization of variables relevant for motor control. 3.4.2. Calibration In this state the DC current measurement calibration takes place. 3.4.3. Alignment As mentioned previously, the main task for sensorless control of a BLDC motor is position estimation. Before starting the motor, however, the rotor position is not known. The aim of the alignment state is to align the rotor to a known position. This known position enables starting the rotation of the shaft in the desired direction and generating the maximal torque during start-up. During the alignment state, all three phases are powered in order to get the best performance behavior in either direction of shaft rotation. Phase C is connected to the positive DC bus voltage and phases A and B are grounded. The alignment time depends on the mechanical constant of the motor, including load, and also on the applied motor current. 3.4.4. Start-up In the start-up state, motor commutation is controlled in an open-loop mode without any rotor position feedback. The commutation period is controlled by an open-loop starting curve. The open-loop start is required only until the shaft speed is high enough (approximately 5% of nominal motor speed) to produce an identifiable BEMF voltage. 3.4.5. Run The block diagram of the run state is represented by Figure 1 and includes the BEMF acquisition with zero-crossing detection in order to control the commutations. The motor speed is estimated based on zero-crossing time periods. The difference between the demanded and estimated speeds is fed into the speed PI controller. The output of the speed PI controller is proportional to the voltage to be applied to the BLDC motor. The motor current is measured and filtered during the BEMF zero-crossing event and used as feedback into the current controller. The output of the current PI controller limits the output of the speed PI controller. The limitation of the speed PI controller output protects the motor current from exceeding the maximal allowed motor current.  Figure 1. Speed control with current limitation   jump to top 4. Software implementation on S32M244    4.1. S32M244 – Key modules for BLDC 6-step control The S32M244 is an integrated solution which comprises MCU and Application Extension (AE).  The MCU part includes modules such as the FlexTimer Module (FTM), Trigger MUX Control (TRGMUX), Programmable Delay Block (PDB) and Analog-to-Digital Converter (ADC) suitable for control applications, in particular, motor control applications. These modules are directly interconnected and can be configured to meet various motor control application requirements. Figure 2 shows module interconnection for a typical BLDC 6-step application working in Sensorless mode using single shunt current sensing. The modules are described in further chapters and the detailed description can be found in the S32M24x Series Reference Manual (see section References). jump to top 4.1.1. Modules interconnection As mentioned earlier, S32M24x consists of two parts: MCU and AE which are connected together via die-to-die (D2D) connections. The SPI interface (part of D2D) serves for parameter settings and status monitoring of AE and the rest of D2D interface is used for motor control loop (e.g.: DC bus current reading). The AE comprises modules vital for motor control such as Gate Driver Unit (GDU) and Digital Programmable Gain Amplifier (DPGA) which allow for using S32M244 in motor control applications with minimum of external components. The GDU drives the power MOSFETs. The GDU is interconnected with the outputs of FTM via D2D connections. The shunt resistor voltage drop signal (proportional to DC Bus current) is conditioned by the integrated DPGA which output is connected to the ADC via D2D connection. DC Bus voltage and BEMF voltages are conditioned via integrated voltage dividers which outputs are connected to the ADC via D2D connection. The MCU die modules involved in output actuation, data acquisition and the synchronization of actuation and acquisition, form the so-called Control Loop. This control loop consists of the FTM, TRGMUX, PDB, and ADC modules. The control loop is very flexible in operation and can support static, dynamic or asynchronous timing. Each control loop cycle can be initiated either by FTM initialization trigger init_trig or by FTM external trigger ext_trig. While init_trig signal is generated at beginning of PWM cycle, ext_trig can be generated any time within the PWM period based on the value defined in the corresponding FTM Channel Value register CnV. FTM trigger signal is routed to hardware trigger input of the PDB module through flexible TRGMUX unit. In S32M24x, there are two ADC modules and two PDB modules that work in pairs. This means that PDB0 is linked with ADC0 and PDB1 is linked with ADC1.  PDB pre-triggers ch0pretrigx are used as a precondition for ADC module. They are directly connected to ADHWTS ports to select ADC channels as well as order of the channels by configurable pre-triggers delays. When ADC receives rising edge of the trigger, ADC will start conversion according to the order defined by pre-triggers ch0pretrigx. PDB pre-trigger delays must be properly set to allow reliable operation between PDB and corresponding ADC module. When the first pre-trigger is asserted, associated lock of the pre-trigger becomes active until corresponding conversion is not completed. This associated lock is released by corresponding ADC conversion complete flag ADC_SC1[COCOx]. This means that next pre-trigger can be generated only if the ongoing conversion is completed. FTM0 module is used for commutation control. It is configured to schedule and force commutation events which are determined from the actual BEMF zero-crossing period.  Detailed description can be found in the S32M24x Series Reference Manual (see section References).   Figure 2. S32M244 modules interconnection. jump to top 4.1.2. Modules involvement in digital BLDC control loop This section will discuss timing and modules synchronization to accomplish BLDC 6-step control on the S32M244 and the internal hardware features. The timing diagram of the automatic synchronization between PWM and ADC in the BLDC application is shown in Figure 3. Figure3. Time Diagram of PWM and ADC Synchronization. jump to top 4.2. S32M244 Device initialization To simplify and accelerate application development, embedded part of the BLDC 6-step sensorless motor control application has been created using S32M244 Real Time Drivers (RTD). S32M244 can be configured either by means of S32 Configuration Tools (CT) - using GUI  or programmed directly using RTD drivers. Peripherals are initialized at beginning of the main() function. For each S32M244 module, there is a specific configuration function that uses S32M244 RTD APIs and configuration structures generated by RTD graphical tools to configure the MCU (as per Table 1).  Detailed RTD documentation can be found in folder created with S32 Design Studio installation (see References). Table 1. Modules and their configuration functions. Function Module McuClockConfig() MCU clock configuration McuCacheConfig() MCU cache configuration McuPowerConfig() MCU power management configuration McuIntConfig() MCU interrupt management configuration McuTrigmuxConfig() TRGMUX module configuration McuPinsConfig() PINs and PORT modules configuration McuLpuartConfig() LPUART module configuration McuAdcConfig() ADC modules configuration McuPdbConfig() PDB modules configuration McuFtmConfig() FTM modules configuration McuSPIConfig() SPI module configuration AECConfig()   AE module configuration AEC_DPGAConfig() DPGA module configuration AEC_GDUConfig() GDU module configuration AEC_HVMConfig() HV module configuration jump to top 4.2.1. Clock configuration and power management S32M244 features a complex clocking sourcing, distribution and power management. To run a core of the S32M244 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal. This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 and divides by 2 resulting 160 MHz frequency on output. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by two and four to supply bus clock (40 MHz) and flash clock (20 MHz), respectively. This clock configuration belongs to one of the typical and recommended. It is summarized in Table 2.   Table 2. S32M244 clock configuration in RUN mode. Clock Frequency CORE_CLOCK 80 MHz SYS_CLK 80 MHz BUS_CLK 40 MHz FLASH_CLK 20 MHz (max frequency in RUN mode)   This clock configuration can be setup by S32 CT Clocks graphical tool, for further details see the SW example, where the detailed clock settings for the particular peripherals can be found. Once the clock configuration is set, RTD generates static configuration structure Clock_Ip_aClockConfig[0], the respective RTD API is then called in MCUClockConfig which can be found in the SW example in .../src/Peripherals/peripherals_config.c. As discussed at the beginning of this chapter, power management of the S32M244 is configured for normal RUN mode. This power mode can be set in S32CT Peripherals graphical tool, Figure 4. Figure 4. S32M244 power management configuration in S32CT Peripherals tool. Static configuration generated by RTD is called by the respective RTD API and this is encapsulated in MCUPowerConfig function, which can be found in the SW example in .../src/Peripherals/peripherals_config.c The same mechanism for peripherals configuration by RTD works for all S32M244 peripherals, which are discussed below. jump to top 4.2.2. FlexTimer Module (FTM) FlexTimer module (FTM) is built upon a timer with a 16-bit counter. It contains an extended set of features that meet the demands of motor control, including the signed up-counter, dead time insertion hardware, fault control inputs, enhanced triggering functionality, and initialization and polarity control. jump to top 4.2.2.1. Center-aligned PWM mode FTM3 instance is used in BLDC 6-Step motor control application to generate center-aligned PWM by three complementary channels pairs to control power MOSFETs. The configuration is shown in Figure 5, FTM3 PWM frequency of 20 kHz is adjusted by Counter Period = 4000,  taking 80MHz clock source frequency into account. Note that while Center-aligned mode is selected (up-down counter), the value written into FTM3 modulo register is half of Counter Period - this is done internally by the RTD. To protect power MOSFETs against short circuit, deadtime 0.5μs is inserted for each complementary channels pair in number of clock ticks 40 with default deadtime prescaler 1. This FTM3 configuration can be carried out by using S32CT, FTM_Pwm module, Figure 5.  For detailed settings, please see all the settings tabs in Ftm_Pwm module in S32CT Peripherals tool.   Figure 5. S32M244 FTM3 configuration in S32CT. The double-buffered register FTM3_SWOCTRL is used to control the unipolar PWM pattern as discussed in 3.2. The FTM3_SWOCTRL register controls the PWM output by forcing selected channels into a defined state.  The PWM channel which is not SW-controlled is not forced into a SW-defined state but is PWM-controlled. The double-buffered values are applied at each commutation event triggered by FTM0 init_trig . To allow this triggering mechanism, Hardware trigger 0 is enabled in Ftm Synchronization Config tab, Figure 5. The following table shows the SWOCTRL values applied at a commutation event in a particular sector of the six-step commutation sequence. Table 3.  Software control definition in six-step commutation sequence Sector FTM3_SWOCTRL PWM Output settings 0 0x0838 Phase A standard PWM, Phase B low side on, Phase C low/high OFF 1 0x203C Phase A standard PWM, Phase C low side on, Phase B low/high OFF 2 0x2033 Phase B standard PWM, Phase C low side on, Phase A low/high OFF 3 0x020F Phase B standard PWM, Phase A low side on, Phase C low/high OFF 4 0x080F Phase C standard PWM, Phase A low side on, Phase B low/high OFF 5 0x0A0F Phase C standard PWM, Phase B low side on, Phase A low/high OFF Alignment 1 0x0A0F Phase C standard PWM, Phase A low side on, Phase B low side on PWM off 0x003F   1 Alignment vector is set to allow a commutation sequence starting from sector 0 To allow the application of the double-buffered values outside the commutation event, Hardware trigger 1 is enabled in Ftm Synchronization Config tab, Figure 5. This hardware trigger is generated by writing 1 to the SIM_FTMOPT1[FTM3SYNCBIT] bit. The duty cycle of the center-aligned PWM is controlled by the FTM3_CnV (n = 0, 2, 4) register values. In up-down counting mode, even channels define both, leading as well as trailing edges. Even channels are set according to: Equation 1. To initiate control loop at beginning of the PWM period, Initialization trigger is enabled in FTM Instance Configuration tab as well, Figure 5. Once the FTM3 setting is completed, RTD generates configuration structure Ftm_Pwm_Ip_BOARD_INITPERIPHERALS_UserCfg3 which, using the respective RTD API Ftm_Pwm_Ip_Init configures FTM3, this is encapsulated in function MCUFTMConfig, which can be found in the SW example in .../src/Peripherals/peripherals_config.c. jump to top 4.2.2.2. Commutation timer for Sensorless mode FTM0 is used in Sensorless mode to schedule and identify the commutation event. External trigger output signal ext_trig is internally routed to the FTM3 module trigger 0 input in order to perform commutation of the PWM pairs. The commutation event is scheduled by setting the PWM period (CHTM0 CH0 value). When the counter reaches CH0 value, ext_trig is generated and an interrupt is invoked. The ext_trig is also routed to FTM0 trigger 0, what resets FTM0 counter. This ensures FTM0 counter is in the range from 0 to CH0 value (commutation scheduling) and it triggers FTM3 via ext_trig to perform commutation when scheduled. To be able to schedule long commutation periods at low speeds, the FTM0 counter is configured to run at 625 kHz frequency. This module settings can be configured by S32CT as per Figure 6. In order to make use of RTD APIs, FTM0 is configured as FTM PWM but is used for timing exclusively, the outputs of FTM0 are disabled. For detailed FTM0 configuration, please see all the configuration tabs as per Figure 6 in SW example. Once the FTM0 setting is completed, RTD generates configuration structure Ftm_Pwm_Ip_BOARD_INITPERIPHERALS_UserCfg0 which, using the respective RTD API Ftm_Pwm_Ip_Init configures FTM0, this is encapsulated in function MCUFTMConfig, which can be found in the SW example in .../src/Peripherals/peripherals_config.c. Figure 6. FTM0 configuration. jump to top 4.2.3. Trigger MUX Control (TRGMUX) The TRGMUX provides an extremely flexible mechanism for connecting various trigger sources to multiple pins/peripherals. With the TRGMUX, each peripheral that accepts external triggers usually has one specific 32-bit trigger control register. Each control register supports up to four triggers, and each trigger can be selected from the available input triggers. To trigger PDB0 and PDB1 modules by FTM3 initialization trigger signal init_trig, TRGMUX needs to be set appropriately. RTD allows to generate configuration structure Trgmux_Ip_xTrgmuxInitPB that sets all TRGMUX registers to assign trigger inputs with trigger outputs as demanded, Figure 7. The configuration structure Trgmux_Ip_xTrgmuxInitPB is then used as the argument of Trgmux_Ip_Init() which is encapsulated in .../src/Peripherals/peripherals_config.c Figure 7. S32M244 TRGMUX configuration in RTD. In particular, FTM3 initialization trigger signal as a source is assigned to three targets: PDB0, PDB1 and for debug/visualization purposes to TRGMUX output 2. As mentioned before, FTM0 external trigger output is connected to FTM3 hardware trig 0 input  and FTM0 hardware trig 0 input for commutation scheduling and control. ADC0 conversion complete flag COCO is assigned to TRGMUX output 5 for debug/visualization.  jump to top 4.2.4. Programmable delay block (PDB) The Programable Delay Block (PDB) is intended to completely avoid CPU involvement in the timed acquisition of state variables during the control cycle. The PDB module contains a 16-bit programmable delay counter that delays FTM3 initialization trigger and schedules ADC channels sampling through PDB pre-triggers delays. When FTM3 initialization trigger is detected on the PDB0 and PDB1 trigger input, PDB0 and PDB1 generate hardware signal to trigger ADC0 and ADC1 channels in order defined by pre-trigger delays, Figure 8.  Figure 8. PDB pre-triggers and trigger output. PDB pre-trigger delays can be set independently using CHnDLYm registers. Since the PDB0, PDB1 and FTM3 modules are synchronized and share the same source frequency 80MHz, values of the CHnDLYm registers are set using the same time base as for PWM. The following table shows all PDB0 and PDB1 pre-triggers used in BLDC six-step motor control application. Table 4. PDB0 and PDB1 pre-triggers State variable PDB pre-trigger CHnDLYm value [ticks] Relation to PWM Phase BEMF voltage pdb1_ch0_pretrig0 pdb_delay At 90% of the active PWM pulse DC bus current pdb0_ch0_pretrig0 0 At beginning of the PWM DC bus voltage pdb0_ch0_pretrig1 pdb_delay At 90% of the active PWM pulse DC bus current measurement is triggered every PWM cycle at beginning of the PWM period by pdb0_ch0_pretrig0. This delay is static value defined only once at the initialization phase. To measure BEMF voltage and DC bus voltage simultaneously towards the end of the active PWM pulse, pdb1_ch0_pretrig0 and pdb1_ch0_pretrig0 pre-trigger delays are dynamically modified according to actual duty cycle: Equation 2. A software routine limits pdb_delay to 180 ticks to prevent collision between pdb0_ch0_pretrig1 and pdb0_ch0_pretrig0, at low duty cycles. This limit respects ADC conversion time that typically takes ~1.25µs considering short ADC sample time and 40MHz ADC input frequency. PDB Sequence Error Interrupt can be activated as well as hardware detector.   It should be noticed that CHnDLYx are double buffered registers meaning pdb_delay value is first latched into CHnDLYx buffers and then loaded from their buffers at beginning of the PWM period when 1 is written to SC[LDOK] bit and FTM3 init_trig signal is detected on PDB0 and PDB1 input. General settings of the PDB module such as clock pre-scaler, input trigger source, loading mechanism for double buffered registers as well as operation mode for pre-triggers can be configured by means of S32CT as shown in Figure 9, for details, see the PDB configuration in the SW example.    Figure 9. S32M244 PDB module and pre-triggers configuration. RTD generates configuration structures PdbHwUnit_0_BOARD_INITPERIPHERALS  and PdbHwUnit_1_BOARD_INITPERIPHERALS for appropriate PDB registers. This configuration is loaded calling .../src/Peripherals/peripherals_config.c/McuPdbConfig().  jump to top 4.2.5. Analog-to-digital converter (ADC) The S32M244 device has two 12-bit Analog-to-Digital Converters (ADCs). These are 32-channel multiplexed input successive approximation ADCs with 16 result registers. Both ADC instances are triggered independently by two PDBs. ADC channels are sampled in the order defined by PDB pre-triggers. When the first pre-trigger is asserted, associated lock of the pre-trigger becomes active waiting for the conversion complete flag COCO generated by the corresponding ADC channel. This sequence is repeated for each PDB pre-trigger and ADC channel couple. The configuration in S32CT is shown in Figure 10, see the SW example for details.    Figure 10. S32M244 ADC0 module configuration. ADC0 channel 0 measures DC bus current, ADC0 channel 1 measures DC Bus voltage. ADC1 channel 0 measures BEMF voltage. Note that the respective BEMF phase voltage is dynamically assigned to ADC1 channel 0 depending on the commutation sector. This happens in FTM0 ISR notification function FTM0_CH0_Notif(), by calling MEAS_SetBEMFPhase(). RTD generates module configuration structures  AdcHwUnit_0_BOARD_INITPERIPHERALS, and AdcHwUnit_1_BOARD_INITPERIPHERALS, which take effect calling the respective RTD API in function .../src/Peripherals/peripherals_config/McuAdcConfig(). jump to top 4.2.6. Low Power Serial Peripheral Interface (LPSPI) LPSPI is used as communication interface between S3M244 MCU and AE. Configuration of LPSPI1 by means of S32CT can be seen in Figure 11.   Figure 11. S32M244 LPSPI module configuration. LPSPI is then initialized using the RTD-generated configuration structure in .../src/Peripherals/peripherals_config/McuSPIConfig(). jump to top 4.2.7. Low Power Universal Asynchronous Receiver/Transmitter (LPUART) LPUART1 is used as a communication interface between S32M244 processor and FreeMASTER run-time debugging and visualization tool. Function .../src/Peripherals/peripherals_config/McuLpuartConfig() initializes LPUART0 module with baud rate 115200, 1 stop bit and 8 bits per channel. This configuration is carried out by RTD’s LPUART driver. Configuration structure Lpuart_Uart_Ip_xHwConfigPB_0_BOARD_INITPERIPHERALS is configured by means of S32CT as shown in Figure 12.   Figure 12. S32M244 LPUART module configuration. jump to top 4.2.8. Port control and pin multiplexing BLDC 6-step sensorless motor control application requires following on chip pins assignment:    Table 5. Pins assignment for S32M244 BLDC 6-step sensorless control. Peripheral Signal Pin Description ADC0 DCBI PTB13 / ADC0_SE8 DC Bus current DCBV PTA6 / ADC0_SE2 DC Bus voltage ADC1 HS0V PTD2/ADC1_SE2 BEMF Phase A HS1V PTB4/ADC1_SE6 BEMF Phase B HS2V PTB12/ADC1_SE7 BEMF Phase C FTM3 PWMA_HS PTA2 / FTM3_CH0 PWM A high-side driver PWMA_LS PTA3 / FTM3_CH1 PWM A low-side driver PWMB_HS PTB10 / FTM3_CH2 PWM B high-side driver PWMB_LS PTB11 / FTM3_CH3 PWM B low-side driver PWMC_HS PTC10 / FTM3_CH4 PWM C high-side driver PWMC_LS PTC11 / FTM3_CH5 PWM C low-side driver LPSPI1 SPI_SCLK PTB14 / LPSPI1_SCK SPI clock SPI_SIN PTB15 / LPSPI1_SIN SPI data in SPI_SOUT PTB16  / LPSPI1_SOUT SPI data out SPI_CS PTB17 / LPSPI1_PCS3 SPI chip select GPIO AE_Fault PTD3 Application Extension fault (active low) LPUART0 LPUART_In PTC2 / lpuart_rx Receive data from FreeMASTER LPUART_Out PTC3 / lpuart_tx Send data to FreeMASTER TRGMUX TRGMUX_InitTrg PTD1 / trgmux_out2 FTM3 Init trigger visualization TRGMUX_CoCo PTE11 / trgmux_out5 ADC0 CH1   conversion complete visualization GPIO Exec_Meas PTE15 Toggled pin for execution time measurement SW0 PTB4 Application control via board button SW1 PTB5 LED PTE15 LED indication: steady lit - ready, slow flashing - run fast flashing - fault   This pins assignment can be carried out by means of RTD, Pins tool. Pin assignment of the FTM3 module is shown in Figure 13 as an example. Figure 13. S32M244 Pins assignment for FTM3 in S32CT. The RTD-generated configuration structure g_pin_mux_InitConfigArr_BOARD_InitPins and the respective RTD function is then called in ...src/Peripherals/peripherals_config.c/MCUPinsConfig(). Note: At the time of this article publication, ADC0 interleave on pin PTB13 was not available in the S32CT Pins tool, therefore the interleave is set in ...src/Peripherals/peripherals_config.c/MCUPinsConfig() by calling Port_Ci_Port_Ip_SetMuxModeSel(IP_PORTB, 13, PORT_MUX_ADC_INTERLEAVE) jump to top 4.2.9. Interrupt configuration The configuration of the respective interrupts takes place in RTD Peripherals tool. The interrupts are configured as per the following table:.   Table 6. Interrupts in S32M244 BLDC 6-step sensorless example. Name Priority Description ADC0_IRQn 2 Zero cross detection, state variables acquisition FTM0_Ch0_Ch1_IRQn 1 Commutation scheduling PDB0_IRQn 0 Sequence error reset - presence of sequence errors is normal due to asynchronous commutation and resulting switch-over between ADC channels connected to the respective BEMF voltages. PDB1_IRQn 0 PORTD_IRQn 1 AE fault detection LPIT0_Ch0_IRQn 0 Control loop calculation   The configuration of the interrupts in S32CT peripherals tool is shown in Figure 14, see SW example for details.   Figure 14. S32M244 interrupt configuration in RTD. The interrupt from AE fault is carried out by detection of falling edge on PTD3, this needs to be set in RTD peripherals tool as well, a part of the setting is shown in Figure 15. See the detailed setting in RTD peripherals tool for the module Port_Ci_Icu. The S32CT -generated configuration structure IntCtrlConfig_0 and the structure for PTD3 interrupt Port_Ci_Icu_Ip_3_Config_PB_BOARD_INITPERIPHERALS and the respective RTD function is then called in src/peripherals/peripherals_config.c/MCUIntConfig(). Figure 15. S32M244 enabling PTD3 falling edge detection. jump to top 4.2.10. Low Power Interrupt Timer (LPIT) configuration The LPIT channel 0 is employed to control the speed and motor current in a software task. LPIT channel 0 is configured to generate a periodic interrupt every 1 ms. The configuration by means of S32CT is as follows:  Figure 16. S32M244 LPIT configuration. The S32CT -generated configuration structure LPIT_0_InitConfig_PB_BOARD_INITPERIPHERALS and the respective RTD function is then called in src/peripherals/peripherals_config.c/MCULpitConfig(). jump to top 4.2.11. Application Extension (AE) configuration Configuration of AE is describen in NXP application note AN14454: 3-phase Sensorless PMSM Motor Control with S32M244. Identical AE configuration is used also for this SW example. jump to top 4.3. Software architecture Figure 17 presents the conceptual system block diagram of the BLDC Six-step control technique working in sensorless mode. This section is focused on the software design of the Sensorless algorithm based on the zero-crossing detection technique. The application is optimized for S32M244 motor control peripherals to achieve the least possible core involvement in state variable acquisition and output action application. The motor control peripherals (FTM0, FTM3, PDB0, PDB1, ADC0, ADC1) are internally linked together to work independently from the core, and to achieve deterministic sampling of analog quantities and precise commutation of the stator field. The software part of the application consists of different blocks which are described below. The entire application behavior is controlled from a PC through the FreeMASTER run-time debugging tool. The inputs of the control loop are the measured voltages and current on the power stage, in particular the phase/BEMF voltages, the DC bus current, and DC bus voltage.  From a control perspective, the block diagram can be divided into two logical parts: Commutation control, where the phase voltages and DC bus voltage are used to calculate the actual position of the shaft. According to the identified position, the next commutation event can be prepared. Speed/torque control, where the required shaft velocity is compared to the actual measured speed and regulated by the PI controller. The output of the speed PI controller is the duty cycle. The duty cycle is limited by the current PI controller and assigned to the PWM. Figure 17. System block diagram. 4.3.1. Introduction This section describes the software design of the Sensorless BLDC Six Step Control framework application. The application overview and description of software implementation are provided. The aim of this chapter is to help in understanding of the designed software.   4.3.2. Application data flow overview Figure 18 explains the different application states. The figure consists of two interconnected parts: The speed over time characteristic The blocks in the lower part of the picture, which show the states of the application and the transitions between respective states The application software has three main states: the alignment state, the open-loop start state, and the run state. In the run state, the BLDC motor is fully controlled in a closed-loop sensorless mode. After the initialization of the peripheral modules has completed, the software enters the alignment state. In alignment state, the rotor position is stabilized into a known position in order to create the same start-up torque in both directions of rotation. This is achieved by applying a PWM signal to phase C. Phases A and B are assigned with a duty cycle equal to zero; that is, they are connected to the negative pole of the DC bus. The value of the duty cycle on phase C depends on the motor inertia and load applied on the shaft. Such a technique aligns the shaft into position between phase A and B, which is perpendicular to both start-up flux vectors (vectors 0 and 3) generated by the stator winding, and therefore ensures the same start-up torque in both directions of rotation. The duration of the alignment state depends on the motor’s electrical and mechanical constants, the applied current (meaning duty cycle), and the mechanical load. When the alignment time-out expires, the application software moves to the open-loop start state. At a very low shaft velocity, the BEMF voltage is too low to reliably detect the zero-crossing. Therefore, the motor has to be controlled in an open-loop mode for a certain time period. The very first vector generated by the stator windings needs to be set to a position 90° relative to the position of the flux vector generated by magnets mounted on the rotor. The alignment and first start-up vector are shown in Figure 18 . The duration of the open-loop start state is defined by the number of open-loop commutations. The number of open-loop commutations depends on the mechanical time constant of the motor, including load, and also on the applied voltage (duty cycle). The shaft velocity after an open-loop start-up is approximately 5% of nominal velocity. At a velocity approximately 5% of nominal velocity, the BEMF voltage is high enough to reliably detect the zero-crossing. After a defined number of commutation cycles, the state changes from the open-loop start state to the run state. From here on, the commutation process based on the BEMF zero-crossing measurement takes place, and the control enters the closed-loop mode.  Figure 18. Flow chart diagram of main function with background loop. jump to top 4.3.3. State Machine  The application state machine is implemented using a one-dimensional array of pointers to state functions, called AppStateMachine[]. The index of the array specifies the pointer to the related application state function. The application state machine consists of the following seven states selected using the index variable appState value. Possible state transitions are shown in Figure 19. The application states are listed in the following table: Table 7. Application states in Sensorless mode AppState Application state Description 0 INIT The INIT state provides the initial configuration of the PWM duty cycle and initialization of DC bus current offset calibration. The state machine then transitions to the STOP state. 1 CALIB The CALIB state provides the DC bus current calibration. The state machine then transitions to ALIGNMENT state. 2 ALIGNMENT In the ALIGNMENT state, the alignment vector is applied to the stator to set the rotor to the defined position. The duration of the alignment state and the duty cycle applied during the state are defined by the ALIGN_DURATION and ALIGN_VOLTAGE macro values accessible in the BLDC appconfig.h header file. The state machine then transitions to the START state. 3 START In the START state, the motor commutation is controlled in an open-loop without any rotor position feedback. The initial commutation period is controlled by the STARTUP_CMT_PER macro value. Motor acceleration (commutation period multiplier <1) is set by the START_CMT_ACCELER macro value. The number of commutations in the START state is defined by STARTUP_CMT_CNT macro value. All macro values are accessible in the BLDC_appconfig.h header file. The aim of the START state is to achieve an RPM where the zero-crossing event can be reliably detected (BEMF high enough). Once the defined number of commutations is performed, the state machine transitions to the RUN state. 4 RUN In the RUN state, the BLDC motor is controlled in the closed-loop by the sensorless algorithm (BEMF zero-crossing detection). Speed control and current limitation are performed as described in 4.3.6, “Speed evaluation, motor current limitation and control”. The transition to the INIT state is done by setting the appSwitchState variable to 0. 5 STOP In the STOP state, the motor is stopped and prepared to start running. Transition to the ALIGNMENT state is performed once the appSwitchState variable is set to 1 and the freewheeling counter expires. 6 FAULT The fault detection function is executed in the main endless loop, detecting DC bus undervoltage, DC bus overvoltage, DC bus overcurrent, and AE faults. Once any of the faults are detected, the state machine automatically transitions to the FAULT state. The PWM outputs are set to the safe state. To exit the FAULT state, all fault sources must be removed and the faultSwitchClear variable has to be set to 1 to clear the fault latch. The state machine then automatically transitions to the INIT state.   Figure 19. Application state machine jump to top 4.3.4. Application timing and interrupts Figure 20  shows the application timing and the associated interrupts used for the commutation, zero-crossing and speed control. The grey boxes show the executed interrupt routines versus the phase voltage measurement. The top row shows the interrupt that is activated when the ADC conversion sequence of BEMF voltage, DC bus current, and DC bus voltage has been completed. In this interrupt, the FTM0 timer counter value is saved as a BEMF measurement reference point. The zero-crossing detection algorithm is executed in each ADC0 conversion complete interrupt after a commutation event. Once the zero-crossing is found, the detection algorithm is disabled until the new commutation event occurs. The second row shows the FTM0 timer counter interrupt generated at the time of the commutation event. The time between each FTM0 timer counter interrupt is dependent on the actual speed of the motor. Channel of the ADC1 is reconfigured to reflect the change in the phase used for the BEMF voltage sensing. The last row shows the LPIT channel 0 time-out interrupt generated every 1 ms. This interrupt is used for speed loop control and motor current limitation, executing PI controller functions.    Figure 20. Application timing and interrupts jump to top 4.3.5. Zero crossing detection algorithm For state variable acquisition and zero-crossing detection processing, the ADC0 conversion sequence complete interrupt is used. The interrupt service routine is executed once the conversion sequence consisting of BEMF voltage, DC bus current and DC bus current conversion is finished. The ADC0 conversion sequence complete interrupt service routine can be found in the SW example in .../src/main.c/ADC0_ConversionCompleteNotif(). Before the ADC0 conversion complete ISR is executed, the ADC0 and ADC1 store the results in the ADC0 and ADC1 results registers; BEMF voltage into ADC1_R0, DC bus current into ADC0_R0, and DC bus voltage into ADC0_R1. These measurements are then saved into the result structure. The value of the current sense amplifier bias voltage offset is subtracted from the measured DC bus current value to obtain the bidirectional DC bus current.  A filtering of the DC bus voltage and DC bus current is provided using the moving average filter functions. The BEMF voltage is then calculated as the difference between the phase voltage and the half of the DC bus voltage. The BEMF voltage value is a signed number. The software checks whether the current decay period has already passed to initiate the zero-crossing detection. (See the details on BEMF-based position detection in chapter 3.3.3.1. of NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144). The current decay period is called T OFF (variable timeZCToff) in the application implementation: Example 1. Conditions for zero-crossing detection initiation       void ADC0_ConversionCompleteNotif(const uint8 ControlChanIdx) { . . . timeOldBackEmf = timeBackEmf; timeBackEmf = Ftm_Gpt_Ip_GetCntValue(INST_FTM0); if(driveStatus.B.AfterCMT == 1) { if(timeBackEmf > timeZCToff) { driveStatus.B.AfterCMT = 0; } } if((driveStatus.B.AfterCMT == 0) && (driveStatus.B.NewZC == )&& (driveStatus.B.Sensorless == 1)) { . . . }       Where the commutation transient time T OFF has not yet expired (driveStatus.B.AfterCMT = 1), the zero-crossing calculation will not be performed. The calculation will also not be performed if the zero-crossing point has already been identified in the current commutation period (driveStatus.B.NewZC= 1), or if the application is running in open-loop mode (driveStatus.B.Sensorless = 0). If the above mentioned conditions are not met, the zero-crossing detection routine will be executed. Based on the current commutation sector, the BEMF slope direction is checked. If the BEMF slope is negative, the sign of the calculated value is changed. This operation allows usage of a single BEMF zero-crossing detection function for a positive slope BEMF in all commutation sectors. When the zero-crossing position calculation is finished, the BEMF voltage value is stored as the old value as it will be referenced again in the next PWM cycle. In the case of a negative BEMF voltage (VBEMF < VDCB / 2), the zero-crossing point has not been passed and the zero-crossing is not detectable. The software exits the zero-crossing detecting routine and leaves the zero-crossing status bit unchanged (driveStatus.B.NewZC = 0). In the case of a zero or a positive BEMF voltage (VBEMF ≥ VDCB / 2), the zero-crossing point was reached or passed and Equation 7 is calculated (see AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144 for Equation 7 and its description), meaning that the BEMF voltage is divided by the delta of the two measured points and multiplied by the measured PWM period (BEMF measurement period). After this calculation, the old zero-crossing time and the new one are saved into the appropriate variables. The zero-crossing period is then calculated based on the calculated time of zero-crossing and the time of the zero-crossing in the previous commutation cycle. The zero-crossing period is also filtered to improve reliability At the end of the routine, the new commutation time is calculated. Here, some motor characteristics have to be taken into account. Instead of just adding half of a zero-crossing period to the actual zero-crossing time, a so-called advance angle factor is taken into account, which actually activates the commutation a bit earlier than calculated. This is usually a constant and depends on the motor characteristics. Finally, the zero-crossing status bit is set (driveStatus.B.NewZC = 1), so the zero-crossing detection does not take place anymore in the current commutation cycle. For details, see the code in the SW example in ADC0 ISR notification  .../src/main.c/ADC0_ConversionCompleteNotif(). jump to top   4.3.6. Speed evaluation, motor current limitation and control The speed controller is executed in a timer interrupt every 1 ms. The actual speed is calculated from all of the last six zero-crossing periods, and this is stored as the actual speed. The required speed is fed into the ramp function controlling the motor speed slope. The difference between the speed ramp function output and actual speed defines the speed error. In the closed-loop mode, the actual speed error is fed into the PI controller function. Inputs to the PI controller function include the speed error and the PI controller’s parameters such as the proportional and integral gain constants. The output of the PI controller is the duty cycle, which is scaled to the PWM resolution. At the end of the speed control function, the duty cycle is loaded into the FTM3 PWM module. The current limit controller is located in the same 1 ms timer interrupt (.../src/main.c/LpitNotif() ) as the speed controller because the inputs and outputs of both controllers are linked together. When the actual speed has been calculated, the current limit PI controller can be called by feeding it with the difference between the actual current and the maximum allowed current of the motor. The output of the PI controller is scaled to the number proportional to the PWM period. After the current PI controller has calculated its duty cycle, both duty cycle output values are compared to each other. If the speed PI controller duty cycle output is higher than the current limit PI controller output, then the speed PI Controller duty cycle output value is limited to the output value of the current limit PI controller. Otherwise, the speed PI duty cycle output will be taken as the duty cycle update value. The value of the duty cycle will be used to update the FTM3 PWM module. At the end, the integral portion values of both the PI controllers need to be synchronized to avoid one of the controllers increasing its internal value as far as the upper limit. If the duty cycle was limited to the current PI duty cycle output, then the integral portion of the current PI controller will be copied into the integral portion of the speed controller, and vice versa.  At the end of .../src/main.c/LpitNotif() PDB0 and PDB1 pre-trigger delays are calculated based on the actual duty cycle to measure DC Bus voltage and BEMF voltage towards the end of the active PWM pulse as discussed in chapter 4.2.4. 4.3.7. AMMCLIB Integration The integration of AMMCLIB is done in the manner identical to the one described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top   5. FreeMASTER and MCAT user interface The FreeMASTER debugging tool is used to control the application and monitor variables during run time.  FreeMASTER and MCAT interface enables online application tuning and control.  MCAT (Motor Control Application Tuning) is a graphical tool dedicated to motor control developers and the operators of modern electrical drives. The main feature of proposed approach is automatic calculation and real-time tuning of selected control structure parameters. Connecting and tuning new electric drive setup becomes easier because the MCAT tool offers a possibility to split the control structure and consequently to control the motor at various levels of cascade control structure. FreeMASTER and MCAT user interface are described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top 6. Conclusion The design described shows the simplicity and efficiency in using the S32M244 microcontroller for Sensorless BLDC motor control and introduces it as an appropriate candidate for various low-cost applications in the automotive area. MCAT tool provides interactive online tool which makes the BLDC drive application tuning friendly and intuitive. jump to top 7. References • S32 Design Studio IDE for S32 Platform • Real-Time Drivers (RTD) • FreeMASTER Run-Time Debugging Tool • Automotive Math and Motor Control Library • S32M24x Reference Manual • S32M2xx Data Sheet • S32M24x PMSM/BLDC Motor Control Evaluation Boards • BLDC PMSM low voltage motor control accessory kit • Rashid, M. H. Power Electronics Handbook, 2nd Edition. Academic Press • Motor Control Application Tuning (MCAT) Tool jump to top
View full article
Note: The example was designed on: S32M24 PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors C-project based example is a part of S32M24XEVB-SW application SW (the 6-step example has been the part of the application SW from release 1.1).  Application software contains:  S32M24xEVB_BLDC_6Step_Hall - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a 6-step Hall application. Contents 1. Introduction 2. System concept 3. Hall sensor-based BLDC control 3.1. Overview of the brushless DC motor 3.2. Output voltage actuation and complementary unipolar PWM modulation technique 3.3. Position estimation based on Hall sensors 3.4 States of the BLDC control based on Hall sensors 4. Software implementation on the S32M244 4.1. S32M244 – Key modules for BLDC 6-step control 4.2. S32M244 Device initialization 4.2.1. Clock configuration and power management 4.2.2. FlexTimer Module (FTM) 4.2.3. Trigger MUX Control (TRGMUX) 4.2.4. Programmable delay block (PDB) 4.2.5. Analog-to-digital converter (ADC) 4.2.6. Low Power Serial Peripheral Interface (LPSPI) 4.2.7. Low Power Universal Asynchronous Receiver/Transmitter (LPUART) 4.2.8. Port control and pin multiplexing 4.2.9. Interrupt configuration 4.2.10. Low Power Interrupt Timer (LPIT) configuration 4.2.11. Application Extension (AE) configuration 4.3. Software architecture 4.3.1. Introduction 4.3.2. Application data flow overview 4.3.3. State Machine  4.3.4  Application timing and interrupts 4.3.5  Speed evaluation, motor current limitation and control 4.3.6. AMMCLIB Integration 5. FreeMASTER and MCAT user interface 6. Conclusion 7. References 1. Introduction This article describes the design of a 3-phase Brushless DC (BLDC) motor control drive using S32M244 NXP integrated solution. Following are the supported features: 3-phase BLDC speed control based on Six-step commutation control Shaft position obtained by hall sensors DC-bus current and DC-bus voltage Motor speed determined by hall sensors Application control user interface using FreeMASTER debugging tool Motor Control Application Tuning (MCAT) tool jump to top 2. System concept The system is designed to drive a 3-phase BLDC motor. The application meets the following performance specifications: Targeted at the S32M24xEVB-C064/L064 Evaluation Board (refer to dedicated user manual for S32M24xEVB available at www.nxp.com) See section References for more information. Control technique incorporating: Six-step commutation control of 3-phase brushless DC motor with hall sensors Rotor position is obtained by hall sensors Closed-loop speed control with action period 1ms Bi-directional rotation Motor current limitation Alignment and start-up 50μs current sampling period Automotive Math and Motor Control Library (AMMCLIB) – Speed control loop built on blocks of precompiled SW library (see section References) FreeMASTER software control interface (motor start/stop, speed setup) FreeMASTER software monitor FreeMASTER embedded Motor Control Application Tuning (MCAT) tool (motor parameters, speed loop) FreeMASTER software MCAT graphical control page (required speed, actual motor speed, start/stop status, DC-Bus voltage level, DC-Bus current, system status) FreeMASTER software speed scope (observes actual and desired speeds, DC-Bus voltage and DC-Bus current) FreeMASTER software high-speed recorder (six-step commutation control quantities) DC-Bus over-voltage and under-voltage, over-current, overload and start-up fail protection. jump to top 3. Hall sensor-based BLDC control 3.1. Overview of the brushless DC motor The description of fundamental brushless DC motor principles, overview of electronic commutation control and speed/torque control of BLDC motor can be found in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapters 3.1., 3.1.1., 3.1.2. jump to top 3.2. Output voltage actuation and complementary unipolar PWM modulation technique The 3-phase voltage source inverter is shown on page 7 of S32M24xEVB schematics, see References. It uses single DC-bus shunt resistor (represented as R134 and R135 in parallel). DC-bus current which flows through the shunt resistor produces a voltage drop which is interfaced to the AD converter of microcontroller through the integrated Digital Programmable Gain Amplifier (DPGA) integrated inside S32M244 . The description of the PWM technique used for BLDC motor control, is available in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapter 3.2. The Hall sensors are connected to terminal header J200. jump to top 3.3. Position estimation based on Hall sensor The position estimation based on Hall sensor is a simple and cost-effective way to control the commutation of BLDC motor. In BLDC motors, there are three Hall sensors mounted around the rotor or stator periphery shifted 120° apart from each other. When the rotor magnet crosses one of the sensor, sensor generates high or low logic signal depending on the magnet polarity. As rotor magnets cross all three sensors, these sensors give out position angle from 0° to 360° every 60°. To get optimal torque and efficiency conditions in Six-step commutation control, switching sequence of the phases energizing has to produce stator magnetic flux which is 120° - 60° in relation to rotor magnetic flux, Figure 1. The picture depicts the situation when rotor enters first commutation sector “Sector 0”. This moment is indicated by Hall sensor logic “110”. In this sector, phase C is connected to positive polarity of the DC bus voltage, phase B is connected to negative polarity of the DC bus voltage and phase A is unpowered. This phases energizing creates stator magnetic flux which is 120° ahead to rotor magnetic flux. Torque is produced and angle between stator flux and rotor flux decreases from 120° to 60° as rotor moves towards the next commutation sector “Sector 2”. This process is then repeated for each commutation sector.   Figure 1. Speed control with current limitation    The shown Hall sensor states for the particular sectors are applicable to Sunrise motor 42BLY3A78-24110 and may differ for other motor type. The resulting switching statesfor the mentioned motor are as per the following table, where NC denotes the not connected motor phase, LS means low side transistor and HS means high side transistor: Table 1. Switching table. Direction Hall A Hall B Hall C Phase A Phase B Phase C ccw 1 1 0 NC LS ON HS PWM ccw 1 0 0 LS ON NC HS PWM ccw 1 0 1 LS ON HS PWM NC ccw 0 0 1 NC HS PWM LS ON ccw 0 1 1 HS PWM NC LS ON ccw 0 1 0 HS PWM LS ON NC cw 1 1 0 NC HS PWM LS on cw 0 1 0 LS ON HS PWM NC cw 0 1 1 LS ON NC HS PWM cw 0 0 1 NC LS ON HS PWM cw 1 0 1 HS PWM LS ON NC cw 1 0 0 HS PWM NC LS ON Note: The rotation direction is valid for the aforementioned Sunrise motor and may be reversed in case of other motor. Please note that in case of S32M244 the Flex Timer Module (FTM) is used for PWM control and thus for realization of the switching table. The FTM registers used for execution of the particular switching pattern (table) are double buffered.  Meaning they only take effect after a synchronization event. In this SW example, the synchronization event occurs when the state of Hall sensors has changed. Therefore, the algorithm chooses the switching state based on Hall sensors state for "next commutation sector", loads the corresponding settings into FTM registers and they are applied when the Hall state changes to "next commutation sector". For example: the desired rotation is ccw, the Hall state changes to [110]. Now the algorithm prepares the FTM registers for the switching pattern applicable or the next commutation sector (Hall state [100]) meaning the respective double-buffered registers are set to generate pattern: Phase A - LS ON, Phase B - NC, Phase C - HS PWM, but this pattern is not applied yet, it is only applied after the Hall state changes to "next commutation sector" i.e., when Hall state is [100].  This happens for all Hall states in both directions of rotation. 3.4. States of the BLDC control based on Hall sensors In order to start and run the BLDC motor, the control algorithm has to go through the following states: Initialization Calibration Alignment (initial position setting) Run 3.4.1. Initialization Initialization of variables relevant for motor control. 3.4.2. Calibration In this state the DC current measurement calibration takes place. 3.4.3. Alignment Before starting, the motor is aligned to the middle of commutation sector. During the alignment state, all three phases are powered in order to get the best performance behavior in either direction of shaft rotation. Phase C is connected to the positive DC bus voltage and phases A and B are grounded. The alignment time depends on the mechanical constant of the motor, including load, and also on the applied motor current. 3.4.4. Run The block diagram of the run state is represented by Figure 2 . The motor speed is estimated based on Hall events. The difference between the demanded and estimated speeds is fed into the speed PI controller. The output of the speed PI controller is proportional to the voltage to be applied to the BLDC motor. The motor current is measured and filtered and used as feedback into the current controller. The output of the current PI controller limits the output of the speed PI controller. The limitation of the speed PI controller output protects the motor current from exceeding the maximal allowed motor current.  Figure 2. Speed control with current limitation   jump to top 4. Software implementation on S32M244    4.1. S32M244 – Key modules for BLDC 6-step control The S32M244 is an integrated solution which comprises MCU and Application Extension (AE).  The MCU part includes modules such as the FlexTimer Module (FTM), Trigger MUX Control (TRGMUX), Programmable Delay Block (PDB) and Analog-to-Digital Converter (ADC) suitable for control applications, in particular, motor control applications. These modules are directly interconnected and can be configured to meet various motor control application requirements. Figure 3 shows module interconnection for a typical BLDC 6-step application working in Hall sensor-based mode using single shunt current sensing. The modules are described in further chapters and the detailed description can be found in the S32M24x Series Reference Manual (see section References). jump to top 4.1.1. Module interconnection As mentioned earlier, S32M24x consists of two parts: MCU and AE which are connected together via die-to-die (D2D) connections. The SPI interface (part of D2D) serves for parameter settings and status monitoring of AE and the rest of D2D interface is used for motor control loop (e.g.: DC bus current reading). The AE comprises modules vital for motor control such as Gate Driver Unit (GDU) and Digital Programmable Gain Amplifier (DPGA) which allow for using S32M244 in motor control applications with minimum of external components. The GDU drives the power MOSFETs. The GDU is interconnected with the outputs of FTM via D2D connections. The shunt resistor voltage drop signal (proportional to DC Bus current) is conditioned by the integrated DPGA which output is connected to the ADC via D2D connection. DC Bus voltage is conditioned via integrated voltage dividers which outputs are connected to the ADC via D2D connection. The MCU die modules involved in output actuation, data acquisition and the synchronization of actuation and acquisition, form the so-called Control Loop. This control loop consists of the FTM, TRGMUX, PDB, and ADC modules. The control loop is very flexible in operation and can support static, dynamic or asynchronous timing. Each control loop cycle can be initiated either by FTM initialization trigger init_trig or by FTM external trigger ext_trig. While init_trig signal is generated at beginning of PWM cycle, ext_trig can be generated any time within the PWM period based on the value defined in the corresponding FTM Channel Value register CnV. FTM trigger signal is routed to hardware trigger input of the PDB module through flexible TRGMUX unit. In S32M24x, there are two ADC modules and two PDB modules that work in pairs. This means that PDB0 is linked with ADC0 and PDB1 is linked with ADC1. The Hall sensor-based 6-step example only uses ADC0 and PDB0. PDB pre-triggers ch0pretrigx are used as a precondition for ADC module. They are directly connected to ADHWTS ports to select ADC channels as well as order of the channels by configurable pre-triggers delays. When ADC receives rising edge of the trigger, ADC will start conversion according to the order defined by pre-triggers ch0pretrigx. PDB pre-trigger delays must be properly set to allow reliable operation between PDB and corresponding ADC module. When the first pre-trigger is asserted, associated lock of the pre-trigger becomes active until corresponding conversion is not completed. This associated lock is released by corresponding ADC conversion complete flag ADC_SC1[COCOx]. This means that next pre-trigger can be generated only if the ongoing conversion is completed. FTM2 module is used for commutation control. It is configured to schedule and force commutation events which are determined from the states of the Hall sensors.  Detailed description can be found in the S32M24x Series Reference Manual (see section References).     Figure 3. S32M244 modules interconnection. jump to top 4.1.2. Module involvement in digital BLDC control loop This section will discuss timing and modules synchronization to accomplish BLDC 6-step control on the S32M244 and the internal hardware features. The timing diagram of the automatic synchronization between PWM and ADC in the BLDC application is shown in Figure 4.   Figure 4. Time Diagram of PWM and ADC Synchronization. jump to top 4.2. S32M244 Device initialization To simplify and accelerate application development, embedded part of the BLDC 6-step motor control application has been created using S32M244 Real Time Drivers (RTD). S32M244 can be configured either by means of S32 Configuration Tools (CT) - using GUI  or programmed directly using RTD drivers. Peripherals are initialized at beginning of the main() function. For each S32M244 module, there is a specific configuration function that uses S32M244 RTD APIs and configuration structures generated by RTD graphical tools to configure the MCU (as per Table 2).  Detailed RTD documentation can be found in folder created with S32 Design Studio installation (see References). Table 2. Modules and their configuration functions. Function Module McuClockConfig() MCU clock configuration McuCacheConfig() MCU cache configuration McuPowerConfig() MCU power management configuration McuIntConfig() MCU interrupt management configuration McuTrigmuxConfig() TRGMUX module configuration McuPinsConfig() PINs and PORT modules configuration McuLpuartConfig() LPUART module configuration McuAdcConfig() ADC modules configuration McuPdbConfig() PDB modules configuration McuFtmConfig() FTM modules configuration McuSPIConfig() SPI module configuration AECConfig()   AE module configuration AEC_DPGAConfig() DPGA module configuration AEC_GDUConfig() GDU module configuration AEC_HVMConfig() HV module configuration jump to top 4.2.1. Clock configuration and power management S32M244 features a complex clocking sourcing, distribution and power management. To run a core of the S32M244 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal. This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 and divides by 2 resulting 160 MHz frequency on output. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by two and four to supply bus clock (40 MHz) and flash clock (20 MHz), respectively. This clock configuration belongs to one of the typical and recommended. It is summarized in Table32. Table 3. S32M244 clock configuration in RUN mode. Clock Frequency CORE_CLOCK 80 MHz SYS_CLK 80 MHz BUS_CLK 40 MHz FLASH_CLK 20 MHz (max frequency in RUN mode)   This clock configuration can be setup by S32 CT Clocks graphical tool, for further details see the SW example, where the detailed clock settings for the particular peripherals can be found. Once the clock configuration is set, RTD generates static configuration structure Clock_Ip_aClockConfig[0], the respective RTD API is then called in MCUClockConfig which can be found in the SW example in .../src/Peripherals/peripherals_config.c. As discussed at the beginning of this chapter, power management of the S32M244 is configured for normal RUN mode. This power mode can be set in S32CT Peripherals graphical tool, Figure 5.   Figure 5. S32M244 power management configuration in S32CT Peripherals tool. Static configuration generated by RTD is called by the respective RTD API and this is encapsulated in MCUPowerConfig function, which can be found in the SW example in .../src/Peripherals/peripherals_config.c The same mechanism for peripherals configuration by RTD works for all S32M244 peripherals, which are discussed below. jump to top 4.2.2. FlexTimer Module (FTM) FlexTimer module (FTM) is built upon a timer with a 16-bit counter. It contains an extended set of features that meet the demands of motor control, including the signed up-counter, dead time insertion hardware, fault control inputs, enhanced triggering functionality, and initialization and polarity control. jump to top 4.2.2.1. Center-aligned PWM mode FTM3 instance is used in BLDC 6-Step motor control application to generate center-aligned PWM by three complementary channels pairs to control power MOSFETs. The configuration is shown in Figure 6, FTM3 PWM frequency of 20 kHz is adjusted by Counter Period = 4000,  taking 80MHz clock source frequency into account. Note that while Center-aligned mode is selected (up-down counter), the value written into FTM3 modulo register is half of Counter Period - this is done internally by the RTD. To protect power MOSFETs against short circuit, deadtime 0.5μs is inserted for each complementary channels pair in number of clock ticks 40 with default deadtime prescaler 1. This FTM3 configuration can be carried out by using S32CT, FTM_Pwm module, Figure 6.  For detailed settings, please see all the settings tabs in Ftm_Pwm module in S32CT Peripherals tool.   Figure 6. S32M244 FTM3 configuration in S32CT. The double-buffered register FTM3_SWOCTRL is used to control the unipolar PWM pattern as discussed in 3.2. The FTM3_SWOCTRL register controls the PWM output by forcing selected channels into a defined state.  The PWM channel which is not SW-controlled is not forced into a SW-defined state but is PWM-controlled. The double-buffered values are applied at each commutation event triggered by FTM2 init_trig . To allow this triggering mechanism, Hardware trigger 0 is enabled in Ftm Synchronization Config tab, Figure 6. The following table shows the SWOCTRL values applied at a commutation event in a particular sector of the six-step commutation sequence. Table 4.  Software control definition in six-step commutation sequence Sector FTM3_SWOCTRL PWM Output settings 0 0x0838 Phase A PWM, Phase B low side on, Phase C low/high OFF 1 0x203C Phase A PWM, Phase C low side on, Phase B low/high OFF 2 0x2033 Phase B PWM, Phase C low side on, Phase A low/high OFF 3 0x020F Phase B PWM, Phase A low side on, Phase C low/high OFF 4 0x080F Phase C PWM, Phase A low side on, Phase B low/high OFF 5 0x0A0F Phase C PWM, Phase B low side on, Phase A low/high OFF Alignment 1 0x0A0F Phase C PWM, Phase A low side on, Phase B low side on PWM off 0x003F   1 Alignment vector is set to allow a commutation sequence starting from sector 0 To allow the application of the double-buffered values outside the commutation event, Hardware trigger 1 is enabled in Ftm Synchronization Config tab, Figure 6. This hardware trigger is generated by writing 1 to the SIM_FTMOPT1[FTM3SYNCBIT] bit. The duty cycle of the center-aligned PWM is controlled by the FTM3_CnV (n = 0, 2, 4) register values. In up-down counting mode, even channels define both, leading as well as trailing edges. Even channels are set according to: Equation 1. To initiate control loop at beginning of the PWM period, Initialization trigger is enabled in FTM Instance Configuration tab as well, Figure 6. Once the FTM3 setting is completed, RTD generates configuration structure Ftm_Pwm_Ip_BOARD_INITPERIPHERALS_UserCfg3 which, using the respective RTD API Ftm_Pwm_Ip_Init configures FTM3, this is encapsulated in function MCUFTMConfig, which can be found in the SW example in .../src/Peripherals/peripherals_config.c. jump to top 4.2.2.2. Commutation for 6-step In 6-step Hall-based control, the commutation depends on the change of Hall sensor state. The Hall sensors are routed to GPIOs which trigger interrupts on both raising and falling signal edges. In the interrupt service routine for GPIO the Hall signals are processed, new switching combination of the MOSFETs is stipulated based on Hall sensor signals and desired direction of rotation. The time which has elapsed between two Hall signal events is measured by FTM2. After each Hall (commutation event) FTM2 CNT (counter) value is recorded and FTM2 CNT is restarted. Init trigger signal init_trig is internally routed to the FTM3 module trigger 0 input in order to perform commutation of the PWM pairs.  FTM2 module settings can be configured by S32CT as per Figure 7. In order to make use of RTD APIs, FTM2 is configured as FTM PWM but is used for measurement of time between Hall (commutation) events exclusively, the outputs of FTM2 are disabled. For detailed FTM2 configuration, please see all the configuration tabs as per Figure 7 in SW example. Once the FTM2 setting is completed, RTD generates configuration structure Ftm_Pwm_Ip_BOARD_INITPERIPHERALS_UserCfg0 which, using the respective RTD API Ftm_Pwm_Ip_Init configures FTM2, this is encapsulated in function MCUFTMConfig, which can be found in the SW example in .../src/Peripherals/peripherals_config.c.   Figure 7. FTM2 configuration. jump to top 4.2.3. Trigger MUX Control (TRGMUX) The TRGMUX provides an extremely flexible mechanism for connecting various trigger sources to multiple pins/peripherals. With the TRGMUX, each peripheral that accepts external triggers usually has one specific 32-bit trigger control register. Each control register supports up to four triggers, and each trigger can be selected from the available input triggers. To trigger PDB0 module by FTM3 initialization trigger signal init_trig, TRGMUX needs to be set appropriately. RTD allows to generate configuration structure Trgmux_Ip_xTrgmuxInitPB that sets all TRGMUX registers to assign trigger inputs with trigger outputs as demanded, Figure 8. The configuration structure Trgmux_Ip_xTrgmuxInitPB is then used as the argument of Trgmux_Ip_Init() which is encapsulated in .../src/Peripherals/peripherals_config.c Figure 8. S32M244 TRGMUX configuration in RTD. In particular, FTM3 initialization trigger signal as a source is assigned to two targets: PDB0 and for debug/visualization purposes to TRGMUX output 2. As mentioned before, FTM2 init trigger output is connected to FTM3 hardware trig 0 input. ADC0 conversion complete flag COCO is assigned to TRGMUX output 5 for debug/visualization.  jump to top 4.2.4. Programmable delay block (PDB) The Programable Delay Block (PDB) is intended to completely avoid CPU involvement in the timed acquisition of state variables during the control cycle. The PDB module contains a 16-bit programmable delay counter that delays FTM3 initialization trigger and schedules ADC channels sampling through PDB pre-triggers delays. When FTM3 initialization trigger is detected on the PDB0 input, PDB0 generates hardware signal to trigger ADC0 channels in order defined by pre-trigger delays, Figure 9.  Figure 9. PDB pre-triggers and trigger output. PDB pre-trigger delays can be set independently using CHnDLYm registers. Since the PDB0, PDB1 and FTM3 modules are synchronized and share the same source frequency 80MHz, values of the CHnDLYm registers are set using the same time base as for PWM. The following table shows all PDB0 pre-triggers used in BLDC six-step motor control application. Table 5. PDB0 pre-triggers State variable PDB pre-trigger CHnDLYm value [ticks] Relation to PWM DC bus current pdb0_ch0_pretrig0 0 At beginning of the PWM DC bus voltage pdb0_ch0_pretrig1 pdb_delay In the middle of the PWM DC bus current measurement is triggered every PWM cycle at beginning of the PWM period by pdb0_ch0_pretrig0. This delay is static value defined only once at the initialization phase. The DC Bus voltage is measured in the middle of the PWM period. General settings of the PDB module such as clock pre-scaler, input trigger source, loading mechanism for double buffered registers as well as operation mode for pre-triggers can be configured by means of S32CT as shown in Figure 10, for details, see the PDB configuration in the SW example.          Figure 10. S32M244 PDB module and pre-triggers configuration. RTD generates configuration structure PdbHwUnit_0_BOARD_INITPERIPHERALS  for appropriate PDB registers. This configuration is loaded calling .../src/Peripherals/peripherals_config.c/McuPdbConfig().  jump to top 4.2.5. Analog-to-digital converter (ADC) The S32M244 device has two 12-bit Analog-to-Digital Converters (ADCs). These are 32-channel multiplexed input successive approximation ADCs with 16 result registers. The ADC0 instance is used in the SW example and is triggered by PDB0. ADC channels are sampled in the order defined by PDB pre-triggers. When the first pre-trigger is asserted, associated lock of the pre-trigger becomes active waiting for the conversion complete flag COCO generated by the corresponding ADC channel. This sequence is repeated for each PDB pre-trigger and ADC channel couple. The configuration in S32CT is shown in Figure 11, see the SW example for details.      Figure 11. S32M244 ADC0 module configuration. ADC0 channel 0 measures DC bus current, ADC0 channel 1 measures DC Bus voltage.  RTD generates module configuration structure  AdcHwUnit_0_BOARD_INITPERIPHERALS, which takes effect calling the respective RTD API in function .../src/Peripherals/peripherals_config/McuAdcConfig(). jump to top 4.2.6. Low Power Serial Peripheral Interface (LPSPI) LPSPI is used as communication interface between S3M244 MCU and AE. Configuration of LPSPI1 by means of S32CT can be seen in Figure 12.   Figure 12. S32M244 LPSPI module configuration. LPSPI is then initialized using the RTD-generated configuration structure in .../src/Peripherals/peripherals_config/McuSPIConfig(). jump to top 4.2.7. Low Power Universal Asynchronous Receiver/Transmitter (LPUART) LPUART1 is used as a communication interface between S32M244 processor and FreeMASTER run-time debugging and visualization tool. Function .../src/Peripherals/peripherals_config/McuLpuartConfig() initializes LPUART0 module with baud rate 115200, 1 stop bit and 8 bits per channel. This configuration is carried out by RTD’s LPUART driver. Configuration structure Lpuart_Uart_Ip_xHwConfigPB_0_BOARD_INITPERIPHERALS is configured by means of S32CT as shown in Figure 13.   Figure 13. S32M244 LPUART module configuration. jump to top 4.2.8. Port control and pin multiplexing BLDC 6-step motor control application requires following on chip pins assignment:    Table 6. Pins assignment for S32M244 BLDC 6-step Hall sensor-based control. Peripheral Signal Pin Description ADC0 DCBI PTB13 / ADC0_SE8 DC Bus current DCBV PTA6 / ADC0_SE2 DC Bus voltage GPIO HALL_A PTE4 Hall sensor Phase A HALL_B PTE5 Hall sensor Phase B HALL_C PTD0 Hall sensor Phase C FTM3 PWMA_HS PTA2 / FTM3_CH0 PWM A high-side driver PWMA_LS PTA3 / FTM3_CH1 PWM A low-side driver PWMB_HS PTB10 / FTM3_CH2 PWM B high-side driver PWMB_LS PTB11 / FTM3_CH3 PWM B low-side driver PWMC_HS PTC10 / FTM3_CH4 PWM C high-side driver PWMC_LS PTC11 / FTM3_CH5 PWM C low-side driver LPSPI1 SPI_SCLK PTB14 / LPSPI1_SCK SPI clock SPI_SIN PTB15 / LPSPI1_SIN SPI data in SPI_SOUT PTB16  / LPSPI1_SOUT SPI data out SPI_CS PTB17 / LPSPI1_PCS3 SPI chip select GPIO AE_Fault PTD3 Application Extension fault (active low) LPUART0 LPUART_In PTC2 / lpuart_rx Receive data from FreeMASTER LPUART_Out PTC3 / lpuart_tx Send data to FreeMASTER TRGMUX TRGMUX_InitTrg PTD1 / trgmux_out2 FTM3 Init trigger visualization TRGMUX_CoCo PTE11 / trgmux_out5 ADC0 CH1   conversion complete visualization GPIO Exec_Meas PTE15 Toggled pin for execution time measurement SW0 PTB4 Application control via board button SW1 PTB5 LED PTE15 LED indication: steady lit - ready, slow flashing - run fast flashing - fault   This pins assignment can be carried out by means of RTD, Pins tool. Pin assignment of the FTM3 module is shown in Figure 14 as an example. Figure 14. S32M244 Pins assignment for FTM3 in S32CT. The RTD-generated configuration structure g_pin_mux_InitConfigArr_BOARD_InitPins and the respective RTD function is then called in ...src/Peripherals/peripherals_config.c/MCUPinsConfig(). Note: At the time of this article publication, ADC0 interleave on pin PTB13 was not available in the S32CT Pins tool, therefore the interleave is set in ...src/Peripherals/peripherals_config.c/MCUPinsConfig() by calling Port_Ci_Port_Ip_SetMuxModeSel(IP_PORTB, 13, PORT_MUX_ADC_INTERLEAVE) jump to top 4.2.9. Interrupt configuration The configuration of the respective interrupts takes place in RTD Peripherals tool. The interrupts are configured as per the following table:.   Table 7. Interrupts in S32M244 BLDC 6-step Hall sensor-based example. Name Priority Description ADC0_IRQn 2 State variables acquisition PORT_CI_ICU_IP_D_EXT_IRQ_ISR PORT_CI_ICU_IP_E_EXT_IRQ_ISR 1 Interrupt from Hall sensor status change PDB0_IRQn 0 PDB0 Sequence Error PORTD_IRQn 1 AE fault detection LPIT0_Ch0_IRQn 0 Control loop calculation   The configuration of the interrupts in S32CT peripherals tool is shown in Figure 15, see SW example for details.   Figure 15. S32M244 interrupt configuration in RTD. The interrupt from AE fault is carried out by detection of falling edge on PTD3, this needs to be set in RTD peripherals tool as well, a part of the setting is shown in Figure 16. See the detailed setting in RTD peripherals tool for the module Port_Ci_Icu. The same applies for Hall sensor signals, pins PTE4, PTE5 and PTD0. The S32CT -generated configuration structure IntCtrlConfig_0 and the structures for PTD3, PTE4, PTE5 and PTD0 interrupt:  Port_Ci_Icu_Ip_3_Config_PB_BOARD_INITPERIPHERALS, Port_Ci_Icu_Ip_4_Config_PB_BOARD_INITPERIPHERALS and the respective RTD function is then called in src/peripherals/peripherals_config.c/MCUIntConfig(). Figure 16. S32M244 enabling PTD3 falling edge detection. jump to top 4.2.10. Low Power Interrupt Timer (LPIT) configuration The LPIT channel 0 is employed to control the speed and motor current in a software task. LPIT channel 0 is configured to generate a periodic interrupt every 1 ms. The configuration by means of S32CT is as follows:  Figure 17. S32M244 LPIT configuration. The S32CT-generated configuration structure LPIT_0_InitConfig_PB_BOARD_INITPERIPHERALS and the respective RTD function is then called in src/peripherals/peripherals_config.c/MCULpitConfig(). jump to top 4.2.11. Application Extension (AE) configuration Configuration of AE is described in NXP application note AN14454: 3-phase Sensorless PMSM Motor Control with S32M244. Identical AE configuration is used also for this SW example. jump to top 4.3. Software architecture Figure 18 presents the conceptual system block diagram of the BLDC Six-step control technique working in Hall sensor-based mode. The application is optimized for S32M244 motor control peripherals to achieve the least possible core involvement in state variable acquisition and output action application. The motor control peripherals (FTM2, FTM3, PDB0, ADC0) are internally linked together to work independently from the core, and to achieve deterministic sampling of analog quantities and precise commutation of the stator field. The software part of the application consists of different blocks which are described below. The entire application behavior is controlled from a PC through the FreeMASTER run-time debugging tool. The inputs of the control loop are the measured voltages and current on the power stage, in particular the phase/BEMF voltages, the DC bus current, and DC bus voltage.  From a control perspective, the block diagram can be divided into two logical parts: Commutation control, where the signals from Hall sensors are used to determine the actual position of the shaft. According to the identified position, the next commutation event can be prepared. Speed/torque control, where the required shaft velocity is compared to the actual measured speed and regulated by the PI controller. The output of the speed PI controller is the duty cycle. The duty cycle is limited by the current PI controller and assigned to the PWM.     Figure 18. System block diagram. 4.3.1. Introduction This section describes the software design of the Hall sensor-based BLDC Six Step Control framework application. The application overview and description of software implementation are provided. The aim of this chapter is to help in understanding of the designed software.   4.3.2. Application data flow overview The application software has two main states: the alignment state and the run state. In the run state, the BLDC motor is fully controlled in a closed-loop mode. After the initialization of the peripheral modules has completed, the software enters the alignment state. In alignment state, the rotor position is stabilized into a known position in order to create the same start-up torque in both directions of rotation. This is achieved by applying a PWM signal to phase C. Phases A and B are assigned with a duty cycle equal to zero; that is, they are connected to the negative pole of the DC bus. The value of the duty cycle on phase C depends on the motor inertia and load applied on the shaft. Such a technique aligns the shaft into position between phase A and B, which is perpendicular to both start-up flux vectors generated by the stator winding, and therefore ensures the same start-up torque in both directions of rotation. The duration of the alignment state depends on the motor’s electrical and mechanical constants, the applied current (meaning duty cycle), and the mechanical load. When the alignment time-out expires, the application software moves to start state, which in case of Hall-based example is only a one-pass state (on the contrary to sensorless application where open loop startup takes place. Then the state changes to the run state, where the commutation process based on the Hall sensor signals takes place, and the control enters the closed-loop mode. jump to top 4.3.3. State Machine  The application state machine is implemented using a one-dimensional array of pointers to state functions, called AppStateMachine[]. The index of the array specifies the pointer to the related application state function. The application state machine consists of the following seven states selected using the index variable appState value. Possible state transitions are shown in Figure 19. The application states are listed in the following table: Table 8. Application states AppState Application state Description 0 INIT The INIT state provides the initial configuration of the PWM duty cycle and initialization of DC bus current offset calibration. The state machine then transitions to the STOP state. 1 CALIB The CALIB state provides the DC bus current calibration. The state machine then transitions to ALIGNMENT state. 2 ALIGNMENT In the ALIGNMENT state, the alignment vector is applied to the stator to set the rotor to the defined position. The duration of the alignment state and the duty cycle applied during the state are defined by the ALIGN_DURATION and ALIGN_VOLTAGE macro values accessible in the BLDC appconfig.h header file. The state machine then transitions to the START state. 3 START Only a one-pass state in Hall-based application 4 RUN In the RUN state, the BLDC motor is controlled in the closed-loop . Speed control and current limitation are performed as described in 4.3.5, “Speed evaluation, motor current limitation and control”. The transition to the INIT state is done by setting the appSwitchState variable to 0. 5 STOP In the STOP state, the motor is stopped and prepared to start running. Transition to the ALIGNMENT state is performed once the appSwitchState variable is set to 1 and the freewheeling counter expires. 6 FAULT The fault detection function is executed in the main endless loop, detecting DC bus undervoltage, DC bus overvoltage, DC bus overcurrent, and AE faults. Once any of the faults are detected, the state machine automatically transitions to the FAULT state. The PWM outputs are set to the safe state. To exit the FAULT state, all fault sources must be removed and the faultSwitchClear variable has to be set to 1 to clear the fault latch. The state machine then automatically transitions to the INIT state.   Figure 19. Application state machine jump to top 4.3.4. Application timing and interrupts Figure 20  shows the application timing and the associated interrupts used for the commutation, Hall sensor processing and speed control. The grey boxes show the executed interrupt routines versus the phase voltage measurement. The top row shows the interrupt that is activated when the ADC conversion sequence of DC bus current, and DC bus voltage has been completed.  The second row shows the GPIO interrupt caused by Hall sensors state change generated at the time of the commutation event. The time between each GPIO interrupt is measured by FTM2 counter. The last row shows the LPIT channel 0 time-out interrupt generated every 1 ms. This interrupt is used for speed loop control and motor current limitation, executing PI controller functions.    Figure 20. Application timing and interrupts jump to top   4.3.5. Speed evaluation, motor current limitation and control The speed controller is executed in a timer interrupt every 1 ms. The actual speed is calculated from all of the last six commutation periods, and this is stored as the actual speed. The required speed is fed into the ramp function controlling the motor speed slope. The difference between the speed ramp function output and actual speed defines the speed error. In the closed-loop mode, the actual speed error is fed into the PI controller function. Inputs to the PI controller function include the speed error and the PI controller’s parameters such as the proportional and integral gain constants. The output of the PI controller is the duty cycle, which is scaled to the PWM resolution. At the end of the speed control function, the duty cycle is loaded into the FTM3 PWM module. The current limit controller is located in the same 1 ms timer interrupt (.../src/main.c/LpitNotif() ) as the speed controller because the inputs and outputs of both controllers are linked together. When the actual speed has been calculated, the current limit PI controller can be called by feeding it with the difference between the actual current and the maximum allowed current of the motor. The output of the PI controller is scaled to the number proportional to the PWM period. After the current PI controller has calculated its duty cycle, both duty cycle output values are compared to each other. If the speed PI controller duty cycle output is higher than the current limit PI controller output, then the speed PI Controller duty cycle output value is limited to the output value of the current limit PI controller. Otherwise, the speed PI duty cycle output will be taken as the duty cycle update value. The value of the duty cycle will be used to update the FTM3 PWM module. At the end, the integral portion values of both the PI controllers need to be synchronized to avoid one of the controllers increasing its internal value as far as the upper limit. If the duty cycle was limited to the current PI duty cycle output, then the integral portion of the current PI controller will be copied into the integral portion of the speed controller, and vice versa.  4.3.6. AMMCLIB Integration The integration of AMMCLIB is done in the manner identical to the one described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top   5. FreeMASTER and MCAT user interface The FreeMASTER debugging tool is used to control the application and monitor variables during run time.  FreeMASTER and MCAT interface enables online application tuning and control.  MCAT (Motor Control Application Tuning) is a graphical tool dedicated to motor control developers and the operators of modern electrical drives. The main feature of proposed approach is automatic calculation and real-time tuning of selected control structure parameters. Connecting and tuning new electric drive setup becomes easier because the MCAT tool offers a possibility to split the control structure and consequently to control the motor at various levels of cascade control structure. FreeMASTER and MCAT user interface are described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top 6. Conclusion The design described shows the simplicity and efficiency in using the S32K144 microcontroller for Hallsensor-based BLDC motor control and introduces it as an appropriate candidate for various low-cost applications in the automotive area. MCAT tool provides interactive online tool which makes the BLDC drive application tuning friendly and intuitive. jump to top 7. References • S32 Design Studio IDE for S32 Platform • Real-Time Drivers (RTD) • FreeMASTER Run-Time Debugging Tool • Automotive Math and Motor Control Library • S32M24x Reference Manual • S32M2xx Data Sheet • S32M24x PMSM/BLDC Motor Control Evaluation Boards • BLDC PMSM low voltage motor control accessory kit • Rashid, M. H. Power Electronics Handbook, 2nd Edition. Academic Press • Motor Control Application Tuning (MCAT) Tool jump to top
View full article
This example demonstrates a 3-phase Permanent Magnet Synchronous Motor (PMSM) vector control (Field Oriented Control - FOC) drive with single shunt current sensing with and without position sensor. This design serves as an example of motor control design using NXP S32M244 automotive family. The example was designed on: S32M24 PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors C-project based example is a part of S32M24XEVB-SW application SW.  Application software contains:  S32M24xEVB_PMSM_FOC_1Sh - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a single shunt FOC application. The detailed description of the example can be found in application note AN14454.
View full article
This example demonstrates a 3-phase Permanent Magnet Synchronous Motor (PMSM) vector control (Field Oriented Control - FOC) drive with single shunt current sensing with and without position sensor. This design serves as an example of motor control design using NXP S32M276 automotive family.   The example was designed on: S32M27x PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors S32M276SFFRD Reference Design Board for Automotive Motor Control | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors C-project based example is a part of: S32M27XEVB-SW application SW for S32M27xEVB Application software contains:  S32M27xEVB_PMSM_FOC_1Sh - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a single shunt FOC application. The detailed description of the example can be found in application note AN14482. S32M276SFFRD_MC_SW  application SW for S32M276SFFRD Application software contains:  S32M276SFFRD_PMSM_FOC_1Sh - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a single shunt FOC application. The detailed description of the example can be found in application note AN14482.
View full article
Note: The example was designed on: S32M27x PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors S32M276SFFRD Reference Design Board for Automotive Motor Control | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors C-project based example is a part of: S32M27XEVB-SW application SW for S32M27xEVB (this 6-step application has been the part of the appliction SW from revision 1.1)  Application software contains:  S32M27xEVB_BLDC_6Step_Hall - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a BLDC 6-step Hall application. S32M276SFFRD_MC_SW  application SW for S32M276SFFRD (this 6-step application has been the part of the appliction SW from revision 1.1)  Application software contains:  S32M276SFFRD_BLDC_6Step_Hall - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a BLDC 6-step Hall application. Contents 1. Introduction 2. System concept 3. Hall sensor-based BLDC control 3.1. Overview of the brushless DC motor 3.2. Output voltage actuation and complementary unipolar PWM modulation technique 3.3. Position estimation based on Hall sensors 3.4 States of the BLDC control based on Hall sensors 4. Software implementation on the S32M276 4.1. S32M276 – Key modules for BLDC 6-step control 4.2. S32M276 Device initialization 4.2.1. Pins 4.2.2. AE fault interrupt 4.2.3. Clock configuration 4.2.4. Pwm and triggers - eMIOS 4.2.5. TRGMUX 4.2.6. PWM and commutation - LCU 4.2.7. eMIOS ICU 4.2.8. PIT 4.2.9. Analogue data capturing  4.2.10.Communication and Application Extension (AE) configuration 4.3. Software architecture 4.3.1. Introduction 4.3.2. Application data flow overview 4.3.3. State Machine  4.3.4  Application timing and interrupts 4.3.5  Speed evaluation, motor current limitation and control 4.3.6. AMMCLIB Integration 5. FreeMASTER and MCAT user interface 6. Conclusion 7. References 1. Introduction This article describes the design of a 3-phase Brushless DC (BLDC) motor control drive using S32M276 NXP integrated solution. Following are the supported features: 3-phase BLDC speed control based on Six-step commutation control Shaft position obtained by Hall sensors DC-bus current and DC-bus voltage sensing Motor speed determined by hall sensors Application control user interface using FreeMASTER debugging tool Motor Control Application Tuning (MCAT) tool jump to top 2. System concept The system is designed to drive a 3-phase BLDC motor. The application meets the following performance specifications: Targeted at the S32M76xEVB-C064/L064 and S32MSFFRD Evaluation Boards (refer to dedicated user manual for EVBs available at www.nxp.com) See section References for more information. Control technique incorporating: Six-step commutation control of 3-phase brushless DC motor with hall sensors Rotor position is obtained by hall sensors Closed-loop speed control with action period 1ms Bi-directional rotation Motor current limitation Alignment and start-up 50μs current sampling period Automotive Math and Motor Control Library (AMMCLIB) – Speed control loop built on blocks of precompiled SW library (see section References) FreeMASTER software control interface (motor start/stop, speed setup) FreeMASTER software monitor FreeMASTER embedded Motor Control Application Tuning (MCAT) tool (motor parameters, speed loop) FreeMASTER software MCAT graphical control page (required speed, actual motor speed, start/stop status, DC-Bus voltage level, DC-Bus current, system status) FreeMASTER software scope (observes actual and desired speeds, DC-Bus voltage and DC-Bus current) FreeMASTER software high-speed recorder (six-step commutation control quantities) DC-Bus over-voltage and under-voltage, over-current, overload and start-up fail protection. jump to top 3. Hall sensor-based BLDC control 3.1. Overview of the brushless DC motor The description of fundamental brushless DC motor principles, overview of electronic commutation control and speed/torque control of BLDC motor can be found in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapters 3.1., 3.1.1., 3.1.2. jump to top 3.2. Output voltage actuation and complementary unipolar PWM modulation technique The 3-phase voltage source inverter is shown on page 7 of S32M27xEVB schematics, see References. It uses single DC-bus shunt resistor (represented as R134 and R135 in parallel). DC-bus current which flows through the shunt resistor produces a voltage drop which is interfaced to the AD converter of microcontroller through the integrated Digital Programmable Gain Amplifier (DPGA) integrated inside S32M276 . The description of the PWM technique used for BLDC motor control, is available in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapter 3.2. The Hall sensors are connected to terminal header J200. (In case of S32M276SFFRD, please refer to the boardmanuals and schematis, see  References) jump to top 3.3. Position estimation based on Hall sensor The position estimation based on Hall sensor is a simple and cost-effective way to control the commutation of BLDC motor. In BLDC motors, there are three Hall sensors mounted around the rotor or stator periphery, shifted 120° apart from each other. When the rotor magnet crosses one of the sensor, sensor generates high or low logic signal depending on the magnet polarity. As rotor magnets cross all three sensors, these sensors give out position angle from 0° to 360° every 60°. To get optimal torque and efficiency conditions in Six-step commutation control, switching sequence of the phases energizing has to produce stator magnetic flux with 120° - 60° in relation to rotor magnetic flux, Figure 1. The picture depicts the situation when rotor enters first commutation sector “Sector 0”. This moment is indicated by Hall sensor logic “110”. In this sector, phase C is connected to positive polarity of the DC bus voltage, phase B is connected to negative polarity of the DC bus voltage and phase A is unpowered. This phases energizing creates stator magnetic flux which is 120° ahead to rotor magnetic flux. Torque is produced and angle between stator flux and rotor flux decreases from 120° to 60° as rotor moves towards the next commutation sector “Sector 2”. This process is then repeated for each commutation sector.   Figure 1. Speed control with current limitation    The shown Hall sensor states for the particular sectors are applicable to Sunrise motor 42BLY3A78-24110 and may differ for other motor type. The resulting switching states for the mentioned motor are as per the following table, where NC denotes the not connected motor phase, LS means low side transistor and HS means high side transistor: Table 1. Switching table. Direction Hall A Hall B Hall C Phase A Phase B Phase C ccw 1 1 0 NC LS ON HS PWM ccw 1 0 0 LS ON NC HS PWM ccw 1 0 1 LS ON HS PWM NC ccw 0 0 1 NC HS PWM LS ON ccw 0 1 1 HS PWM NC LS ON ccw 0 1 0 HS PWM LS ON NC cw 1 1 0 NC HS PWM LS on cw 0 1 0 LS ON HS PWM NC cw 0 1 1 LS ON NC HS PWM cw 0 0 1 NC LS ON HS PWM cw 1 0 1 HS PWM LS ON NC cw 1 0 0 HS PWM NC LS ON   Note: The rotation direction is valid for the aforementioned Sunrise motor and may be reversed in case of other motor. 3.4. States of the BLDC control based on Hall sensors In order to start and run the BLDC motor, the control algorithm has to go through the following states: Initialization Calibration Alignment (initial position setting) Run 3.4.1. Initialization Initialization of variables relevant for motor control is performed in this state. 3.4.2. Calibration In this state the DC current measurement calibration takes place. 3.4.3. Alignment Before starting, the motor is aligned to the middle of commutation sector 0. During the alignment state, all three phases are powered in order to get the best performance behavior in either direction of shaft rotation. Phase C is connected to the positive DC bus voltage and phases A and B are grounded. The alignment time depends on the mechanical constant of the motor, including load, and also on the applied motor current. 3.4.4. Run The block diagram of the run state is represented by Figure 2. The motor speed is estimated based on Hall events. The difference between the demanded and estimated speeds is fed into the speed PI controller. The output of the speed PI controller is proportional to the voltage to be applied to the BLDC motor. The motor current is measured and filtered and used as feedback into the current controller. The output of the current PI controller limits the output of the speed PI controller. The limitation of the speed PI controller output protects the motor current from exceeding the maximal allowed motor current.  Figure 2. Speed control with current limitation   jump to top 4. Software implementation on S32M276    4.1. S32M276 – Key modules for BLDC 6-step control The S32M276 is an integrated solution which comprises MCU and Application Extension part (AE). The AE includes modules such as Gate Driver Unit (GDU) and Digital Programmable Gain Amplifier (DPGA) which allow for using S32M276 in motor control applications with minimum of external components. The MCU part includes modules such as the Enhanced Modular IO Subsystem (eMIOS), Logic Control Unit (LCU), Trigger MUX (TRGMUX), Body Cross-triggering Unit (BCTU) and Analogue-to-Digital Converter (ADC) suitable for real-time control applications, in particular, motor control applications. These modules are directly interconnected and can be configured to meet various motor control application requirements. Figure 3 shows a module interconnection for a typical BLDC 6-step application working in Hall sensor-based mode using single shunt current sensing. The modules are described in further chapters and the detailed description can be found in the S32M27x Series Reference Manual (see section References). jump to top 4.1.1. Module interconnection As mentioned earlier, S32M27x consists of two parts: MCU and AE which are connected together via die-to-die (D2D) connections. The SPI interface (part of D2D) serves for parameter settings and status monitoring of AE and the rest of D2D interface is used for motor control loop (e.g.: DC bus current reading). The AE comprises modules vital for motor control such as Gate Driver Unit (GDU) and Digital Programmable Gain Amplifier (DPGA) which allow for using S32M276 in motor control applications with minimum of external components. The GDU drives the power MOSFETs. The GDU is interconnected with the outputs of LCU via D2D connections. The shunt resistor voltage drop signal (proportional to DC Bus current) is conditioned by the integrated DPGA which output is connected to the ADC via D2D connection. DC Bus voltage is conditioned via integrated voltage dividers which outputs are connected to the ADC via D2D connection. The MCU die modules involved in output actuation, data acquisition and synchronization of actuation and acquisition are called Control Loop. This control loop consists of the eMIOS, LCU, TRGMUX, BCTU and ADC modules. The control loop is a modular concept and is very flexible in operation and can support static, dynamic or asynchronous timing. eMIOS plays a role of the real time timer/counter. Within the control loop it is responsible for generation of basic PWM signal (period, duty cycle), generation of the trigger for analogue data capturing in the precise moment or measuring the time between commutation events. LCU enriches this modular concept with advanced features. In PWM generation it is responsible for creation of PWM complementary pairs, dead time insertion, decoding of HALL pattern and execution of a commutation table (role of the phases based on the sector) and disabling/enabling PWM outputs. BCTU and ADC modules are responsible for analog data capturing. BCTU answers question “what is going to be measured?” by a predefined list of ADC channels. The ADC answers question “How it is going to be measured?” by setting a conversion resolution, sampling duration etc. eMIOS timer uses the concept of time-bases for signal synchronization. There are 5 channels (CH0, CH8, CH16, CH22 and CH23) which can act as the time-base what means that the other channels can see value of their counter through the bus. CH0, CH8, CH16 can create local time-bases for 7 following channels and CH22 and CH23 can create a global time-bases for any channel. In the example eMIOS0 is used for PWM and triggers. CH1 is responsible for PWM. CH3 is responsible for triggering of the BCTU. CH3 triggers consecutive measurement of DC-bus voltage and the DC-bus current sample. eMIOS0 and LCU are connected through TRGMUX unit which is responsible for a configurable signal interconnection within the microcontroller. The eMIOS0 channel CH1 creates basic PWM signal, and it is formed using flexible Output Pulse Width Modulation Buffered (OPWMB) mode where two compare registers (A, B) are used to control rising and falling edge independently. LCU OUT0-OUT3, OUT8-9 create complementary PWM pairs to control MOSFETs. Besides PWM signals there is LCU input serving as direction input controlled by SW override feature and LCU inputs serving as sector inputs connected to HALL pins using TRGMUX. The LCU uses look-up tables, output polarity control to perform commutation based on current state of the HALL signals and to create complementary PWM pattern for active phase. Configurable digital filters are used to insert deadtime to the final complementary signals for transistors. Moreover, LCU creates speed signal by applying XOR on the HALL signals for rotor speed measurement. Same as in PWM signal generation, OPWMB mode is used for generation of trigger signal. Channels are linked with PWM time base CH0. Time-bases CH0 operates in Modulus Counter Buffered (MCB) up counting mode, where period is set by register A. eMIOS trigger channel is connected internally to BCTU (input channel BCTU_EMIOS_0_3) through eMIOS channel flag. In this example flag is generated on compare with register B. BCTU handles flag clearing. BCTU can control both ADCs, so list of single or parallel conversions can be invoked. In this example BCTU_EMIOS_0_3 triggers a list of single conversion of ADC0 (channel S8 to obtain DC-link current and channel S18 to obtain DC-bus voltage). Result can be stored into BCTU result register, BCTU FIFO and they are also visible in original ADC result registers or can be transferred by DMA. eMIOS1 CH1 is used as an input capture timer to measure commutation time. CH1 operates in single action input capture (SAIC) mode where it captures value of the running timebase eMIOS1 CH23 counter to register A on the edge of the speed signal (which is brought from LCU to eMIOS using TRGMUX) for speed calculation. Detailed description can be found in the S32M27x Series Reference Manual (see section References).       Figure 3. S32M276 modules interconnection. jump to top 4.1.2. Module involvement in digital BLDC control loop This section will discuss timing and modules synchronization to accomplish BLDC 6-step control on the S32M276 and the internal hardware features. The timing diagram of the automatic synchronization between PWM and ADC in the BLDC application is shown in Figure 4. Figure 4. Time Diagram of PWM and ADC Synchronization and notifications. eMios is the main component in the peripheral chain which defines precision timing. CH0 is used as time-bases for PWM and for trigger signals generation. Time-base counter is configured to up counting mode and wrapping value is defined by register A. In this example, PWM frequency and sampling frequency is 20 kHz. eMios PWM and trigger channels can see time-base counter through the internal bus and perform compare action with registers A, B and change the channels output and generate flag on compare event. Registers A and B are double buffered and updated on reload of selected time-base. LCU using LUTs (look up tables) creates complementary PWM pairs of active phase and grounds and disconnect other phases depending on sector and direction (Phase A OUT2 and OUT3 are depicted in the diagram for simplicity). Sector is detected automatically from current state of the HALL inputs and LCU also creates speed signal output as XOR of the HALL signals. LCU Digital filters are capable to delay edges of the LUT output and to insert the dead time. When commutation event occurs (one of the HALL signals changes its state) LCU performs commutation and eMIOS1 CH1 captures time stamp of the speed time base eMIOS1 CH23 for the speed calculation. PWM duty cycle is calculated dynamically in periodic interrupt routine (PIT1 timer). DC-bus current and the DC-bus voltage measurement is triggered in the middle of the PWM cycle (CH3 flag on compare B) as a list of single conversions.  When end of list event occurs, notification function is called to perform analogue data processing.    There are three notification functions (Call from peripheral ISR is ensured by RTD) in the example. PitNotif is called periodically with 1ms period to calculate speed control algorithm and to update duty cycle. BctuListNotif is also called periodically (when all analogue quantities are measured) with the same period as PWM 50us. When commutation event occurs, eMIOS1 CH1 takes a time stamp. After 7 consecutive time stamps eMIOS1GptNotify function is called and speed is calculated. eMIOS1GptNotify is asynchronous interrupt depending on rotor speed. Note: example also contains AE fault notification handler. This is called when AE interrupt pin (PTD3) falling edge is detected. jump to top 4.2. S32M276 Device initialization To simplify and accelerate application development, embedded part of the BLDC 6-step motor control application has been created using S32M276 Real Time Drivers (RTD). S32M276 can be configured either by means of S32 Configuration Tools (CT) - using GUI  Peripherals are initialized at beginning of the main() function. For each S32M276 module, there is a specific configuration function that uses S32M276 RTD APIs and configuration structures generated by RTD graphical tools to configure the MCU.  Detailed RTD documentation can be found in folder created with S32 Design Studio installation (see References). jump to top 4.2.1. Pins Pins input/output functionality and pins electrical configuration is generated by “PINs tool” and configuration is applied by calling Siul2_Port_Ip_Init API.    Figure 5. Pin configuration in Pins tool. jump to top 4.2.2. AE fault interrupt PTD3 pin is used to capture interrupt from AE and input capture functionality is configured by Siul2_Icu_Ip driver. AE_INT_Handler is then the callback function used in the SW example for AE fault interrupt processing.     Figure 6. Configuration of input capture for AE fault detection. jump to top 4.2.3. Clock configuration This clock configuration can be setup by S32CT Clocks tool which offers visual graphical user interface (GUI) to change the settings. Clock settings are applied by calling Clock_Ip_Init() function, where generated configuration by Clocks tool is an argument. To run the core of the S32M276 at maximum frequency 120MHz, S32M276 is supplied externally by 16 MHz crystal in case of S32M27xEVB (in case of S32M276SFFRD the crystal frequency is 24 MHz). This needs to be reflected in the settings of Cloks tool. This clock source supplies Phase-lock-loop (PLL) which its output is adjusted by dividers to 120 MHz frequency. PLL output PHI0 is then used to supply the core CORE_CLK. All real-time control peripherals are supplied by CORE_CLK, what eliminates unwanted wait states on the bus when peripherals are controlled by core during runtime.  jump to top 4.2.4. Pwm and triggers - eMIOS   eMIOS timer settings for PWM generation and trigger generation are covered by Emios_Mcl_Ip and Emios_Pwm drivers. Emios_Mcl_Ip driver is responsible for the time-base configuration. PWM time-base is up counting which is selected by item Master Bus Mode Type and wrapping value is defined by Default period item which is the value for register A (see timing diagram). eMios time-bases are initialized by calling Emios_Pwm_Ip_InitChannel  and  Emios_Mcl_Ip_Init(), they are started synchronously by calling Emios_Mcl_Ip_ConfigureGlobalTimebase. Emios_Mcl_Ip and Emios_Pwm drivers cover the same eMIOS peripheral instance, so PWM exclusive access is allowed. PWM and trigger channels are configured by calling Emios_Pwm_Ip_InitChannel where important settings in configuration tool are Mode select to select OPWMB mode where B stands for buffered. This mode allows double buffered update of compare registers A and B on time-base reload. Time-base for the channel is selected by Counter Bus field where BCDE means local time-base and PwmEmiosBusRef is a reference to time-base settings. The initial duty cycle is defined by Phase Shift (which is value for reg A) and Duty cycle (where value for register B is Duty cycle + Phase Shift). For the update of new values  Emios_Pwm_Ip_UpdateUCRegA and Emios_Pwm_Ip_UpdateUCRegB are called. Emios_Mcl_Ip_ComparatorTransferDisable disables update of A and B registers, and new vales can be set. Emios_Mcl_Ip_ComparatorTransferEnable again enables update, and new values are propagated synchronously on the nearest time-base reload event. See the BLDC 6-Step SW example for reference.        Figure 7. Configuration of PWM and BCTU triggers. jump to top 4.2.5. TRGMUX  TRGMUX is responsible for interconnection of microcontroller internal signals. Hardware Group defines group of TRGMUX outputs (from TRGMUX to peripheral). Hardware Output defines the output from TRGMUX to peripheral, and Hardware Input defines input from peripheral to TRGMUX. All possibilities for TRGMUX connection can be found in S32M27x reference manual, see References. Hint: Pins with TRGMUX out functionality are useful for debugging/visualization of internal signals.      Figure 8. TRGMUX configuration for Pwm, Hall and test/debug signals. jump to top 4.2.6. PWM and commutation - LCU The whole LCU0 instance is used for commutation control.  Logic Cells LC0 and LC2 are responsible for generation of PWM signal for MOSFETs based on PWM signal from eMIOS and selected voltage vector - switching combination of the MOSFETs. The vector defines which phase is grounded which phase is not connected (both MOSFETs are turned off) and which phase is controlled by PWM, see Table 1 in chapter 3.3. Logic Cell LC1 converts speed direction and current HALL state (representing position sector) to desired vector. Direction input is using SW override feature and can be set by software.      Figure 9. LCU 0 usage and LUT for LCU0_LC1 for Hall processing. Every Logic Cell is equipped with 4 inputs and 4 outputs. Outputs of the Look Up Table - LUT (true table) define the output state of all combinations of inputs where combination “0000” represents LSB and combination “1111” represents MSB of LUT register value. For LC1, inputs I0-I2 are Hall signals and input I3 is speed direction. There are six possible sectors 0-5. Other values (6,7) shouldn’t appear on input so zero vector is defined for them. So, Hall signals are converted to vector and speed signal is created by XOR function. Inputs of Logic Cells LC0 and LC2 are representing the selected vector (I0-I2) and PWM signal I3. LC0 generates outputs for MOSFETs of Phase A and Phase C and LC2 generates MOSFETs outputs for the Phase B. There are six active vectors (1-6) zero vector (0) and vector for alignment (V7). During alignment process, vector inputs are set to SW override mode and align vector is selected by SW. After alignment process, vector inputs are again controlled by LC0 and LC2. Outputs from Look Up Tables of LC0 and LC2 are adjusted by digital filters to form the final signal for MOSFETs with inserted dead time.     Figure 10. LCU0_LC0 and LCU0_LC2 LUTs vs the desired voltage vector. LCU is configured by LCU_Ip driver. Configuration is applied by calling Lcu_Ip_Init. The most important parts of the configuration can be found in Lcu Logic Input tab for LCU inputs configuration and in Lcu Logic Output tab for LCU outputs configuration. The key items for Output configuration are Output LUT Control to configure the logic of the output Look Up Table, LUT Rise Filter and LUT Fall Filter to delay the edges of the LUT output. LCU channels are enabled/disabled by calling Lcu_Ip_SetSyncOutputEnable. SW override of the LCU inputs is controlled by Lcu_Ip_SetSyncInputSwOverrideEnable and values for the inputs are set by Lcu_Ip_SetSyncInputSwOverrideValue. More detailed information about working with LUT can be found in AN14482: 3-phase Sensorless PMSM Motor Control with S32M276, chapter 4.2.3.3 LCU and in the S32M27x Reference Manual (see section References).     Figure 11. LCU settings in S32CT. jump to top 4.2.7. eMIOS ICU eMIOS1 CH1 operates in SAIC mode and is used to capture the time stamp of the HALL time base eMIOS1 Ch23 on the edge of the speed signal (preprocessed by LCU by applying XOR on Hall sensor signals). The first important setting is in Emios_Mcl_Ip driver clock divider value = 192, which scales the clock to 625KHz to cover longer commutation periods. Important settings can be found in tabs IcuChannels and IcueMIOS. The settings are applied by calling Emios_Icu_Ip_Init. Capturing is started by calling Emios_Icu_Ip_StartTimestamp and notification is enabled by Emios_Icu_Ip_EnableNotification, see the BLDC 6-step SW example for details.  Notification function eMIOS1IcuNotify is called after 7 captured edges so the time per one mechanical revolution can be calculated. The final mechanical speed is calculated in Pit1Notif where speed control calculations are performed.      Figure 12. eMIOS ICU settings. jump to top 4.2.8. PIT  PIT timer is used to generate 1KHz periodic interrupt routine where speed control algorithm is executed. PIT is started by calling Pit_Ip_StartChannel where the period is defined by the third argument in PIT ticks.       Figure 13. LPIT settings. jump to top 4.2.9. Analogue data capturing  Adc_Sar_Ip driver is responsible for configuration of ADCs. ADC1 instance is used for motor control measurements and is controlled by BCTU (ADC Ctu mode: Control mode). The configuration is focused on how the conversion is performed. The important parameters are Conversion resolution, Data alignment, voltage reference, Sampling duration etc. The settings are applied by calling Adc_Sar_Ip_Init and calibration is executed by calling  Adc_Sar_Ip_DoCalibration.         Figure 14. ADC configuration. BCTU settings are covered by Bctu_Ip driver. Trigger configuration Channel BCTU_EMIOS_0_3 (Trigger source item) is configured as the trigger of the list of single conversions of ADC1. List operation is set by Defines the BCTU ADC command list operational mode and selected ADC instance is defined by Adc Target Mask (2-bit information where bit0 – ADC0, bit1 – ADC1). Predefined list contains 2 items (DC-link current and DC-link voltage) where end of the list is defined by Last channel checkbox in Bctu LIST Items. List starts conversion of ADC1 S8 (DC-link current) and when it is finished list continues with ADC1 channel S28 (DC-link voltage). After the conversion of the last item, the list stars from the beginning and waits for the trigger from eMIOS. Data are stored into FIFO1 as it is configured in Data destination item. When all 2 measured quantities are stored into the FIFO, Watermark value is exceeded, and Watermark notification is called. BCTU configuration is applied by Bctu_Ip_Init. Bctu_Ip_GetFifoCount and    Bctu_Ip_GetFifoResult are called for read the result from the FIFO. Figure 15. BCTU configuration.  jump to top 4.2.10. Communication and Application Extension (AE) configuration Configuration of communication and AE is described in NXP application note AN14482: 3-phase Sensorless PMSM Motor Control with S32M276. Identical AE configuration is used also for this SW example. jump to top 4.3. Software architecture Figure 16 presents the conceptual system block diagram of the BLDC Six-step control technique working in Hall sensor-based mode. The application is optimized for S32M276 motor control peripherals to achieve the least possible core involvement in state variable acquisition and output action application. The motor control peripherals (ADC, BCTU, eMIOS, LCU) are internally linked together to work independently from the core, and to achieve deterministic sampling of analog quantities and precise commutation of the stator field. The software part of the application consists of different blocks which are described below. The entire application behavior is controlled from a PC through the FreeMASTER run-time debugging tool. The inputs of the control loop are the measured voltages and current on the power stage: the DC bus current, and DC bus voltage.  From a control perspective, the block diagram can be divided into two logical parts: Commutation control, where the signals from Hall sensors are used to determine the actual position of the shaft. According to the identified position, the next commutation event can be prepared. This happens automatically by means of LCU without CPU processing. Speed/torque control, where the required shaft velocity is compared to the actual measured speed and regulated by the PI controller. The output of the speed PI controller is the duty cycle. The duty cycle is limited by the current PI controller and assigned to the PWM. Figure 16. System block diagram. 4.3.1. Introduction This section describes the software design of the Hall sensor-based BLDC Six Step Control framework application. The application overview and description of software implementation are provided. The aim of this chapter is to help in understanding of the designed software. 4.3.2. Application data flow overview The application software has two main states: the alignment state and the run state. In the run state, the BLDC motor is fully controlled in a closed-loop mode. After the initialization of the peripheral modules has completed, the software enters the alignment state. In alignment state, the rotor position is stabilized into a known position in order to create the same start-up torque in both directions of rotation. This is achieved by applying a PWM signal to phase A. Phases B and C are assigned with a duty cycle equal to zero; that is, they are connected to the negative pole of the DC bus. The value of the duty cycle on phase A depends on the motor inertia and load applied on the shaft. Such a technique aligns the shaft into position between phase A and B, which is perpendicular to both start-up flux vectors generated by the stator winding and therefore ensures the same start-up torque in both directions of rotation. The duration of the alignment state depends on the motor’s electrical and mechanical constants, the applied current (meaning duty cycle), and the mechanical load. When the alignment time-out expires, the application software moves to start state, which in case of Hall-based example is only a one-pass state (on the contrary to sensorless application where open loop startup takes place. Then the state changes to the run state, where the commutation process based on the Hall sensor signals takes place, and the control enters the closed-loop mode. jump to top 4.3.3. State Machine  The application state machine is implemented using a one-dimensional array of pointers to state functions, called AppStateMachine[]. The index of the array specifies the pointer to the related application state function. The application state machine consists of the following seven states selected using the index variable appState value. Possible state transitions are shown in Figure 17. The application states are listed in the following table: Table 2. Application states AppState Application state Description 0 INIT The INIT state provides the initial configuration of the PWM duty cycle and initialization of DC bus current offset calibration. The state machine then transitions to the STOP state. 1 CALIB The CALIB state provides the DC bus current calibration. The state machine then transitions to ALIGNMENT state. 2 ALIGNMENT In the ALIGNMENT state, the alignment vector is applied to the stator to set the rotor to the defined position. The duration of the alignment state and the duty cycle applied during the state are defined by the ALIGN_DURATION and ALIGN_VOLTAGE macro values accessible in the BLDC appconfig.h header file. The state machine then transitions to the START state. 3 START Only a one-pass state in Hall-based application 4 RUN In the RUN state, the BLDC motor is controlled in the closed-loop . Speed control and current limitation are performed as described in 4.3.5, “Speed evaluation, motor current limitation and control”. The transition to the INIT state is done by setting the appSwitchState variable to 0. 5 STOP In the STOP state, the motor is stopped and prepared to start running. Transition to the ALIGNMENT state is performed once the appSwitchState variable is set to 1 and the freewheeling counter expires. 6 FAULT The fault detection function is executed in the main endless loop, detecting DC bus undervoltage, DC bus overvoltage, DC bus overcurrent, and AE faults. Once any of the faults are detected, the state machine automatically transitions to the FAULT state. The PWM outputs are set to the safe state. To exit the FAULT state, all fault sources must be removed and the faultSwitchClear variable has to be set to 1 to clear the fault latch. The state machine then automatically transitions to the INIT state.   Figure 17. Application state machine jump to top   4.3.5. Speed evaluation, motor current limitation and control The speed controller is executed in a timer interrupt every 1 ms. The actual speed is calculated from all of the last six commutation periods, and this is stored as the actual speed. The required speed is fed into the ramp function controlling the motor speed slope. The difference between the speed ramp function output and actual speed defines the speed error. In the closed-loop mode, the actual speed error is fed into the PI controller function. Inputs to the PI controller function include the speed error and the PI controller’s parameters such as the proportional and integral gain constants. The output of the PI controller is the duty cycle, which is scaled to the PWM resolution. At the end of the speed control function, the duty cycle is loaded into the eMIOS compare registers of eMIOS0_CH1. The current limit controller is located in the same 1 ms timer interrupt (.../src/main.c/Pit1Notif() ) as the speed controller because the inputs and outputs of both controllers are linked together. When the actual speed has been calculated, the current limit PI controller can be called by feeding it with the difference between the actual current and the maximum allowed current of the motor. The output of the PI controller is scaled to the number proportional to the PWM period. After the current PI controller has calculated its duty cycle, both duty cycle output values are compared to each other. If the speed PI controller duty cycle output is higher than the current limit PI controller output, then the speed PI Controller duty cycle output value is limited to the output value of the current limit PI controller. Otherwise, the speed PI duty cycle output will be taken as the duty cycle update value. At the end, the integral portion values of both the PI controllers need to be synchronized to avoid one of the controllers increasing its internal value as far as the upper limit. If the duty cycle was limited to the current PI duty cycle output, then the integral portion of the current PI controller will be copied into the integral portion of the speed controller, and vice versa.  4.3.6. AMMCLIB Integration The integration of AMMCLIB is done in the manner identical to the one described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top 5. FreeMASTER and MCAT user interface The FreeMASTER debugging tool is used to control the application and monitor variables during run time.  FreeMASTER and MCAT interface enables online application tuning and control.  MCAT (Motor Control Application Tuning) is a graphical tool dedicated to motor control developers and the operators of modern electrical drives. The main feature of proposed approach is automatic calculation and real-time tuning of selected control structure parameters. Connecting and tuning new electric drive setup becomes easier because the MCAT tool offers a possibility to split the control structure and consequently to control the motor at various levels of cascade control structure. FreeMASTER and MCAT user interface are described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top 6. Conclusion The design described shows the simplicity and efficiency in using the S32M276 microcontroller for Hall sensor-based BLDC motor control and introduces it as an appropriate candidate for various low-cost applications in the automotive area. MCAT tool provides interactive online tool which makes the BLDC drive application tuning friendly and intuitive. jump to top 7. References • S32 Design Studio IDE for S32 Platform • Real-Time Drivers (RTD) • FreeMASTER Run-Time Debugging Tool • Automotive Math and Motor Control Library • S32M27x Reference Manual • S32M2xx Data Sheet • S32M27x PMSM/BLDC Motor Control Evaluation Boards • S32M276SFFRD Reference Design Board for Automotive Motor Control • BLDC PMSM low voltage motor control accessory kit • Rashid, M. H. Power Electronics Handbook, 2nd Edition. Academic Press • Motor Control Application Tuning (MCAT) Tool jump to top
View full article
Note: The example was designed on: S32M27x PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors S32M276SFFRD Reference Design Board for Automotive Motor Control | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors C-project based example is a part of: S32M27XEVB-SW application SW for S32M27xEVB (this 6-step application has been the part of the appliction SW from revision 1.1)  Application software contains:  S32M27xEVB_BLDC_6Step_Sensorless - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a BLDC 6-step sensorless application. S32M276SFFRD_MC_SW  application SW for S32M276SFFRD (this 6-step application has been the part of the appliction SW from revision 1.1)  Application software contains:  S32M276SFFRD_BLDC_6Step_Sensorless - Low-level drivers of RTD and S32 Design Studio Configuration Tools (S32CT) are used to demonstrate a BLDC 6-step sensorless application. Contents 1. Introduction 2. System concept 3. Sensorless BLDC control 3.1. Overview of the brushless DC motor 3.2. Output voltage actuation and complementary unipolar PWM modulation technique 3.3. Position estimation based on BEMF zero-crossing detection 3.4 States of the sensorless BLDC control 4. Software implementation on the S32M276 4.1. S32M276 – Key modules for BLDC 6-step control 4.2. S32M276 Device initialization 4.2.1. Pins 4.2.2. AE fault interrupt 4.2.3. Clock configuration 4.2.4. Pwm and triggers - eMIOS 4.2.5. TRGMUX 4.2.6. PWM and commutation - LCU 4.2.7. eMIOS GPT 4.2.8. PIT 4.2.9. Analogue data capturing  4.2.10.Communication and Application Extension (AE) configuration 4.3. Software architecture 4.3.1. Introduction 4.3.2. Application data flow overview 4.3.3. State Machine  4.3.4  Application timing and interrupts 4.3.5  Speed evaluation, motor current limitation and control 4.3.6. AMMCLIB Integration 5. FreeMASTER and MCAT user interface 6. Conclusion 7. References 1. Introduction This article describes the design of a 3-phase Brushless DC (BLDC) motor control drive using S32M276 NXP integrated solution. Following are the supported features: 3-phase BLDC speed control based on Six-step commutation control Shaft position obtained by BEMF (Back Electromotive Force) voltage zero-crossing detection technique DC-bus current, DC-bus voltage and BEMF voltage sensing Motor speed determined by BEMF zero-crossing period Application control user interface using FreeMASTER debugging tool Motor Control Application Tuning (MCAT) tool jump to top 2. System concept The system is designed to drive a 3-phase BLDC motor. The application meets the following performance specifications: Targeted at the S32M76xEVB-C064/L064 Evaluation Board and S32M276SFFRD EVB (refer to dedicated user manual for EVBs available at www.nxp.com) See section References for more information. Control technique incorporating: Six-step commutation control of 3-phase brushless DC motor without position sensor Rotor position is obtained by BEMF voltage zero-crossing detection technique Closed-loop speed control with action period 1ms Bi-directional rotation Motor current limitation Alignment and start-up 50μs current sampling period Automotive Math and Motor Control Library (AMMCLIB) – Speed control loop built on blocks of precompiled SW library (see section References) FreeMASTER software control interface (motor start/stop, speed setup) FreeMASTER software monitor FreeMASTER Motor Control Application Tuning (MCAT) tool (motor parameters, speed loop, sensorless parameters) FreeMASTER software MCAT graphical control page (required speed, actual motor speed, start/stop status, DC-Bus voltage level, DC-Bus current, system status) FreeMASTER software speed scope (observes actual and desired speeds, DC-Bus voltage and DC-Bus current) FreeMASTER software high-speed recorder (six-step commutation control quantities) DC-Bus over-voltage and under-voltage, over-current, overload and start-up fail protection. jump to top 3. Sensorless BLDC control 3.1. Overview of the brushless DC motor The description of fundamental brushless DC motor principles, overview of electronic commutation control and speed/torque control of BLDC motor can be found in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapters 3.1., 3.1.1., 3.1.2. jump to top 3.2. Output voltage actuation and complementary unipolar PWM modulation technique The 3-phase voltage source inverter shown on page 7 of S32M27xEVB schematics, see References. It uses single DC-bus shunt resistor (represented as R134 and R135 in parallel). DC-bus current which flows through the shunt resistor produces a voltage drop which is interfaced to the AD converter of microcontroller through the integrated Digital Programmable Gain Amplifier (DPGA) integrated inside S32M276 .  The BEMF voltage dividers for BEMF measurement (used for sensorless 6-step control) are integrated in S32M276. The description of the PWM technique used for BLDC motor control, is available in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapter 3.2. jump to top 3.3. Position estimation based on BEMF zero-crossing detection The position detection based on BEMF measurement and BEMF measurement are explained in NXP application note AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144, chapter 3.3. The only difference in conditioning of BEMF voltages and DC Bus current - in case of S32M27x no external dividers for BEMF voltage are needed since these are integrated in S32M27x and voltage drop on shunt resistor is conditioned by S32M27x-integrated DPGA (Digital Programmable Gain Amplifier), Refer to S32M276 Reference Manual and Datasheet, see section References . 3.4. States of the sensorless BLDC control based on Hall sensors In order to start and run the BLDC motor, the control algorithm has to go through the following states: Initialization Calibration Alignment (initial position setting) Start-up (forced commutation or open-loop mode) Run (sensorless running with BEMF acquisition and zero-crossing detection) 3.4.1. Initialization Initialization of variables relevant for motor control. 3.4.2. Calibration In this state the DC current measurement calibration takes place. 3.4.3. Alignment Before starting, the motor is aligned to the middle of commutation sector 0. During the alignment state, all three phases are powered in order to get the best performance behavior in either direction of shaft rotation. Phase C is connected to the positive DC bus voltage and phases A and B are grounded. The alignment time depends on the mechanical constant of the motor, including load, and also on the applied motor current. 3.4.4. Start-up In the start-up state, motor commutation is controlled in an open-loop mode without any rotor position feedback. The commutation period is controlled by an open-loop starting curve. The open-loop start is required only until the shaft speed is high enough (approximately 5% of nominal motor speed) to produce an identifiable BEMF voltage. 3.4.5. Run The block diagram of the run state is represented by Figure 1. The motor speed is estimated based on Hall events. The difference between the demanded and estimated speeds is fed into the speed PI controller. The output of the speed PI controller is proportional to the voltage to be applied to the BLDC motor. The motor current is measured and filtered and used as feedback into the current controller. The output of the current PI controller limits the output of the speed PI controller. The limitation of the speed PI controller output protects the motor current from exceeding the maximal allowed motor current.    Figure 1. Speed control with current limitation   jump to top 4. Software implementation on S32M276    4.1. S32M276 – Key modules for BLDC 6-step control The S32M276 is an integrated solution which comprises MCU and Application Extension part (AE). The AE includes modules such as Gate Driver Unit (GDU) and Digital Programmable Gain Amplifier (DPGA) which allow for using S32M276 in motor control applications with minimum of external components. The MCU part includes modules such as the Enhanced Modular IO Subsystem (eMIOS), Logic Control Unit (LCU), Trigger MUX (TRGMUX), Body Cross-triggering Unit (BCTU) and Analogue-to-Digital Converter (ADC) suitable for real-time control applications, in particular, motor control applications. These modules are directly interconnected and can be configured to meet various motor control application requirements. Figure 2 shows a module interconnection for a typical BLDC 6-step application working in sensorless mode using single shunt current sensing. The modules are described in further chapters and the detailed description can be found in the S32M27x Series Reference Manual (see section References). jump to top 4.1.1. Module interconnection As mentioned earlier, S32M27x consists of two parts: MCU and AE which are connected together via die-to-die (D2D) connections. The SPI interface (part of D2D) serves for parameter settings and status monitoring of AE and the rest of D2D interface is used for motor control loop (e.g.: DC bus current reading). The AE comprises modules vital for motor control such as Gate Driver Unit (GDU) and Digital Programmable Gain Amplifier (DPGA) which allow for using S32M276 in motor control applications with minimum of external components. The GDU drives the power MOSFETs. The GDU is interconnected with the outputs of FTM via D2D connections. The shunt resistor voltage drop signal (proportional to DC Bus current) is conditioned by the integrated DPGA which output is connected to the ADC via D2D connection. DC Bus voltage and BEMF voltages are conditioned via integrated voltage dividers which outputs are connected to the ADC via D2D connection. The MCU modules involved in output actuation, data acquisition and synchronization of actuation and acquisition are called Control Loop. This control loop consists of the eMIOS, LCU, TRGMUX, BCTU and ADC modules. The control loop is a modular concept and is very flexible in operation and can support static, dynamic or asynchronous timing. eMIOS plays a role of the real time timer/counter. Within the control loop it is responsible for generation of basic PWM signal (period, duty cycle), generation of the trigger for analogue data capturing in the precise moment or measuring the time between events. LCU enriches this modular concept with advance features. In PWM generation it is responsible for creation of PWM complementary pairs, dead time insertion, execution of a commutation table (role of the phases based on the commutation sector) and disabling/enabling PWM outputs. BCTU and ADC modules are responsible for analog data capturing. BCTU answers question “what is going to be measured?” by a predefined list of ADC channels. The ADC answers question “How it is going to be measured?” by setting a conversion resolution, sampling duration etc. eMIOS timer uses the concept of time-bases for signal synchronization. There are 5 channels (CH0, CH8, CH16, CH22 and CH23) which can act as the time-base what means that other channels can see value of their counter through the bus. CH0, CH8, CH16 can create local time-bases for 7 following channels and CH22 and CH23 can create a global time-bases for any channel. In the example eMIOS0 is used for PWM and triggers. CH1 is responsible for PWM. CH2, CH3 are responsible for triggering of the BCTU. CH2 triggers parallel measurement of DC-bus voltage and BEMF voltage of disconnected phase and CH3 triggers the DC-bus current sample. eMIOS0 and LCU are connected through TRGMUX unit which is responsible for a configurable signal interconnection within the microcontroller. The eMIOS0 channel CH1 creates basic PWM signal, and it is formed using flexible Output Pulse Width Modulation Buffered (OPWMB) eMIOS mode where two compare registers (A, B) are used to control rising and falling edge independently. LCU OUT0-OUT3, OUT8-OUT9 create complementary PWM pairs to control MOSFET transistors. Besides PWM signal, there are direction and sector inputs controlled by SW override feature. The LCU uses look-up tables, output polarity control to perform commutation and to create complementary PWM pattern for active phase. Configurable digital filters are used to insert deadtime to the final complementary signals for transistors. Same as in PWM signal generation, OPWMB mode is used for generation of trigger signals. Channels are linked with PWM time base CH0. Time base CH0 operates in Modulus Counter Buffered (MCB) up counting mode, where period is set by register A. Two eMIOS trigger channels are connected internally to BCTU (input channels BCTU_EMIOS_0_2 and BCTU_EMIOS_0_3) through eMIOS channel flag. In this example flag is generated on compare with register B. BCTU handles flag clearing. BCTU is capable of controlling all three ADCs, so list of single or parallel conversions can be invoked. In this example BCTU_EMIOS_0_3 triggers single conversion of ADC1 (channel S8) to obtain DC-link current. BCTU_EMIOS_0_2 triggers list of parallel of conversion ADC1 (channel S18 for DC-bus voltage) and ADC0 (channel S16/S17/S19 for BEMF voltage of disconnected phase). The result can be stored into BCTU result register, BCTU FIFO and they are also visible in original ADC result registers or can be transferred by DMA.  eMIOS1 CH8 is used as a timer to measure zero-cross time and to set commutation event. CH8 operates in MCB mode where actual value of the counter can be read, and it's compared with register A defines the event for commutation. Detailed description of the respective modules can be found in the S32M27x Series Reference Manual (see section References).    Figure 2. S32M276 modules interconnection. jump to top 4.1.2. Module involvement in digital BLDC control loop This section will discuss timing and modules synchronization to accomplish BLDC 6-step control on the S32M276 and the internal hardware features. The timing diagram of the automatic synchronization between PWM and ADC in the BLDC application is shown in Figure 3.   Figure 3. Time Diagram of PWM and ADC Synchronization and notifications. eMios is the main component in the peripheral chain which defines precision timing. CH0 is used as time-bases for PWM and for trigger signals generation. Time-base counter is configured to up counting mode and wrapping value is defined by register A. In this example, PWM frequency and sampling frequency is 20 kHz. eMios PWM and trigger channels can see time-base counter through the internal bus and perform compare action with registers A, B and change the channels output and are able to set flag on compare event. Registers A and B are double buffered and updated on reload of selected time-base. LCU using LUTs (look up tables) creates complementary PWM pairs of active phase and grounds and disconnect other phases depending on sector and direction (Phase A OUT2 and OUT3 are depicted in the diagram for simplicity). LCU Digital filters are capable to delay edges of the LUT output and to insert the dead time. When commutation event occurs (eMIOS1 CH8 compare of its registers A and CNT), eMIOS1GptNotify notification function is invoked, where LCU SW inputs (current sector information) are changed and LCU performs commutation. PWM duty cycle (CH1) and trigger points (CH2 and CH3 flag on compare B) are calculated dynamically in periodic interrupt routine (PIT1 timer). DC bus current measurement is triggered in the middle of the PWM cycle as a single conversion and the DC-bus voltage and BEMF voltage are triggered at the 90% of the second half of active PWM pulse as a list of parallel conversion.  When end of list event occurs, notification function is called to perform zero-cross detection. When zero-cross is found the new commutation event can be set.  There are three notification functions (Call from peripheral ISR is ensured by RTD) in the example. Pit1Notif is called periodically with 1ms period to calculate speed control algorithm and to update duty cycle and trigger points. This notification has the lowest priority. Higher priority is granted to BctuListNotif which is also called periodically (when all analogue quantities are measured) with the same period as PWM 50us. Zero-cross detection is being executed until the zero-cross has been found. When zero-cross is found commutation event is configured (eMIOS1 CH8). When commutation event occurs, eMIOS1GptNotify function is called. This notification is of the highest priority. Sector is incremented or decremented depending on the speed direction and new value is set to LCU input. After the commutation event new BCTU list is selected depending on actual sector and new zero-cross search is started in BctuListNotif. eMIOS1GptNotify is asynchronous interrupt depending on rotor speed. Note: example also contains AE fault notification handler. This is called when AE interrupt pin (PTD3) falling edge is detected. jump to top 4.2. S32M276 Device initialization To simplify and accelerate application development, embedded part of the BLDC 6-step motor control application has been created using S32M276 Real Time Drivers (RTD). S32M276 can be configured either by means of S32 Configuration Tools (CT) - using GUI  or programmed directly using RTD drivers. Peripherals are initialized at beginning of the main() function. For each S32M276 module, there is a specific configuration function that uses S32M276 RTD APIs and configuration structures generated by RTD graphical tools to configure the MCU.  Detailed RTD documentation can be found in folder created with S32 Design Studio installation (see References). jump to top 4.2.1. Pins Pins input/output functionality and pins electrical configuration is generated by “PINs tool” and configuration is applied by calling Siul2_Port_Ip_Init API.    Figure 4. Pin configuration in Pins tool. jump to top 4.2.2. AE fault interrupt PTD3 pin is used to capture interrupt from AE and input capture functionality is configured by Siul2_Icu_Ip driver. AE_INT_Handler is then the callback function used in the SW example for AE fault interrupt processing.     Figure 5. Configuration of input capture for AE fault detection. jump to top 4.2.3. Clock configuration This clock configuration can be setup by S32CT Clocks tool which offers visual graphical user interface (GUI) to change the settings. Clock settings are applied by calling Clock_Ip_Init() function, where generated configuration by Clocks tool is an argument. To run the core of the S32M276 at maximum frequency 120MHz, S32M276 is supplied externally by 16 MHz crystal in case of S32M27xEVB (in case of S32M276SFFRD the crystal frequency is 24 MHz). This needs to be reflected in the settings of Cloks tool. This clock source supplies Phase-lock-loop (PLL) which its output is adjusted by dividers to 120 MHz frequency. PLL output PHI0 is then used to supply the core CORE_CLK. All real-time control peripherals are supplied by CORE_CLK, what eliminates unwanted wait states on the bus when peripherals are controlled by core during runtime.  jump to top 4.2.4. Pwm and triggers - eMIOS eMIOS timer settings for PWM generation and trigger generation are covered by Emios_Mcl_Ip and Emios_Pwm drivers. Emios_Mcl_Ip driver is responsible for the time-base configuration. PWM time-base is up counting which is selected by item Master Bus Mode Type and wrapping value is defined by Default period item which is the value for register A (see timing diagram). eMios time-bases are initialized by calling Emios_Mcl_Ip_Init(), they are started synchronously by calling Emios_Mcl_Ip_ConfigureGlobalTimebase. Emios_Mcl_Ip and Emios_Pwm drivers cover the same eMIOS peripheral instance, so PWM exclusive access is allowed. PWM and trigger channels are configured by calling Emios_Pwm_Ip_InitChannel where important settings in configuration tool are Mode select to select OPWMB mode where B stands for buffered. This mode allows double buffered update of compare registers A and B on time-base reload. Time-base for the channel is selected by Counter Bus field where BCDE means local time-base and PwmEmiosBusRef is a reference to time-base settings. The initial duty cycle is defined by Phase Shift (which is value for reg A) and Duty cycle (where value for register B is Duty cycle + Phase Shift). For the update of new values  Emios_Pwm_Ip_UpdateUCRegA and Emios_Pwm_Ip_UpdateUCRegB are called. Emios_Mcl_Ip_ComparatorTransferDisable disables update of A and B registers, after new vales are set. Emios_Mcl_Ip_ComparatorTransferEnable again enables update, and new values are propagated synchronously on the nearest time-base reload event. See the BLDC 6-Step SW example for reference.        Figure 6. Configuration of PWM and BCTU triggers. jump to top 4.2.5. TRGMUX  TRGMUX is responsible for interconnection of microcontroller internal signals. Hardware Group defines group of TRGMUX outputs (from TRGMUX to peripheral). Hardware Output defines the output from TRGMUX to peripheral, and Hardware Input defines input from peripheral to TRGMUX. All possibilities for TRGMUX connection can be found in S32M27x reference manual, see References. Hint: Pins with TRGMUX out functionality are useful for debugging/visualization of internal signals.      Figure 7. TRGMUX configuration for PWM and test/debug signals. jump to top 4.2.6. PWM and commutation - LCU The whole LCU0 instance is used for commutation control.  Logic Cells LC0 and LC2 are responsible for generation of PWM signal for MOSFETs based on PWM signal from eMIOS and selected voltage vector - switching combination of the MOSFETs. The vector defines which phase is grounded which phase is not connected (both MOSFETs are turned off) and which phase is controlled by PWM. Logic Cell LC1 converts speed direction and current sector to desired vector. Direction input and sector bits are using SW override feature and can be set by software.        Figure 8. LCU 0 usage and sector and switching table definition. Note: The direction of rotation in the switching table is valid for Sunrise motor and may be reversed for other motor type 42BLY3A78-24110.    Figure 9. LCU 0 Logic cell LC2  look-up table for voltage vectors generation based on vector bits. Every Logic cells are equipped with 4 inputs and 4 outputs. Outputs of the Look Up Table defines the output state of all combination of inputs where combination “0000” represents LSB and combination “1111” represents MSB of LUT register value. For LC1, inputs I0-I2 are sector bits and input I3 is speed direction. There are six possible sectors 0-5. Other values (6,7) shouldn’t appear on input so zero vector is defined for them. There is also possibility to create speed signal which is not used for any functional feature in this example but can be displayed on debug pin using TRGMUX.  Inputs of Logic Cells LC0 and LC2 are representing the selected vector (I0-I2) and PWM signal I3. LC0 generates outputs for MOSFETs of Phase A and Phase C and LC2 generates MOSFETs outputs for the Phase B. There are six active vectors (1-6) zero vector (0) and vector for alignment (V7). During alignment process, vector inputs are set to SW override mode and align vector is selected by SW. After alignment process, vector inputs are again controlled by LC1. Outputs from Look Up Tables of LC0 and LC2 are adjusted by digital filters to form the final signal for MOSFETs with inserted dead time.     Figure 10. LCU0_LC0 and LCU0_LC2 LUTs vs the desired voltage vector. LCU is configured by LCU_Ip driver. Configuration is applied by calling Lcu_Ip_Init. The most important parts of the configuration can be found in Lcu Logic Input tab for LCU inputs configuration and in Lcu Logic Output tab for LCU outputs configuration. The key items for Output configuration are Output LUT Control to configure the logic of the output Look Up Table, LUT Rise Filter and LUT Fall Filter to delay the edges of the LUT output. LCU channels are enabled/disabled by calling Lcu_Ip_SetSyncOutputEnable. SW override of the LCU inputs is controlled by Lcu_Ip_SetSyncInputSwOverrideEnable and values for the inputs are set by Lcu_Ip_SetSyncInputSwOverrideValue. More detailed information about working with LUT can be found in AN14482: 3-phase Sensorless PMSM Motor Control with S32M276, chapter 4.2.3.3 LCU and in the S32M27x Reference Manual (see section References).     Figure 11. LCU settings in S32CT. jump to top 4.2.7. eMIOS GPT eMIOS1 CH8 is used as a general-purpose timer. The first important setting is in Emios_Mcl_Ip driver clock divider value 192 which rescale the clock to 625KHz to cover longer commutation periods.  Interrupt and notification call, and next settings are set in Emios_GPT configuration. Settings are applied by Emios_Gpt_Ip_InitChannel, Emios_Gpt_Ip_EnableChannelInterrupt and Emios_Mcl_Ip_Init. Time for notification call (commutation event) is set by consecutive calling  Emios_Gpt_Ip_StopTimer and  Emios_Gpt_Ip_StartTimer.      Figure 12. eMIOS GPT settings. jump to top 4.2.8. PIT  PIT timer is used to generate 1KHz periodic interrupt routine where speed control algorithm is executed. PIT is started by calling Pit_Ip_StartChannel where the period is defined by the third argument in PIT ticks.       Figure 13. LPIT settings. jump to top 4.2.9. Analogue data capturing  Adc_Sar_Ip driver is responsible for configuration of ADCs. ADC0 and ADC1 instances are used for motor control measurements and are controlled by BCTU (ADC Ctu mode: Control mode). Configuration is focused on how the conversion is performed. The important parameters are Conversion resolution, Data alignment, voltage reference, Sampling duration etc. Settings are applied by calling Adc_Sar_Ip_Init  and calibration is executed by calling  Adc_Sar_Ip_DoCalibration. Conversion result is always stored to ADC result register (also when conversion was started by BCTU and result is also transferred to BCTU data destination). Reading conversion result from ADC is demonstrated for DC-link current and DC-link voltage by calling Adc_Sar_Ip_GetConvData.        Figure 14. ADC configuration. BCTU settings are covered by Bctu_Ip driver. There are two trigger configurations. Channel BCTU_EMIOS_0_2 (Trigger source item) is configured as the trigger of the list of parallel conversions of ADC0 and ADC1. List operation is set by Defines the BCTU ADC command list operational mode and selected parallel instances are defined by Adc Target Mask (2-bit information where bit0 – ADC0, bit1 – ADC1). There are 3 predefined lists. Every list contains 2 items where end of the list is defined by Last channel checkbox  in Bctu LIST Items. List starts parallel conversion of ADC0 channel S18 (DC-link voltage) and appropriate BEMF voltage ADC1 S16/S17/S19. After the conversion of the last item, the list stars from the beginning and waits for the trigger from eMIOS. Channel BCTU_EMIOS_0_3 is configured as single conversion of ADC0 S8 (DC-link current). Data are stored into in Data destination item. When the list is completed List last conversion notification is called. Reading from BCTU ADC result register is demonstrated for BEMF voltage by calling Bctu_Ip_GetConvData. BCTU configuration is applied by Bctu_Ip_Init. Current list is changed by calling Bctu_Ip_ConfigTrigger after commutation. Figure 15. BCTU configuration.  jump to top 4.2.10. Communication and Application Extension (AE) configuration Configuration of communication and AE is described in NXP application note AN14482: 3-phase Sensorless PMSM Motor Control with S32M276. Identical AE configuration is used also for this SW example. jump to top 4.3. Software architecture Figure 16 presents the conceptual system block diagram of the BLDC Six-step control technique working in sensorless mode. The application is optimized for S32M276 motor control peripherals to achieve the least possible core involvement in state variable acquisition and output action application. The motor control peripherals (ADC, BCTU, eMIOS, LCU) are internally linked together to work independently from the core, and to achieve deterministic sampling of analog quantities and precise commutation of the stator field. The software part of the application consists of different blocks which are described below. The entire application behavior is controlled from a PC through the FreeMASTER run-time debugging tool. The inputs of the control loop are the measured voltages and current on the power stage: the DC bus current, DC bus voltage and BEMF voltages.  From a control perspective, the block diagram can be divided into two logical parts: Commutation control, where the phase voltages and DC bus voltage are used to calculate the actual position of the shaft. According to the identified position, the next commutation event can be prepared. Speed/torque control, where the required shaft velocity is compared to the actual measured speed and regulated by the PI controller. The output of the speed PI controller is the duty cycle. The duty cycle is limited by the current PI controller and assigned to the PWM. Figure 16. System block diagram. 4.3.1. Introduction This section describes the software design of the Sensorless BLDC Six Step Control framework application. The application overview and description of software implementation are provided. The aim of this chapter is to help in understanding of the designed software. 4.3.2. Application data flow overview The application software has three main states: the alignment state, the open-loop start state, and the run state. In the run state, the BLDC motor is fully controlled in a closed-loop sensorless mode. After the initialization of the peripheral modules has completed, the software enters the alignment state. In alignment state, the rotor position is stabilized into a known position in order to create the same start-up torque in both directions of rotation. This is achieved by applying a PWM signal to phase A. Phases B and C are assigned with a duty cycle equal to zero; that is, they are connected to the negative pole of the DC bus. The value of the duty cycle on phase A depends on the motor inertia and load applied on the shaft. Such a technique aligns the shaft into position between phase B and C, what ensures the same start-up torque in both directions of rotation. The duration of the alignment state depends on the motor’s electrical and mechanical constants, the applied current (meaning duty cycle), and the mechanical load. When the alignment time-out expires, the application software moves to the open-loop start state. At a very low shaft velocity, the BEMF voltage is too low to reliably detect the zero-crossing. Therefore, the motor has to be controlled in an open-loop mode for a certain time period. The very first vector generated by the stator windings needs to be set to a position 90° relative to the position of the flux vector generated by magnets mounted on the rotor. The duration of the open-loop start state is defined by the number of open-loop commutations. The number of open-loop commutations depends on the mechanical time constant of the motor, including load, and also on the applied voltage (duty cycle). The shaft velocity after an open-loop start-up is approximately 5% of nominal velocity. At a velocity approximately 5% of nominal velocity, the BEMF voltage is high enough to reliably detect the zero-crossing. After a defined number of commutation cycles, the state changes from the open-loop start state to the run state. From here on, the commutation process based on the BEMF zero-crossing measurement takes place, and the control enters the closed-loop mode. jump to top 4.3.3. State Machine  The application state machine is implemented using a one-dimensional array of pointers to state functions, called AppStateMachine[]. The index of the array specifies the pointer to the related application state function. The application state machine consists of the following seven states selected using the index variable appState value. Possible state transitions are shown in Figure 17. The application states are listed in the following table: Table 1. Application states AppState Application state Description 0 INIT The INIT state provides the initial configuration of the PWM duty cycle and initialization of DC bus current offset calibration. The state machine then transitions to the STOP state. 1 CALIB The CALIB state provides the DC bus current calibration. The state machine then transitions to ALIGNMENT state. 2 ALIGNMENT In the ALIGNMENT state, the alignment vector is applied to the stator to set the rotor to the defined position. The duration of the alignment state and the duty cycle applied during the state are defined by the ALIGN_DURATION and ALIGN_VOLTAGE macro values accessible in the BLDC appconfig.h header file. The state machine then transitions to the START state. 3 START In the START state, the motor commutation is controlled in an open-loop without any rotor position feedback. The initial commutation period is controlled by the STARTUP_CMT_PER macro value. Motor acceleration (commutation period multiplier <1) is set by the START_CMT_ACCELER macro value. The number of commutations in the START state is defined by STARTUP_CMT_CNT macro value. All macro values are accessible in the BLDC_appconfig.h header file. The aim of the START state is to achieve an RPM where the zero-crossing event can be reliably detected (BEMF high enough). Once the defined number of commutations is performed, the state machine transitions to the RUN state. 4 RUN In the RUN state, the BLDC motor is controlled in the closed-loop by the sensorless algorithm (BEMF zero-crossing detection). Speed control and current limitation are performed as described in 4.3.5, “Speed evaluation, motor current limitation and control”. The transition to the INIT state is done by setting the appSwitchState variable to 0. 5 STOP In the STOP state, the motor is stopped and prepared to start running. Transition to the ALIGNMENT state is performed once the appSwitchState variable is set to 1 and the freewheeling counter expires. 6 FAULT The fault detection function is executed in the main endless loop, detecting DC bus undervoltage, DC bus overvoltage, DC bus overcurrent, and AE faults. Once any of the faults are detected, the state machine automatically transitions to the FAULT state. The PWM outputs are set to the safe state. To exit the FAULT state, all fault sources must be removed and the faultSwitchClear variable has to be set to 1 to clear the fault latch. The state machine then automatically transitions to the INIT state.   Figure 17. Application state machine jump to top   4.3.5. Speed evaluation, motor current limitation and control The speed controller is executed in a timer interrupt every 1 ms. The actual speed is calculated from all of the last six commutation periods, and this is stored as the actual speed. The required speed is fed into the ramp function controlling the motor speed slope. The difference between the speed ramp function output and actual speed defines the speed error. In the closed-loop mode, the actual speed error is fed into the PI controller function. Inputs to the PI controller function include the speed error and the PI controller’s parameters such as the proportional and integral gain constants. The output of the PI controller is the duty cycle, which is scaled to the PWM resolution. At the end of the speed control function, the duty cycle is loaded into the eMIOS compare registers of eMIOS0_CH1. The current limit controller is located in the same 1 ms timer interrupt (.../src/main.c/Pit1Notif() ) as the speed controller because the inputs and outputs of both controllers are linked together. When the actual speed has been calculated, the current limit PI controller can be called by feeding it with the difference between the actual current and the maximum allowed current of the motor. The output of the PI controller is scaled to the number proportional to the PWM period. After the current PI controller has calculated its duty cycle, both duty cycle output values are compared to each other. If the speed PI controller duty cycle output is higher than the current limit PI controller output, then the speed PI Controller duty cycle output value is limited to the output value of the current limit PI controller. Otherwise, the speed PI duty cycle output will be taken as the duty cycle update value. At the end, the integral portion values of both the PI controllers need to be synchronized to avoid one of the controllers increasing its internal value as far as the upper limit. If the duty cycle was limited to the current PI duty cycle output, then the integral portion of the current PI controller will be copied into the integral portion of the speed controller, and vice versa.  4.3.6. AMMCLIB Integration The integration of AMMCLIB is done in the manner identical to the one described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top 5. FreeMASTER and MCAT user interface The FreeMASTER debugging tool is used to control the application and monitor variables during run time.  FreeMASTER and MCAT interface enables online application tuning and control.  MCAT (Motor Control Application Tuning) is a graphical tool dedicated to motor control developers and the operators of modern electrical drives. The main feature of proposed approach is automatic calculation and real-time tuning of selected control structure parameters. Connecting and tuning new electric drive setup becomes easier because the MCAT tool offers a possibility to split the control structure and consequently to control the motor at various levels of cascade control structure. FreeMASTER and MCAT user interface are described in NXP application note  AN12435: 3-phase Sensorless BLDC Motor Control Kit with S32K144. jump to top 6. Conclusion The design described shows the simplicity and efficiency in using the S32M276 microcontroller for sensorless BLDC motor control and introduces it as an appropriate candidate for various low-cost applications in the automotive area. MCAT tool provides interactive online tool which makes the BLDC drive application tuning friendly and intuitive. jump to top 7. References • S32 Design Studio IDE for S32 Platform • Real-Time Drivers (RTD) • FreeMASTER Run-Time Debugging Tool • Automotive Math and Motor Control Library • S32M27x Reference Manual • S32M2xx Data Sheet • S32M27x PMSM/BLDC Motor Control Evaluation Boards • S32M276SFFRD Reference Design Board for Automotive Motor Control • BLDC PMSM low voltage motor control accessory kit • Rashid, M. H. Power Electronics Handbook, 2nd Edition. Academic Press • Motor Control Application Tuning (MCAT) Tool jump to top
View full article
Designed for 12V motor control applications, the S32M2 family, based on system-in-package (SiP) design, integrates high-voltage analog functionalities (MOSFET gate pre-drivers, physical communication interfaces - LIN/CAN FD, and voltage regulators) with a robust embedded MCU Core (S32K Arm ®  Cortex ® -M4/M7 series core). S32M2 integrates voltage regulators, pulse-width modulators, analog to digital converters, timers and non-volatile memory to reduce overall component count and reduce board space in a 64-pin LQFP-EP package. The comprehensive motor control ecosystem based on Automotive Math and Motor Control Library(AMMCLib) set, FreeMASTER with Motor Control ApplicationTuning (MCAT) tool and Model-Based Design Toolbox (MBDT) helps to enable S32M2 MCU in wide range of motor control use cases. The table below points to the articles with more detailed description each of S32M2 motor control use cases, hardware description, links to appropriate application notes articles, and software repositories.  Device HW Article S32M244CC S32M244LC S32M24 PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors FOC with single shunt current measurement The article focuses on solution-based Field Oriented Control (FOC) technique (typically used for 3-phase PMSM motors) with single shunt current measurement and without any position sensor (sensorless). The Encoder sensor is supported by SW option, but missing on BLDC PMSM  low voltage motor control accessory kit. The single shunt current measurement is an advanced technique that allows decrease the cost of Bill of Material (BOM). The example codes uses RTD drivers with low-level non-Autosar API.    Hall sensor based Six-step commutation control. The article focuses on solution-based Six-step commutation (6-step) technique (typically used for 3-phase BLDC motors) with Hall position sensor. The example code uses RTD drivers with low-level non-Autosar API..    Sensorless Six-step commutation control. The article focuses on solution-based Six-step commutation (6-step) technique (typically used for 3-phase BLDC motors) without position sensor (sensorless). The example code uses RTD drivers with low-level non-Autosar API.    S32M276CH S32M276LH       S32M27x PMSM/BLDC Motor Control Evaluation Board | NXP Semiconductors S32M276SFFRD Reference Design Board for Automotive Motor Control | NXP Semiconductors BLDC/PMSM Low Voltage Motor Control Accessory Kit | NXP Semiconductors     FOC with single shunt current measurement The article focuses on solution-based Field Oriented Control (FOC) technique (typically used for 3-phase PMSM motors) with single shunt current measurement and without any position sensor (sensorless). The Encoder sensor is supported by SW option, but missing on BLDC PMSM  low voltage motor control accessory kit. The single shunt current measurement is an advanced technique that allows decrease the cost of Bill of Material (BOM). The example codes uses RTD drivers with low-level non-Autosar API.    Hall sensor based Six-step commutation control. The article focuses on solution-based Six-step commutation (6-step) technique (typically used for 3-phase BLDC motors) with Hall position sensor. The example code uses RTD drivers with low-level non-Autosar API..    Sensorless Six-step commutation control. The article focuses on solution-based Six-step commutation (6-step) technique (typically used for 3-phase BLDC motors) without position sensor (sensorless). The example code uses RTD drivers with low-level non-Autosar API.    Note: the list of use cases cannot cover all combinations of MCU, current measurement scenario, control technique and sensor inputs, but should work as a base reference for most common configurations. 
View full article
Abstract This document describes how to use the FlexTimer Module on S32M24x and S32K14x series. It introduces several operational modes, including the corresponding implementation to provide reference for different applications.   Introduction S32M24x builds on the broad family of S32K14x MCUs, their tools and software by taking select MCUs from that portfolio and co-packaging them with an analog die that supports 12V power management, communications at the physical layer (CAN FD, LIN or CXPI) and the MOSFET gate drivers (6 channels). Based on the above, the FlexTimer Module (FTM) Usage on S32M24x and S32K1xx series can be addressed in same context. Therefore SW and configuration will be quite similar (if not the same) for both devices. However text will be focus on S32M24x implementation. Talking now about the FlexTimer module (FTM), it is built upon a timer with a 16-bit counter. It contains an extended set of features that meet the demands of motor control, including the signed up-counter, dead time insertion hardware, fault control inputs, enhanced triggering functionality, and initialization and polarity control.   Software implementation To simplify and accelerate an application development, embedded part of the FTM examples have been created using S32 Design studio, RTD drivers (low level part) and S32K14x/S32M24x is configured using S32 Configuration Tools, see the following figure: Figure 1: S32 Configuration Tools Regarding Peripherals Tool, it allows to configure FTM functionalities though different drivers as follows: Figure 2: FTM Drivers Once you have selected a driver, you could refer for more details to its respective User Manual in the top corner of the FTM Driver Tab: Figure 3: User Manuals for S32K1_S32M24X FTM Drivers     Project structure Project structure using S32 Design Studio and RTD for S32K14x and S32M24x version 2.0.0 contains the following components: Figure 4: Project structure     Implementation differences between S32M244 and S32K144 devices      Clocking S32M24x and S32K1xx have some spec differences regarding clocking. Additionally, S32M24xEVB-C064 is supplied externally by 16 MHz crystal, meanwhile S32K144EVK is supplied externally by 8 MHz crystal. In Clocks Tool of FTM examples both devices will be configured in Run mode and using PLL as system clock source, the same frequencies will be used for simplicity purposes as follows:      - System and Core clock -> 80MHz      - Bus clock -> 40MHz      - Flash Clock -> 20MHz Figure 5: Clocking in S32M24x devices Figure 6: Clocking in S32K1xx devices        Pinout S32K144EVK contains a S32K144HFT0VLLT MCU with LQFP 100 package and all its FTM channels are routable to at least to an external pin. Meanwhile S32M24xEVB-C064 contains a S32M244CCABWKHST MCU with LQFP 64 package and not all its FTM channels are routable to an external pin. Such is the case of the following signals: - ftm1_ch1 - ftm1_ch5 Particularly, ftm1_ch1 configuration is required to perform PWM Modulation on FTM0, but even though such channel is not routed to an external pin, such feature on FTM0 can be archived (Please refer to S32M24x/S32K14x-> PWM Modulation Implementation example).     FTM examples The FTM examples provided for S32M24x and S32K14x are listed below: • S32M24x/S32K14x -> FTM: Edge-align PWM (EPWM) mode • S32M24x/S32K14x -> FTM: Center-align PWM (CPWM) mode • S32M24x/S32K14x -> FTM: Complementary mode and dead-time insertion • S32M24x/S32K14x -> FTM: Modified Combine PWM Mode for Phase Shift • S32M24x/S32K14x -> FTM: Input capture (In progress) • S32M24x/S32K14x -> FTM: PWM Modulation Implementation • S32M24x/S32K14x -> FTM: Global time base • S32M24x/S32K14x -> FTM: Output compare (In progress)   Conclusion This document, together with the linked FTM examples, shows the simplicity and efficiency in using the S32K1xx and S32M24x MCUs for different timing applications. It allows a better understanding of the implementation of FTM functionalities, making it easy, friendly and intuitive for users as well as to properly use this module in their projects.   References S32 Design Studio for S32 Platform Real-Time Drivers (RTD) S32M2xx Data Sheet S32M24x Reference Manual S32M24XEVB S32K1xx MCU Family - Data Sheet S32K1xx MCU Family - Reference Manual S32K144EVB AN5303: Features and Operation Modes of FlexTimer Module on S32K
View full article
Example Description This application demonstrates the usage FlexTimer Module in Global time base mode. The application includes S32 Design Studio projects for both devices, that uses configurations for for the IP layer only (Clocks, Port_Ip_1, IntCtrl_Ip and Ftm_Gpt). For more details please refer to FlexTimer Module (FTM) Usage on S32M24x and S32K14x Series.   Installation steps Software installation      S32 Design Studio for S32 Platform v.3.5      RTD for S32K1 and S32M24x version 2.0.0 including patch P01 Hardware installation      Supported boards:           - S32M24xEVB-C064           - S32K144EVK      Connections to the scope in S32M24xEVB-C064/S32K144EVK:           - PTD0  (J60-2/J2-6)      Debugger in S32M24xEVB-C064/S32K144EVK           - Use the On-board Debug Interface in J32/J7 Open SDA connector.   S32 Configurations Tool      Clocks Tool S32M244 and S32K144 features a complex clocking sourcing, distribution. To run a core of the S32M244/S32K144 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal (meanwhile S32K144 is supplied externally by 8 MHz crystal). This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 in S32M244 (and by 40 in S32K144) and divides by 2 resulting 160 MHz frequency on output for both devices. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by 2 and 4 to supply bus clock (40 MHz) and flash clock (20 MHz), respectively (See next Figure). Figure 1. S32M244 Clocks Configuration        Pins Tool In Pins Tool are selected the signals to use the PORTD as follows: Figure 2. S32M244 Pins Configuration        Peripherals Tool Below is the FTM GPT configuration (the default configuration of the tabs that are not shown is used): Figure 3: FTM_GPT GptChannelConfigSet Figure 4: FTM_GPT GptHwConfiguration Figure 5: IntCtrl_Ip Interrupt Controller     Software implementation The application software functionality perform the following instructions (see Example 1): - Define FTM notification - Initialize Clock driver. - Initialize Port driver - Initialize ISR - Initialize GPT driver - Initialize GPT channel - Enable channel interrupt - Start timer - Toggle GPIO in a while loop Example 1. S32M244 FTM GPT configured by S32 SDK ... void FtmNotification(void) { ++index; if (index >= 1000U) { toggleLed = TRUE; index = 0; } } ... int main(void) { /* Initial Clock */ Clock_Ip_Init(clockConfig); /* Initial Pin */ Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); /* Initial ISR */ IntCtrl_Ip_Init(&IntCtrlConfig_0); /* Initial FTM instance 0 - Channel 1 */ Ftm_Gpt_Ip_Init(FTM_INSTACE_0, &FTM_0_InitConfig_PB); /* Initial channel 1 */ Ftm_Gpt_Ip_InitChannel(FTM_INSTACE_0, FTM_0_CH_1); /* Enable channel interrupt FTM0 - CH_1 */ Ftm_Gpt_Ip_EnableChannelInterrupt(FTM_INSTACE_0, CH_1); /* Start channel CH_1 */ Ftm_Gpt_Ip_StartTimer(FTM_INSTACE_0, COUNTER_VALUE); /* Waiting for Interrupt occurred */ while (TRUE) { /* Toggle the GPIO when the FTM notification is called */ if (TRUE == toggleLed) { Gpio_Dio_Ip_TogglePins(LED_PORT, (1 << LED_PIN)); toggleLed = 0U; } } return 0; } ...     On the oscilloscope Figure 6 shows PTD0 (D2) signal of S32M244 in the oscilloscope. Such GPIO is toggled when the FTM notification is called.. Figure 6: Global time base in S32M24x  
View full article
Example Description This application demonstrates the usage FlexTimer Module in PWM Modulation Implementation mode. The application includes S32 Design Studio projects for both devices, that uses configurations for for the IP layer only (Clocks, Port_Ip_1 and Ftm_Pwm). For more details please refer to FlexTimer Module (FTM) Usage on S32M24x and S32K14x Series.   Installation steps Software installation      S32 Design Studio for S32 Platform v.3.5      RTD for S32K1 and S32M24x version 2.0.0 including patch P01 Hardware installation      Supported boards:           - S32M24xEVB-C064           - S32K144EVK      Connections to the scope in S32M24xEVB-C064/S32K144EVK:           - ftm0_ch0 -> PTD15 (J21-2/J2-2)           - ftm0_ch1  -> PTD16 (J21-1/J2-4)           - ftm0_ch2 -> PTD0  (J60-2/J2-6)           - ftm1_ch1   -> PTB3 (NA/J2-9) Not routable to an external pin in S32M244C_64LQFP      Debugger in S32M24xEVB-C064/S32K144EVK           - Use the On-board Debug Interface in J32/J7 Open SDA connector.   S32 Configurations Tool      Clocks Tool S32M244 and S32K144 features a complex clocking sourcing, distribution. To run a core of the S32M244/S32K144 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal (meanwhile S32K144 is supplied externally by 8 MHz crystal). This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 in S32M244 (and by 40 in S32K144) and divides by 2 resulting 160 MHz frequency on output for both devices. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by 2 and 4 to supply bus clock (40 MHz) and flash clock (20 MHz), respectively (See next Figure). Figure 1. S32M244 Clocks Configuration        Pins Tool In Pins Tool are selected the signals to use the FTM0 module as follows: Figure 2. S32M244 Pins Configuration        Peripherals Tool Below is the FTM0 configuration (the default configuration of the tabs that are not shown is used): Figure 3: FTM0 Hardware instance Figure 4: FTM0 Clock Configuration Figure 5: FTM0 Global Channel Configuration Figure 6: FTM0 PwmFtmCh Figure 7: FTM1 Clock Configuration Figure 8: FTM1 PwmFtmCh     Software implementation The application software functionality perform the following instructions (see Example 1): - Initialize Clock driver. - Initialize Port driver - FTM Modulation configuration - Initialize PWM drivers - Update periods for FTM0/1 - Update duty cycle to PWM signals Example 1. S32M244 FTM0/1 configured by S32 SDK int main(void) { /* Init clock () */ Clock_Ip_Init(&Clock_Ip_aClockConfig[0]); /* Initialize all pins using the Port driver */ Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); /* FTM Modulation Implementation */ SIM_Type * simeBase = IP_SIM_BASE_PTRS; simeBase->FTMOPT1 = SIM_FTMOPT1_FTM0_OUTSEL(7); /* 0000_0111b channels 1, 2 and 3*/ /* Initialize PWM drivers */ Ftm_Pwm_Ip_Init(FTM_INSTANCE_1, &Ftm_Pwm_Ip_UserCfg0); Ftm_Pwm_Ip_Init(FTM_INSTANCE_0, &Ftm_Pwm_Ip_UserCfg0); /* Set new period for for Edge-Align Pwm */ Ftm_Pwm_Ip_UpdatePwmPeriod(FTM_INSTANCE_1, 0x500, TRUE); Ftm_Pwm_Ip_UpdatePwmPeriod(FTM_INSTANCE_0, 0x5000, TRUE); /* Setup new duty cycle to PWM signals */ Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_1, FTM1_CH_1, 0x250, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_0, 0x4000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_1, 0x3000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_2, 0x2000, 0x000, TRUE); … }     On the oscilloscope Figure 9 shows ftm0_ch0 (D0), ftm0_ch1 (D1) and ftm0_ch2 (D2) signals of S32M244 on the oscilloscope. Such signals have the same period aligned in the edge, with different duty cycle and without PWM Modulation Implementation. Figure 9: Edge-align PWM (EPWM) mode without PWM Modulation Implementation (in S32M244) Figure 10 shows same signals from Figure 9, but now with PWM Modulation. Figure 10: PWM Modulation Implementation (in S32M244) Figure 11 shows ftm0_ch0 (D4), ftm0_ch1 (D5) and ftm0_ch2 (D6) signals of S32K144 on the oscilloscope. Such signals have the same period aligned in the edge, with different duty cycle and with PWM Modulation. Additionally this device allows to route externally the ftm1_ch1 (D7). Figure 11: PWM Modulation Implementation (in S32K144)  
View full article
Example Description This application demonstrates the usage FlexTimer Module in Modified Combine mode for Phase Shift. The application includes S32 Design Studio projects for both devices, that uses configurations for for the IP layer only (Clocks, Port_Ip_1 and Ftm_Pwm). For more details please refer to FlexTimer Module (FTM) Usage on S32M24x and S32K14x Series.   Installation steps Software installation      S32 Design Studio for S32 Platform v.3.5      RTD for S32K1 and S32M24x version 2.0.0 including patch P01 Hardware installation      Supported boards:           - S32M24xEVB-C064           - S32K144EVK      Connections to the scope in S32M24xEVB-C064/S32K144EVK:           - ftm0_ch0 -> PTD15 (J21-2/J2-2)           - ftm0_ch1  -> PTD16 (J21-1/J2-4)           - ftm0_ch2 -> PTD0  (J60-2/J2-6)           - ftm0_ch3 -> PTD1   (J60-3/J6-2)      Debugger in S32M24xEVB-C064/S32K144EVK           - Use the On-board Debug Interface in J32/J7 Open SDA connector.   S32 Configurations Tool      Clocks Tool S32M244 and S32K144 features a complex clocking sourcing, distribution. To run a core of the S32M244/S32K144 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal (meanwhile S32K144 is supplied externally by 8 MHz crystal). This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 in S32M244 (and by 40 in S32K144) and divides by 2 resulting 160 MHz frequency on output for both devices. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by 2 and 4 to supply bus clock (40 MHz) and flash clock (20 MHz), respectively (See next Figure). Figure 1. S32M244 Clocks Configuration        Pins Tool In Pins Tool are selected the signals to use the FTM0 module as follows: Figure 2. S32M244 Pins Configuration        Peripherals Tool Below is the FTM0 configuration (the default configuration of the tabs that are not shown is used): Figure 3: FTM Hardware instance Figure 4: FTM Clock Configuration Figure 5: FTM Global Channel Configuration Figure 6: FTM PwmFtmCh (for Ch0 and Ch1) Figure 7: FTM PwmFtmCh (for Ch2 and Ch3)   Software implementation The application software functionality perform the following instructions (see Example 1): - Initialize Clock driver. - Initialize Port driver - Initialize PWM driver - Update period for FTM0 - Update duty cycle to PWM signals Example 1. S32M244 FTM0 configured by S32 SDK int main(void) { /* Init clock */ Clock_Ip_Init(&Clock_Ip_aClockConfig[0]); /* Initialize all pins using the Port driver */ Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); /* Initialize PWM driver */ Ftm_Pwm_Ip_Init(FTM_INSTANCE_0, &Ftm_Pwm_Ip_UserCfg0); /* Set phase shift, update the period and set duty cycle */ Ftm_Pwm_Ip_SetPhaseShift(FTM_INSTANCE_0, FTM_CH_0, 0x5000, 0x0000, TRUE); Ftm_Pwm_Ip_SetPhaseShift(FTM_INSTANCE_0, FTM_CH_2, 0x5000, 0x1500, TRUE); /* Set phase shift and duty cycle value to PWM signals */ Ftm_Pwm_Ip_SetDutyPhaseShift(FTM_INSTANCE_0, FTM_CH_0, 0x2500, 0x0000, TRUE); Ftm_Pwm_Ip_SetDutyPhaseShift(FTM_INSTANCE_0, FTM_CH_2, 0x2500, 0x1500, TRUE); … }     On the oscilloscope Figure 8 shows that the ftm0_ch0 (D0), ftm0_ch1 (D1), ftm0_ch2 (D2) and ftm0_ch3 (D3) signals on the oscilloscope. Such signals have the same period and duty cycle aligned in the edge, but ftm0_ch2 is phase shifted with respect ftm0_ch0. Also, ftm0_ch1 is the complementary of ftm0_ch0 with inverted output. And ftm0_ch3 is the complementary of ftm0_ch2 with inverted output. Figure 8: Modified Combine mode for Phase Shift
View full article
Example Description This application demonstrates the usage FlexTimer Module in Center-Aligned PWM (CPWM) mode. The application includes S32 Design Studio projects for both devices, that uses configurations for for the IP layer only (Clocks, Port_Ip_1 and Ftm_Pwm). For more details please refer to FlexTimer Module (FTM) Usage on S32M24x and S32K14x Series.   Installation steps Software installation      S32 Design Studio for S32 Platform v.3.5      RTD for S32K1 and S32M24x version 2.0.0 including patch P01 Hardware installation      Supported boards:           - S32M24xEVB-C064           - S32K144EVK      Connections to the scope in S32M24xEVB-C064/S32K144EVK:           - ftm0_ch0 -> PTD15 (J21-2/J2-2)           - ftm0_ch1  -> PTD16 (J21-1/J2-4)           - ftm0_ch2 -> PTD0  (J60-2/J2-6)           - ftm0_ch3 -> PTD1   (J60-3/J6-2)      Debugger in S32M24xEVB-C064/S32K144EVK           - Use the On-board Debug Interface in J32/J7 Open SDA connector.   S32 Configurations Tool      Clocks Tool S32M244 and S32K144 features a complex clocking sourcing, distribution. To run a core of the S32M244/S32K144 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal (meanwhile S32K144 is supplied externally by 8 MHz crystal). This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 in S32M244 (and by 40 in S32K144) and divides by 2 resulting 160 MHz frequency on output for both devices. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by 2 and 4 to supply bus clock (40 MHz) and flash clock (20 MHz), respectively (See next Figure). Figure 1. S32M244 Clocks Configuration        Pins Tool In Pins Tool are selected the signals to use the FTM0 module as follows: Figure 2. S32M244 Pins Configuration        Peripherals Tool Below is the FTM0 configuration (the default configuration of the tabs that are not shown is used): Figure 3: FTM Hardware instance Figure 4: FTM Clock Configuration Figure 5: FTM Global Channel Configuration Figure 6: FTM PwmFtmCh   Software implementation The application software functionality perform the following instructions (see Example 1): - Initialize Clock driver. - Initialize Port driver - Initialize PWM driver - Update period for FTM0 - Update duty cycle to PWM signals Example 1. S32M244 FTM0 configured by S32 SDK int main(void) { /* Init clock */ Clock_Ip_Init(&Clock_Ip_aClockConfig[0]); /* Initialize all pins using the Port driver */ Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); /* Initialize PWM driver */ Ftm_Pwm_Ip_Init(FTM_INSTANCE_0, &Ftm_Pwm_Ip_UserCfg0); /* Set new period for PWM Signals*/ Ftm_Pwm_Ip_UpdatePwmPeriod(FTM_INSTANCE_0, 0x5000, TRUE); /* Setup new duty cycle to PWM signals */ Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_0, 0x4000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_1, 0x3000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_2, 0x2000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_3, 0x1000, 0x000, TRUE); … }   On the oscilloscope Figure 7 shows that the ftm0_ch0 (D0), ftm0_ch1 (D1), ftm0_ch2 (D2) and ftm0_ch3 (D3) signals on the oscilloscope. Such signals have the same period aligned in the center and with different duty cycle. Figure 7: Center-Aligned PWM (CPWM) mode
View full article
Example Description This application demonstrates the usage FlexTimer Module in Edge-align PWM (EPWM) mode. The application includes S32 Design Studio projects for both devices, that uses configurations for for the IP layer only (Clocks, Port_Ip_1 and Ftm_Pwm). For more details please refer to FlexTimer Module (FTM) Usage on S32M24x and S32K14x Series.   Installation steps Software installation      S32 Design Studio for S32 Platform v.3.5      RTD for S32K1 and S32M24x version 2.0.0 including patch P01 Hardware installation      Supported boards:           - S32M24xEVB-C064           - S32K144EVK      Connections to the scope in S32M24xEVB-C064/S32K144EVK:           - ftm0_ch0 -> PTD15 (J21-2/J2-2)           - ftm0_ch1  -> PTD16 (J21-1/J2-4)           - ftm0_ch2 -> PTD0  (J60-2/J2-6)           - ftm0_ch3 -> PTD1   (J60-3/J6-2)      Debugger in S32M24xEVB-C064/S32K144EVK           - Use the On-board Debug Interface in J32/J7 Open SDA connector.   S32 Configurations Tool      Clocks Tool S32M244 and S32K144 features a complex clocking sourcing, distribution. To run a core of the S32M244/S32K144 as well as some MCU peripherals at maximum frequency 80 MHz in normal RUN mode, S32M244 is supplied externally by 16 MHz crystal (meanwhile S32K144 is supplied externally by 8 MHz crystal). This clock source supplies Phase-lock-loop (PLL), which circuit multiplies frequency by 20 in S32M244 (and by 40 in S32K144) and divides by 2 resulting 160 MHz frequency on output for both devices. PLL output is then divided by 2 to supply core and system (80 MHz), further divided by 2 and 4 to supply bus clock (40 MHz) and flash clock (20 MHz), respectively (See next Figure). Figure 1. S32M244 Clocks Configuration        Pins Tool In Pins Tool are selected the signals to use the FTM0 module as follows: Figure 2. S32M244 Pins Configuration        Peripherals Tool Below is the FTM0 configuration (the default configuration of the tabs that are not shown is used): Figure 3: FTM Hardware instance Figure 4: FTM Clock Configuration Figure 5: FTM Global Channel Configuration Figure 6: FTM PwmFtmCh   Software implementation The application software functionality perform the following instructions (see Example 1): - Initialize Clock driver. - Initialize Port driver - Initialize PWM driver - Update period for FTM0 - Update duty cycle to PWM signals Example 1. S32M244 FTM0 configured by S32 SDK int main(void) { /* Init clock */ Clock_Ip_Init(&Clock_Ip_aClockConfig[0]); /* Initialize all pins using the Port driver */ Port_Ci_Port_Ip_Init(NUM_OF_CONFIGURED_PINS_BOARD_InitPins, g_pin_mux_InitConfigArr_BOARD_InitPins); /* Initialize PWM driver */ Ftm_Pwm_Ip_Init(FTM_INSTANCE_0, &Ftm_Pwm_Ip_UserCfg0); /* Set new period for PWM Signals*/ Ftm_Pwm_Ip_UpdatePwmPeriod(FTM_INSTANCE_0, 0x5000, TRUE); /* Setup new duty cycle to PWM signals */ Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_0, 0x4000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_1, 0x3000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_2, 0x2000, 0x000, TRUE); Ftm_Pwm_Ip_UpdatePwmChannel(FTM_INSTANCE_0, FTM_CH_3, 0x1000, 0x000, TRUE); … }     On the oscilloscope Figure 7 shows that the ftm0_ch0 (D0), ftm0_ch1 (D1), ftm0_ch2 (D2) and ftm0_ch3 (D3) signals on the oscilloscope. Such signals have the same period aligned in the edge and with different duty cycle. Figure 7: Edge-align PWM (EPWM) mode
View full article