Home

UM0483 User manual

image

Contents

1. J Figure 53 Processing captured value when timer did not overflow Store capture value Prescaler decreased Store current prescaler value 1 in prev int Reset flag indicating decrement No Capture lt 0x5500 Yes Store current prescaler value Is the prescaler already 0 Store current prescaler value Store current prescaler value Decrease prescaler register Set flag indicating decrement for next capture interrupt UM0483 Additional information Figure 54 Processing captured value when timer did overflow Store capture value in CaptBuf Store prescaler value in PrscBuf Is overflow Cnt 0 Does Capture exceeds 16 bit form at Compute total number of clock cycle 0x10000 per overflow Make it fit 16 bit by increasing PrscBuf Prescaler will overflow Set max value to CaptBuf and PrscBuf Store CaptBuf and PrscBuf in array Did previous capture cause overflow Reset flag indicating increment Is prescaler at Increase Timer clock presale max value already Set flag indicating increment for next capture interrupt z 97 105 Additional information UM0483 A 5 98 105 PID block diagrams The follow
2. LO Mode GPIO Mode AIN O Pin GPIO Pin O0 O_ nitStructure 33 105 Running the demo program UM0483 3 5 34 105 How to build the system when using an incremental encoder Quadrature incremental encoders are widely used to read the rotor position of electric machines As the name implies incremental encoders actually read angular displacements with respect to an initial position if that position is known then rotor absolute angle is known too Quadrature encoders have two output signals represented in Figure 24 as TI1 and T12 With these and with the STM32F103xx standard timer in encoder interface mode it is possible to get information about rolling direction Figure 24 Encoder output signals counter operation forward jitter backward jitter forward l es T HTS Sa a aaa TI2 PEA ae eae EE E ENSE ea COUNTER up down up SEP LETT E In addition rotor angular velocity can be easily calculated as a time derivative of angular position To set up the AC IM IFOC software library for use with an incremental encoder simply modify the stm32 10x MCconf h and MC encoder param h header files according to the indications given in Section 2 2 1 on page 15 and Section 2 2 3 on page 19 respectively However some extra care should be taken concerning what is considered to be the positive rolling direction this software library assumes
3. UM0483 Library functions The prescaler modification is done in the capture interrupt taking advantage of the buffered registers the new prescaler value is taken into account only on the next capture event by the hardware without disturbing the measurement Further details are provided in the flowcharts in Section A 4 on page 96 Figure 45 Automatic tacho timer prescaler decrease Transfer frompreload to active an next capture update evert Figure 46 Automatic tacho timer prescaler increase Transfer from preload to active an next capture update event Figure 46 shows that the prescaler is not decreased although the captured value is below 0x5500 due to an overflow interrupt 77 105 Library functions UM0483 4 7 4 4 8 4 8 1 4 8 2 78 105 Converting Hertz into pseudo frequency From the definition of frequency 1Hz is equal to 2x rad s it is easy to define a pseudo frequency format so that the rotor angular position can be easily determined by accumulating the rotor speed information every time the control loop is executed for example during PWM update interrupt service routine Providing that 27 OxFFFF so that angle roll overs do not need to be managed the frequency with 0 1Hz unit can easily be converted into pseudo frequency using the following formula OxFFFF F F x pseudo 0 1Hz 10x Fawn
4. header file e TB Init on page 86 e TB Waiton page 86 e TB StartUp Timeout IsElapsed TB Delay IsElapsed TB DisplayDelay IsElapsed TB DebounceDelay IsElapsed on page 87 e TB Set Delay 500us TB Set DisplayDelay b500us TB Set StartUp Timeout TB Set DebounceDelay 500us on page 87 e SysrickHandler on page 88 TB Init Synopsis Description Input Returns Functions called TB Wait Synopsis Description Input Returns Functions called Caution void TB Init void The purpose of this function is to initialize the STM32 system tick timer to generate an interrupt every 500 us thus providing a general purpose timebase None None SysTick CLKSourceConfig SysTick SetReload SysTick CounterCmd NVIC SystemHandlerPriority Config SysTick ITConfig void TB Wait u16 time This function produces a programmable delay equal to variable time multiplied by 500us Unsigned 16 bit None None This routine exits only after the programmed delay has elapsed Meanwhile the code execution remains frozen in a waiting loop Care should be taken when this routine is called at main interrupt level a call from an interrupt routine with a higher priority than the timebase interrupt will freeze code execution UM0483 Library functions TB Set Delay 500us TB Set DisplayDelay 500us TB Set StartUp Timeout TB Set DebounceDelay 500ps Synopsis Description Input Returns Functions called voi
5. e ENC Init on page 69 ENC Get Electrical Angle on page 69 ENC Get Mechanical Angle on page 69 ENC Clear Speed Buffer on page 70 ENC Get Mechanical Speed on page 70 ENC Calc Average Speed on page 70 ENC ErrorOnFeedback on page 70 TIMx IRQHandler interrupt routine on page 71 UM0483 Library functions ENC_Init Synopsis Description Functions called See also void ENC_Init void The purpose of this function is to initialize the encoder timer The peripheral clock input pins and update interrupt are enabled The peripheral is configured in 4X mode which means that the counter is incremented decremented on the rising falling edges of both timer input 1 and 2 TIMx_CH1 and TIMx_CH2 pins RCC_APB1PeriphClockCmd RCC APB2PeriphClockCmd GPIO Structlnit GPIO Init NVIC Init TIM Delnit TIM TimeBaseStructlnit TIM TimeBaselnit TIM EncoderlnterfaceConfig TIM IClInit TIM ClearFlag TIM ITConfig TIM Cmd STMS2F103xx datasheet synchronizable standard timer ENC Get Electrical Angle Synopsis Description Input Output Functions called s16 ENC Get Electrical Angle void This function returns the electrical angle in signed 16 bit format This routine returns 0 for O degrees 32768 816 MIN for 180 degrees 32767 816 MAX for 180 degrees None Signed 16 bits None ENC Get Mechanical Angle Synopsis Description Input Output Functions called Note s16 ENC Get Mechanical
6. wy UM0483 J User manual STM32F103xx AC induction motor IFOC software library V1 0 January 2008 Introduction This user manual describes the AC induction motor IFOC software library an indirect field oriented control IFOC firmware library for 3 phase induction motors developed for the STM32F103xx microcontrollers These 32 bit ARM Cortex M3 cored ST microcontrollers STM32F 103xx come with a set of peripherals which makes it suitable for performing both permanent magnet and AC induction motors FOC In particular this manual describes the STM32F103xx software library developed to control AC induction motors equipped with an encoder or tachogenerator in both open and closed loop The control of a permanent magnet PM motor in sinewave mode with encoder hall sensors or sensorless is described in the UMO0492 user manual The AC IM IFOC software library is made of several C modules compatible with the IAR EWARM toolchain version 4 42 It is used to quickly evaluate both the MCU and the available tools In addition when used together with the STM32F103xx motor control starter kit STM3210B MCKIT and an AC induction motor a motor can be made to run in a very short time It also eliminates the need for time consuming development of IFOC and speed regulation algorithms by providing ready to use functions that let the user concentrate on the application layer A prerequisite for using this library is basic knowledge of C prog
7. Flux torque and speed regulators MC PID regulators module Overview The MC PID regulators module contains all the functions required for implementing the necessary PID regulators for controlling flux torque and in case of Speed control mode motor speed List of available functions and interrupt service routines The following is a list of available functions in the MC PID regulators module e PID Init on page 78 PID Flux Regulator On page 79 PID Torque Regulator on page 79 PID Speed Regulator on page 79 PID Reset Integral terms on page 80 PID Speed Coefficients update on page 80 PID Integral Speed update on page 80 PID Init Synopsis void PID Init void Description The purpose of this function is to initialize the PIDs for torque flux and speed regulation For each one a set of default values are loaded target speed torque or flux proportional integral and derivative gains lower and upper limiting values for the output Functions called None Note Default values for PID regulators are declared and can be modified in the MC Control Param h file see Section 2 2 2 on page 16 UM0483 Library functions PID Flux Regulator Synopsis s16 PID Flux regulator PID FluxTYPEDEF PID Flux s16 gld input Description The purpose of this function is to compute the proportional integral and derivative terms if enabled see Id Iq DIFFERENTIAL TERM ENABLED in Section 2 2 1
8. TimePhB X Sector Il V TimePhA ree TimePhB TimePhA Z TimePhC TimePhA Y Sector III VI TimePhA i T 23Y X TimePhB TimePhC X TimePhC TimePhA Y Current sampling in three shunt topology and general purpose A D conversions The three currents l4 lo and l5 flowing through a three phase system follow the mathematical relation ly lo 1g 0 For this reason to reconstruct the currents flowing through a generic three phase load it is sufficient to sample only two out of the three currents while the third one can be computed by using the above relation The flexibility of the STM32F10xxx A D converter makes it possible to synchronously sample the two A D conversions needed for reconstructing the current flowing through the motor The ADC can also be used to synchronize the current sampling point with the PWM output using the external triggering capability of the peripheral Owing to this current conversions can be performed at any given time during the PWM period To do this the 43 105 Library functions UM0483 Figure 30 control algorithm uses the fourth PWM channel of TIM1 to synchronize the start of the conversions Injected conversions as described above are used for current reading purposes whereas regular conversions are reserved for the user As soon as A D conversions for current reading purposes have completed bus voltage and temperature sensing conversions are simultaneously performed
9. Vo Vgs C0S0 Va Sin0 Vg Vgs Sin V4 COSO q 65 105 Library functions UM0483 4 5 4 66 105 Circle limitation As discussed above FOC allows to separately control the torque and the flux of a 3 phase permanent magnet motor After the two new values V d and of the stator voltage producing flux and torque components of the stator current have been independently comput id by flux and torque PIDs it is necessary to saturate the magnitude of the resulting vector fi before passing them to the Reverse Park transformation and finally to the SVPWM block The saturation boundary is normally given by the value 816 MAX 32767 which produces the maximum output voltage magnitude corresponding to a duty cycle going from 096 to 100 Nevertheless when using three shunt resistor configuration and depending on PWM frequency it might be necessary to limit the maximum PWM duty cycle to guarantee the proper functioning of the stator currents reading block For this reason the saturation boundary could be a value slightly lower than 16 MAX depending on PWM switching frequency when using three shunt resistor configuration Table 2 on page 49 repeated below for convenience shows the maximum applicable modulation index as a function of the PWM switching frequency when using the STM3210B MCKIT UM0483 Library functions Table 3 PWM frequency vs maximum dut
10. in order to guarantee the proper working of the algorithm and be sure that the new computed duty cycles will be applied in the next PWM period it is always necessary to finish executing the IFOC algorithm before the next PWM period begins as shown in Figure 51 93 105 Additional information UM0483 94 105 Figure 51 AD conversion intervals for three shunt topology stator currents reading and IFOC algorithm execution PWM Period Case 1 REP RATE 1 Fowm lt 19 kHz New duty cycles ready before next U event OK PWM Period lt gt Case 2 REP_RATE 1 Fowm gt 19 kHz New duty cycles ready after next U event necessary to increase REP_RATE PWM Period 4 Case 3 REP RATE 3 Fpwy gt 19 kHz pa NU U New duty cycles ready before next U Y y event OK CI ADC triggering interval L FOC algorithm execution New duty cycle values ready ai14848 Considered that as seen in Section 4 2 5 ADC conversions are triggered latest Ty Ts 2 after the TIM1 counter overflow and considered the time required for the A D converter to perform injected conversions it can been stated that the IFOC algorithm is started about 5 us after the TIM1 counter overflow worst case Furthermore given that the raw execution time of the IFOC algorithm is around 21 us to compute the new duty cycle values before the next update event it is necessary to guarantee a mi
11. the value to be loaded into the OCR4 register is calculated to set the sampling point for the next PWM period and the A D converter is configured to sample the correct channels ky UM0483 Library functions 4 2 5 Note Regular conversions are reserved for user purposes and must be configured manually See also firmware standard library user manual UM0427 Tuning delay parameters and sampling stator currents in three shunt resistor topology Figure 31 shows one of the three inverter legs with the related shunt resistor Figure 31 Inverter leg and shunt resistor position To indirectly measure the phase current I it is possible to read the voltage V providing that the current flows through the shunt resistor R It is possible to demonstrate that whatever the direction of current l it always flows through the resistor R if transistor T2 is switched on and T1 is switched off This implies that in order to properly reconstruct the current flowing through one of the inverter legs it is necessary to properly synchronize the conversion start with the generated PWM signals This also means that current reading cannot be performed on a phase where the duty cycle applied to the low side transistor is either null or very short Fortunately as discussed in Section 4 2 4 to reconstruct the currents flowing through a generic three phase load it is sufficient to simultaneously sample only two out of three currents
12. 1 Introduction to AC induction motor FOC drive 0 55 13 2 2 How to customize hardware and software parameters 14 2 2 1 Library configuration file stm32 10x MCconf h 15 2 2 2 Drive control parameters MC Control Param h 16 2 2 3 Incremental encoder parameters MC_encoder_param h 19 2 2 4 Tachogenerator parameters MC tacho prm h eee 19 2 2 5 AC induction motor parameters MC ACmotor param h 21 2 3 How to define and add ac module 00 ee eee eee 22 3 Running the demo program 00 cee eee eee eee eee 24 3 1 Torque control mode s Ceu espe Ri ERROR e pra ed seer amp pare prc ges 25 3 2 Speed control mode 2 cee eee 28 3 3 Output IFOC variables using a 2 channel DAC Lusuuus 30 3 4 Setting up the system when using ICS sensors 2055 32 3 4 1 Connecting the two ICS sensors to the motor and to STM32F103xx 32 3 4 2 Selecting PHASE A ADC CHANNEL and PHASE B ADC CHANNEL 000 e cece es 33 3 5 How to build the system when using an incremental encoder 34 3 6 Fault messages xac kane pauco E RR RERO ee OEC ee SER B CR OR 35 3 7 Actual values of DC bus voltage and IGBT heatsink temperature 36 3 8 Note on debugging tools 00 ccc ee 36 2 104 Ti UM0483 Contents 4 Library FUNCIONS a uia acia UE e eee eR e Re 38 4 1 Function description conven
13. 48 Stator currents sampling in ICS configuration REP_RATE 1 0000 eeee 53 Rotor flux angle calculation quadrature encoder 20000 cee eee ee eens 56 Rotor flux angle calculation tachogenerator 0 0c cee 56 Torque and flux optimization bDlOcK 2 2 eee 57 Torque vs speed characteristic curve 000 cece 61 Clarke Park and reverse Park transformations 0 00 0c cece eee eee 62 Transformation from an abc stationary frame to a rotating frame q d 65 Circle limitation working principle llli 67 Automatic tacho timer prescaler decrease 2 00 eee ees 77 Automatic tacho timer prescaler increase lille 77 PID general equation 0 0 tte 81 Time domain to discrete PID equations illie 82 UM0483 List of figures Figure 49 Linear curve for coefficient computation 1 6 0 0 0 cee ee 83 Figure 50 AD conversions for three shunt topology stator currents reading and IFOC algorithm execution when REP_RATE 3 00 0c cece eee teen eee eee 92 Figure 51 AD conversion intervals for three shunt topology stator currents reading and IFOC algorithm execution 000 cette 94 Figure 52 Tacho capture overview 1 6 eee eee eae 96 Figure 53 Processing captured value when timer did not overflow llle 96 Figure 54 Processing captured value when timer did overflow 00 0 cece eee eee 97 Figur
14. Angle void This function returns the mechanical angle in signed 16 bit format This routine returns 0 for 0 degrees 32768 S16 MIN for 180 degrees 32767 816 MAX for 180 degrees None Signed 16 bits None Link between Electrical Mechanical frequency RPM Electrical frequency 2 number of pair poles x mechanical frequency RPM speed 60 x Mechanical frequency RPM revolutions per minute Example electrical frequency 100 Hz motor with 8 pair poles 100Hz electrical lt gt 100 8 212 5Hz mechanical lt gt 12 5 x 602750 RPM 69 105 Library functions UM0483 70 105 ENC Clear Speed Buffer Synopsis Description Functions called void ENC Clear Speed Buffer void This function resets the buffer used for speed averaging None ENC Get Mechanical Speed Synopsis Description Input Output Functions called Note s16 ENC Get Mechanical Speed void This function returns the rotor speed in Hz The value returned is given with 0 1Hz resolution which means that 1234 is equal to 123 4 Hz None Signed 16 bits None This routine returns the mechanical frequency of the rotor To find the electrical speed use the following conversion electrical frequency number of pole pairs mechanical frequency ENC Calc Average Speed Synopsis Description Functions called Input Returns void ENC Calc Average Speed void This function must be called every SPEED MEAS TIMEBASE ms it computes t
15. FOC ACIM SR Category General Options Assembler Linker command file v Overide defaut Debugger Command file configuration tool Simulator Angel Overide default program entry IAR ROM monitor Entry labe program_start J4ink J Trace Defined plication LMI FTDI Search paths one per line Third Party Driver Raw binary image C C Compiler Output Extra Output define Diagnostics List Build Actions SPROJ DIRSWnkam flash xcl z paene Factory Settings Config Proce 4 gt File Symbol Segment Align ee ees o Cancel UM0483 Getting started with the library 2 2 1 Getting started with the library Introduction to AC induction motor FOC drive The AC IM IFOC software library is designed to achieve the high dynamic performance in AC motor control offered by the field oriented control FOC strategy Through complex machine electrical quantity transformations this well established drive system optimizes the control of the motor to the extent that it is able to offer decoupled torque T and magnetic flux A regulation That is it offers the same optimum and favorable conditions as DC motors but in this case carried out with rugged and powerful AC induction motors With this approach it can be stated that the two currents ine and Ius derived from stator currents have in AC induction motor IM the same role that armature and field currents have in DC m
16. INFRINGEMENT OF ANY PATENT COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT UNLESS EXPRESSLY APPROVED IN WRITING BY AN AUTHORIZED ST REPRESENTATIVE ST PRODUCTS ARE NOT RECOMMENDED AUTHORIZED OR WARRANTED FOR USE IN MILITARY AIR CRAFT SPACE LIFE SAVING OR LIFE SUSTAINING APPLICATIONS NOR IN PRODUCTS OR SYSTEMS WHERE FAILURE OR MALFUNCTION MAY RESULT IN PERSONAL INJURY DEATH OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE ST PRODUCTS WHICH ARE NOT SPECIFIED AS AUTOMOTIVE GRADE MAY ONLY BE USED IN AUTOMOTIVE APPLICATIONS AT USER S OWN RISK Resale of ST products with provisions different from the statements and or technical features set forth in this document shall immediately void any warranty granted by ST for the ST product or service described herein and shall not create or extend in any manner whatsoever any liability of ST ST and the ST logo are trademarks or registered trademarks of ST in various countries Information in this document supersedes and replaces all information previously supplied The ST logo is a registered trademark of STMicroelectronics All other names are the property of their respective owners 2008 STMicroelectronics All rights reserved STMicroelectronics group of companies Australia Belgium Brazil Canada China Czech Republic Finland France Germany Hong Kong India Israel Italy Japan Malaysia Malta Morocco Singapore Spain Sweden Switzerland United Kingdom United
17. In particular TIM1 outputs are disabled the main state machine is put into FAULT state None None MCL_SetFault TIM1_ClearlTPendingBit Advanced control timer TIM1 in STM32F103xx reference manual TIM1 UP_IRQHandler Synopsis Description Input Returns Functions called ADC_IRQHandler Synopsis Description Input Returns Functions called See also void TIM1_UP_IRQHandler void This interrupt handler is executed after an update event when an underflow of the TIM1 counter occurs It is used to externally trigger the ADC when a rising edge of the TIM1_OC4Ref signal occurs None None ADC_ClearFlag TIM1_ClearFlag void ADC_IRQHandler void The purpose of this function is to handle the ADC interrupt request The end of the stator current conversion interrupt routine JEOC is utilized to trigger execution of the IFOC algorithm External ADC triggering is disabled until the next TIM1 update event is generated None None IFOC_Model Section 4 2 4 and Section 4 3 3 on page 52 for more details General purpose time base stm32 10x_Timebase module Overview The purpose of the stm32 10x_Timebase module is to generate a time base that can be used by the other modules of the applications 85 105 Library functions UM0483 4 10 2 86 105 List of available functions and interrupt service routines The following is a list of available functions as listed in the stm32 10x_Timebase h
18. States of America www st com 104 104
19. bus voltage thresholds void MCL SetFault u16 On an event fault occurrence this function puts the state machine in Fault state and disables the motor control outputs of Advanced Control Timer TIM1 PWM timer Sets the motor control status flag variable according to the cause of the fault TB Set Delay 500us TIM1 CtrlIPWMOutputs MCL ChkPowerStage Synopsis Description Functions called MCL ClearFault Synopsis Description Returns Functions called void MCL ChkPowerStage void This function checks the power stage operation under critical conditions of temperature and bus voltage MCL_SetFault MCL Chk OverTemp MCL Chk BusVolt bool MCL ClearFault void This function checks if the fault source is over If it is the case it clears the related flag and returns TRUE Otherwise it returns FALSE TRUE or FALSE according to fault source status MCL Chk BusVolt MCL Chk OverTemp GPIO_ReadInputDataBit TAC_ClrTimeout if Tacho speed sensor is used This function checks for all the sources of fault handled by the Motor Control software that is is overcurrent break event Startup failure speed feedback timeout power stage overtemperature and over undervoltage on the DC bus UM0483 Library functions 4 12 MCL Compute BusVolt Synopsis u16 MCL Compute BusVolt void Description This function computes the DC bus voltage in volt units Returns A value representing the bus voltage in volt un
20. choice you will receive an error message when building the project Note that you will not receive an error message if the configuration described in this header file does not match the hardware that is actually in use or in case of wrong wiring More specifically define ICS SENSORS To be uncommented when current sampling is done using isolated current sensors define THREE SHUNT To be uncommented when current sampling is performed via three shunt resistors default e define ENCODER To be uncommented when an incremental encoder is connected to the starter kit for position sensing in parallel fill out MC encoder param h as explained in Section 2 2 3 e define TACHO To be uncommented when a tachogenerator is in use to detect rotor speed default in parallel fill out MC tacho prm h as explained in Section 2 2 4 e define Id Iq DIFFERENTIAL TERM ENABLED To be uncommented when differential terms for torque and flux control loop regulation PID are enabled e define SPEED DIFFERENTIAL TERM ENABLED To be uncommented when differential term for speed control loop regulation PID is enabled define DAC FUNCTIONALITY If uncommented the TIMS timer outputs channels 3 and 4 are configured in PWM mode to show two variables among the ones involved in the IFOC algorithm Once this feature in enabled an additional m
21. frequency selection e define DEADTIME NS Define here in ns the dead time in order to avoid shoot through conditions Flux and torque PID regulators sampling rate e define REP RATE Stator currents sampling frequency and consequently flux and torque PID regulators sampling rate are defined according to the following equation 2 PWM FREQ Flux and torque PID sampling rate REP RATE 1 In fact because there is no reason for either executing the IFOC algorithm without updating the stator currents values or for performing stator current conversions without running the IFOC algorithm in the proposed implementation the stator current sampling frequency and the IFOC algorithm execution rate coincide Power board protection thresholds e define NTC THRESHOLD e define NTC HYSTERIS These two values are used to set the maximum operating temperature rating for the power board in use the default values refer to MB459 included in the STM3210B MCKIT kit and correspond to a maximum temperature of about 60 C The second parameter is related to the hysteresis fixed at 4 C When the heatsink temperature exceeds the fixed threshold an overheat fault event is validated and the motor is stopped define OVERVOLTAGE THRESHOLD e define UNDERVOLTAGE THRESHOLD These two values establish the minimum and maximum limits for the input bus DC volta
22. generic three phase load it is sufficient to sample only two out of the three currents while the third one can be computed by using the above relationship The flexibility of the STM32F103xx A D converter trigger makes it possible to synchronize the two A D conversions necessary for reconstructing the stator currents flowing through the three phase AC induction motor with the PWM reload register updates The update rate can be adjusted using the repetition counter This is important because as shown in Figure 37 it is precisely during counter overflow and underflow that the average level of current is ky UM0483 Library functions equal to the sampled current Refer to the STM32F103xx Reference Manual to learn more about A D conversion triggering and the repetition counter Regular conversions are reserved for the user and must be configured manually See also firmware standard library user manual UM0427 Figure 37 Stator currents sampling in ICS configuration REP_RATE 1 PWM Counter Compare A____ EE ENOTE UNE EA E C AREE TIM1 Update TIM1 Update TIM1 Update ADC trigger ADC trigger ADC trigger ai14854 4 4 Induction motor IFOC vector control MC_IFOC_Drive module 4 4 1 Overview The MC_IFOC_Drive module designed for AC induction machines provides at the core decoupled torque and flux regulation relying on indirect field oriented control algorithm In addition it makes available other important fe
23. manual for more information on programmable repetition counter When using ICS the injected chain of conversions for current reading is directly triggered by a PWM register update event Moreover since the IFOC algorithm is executed at the end of the injected chain of conversions in the related ISR changing repetition counter has a direct impact on IFOC refresh rate and thus on CPU load However in the case of three shunt topology current reading to ensure that the IFOC algorithm is executed once for each PWM register update it is necessary to keep the synchronization between current conversion triggering and PWM register update In the proposed software library this is automatically performed so that you can reduce the frequency of execution of the IFOC algorithm by simply changing the default value of the repetition counter the REP RATE parameter in the MC Control Param h header file Figure 50 shows current sampling triggering and IFOC algorithm execution with respect to PWM period when REP RATE is set to 3 Figure 50 AD conversions for three shunt topology stator currents reading and IFOC algorithm execution when REP RATE 3 PWM Period REP RATE 1 PWM Period d N U N REP_RATE 3 ji ADC triggering interval FOC algorithm execution New duty cycle values ready ai14849 UM0483 Additional information Note A 2 Note Because three shunt resistor to
24. measurement Power of two is desirable for ease of computation 2 2 4 Tachogenerator parameters MC tacho prm h The MC tacho prm h header file is to be filled out if speed sensing is performed using an AC tachogenerator Extra details and more explanations on tacho based speed measurement can be found in Section 4 7 on page 71 and Section A 4 on page 96 define TACHO PULSE PER REV Define here the number of pulses per revolution given by the tachogenerator in order to verify the correct operation of the tacho module this parameter can be set to 1 so that the frequency measurement can be directly compared with the one of a signal generator define TIMER2 HANDLES TACHO To be uncommented if tachogenerator based speed measurement is performed by TIMER2 Default required if using STM3210B MCKIT in conjunction with Input Capture 1 choice see define TACHO INPUT TI1 below 19 105 Getting started with the library UM0483 Note 20 105 define TIMER3 HANDLES TACHO To be uncommented if tachogenerator based speed measurement is performed by TIMERS define TIMER4 HANDLES TACHO To be uncommented if tachogenerator based speed measurement is performed by TIMER4 define TACHO_INPUT_TI1 To be uncommented if sensor output signal is wired to TimerX Input Capture 1 TIMx_CH1 pin Default in conjunction with TIMER2 choice required if using STM3210B MCKIT define TACHO_INPUT_TI2 To be uncommented
25. performed by means of a quadrature square wave relative rotary encoder ENCODER defined in stm32 10x_MCconf h define ENCODER_PPR Define here the number of pulses generated by a single channel for one shaft revolution actual resolution will be 4x define TIMER2 HANDLES ENCODER To be uncommented if the two sensor output signals are wired to TIMER2 input pins default required if using STM3210B MCKIT define TIMER3 HANDLES ENCODER to be uncommented if the two sensor output signals are wired to TIMERS input pins define TIMERA HANDLES ENCODER To be uncommented if the two sensor output signals are wired to TIMER4 input pins define MINIMUM MECHANICAL SPEED RPM Defines in rpm the minimum speed below which the speed measurement is either not realistic or not safe in the application an error counter is increased every time the measured speed is below the specified value define MAXIMUM MECHANICAL SPEED RPM Defines in rpm the maximum speed above which the speed measurement is either not realistic or not safe in the application an error counter is increased every time the measured speed is above the specified value define MAXIMUM ERROR NUMBER Defines the number of consecutive errors on speed measurements to be detected before a fault event is generated check rate is specified by SPEED MEAS TIMEBASE in stm32f10x Timebase c define SPEED BUFFER SIZE Defines the buffer size utilized for averaging speed
26. that the positive rolling direction is the rolling direction of a machine that is fed with a three phase system of positive sequence Because of this and because of how the encoder output signals are wired to the microcontroller input pins it is possible to have a sign discrepancy between the real rolling direction and the direction that is read To avoid this kind of reading error you can apply the following procedure UM0483 Running the demo program 1 Set the DC source at low voltage 50V 2 Run the system in closed loop operation and on the LCD observe the target and measured speeds The error occurs if the sign of the measured speed is opposite to the sign of the target speed For help with the LCD menus see Section 3 2 on page 28 3 Ifthe error occurs you can correct it by simply swapping and rewiring the encoder output signals If this isn t practical you can modify a software setting instead in the stm32f 10x_encoder c file replace the code line TIM EncoderInterfaceConfig ENCODER TIMER TIM EncoderMode TI12 TIM ICPolarity Rising TIM ICPolarity Rising by TIM EncoderInterfaceConfig ENCODER TIMER TIM EncoderMode TI12 TIM ICPolarity Rising TIM ICPolarity Falling 3 6 Fault messages This section provides a list of possible fault message that can be displayed on the LCD when using the software library together with the
27. the hardware in use motor parameters power devices features speed position sensor parameters current sensors transconductance Edit using an IDE the stm32 10x_MCconf h configuration header file as explained in more detail in Section 2 2 1 and the following parameter header files MC Control Param h see Section 2 2 2 MC encoder param h see Section 2 2 3 or MC tacho prm h see Section 2 2 4 MC ACmotor prm h see Section 2 2 5 Re build the project and download it on the STM32F103xx microcontroller UM0483 Getting started with the library 2 2 1 Caution Library configuration file stm32 10x_MCconf h The purpose of this file is to declare the compiler conditional compilation keys that are used throughout the entire library compilation process to e Select which current measurement technique is actually in use the choice is between three shunt or ICS sensors according to availability e Select which speed position sensor is actually performed here the choice is between tachometer and quadrature incremental encoder according to availability e Enable or disable the derivative action in the speed controller or in the current controllers in accordance with expected performance and code size e Enable or disable a virtual 2 channel DAC used to output in real time all the variables involved in the IFOC algorithm If this header file is not edited appropriately no choice or undefined
28. the tacho signal period measurement It updates a Counter of overflows which is reset when next capture occurs Input None Output None Note This is an interrupt routine Integration tips In the MC tacho prm h file of your project select the Timer you have chosen and the input channel on which the tacho signal arrives using the right define see Section 2 2 4 on page 19 In the main c module or the c module just above stm32 10x_tacho include the stm32f10x tacho hfile call TAC TachoTimerInit after MCU reset and TAC InitTachoMeasure before motor startup TAC GetRotorFreqInHz returns a frequency directly with 0 1Hz while TAC GetRotorFreq returns a value that can be directly accumulated in the FOC algorithm to get the rotor angular position the unit is 27 rad that is OXFFFF per sampling period Operating principle Although the principle of measuring a period with a timer is quite simple you must pay attention to keeping the best resolution in particular for signals such as the one provided by a tachogenerator which can vary with a ratio of up to 1 100 In order to have always the best resolution the timer clock prescaler is constantly adjusted in the current implementation The basic principle is to speed up the timer if captured values are too low for an example of low periods see Figure 45 and slow it down when the timer overflows between two consecutive captures see example of large periods in Figure 46
29. 0 Torque P I 00300 00100 Target 08000 Iq Feedback 00000 Iq lt gt Move t Change Figure 20 LCD screen to set the P term of the Flux PID STM32 Motor Control ACIM IFOC ver 1 0 Flux P I 00200 00050 Target 093800 Feedback 00000 Id Move t Change Finally although you cannot directly act on torque and flux references both the target and measured flux and torque stator current components can be observed In fact in closed loop both flux and torque references are the outputs of the speed PID regulator and field weakening blocks As in Torque control mode pressing the joystick or the Key button starts the motor 29 105 Running the demo program UM0483 3 3 30 105 The Speed control ramp up strategy is shown in Figure 21 Basically a linear torque ramp is applied to the motor until it reaches soeed TACHO_SPEED_VAL if a tacho speed sensor is used or ENCODER CL ENABLE if an encoder is used Then the speed PID regulator is enabled and takes control of the torque reference However if the motor does not reach the above mentioned speeds before STARTUP RAMP DURATION the final torque reference value STARTUP FINAL TORQUE is further applied until STARTUP TIMEOUT Finally in the case where the speeds that enable the Speed control are not reached before STARTUP_TIMEOUT the state machine goes into Fault state for a few seconds and the error message Startup fai
30. 05 Output signed 16 bits Functions called None Caution Default values for the PID speed regulation are declared and can be modified in the MC_Control_Param h file see Section 2 2 2 on page 16 See also Figure 56 on page 99 shows the PID block diagram PID Reset Integral terms Synopsis void PID Reset Integral terms void Description The purpose of this function is to reset all the integral terms of the torque flux and speed PID regulators PID Speed Coefficients update Synopsis void PID Speed coefficients update s16 motor speed Description This function automatically computes the proportional integral and derivative gain for the speed PID regulator according to the actual motor speed The computation is done following a linear curve based on 4 set points See Section 4 8 5 on page 82 for more information Functions called None Caution Default values for the four set points are declared and can be modified in the MC Control Param h file see Section 2 2 2 on page 16 PID Integral Speed update Synopsis void PID Integral Speed update s32 value Description The purpose of this function is to load the speed integral term with a default value PID regulator theoretical background The regulators implemented for Torque Flux and Speed are actually Proportional Integral Derivative PID regulators see note below regarding the derivative term PID regulator theory and tuning methods are subjects which have been e
31. 2 List of available C functions 0 0 0 ccc eee eee 62 4 5 3 Detailed explanation about reference frame transformations 64 4 5 4 Circle limitation 14223 ntact aida y ek ek chon Hn daa 66 4 6 Encoder feedback processing stm32 10x encoder module 68 4 6 1 List of available functions and interrupt service routines 68 4 7 Tachogenerator feedback processing stm32 10x tacho module 71 4 7 1 List of available functions and interrupt service routines 71 4 7 2 Integration tips gcc voler eee aed ape ney eta desea eee 76 4 7 3 Operating principle 2 0 tee 76 4 7 4 Converting Hertz into pseudo frequency 00 eee eee 78 4 8 Flux torque and speed regulators MC PID regulators module 78 4 8 1 eu A P T Lad ated AE ER A de da nee wan oe 78 4 8 2 List of available functions and interrupt service routines 78 ky 3 104 Contents UM0483 4 8 3 PID regulator theoretical background 000 e eee eee 80 4 8 4 Regulator sampling time setting llle 81 4 8 5 Adjusting speed regulation loop Ki Kp and Kd vs motor frequency 82 4 9 Main interrupt service routines stm32 10x_it module 84 4 9 1 OVEINVICW siirad bod ette a cae oh eed eats eh baad 84 4 9 2 List of non empty interrupt service routines 84 4 10 General purpose time base stm32 10x Timebase module 85 4 10 1 OvervieW s eg Rak onm Ro
32. 5 bits for the resolution the expressible range is from 4 to 3 96875 the resolution is 0 03125 the bit weighting is bit n 7 6 5 4 3 2 1 0 value 4 2 1 1 2 1 4 1 8 1 16 1 32 This software library uses the PU Per Unit system to express current values They are always referred to a base quantity that is the maximum measurable current Imax which for the proposed hardware can be estimated approximately at Imax 0 6 Rehynt So the per unit current value is obtained by dividing the physical value by that base max In this way ig is always in the range from 1 to 1 Therefore the q1 15 format which ranges from 1 to 0 999969482421 875 with a resolution of 0 00003051 7578125 is perfectly suitable taking care of the overflow value 1 1 21 and thus extensively used Thus the complete transformation equation from SI units is l inss fioor 72 2 max 95 105 Additional information UM0483 A 4 96 105 Tacho based speed measurement flow charts This section summarizes the main tasks achieved in the tacho capture interrupt in the form of flow charts The purpose of these flow charts is to help understand how the automatic prescaler adjustment is done Figure 52 Tacho capture overview See no overflow diagram Increase resolution if possible Ye z Init rolling 2 es md last ipei into No Cleer interrupt flag
33. BLE this look up table 256 signed 16 bit values provides reference values of current ig expressed in q1 15 format according to increasing stator frequencies see Section 4 4 4 on page 60 The first element of the table should have the same value as the NOMINAL FLUX parameter TORQUE REFERENCE TABLE this look up table 256 signed 16 bit values provides saturation values of current ig expressed in q1 15 format according to increasing stator frequencies see Section 4 4 4 on page 60 How to define and add a c module This section describes with an example how to define and include a new module in a project based on the library The example is based on the addition of two files my i1e candthe corresponding header file my_file h 1 Create a new file You can either copy and paste an existing file and rename it or in the File menu choose New then click the File icon and save it in the right format c h extension as shown in Figure 8 2 Declare the new file containing your code in the toolchain workspace To do this simply right click in the workspace folder then choose the Add Files sub menu The new file is automatically added to the workspace and taken into account for the compilation of the whole project UM0483 Getting started with the library The procedure of adding the module to the project is very easy with the IAR Embedded Workbench as the ma
34. STM3210B MCKIT Overcurrent A Break Input was detected on the TIM1 peripheral dedicated pin If using STM3210B MCKIT it could mean that either the hardware overtemperature protection or the hardware overcurrent protection were triggered Refer to the STM3210B MCKIT user manual for details Overheating An overtemperature was detected on the dedicated analog channel the digital threshold NTC THRESHOLD and the relative hysteresis NTC HYSTERESIS are specified in the MC Control Param h header file Refer to the STM3210B MCKIT user manual for details Error on speed feedback The speed feedback timed out Verify speed sensor connections Startup failed The motor ramp up failed Refer to Section 3 1 and Section 3 2 for in depth information Bus overvoltage An overvoltage was detected on the dedicated analog channel The digital threshold OVERVOLTAGE THRESHOLD is specified in the MC Control Param h header file Refer to the STM3210B MCKIT user manual for details Bus undervoltage The bus voltage is below 20 V DC This threshold is specified in the UNDERVOLTAGE THRESHOLD parameter in the MC Control Param h header file Figure 25 shows the example of the error message screen that appears when the applied DC bus voltage level is too low 35 105 Running the demo program UM0483 3 7 3 8 Caution 36 105 Figure 25 Error message shown in case of an undervoltage fault STM32 Motor Cont
35. STM32F103xx reference manual TIMx in encoder interface mode 4 7 Tachogenerator feedback processing stm32 10x tacho module 4 7 1 List of available functions and interrupt service routines The following is a list of available functions as listed in the stm32 10x_tacho h header file TAC TachoTimerInit on page 72 TAC InitTachoMeasure on page 72 TAC GetRotorFreqInHz On page 72 TAC_GetRotorFreg on page 73 GetLastTachoPeriod on page 73 this is a private function defined inside the stm32f10x tacho c file GetAvrgTachoPeriod on page 73 this is a private function defined inside the stm32f10x tacho c file TAC IsTimedOut on page 74 TAC CIrTimeOut on page 74 TAC GetCaptCounter on page 74 TAC ClIrCaptCounter on page 74 TAC StartTachoFiltering On page 75 e TAC ValidSpeedinfo on page 75 e TIMx IRQHandler on page 76 71 105 Library functions UM0483 72 105 TAC TachoTimerInit Synopsis void TAC_TachoTimerInit void Description The purpose of this function is to initialize the timer that will perform the tacho signal period measurement the timer can be chosen in the MC tacho prm h file The peripheral clock and the capture interrupt are enabled and the timer is initialized in Slave reset mode Functions TIM ICStructlnit TIM TimeBaselnit TIM IClInit TIM PrescalerConfig called TIM InternalClockConfig TIM SelectInputTrigger TIM SelectSlaveMode TIM UpdateRequestConfig NVIC I
36. Stack and heap segments f FRCRCKECkCkCkckckckckckckckckckckckckckckck ck chckckckckckckckckckckckckckckckckckckckckckckckckckckck ck ck ck ckckck kckck ch ck KKK ckckckck kk D CSTACK SIZE 800 D HEAP SIZE 400 Z DATA CSTACK _CSTACK_SIZE RAMSTART RAMEND Z DATA HEAP _HEAP_STZE RAMSTART RAMEND 11 105 Getting started with tools UM0483 1 4 2 12 105 Memory size modifications might also be necessary according to the MCU specifications Default settings are done for a 128 KB embedded Flash memory If you use a different device you must edit the Inkarm flash xcl file as explained in Section 1 4 2 Extended linker file setting As mentioned in the previous section in the provided IAR workspace the internal Flash extended linker file is set by default Inkarm_flash xcl To modify the linker file to be used for example Inkarm ram xc1 1 Open the IAR workspace by double clicking on the STM32_FOC_ACIM_SR EWARM STM32_FOC_ACIM_SR eww file 2 Go to the Project menu select Options then Linker and select the Config sub menu The dialog box shown in Figure 4 is displayed 3 Inthe Override default field type the name of the linker file you want to use and then click OK Selecting the Inkarm_ram xc1 file makes the IAR XLINK linker place the memory segments on RAM memory Figure 4 Extended linker file setting Options for node STM32
37. VPWM_3ShuntCalcDutyCycles Synopsis void SVPWM_3ShuntCalcDutyCycles Volt_Components Stat_Volt_Input Description After execution of the IFOC algorithm new stator voltage components Va and Vg are computed The purpose of this function is to calculate exactly the three duty cycles to be applied to motor phases from the values of these voltage components Moreover once the three duty cycles to be applied in the next PWM period are known this function sets the TIM1 Channel 4 capture compare register TIM1_CCR4 to set the sampling point for the next current reading In particular depending on the duty cycle values the sampling point is computed see Section 4 2 5 on page 45 Refer to Section 4 2 3 for information on the theoretical approach of SVPWM Input V and Vg Returns None Note None Functions called None SVPWM 3ShuntAdvCurrentReading Synopsis void SVPWM 3ShuntAdvCurrentReading FunctionalState cmd Description It is used to enable or disable advanced current reading If advanced current reading is disabled current reading is performed in conjunction with the update event Input cmd ENABLE or DISABLE Returns None Note None Functions called TIM1 ClearFlag TIM1 ITConfig ky 41 105 Library functions UM0483 4 2 3 42 105 Space vector PWM implementation Figure 28 shows the Stator Voltage components Va and Vg while Figure 29 illustrates the corresponding PWM for each of the six space vector se
38. ack 5 KB for LCD joystick management These figures are for information only this software library may be subject to changes depending on the final application and peripheral resources Note that it was built using robustness oriented structures thus preventing the speed or code size from being fully optimized Related documents Available on www st com e STM32F103xx datasheet e ARM based 32 bit MCU STM32F101xx and STMS2F 103xx firmware library user manual e STM32F103xx Flash programming manual Available on www arm com e Cortex M3 Technical Reference Manual UM0483 Getting started with tools 1 1 1 2 Getting started with tools To develop an application for an AC induction motor using the AC IM IFOC software library you must set up a complete development environment as described in the following sections A PC running Windows XP is necessary Working environment The AC IM IFOC software library was fully validated using the main hardware boards included in STM3210B MCKIT starter kit a complete inverter and control board The STM3210B MCKIT starter kit provides an ideal toolset for starting a project and using the library Therefore for rapid implementation and evaluation of the software described in this user manual it is recommended to acquire this starter kit It is also recommended to install the IAR EWARM C toolchain which was used to compile the AC IM IFOC software library With this tool
39. applied phase voltage magnitude expressed as a percentage of the maximum applicable phase voltage the duty cycle ranges from 096 to 100 Figure 33 offers a reconstruction of the PWM signals applied to low side switches of Phase A and B in these conditions plus a view of the analog voltages measured on the STM32F10xxx A D converter pins for both Phase B and C the time base is lower than the PWM period Figure 32 Low side switches gate signals low modulation indexes 10096 9096 80 70 60 50 40 30 0 30 60 Phase A Phase B Phase C Note that these current feedbacks are constant in the view in Figure 33 because it is assumed that commutations on Phase B and C have occurred out of the visualized time window Moreover it can be observed that in this case the two stator current sampling conversions can be performed synchronized with the counter overflow as shown in Figure 33 UM0483 Library functions Figure 33 Low side Phase A duty cycle gt DT Ty 1 ADutyA Counter overflow S a a HP Tg lt lt DT Ty Low side phase A DT b D T 5 High side phase A Li H Low side phase B T High side phase B e a i 1 5 T i WANA S Current feedback i phase B eu 9 Sampling start Current feedback 1 Tele 9 Sampling end phase C puuwwwwmg Space available for sampling 2114836 Case 2 DT Ty Ts 2 lt ADu
40. ategy 1 tees 27 LCD screen for Speed control settings llle 28 LCD screen to set the Target speed 2 2 20 c eee 28 LCD screen for setting P term of Speed PID 0 00 c eee eee 29 LCD screen to set the P term of the Torque PID 0 000 cece eens 29 LCD screen to set the P term of the Flux PID 0 0 00 29 Speed control startup strategy 0 0 0 0c tees 30 LCD screen to select and view IFOC variables 0 00 0c cece eee eee eee 31 ICS hardware connections 0 00 cee n 32 Encoder output signals counter operation 0 000 cece ee eee 34 Error message shown in case of an undervoltage fault 00 0 0 e eee eee 36 LCD screen to monitor power stage statuS 00 cece eee eee 36 DBG_TIM1_STOP bit in TIM1 control register extract from STM32 reference manual 37 Vo and VB stator voltage components 0 ene eens 42 SVPWM phase voltages waveforms 00 000s 42 PWM and ADC synchronization liliis eee 44 Inverter leg and shunt resistor position 2 2 0 0 cee 45 Low side switches gate signals low modulation indexes 2 22055 46 Low side Phase A duty cycle gt DT TN 0 eee eee 47 DT Ty Ts 2 lt ADuty a lt D Ty and ADuty ap lt Dr Tp Ts Nara Remand wc Akon dea A 47 ADutyA lt DT Ty Ts 2 and ADutya_p gt DT Tatls leslie 48 ADutya lt DT Tyt Tg 2 and ADutya p lt DT Tptls 0 cee
41. atures e speedregulation by PID feedback control e flux weakening for extended speed range It works requiring no adjustment with all of the selectable current or speed sensing configurations in accordance with the settings in the stm32 10x_MCconf h file e isolated current sensing ICS e three shunt resistors current sensing e encoder position and speed sensing e tachometer speed sensing It handles several functions of other modules and has no direct access on the microcontroller peripheral registers 53 105 Library functions UM0483 4 4 2 List of available C functions e IFOC Init on page 54 e FOC Model on page 55 e IFOC CalcFluxTorqueRef on page 57 e Calclm on page 58 e CalcHRotFlxSlipFreq on page 58 IFOC Init Synopsis void IFOC Init void Description This function is normally called at every motor startup It performs the initialization of some of the variables used for IFOC implementation by the MC IFOC Drive c module Input None Returns None Note None Functions called if working with ICs SVPWM lcsCalcDutyCycles if working with three shunts SVPWM_3ShuntCalcDutyCycles 54 105 ky UM0483 Library functions IFOC_Model Synopsis Description Input Returns void IFOC_Model void The purpose of this function is to perform AC IM torque and flux regulation implementing the IFOC vector algorithm Ar x Mg Current commands ig and igs which under fie
42. be limited to max u16 value Note This function is typically used to monitor the interrupts activity while the motor is running tacho related interrupts must not be stopped or too frequent See also TAC_ClrCaptCounter TAC ClrCaptCounter Synopsis void TAC ClrCaptCounter void Description This routine clears the number of capture events variable Input None Output None UM0483 Library functions TAC StartTachoFiltering Synopsis void TAC_StartTachoFiltering void Description This routine initiates the tacho value smoothing mechanism The result of the next capture will be copied in all storage array locations to have the first average equal to the last value Input None Output None Note The initialization of the FIFO used to do the averaging will be done when the next tacho capture interrupt occurs Consequently the TAC_GetRotorFreq will continue to return a raw period value until the next interrupt event TAC ValidSpeedInfo Synopsis bool TAC ValidSpeedlnfo u16 hMinRotorFreq Description This routine indicates if the information provided by the tachogenerator is reliable this is particularly important at startup when the signal of the tacho is very weak and cannot be properly conditioned by the external circuitry glitches It is also used in startup functions to find out if the rotor shaft is turning at the right speed Input Rotor frequency 0 1Hz resolution above which speed information is not consi
43. ble duty cycles are listed in Table 2 as a function of the PWM frequency Table 2 PWM frequency vs maximum duty cycle relationship PWM frequency Max duty cycle Max modulation Index Up to 11 4 kHz 100 100 12 2 kHz 99 98 12 9 kHz 98 5 97 13 7 kHz 98 96 14 4 kHz 98 96 15 2 kHz 97 94 16 kHz 96 5 93 16 7 kHz 96 596 93 17 5 kHz 95 5 91 Note The values above were measured using the MB459 board This evaluation platform is designed to support several motor driving topologies PMSM and AC induction and current reading strategies single and three shunt resistor Therefore the figures provided in Table 2 should be understood as a starting point and not as a best case It is possible to adjust the noise parameters based on customized hardware by editing the following definitions in the MC_pwm_3shunt_prm h header file define SAMPLING TIME NS 700 0 7usec define TNOISE NS 2550 2 55usec define TRISE NS 2550 2 55usec Changing the noise parameters sampling time and dead time affects the values provided in Table 2 49 105 Library functions UM0483 4 3 4 3 1 4 3 2 50 105 Isolated current sensor reading and space vector PWM generation stm32 10x_svpwm_ics module Overview Two important tasks are performed in the stm32 10x_svpwm_ics module Space vector pulse width modulation SVPWM e Ihree phase current reading when two isolated current sensors ICS are used In order to rec
44. by the dual A D Figure 30 shows the synchronization strategy between the TIM1 PWM output and the ADC The A D converter peripheral is configured so that it is triggered by the rising edge of TIM1_CH4 PWM and ADC synchronization OCR 4 OCR 1 OCR 2 OCR 3 TIM1_CH1 TIM1_CH2 TIM1_CH3 TIM1_CH4 44 105 Counter overflow OCR 4 OCR 1 OCR 2 OCR 3 TIM1_CH1 TIM1 CH2 ADC Start TIM1_CH3 TIM1_CH4 Sampling point before counter overflow Sampling point after counter overflow ai14835 In this way supposing that the sampling point must be set before the counter overflow that is before the TIM1 counter value matches the OCR4 register value during the upcounting the A D conversions for current sampling are started If the sampling point must be set after the counter overflow the PWM 4 output has to be inverted by modifying the CCAP bit in the TIM1 CCER register In so doing when the TIM1 counter matches the OCR4 register value during the downcounting the A D samplings are started After the first two simultaneous conversions other two simultaneous conversions are started one for the bus voltage and the other for the temperature sensor At the end of the second conversion the three phase load current has been updated and the FOC algorithm can then be executed in the A D end of injected conversion interrupt service routine JEOC ISR After execution of the FOC algorithm
45. ce inputs for two PID controllers one to control the current component of the motor torque and the other to control the magnetizing current component Id Two additional menus allow the user to change up to three parameters for each PID in runtime Figure 14 shows an example screenshot used to enter the proportional term P of the torque controller UM0483 Running the demo program Caution Figure 14 LCD screen to set the P term of the Torque PID STM32 Motor Control ACIM IFOC ver 1 0 Torque P 00300 00100 Target 08000 Iq Feedback 00000 Iq Move t 1 Change Finally press either the Key button or the joystick to stop the motor main state machine moves from Run to Stop state The ramp up strategy is illustrated in Figure 15 Basically the actual torque reference reaches the final Target Iq value set with the joystick in the time interval specified in the STARTUP RAMP DURATION parameter defined in MC Control Param h by following a linear ramp After STARTUP RAMP DURATION if valid information from the speed sensor tachometer or encoder is detected the torque reference becomes adjustable on the fly from the joystick On the contrary if no valid information from the speed sensor is detected for example because a problem occurred with speed sensor connections or because the load torque is higher then the value that you set then the final torque reference is kept constan
46. chain you do not need to configure your workspace You can set up your workspace manually for any other toolchain A free kickstart edition of the IAR EWARM C toolchain with a 32Kb limitation can be downloaded from www iar com it is sufficient to compile and evaluate the software library presented here Software tools A complete software package consists of eA third party integrated development environment IDE eA third party C compiler This library was compiled using the third party IAR C toolchain e JTAG interface for debugging and programming Using the JTAG interface of the MCU you can enter in circuit debugging session with most of toolchains Each toolchain can be provided with an interface connected between the PC and the target application Figure 2 JTAG interface for debugging and programming Application board MB525 The JTAG interface can also be used for in circuit programming of the MCU Other production programmers can be obtained from third parties 9 105 Getting started with tools UM0483 1 3 1 3 1 Note 1 3 2 1 3 3 10 105 Library source code Download The complete source files are available for free download on the ST website www stmcu com in the Technical Literature and Support Files section as a zip file It is highly recommended to check for the latest releases of the library before starting any new development and then to verify from time to tim
47. cmax inverter current rating and motor thermal rating usually in order to provide better dynamic response the inverter current rating is higher than that of the machine must be considered and a precise knowledge of motor parameters such as magnetizing inductance Lm rotor leakage inductance Li rotor resistance r is required There are two different field weakening operation regions see Figure 41 e the constant power region where rotor flux is decreased inversely with the speed considering the influence of the voltage drop across Lis while slip frequency increases until breakdown value e the constant power speed region where rotor flux is decreased but keeping the slip frequency fixed at breakdown value UM0483 Library functions Figure 41 Torque vs speed characteristic curve Torque characteristic Constant Torque region Constant Power region e 00 Constant Power Speed j region rTrrrtt tow rT ert To oT tea oo ed eo N N N Speed Per Unit Torque Per Unit o o AR o e ho 0 In order to help you select the most suitable values of flux reference and torque saturation as needed by the CalcRotFlxSlipFreq function a spreadsheet is available to be filled out with the following system parameters e Mains AC voltage rms Volt cell B1 Volt e motor rated current peak amplitude cell B2 Ampere as said before this data is to be
48. ctors Figure 28 V and Vz stator voltage components 0 5 4 0 3 0 1 Vbeta Valfa Figure 29 SVPWM phase voltages waveforms 100 NOE E NE 90 80 70 60 50 40 30 20 10 0 Jac a et 0 60 120 180 240 300 360 Phase A Phase B Phase C Sector 1 Sector2 Sector3 Sector 4 Sector5 Sector 6 ky UM0483 Library functions 4 2 4 With the following definitions for U 3x Tx Vara Ug Tx Vpeta and X Ug _ Us Ug Ug UR 2 NER Y and Z literature demonstrates that the space vector sector is identified by the conditions shown in Table 1 Table 1 Sector identification Y lt 0 Y20 Z lt 0 Z gt 0 Z lt 0 Zz20 X lt 0 X gt 0 X lt 0 X gt 0 Sector V IV III VI II The duration of the positive pulse widths for the PWM applied on Phase A B and C are respectively computed by the following relationships _T X Z Sector I IV t4 5 et ta tZ to tg X T Y Z Sector Il V mm gt te ee to ta Y Sector Ill VI t a ERU tp te X te ta Y where T is the PWM period QVE ty gS ee ee to tou p Now considering that the PWM pattern is center aligned and that the phase voltages must be centered at 5096 of duty cycle it follows that the values to be loaded into the PWM output compare registers are given respectively by Tolg 2 X Z Sector I IV TimePhA 4 2 TimePhB TimePhA Z TimePhC
49. d TB Set Delay 500us u16 void TB Set DisplayDelay 500us u16 void TB Set StartUp Timeout u16 void TB Set DebounceDelay 500us These functions are used to respectively update the values of the hTimebase 500us hTimebase display 500us hStart Up TimeBase 500us and hKey debounce 500us variables They are used to maintain the main state machine in Fault state to set the refresh rate of the LCD the Startup timeout and to filter the user key bouncing Unsigned 16 bits None None TB StartUp Timeout IsElapsed TB Delay IsElapsed TB DisplayDelay IsElapsed TB DebounceDelay IsElapsed Synopsis Description Input Returns Functions called bool TB StartUp Timeout IsElapsed void bool TB Delay IsElapsed void bool TB DisplayDelay IsElapsed void bool TB DebounceDelay IsElapsed void These functions return TRUE if the related delay is elapsed FALSE otherwise None Boolean None 87 105 Library functions UM0483 4 11 4 11 1 4 11 2 88 105 SysTickHandler Synopsis Description Input Returns Functions called Note void SysTickHandler void This is the System Tick timer interrupt routine It is executed every 500us as determined by TB_Init and is used to refresh various variables used mainly as counters for example PID sampling time Moreover this routine implements the startup torque ramp described in Section 3 Running the demo program on page 24 None None IFOC_CalcFluxTorqu
50. dered reliable rolling averages cannot be computed Output Boolean TRUE if the tacho provides clean signals Caution Because there is no way to differentiate rotation direction with a tachogenerator you must be aware that this routine may return TRUE in certain conditions re start with very short or no stop time and high inertia load You should therefore manage a minimal amount of time before re starting This function is not effective if the startup duration time for the voltage to settle is much shorter than the time needed to obtain at least two consecutive speed data ky 75 105 Library functions UM0483 4 7 2 4 7 3 76 105 TIMx IRQHandler Synopsis void TIMx_IRQHandler void Description This function handles e the capture event interrupt in charge of tacho signal period measurement It updates an array where the 4 latest period measurements are stored resets the overflow counter and updates the clock prescaler to optimize the accuracy of the measurement If the average is enabled the last captured measurement is copied into the whole array Period captures are managed as follows If too low capture value below 0x5500 the clock prescaler is decreased for the next measurement ftoo high for example the timer overflowed the result is re computed as if there was no overflow and the prescaler is increased to avoid overflows during the next capture e the overflow of the timer in charge of
51. description function CalcRotFlxSlipFreq see CalcRotFlxSlipFreq function description evaluates rotor flux slip frequency relying on known rotor time constant if using a tachogenerator the rotor flux position 8 is calculated by integrating the sum of a and rotor electrical speed Figure 39 while with an incremental encoder 6 is determined by summing the rotor electrical angle and the integral of Figure 38 None None 55 105 Library functions UM0483 56 105 Functions called Figure 38 Calclm CalcRotFIxSlipFreq Clarke Park RevPark Circle Limitation PID Torque Regulator PID Flux Regulator Rev Park If working with encoder ENC Get Electrical Angle if Working with tachogenerator TAC_GetRotorFreq if working with ICS SVPWM_lIcsGetPhaseCurrentValues SVPWM_IcsCalcDutyCycles if working with three shunt SVPWM_3ShuntGetPhaseCurrentValues SVPWM_3ShuntCalcDutyCycles Rotor flux angle calculation quadrature encoder 6 calculation uncompensated flux response controller ai14790 Figure 39 Rotor flux angle calculation tachogenerator 6 calculation uncompensated flux response controller electrical degrees OO ai14791 UM0483 Library functions IFOC_CalcFluxTorqueRef Synopsis void IFOC_CalcFluxTorqueRef void Description This function provides curr
52. e flux and speed regulation are used See PID_TORQUE_Kx_DEFAULT PID_FLUX_Kx_DEFAULT PID_SPEED_Kx_DEFAULT in the MC control Param h file To disable the linear curve computation routine in stm32 10x_Timebase c void SysTickHandler void el if State RUN if wGlobal Flags amp CLOSED LOOP CLOSED LOOP Ls PID Speed Coefficients update hRot Freq Hz to be commented out ss Main interrupt service routines stm32 10x it module Overview The stm32f10x it module can be used to describe all the exception subroutines that might occur within your application When an interrupt happens the software will automatically branch to the corresponding routine accordingly with the interrupt vector table With the exception of the ADC and TIM1 Break Input interrupt requests all the routines are empty so that you can write your own code for exception handlers and peripheral interrupt requests List of non empty interrupt service routines As mentioned above only two interrupts are managed by motor control tasks e TIMi1_BRK_IRQHandler on page 85 e TIM1 UP IRQHandler on page 85 e ADC IRQHandler on page 85 UM0483 Library functions 4 10 4 10 1 TIM1 BRK IRQHandler Synopsis Description Input Returns Functions called See also void TIM1_BRK_IRQHandler void The purpose of this function is to manage a break input signal on the dedicated BRK IN pin
53. e 55 Torque flux control loop block diagram 1 ee 98 Figure 56 Speed control loop block diagram 0 0 cette eee 99 Figure 57 Block diagram of PI Controller 0 00000 cece tee eee 100 Figure 58 Closed loop block diagram l i eh 100 Figure 59 Pole zero cancellation 0 cee e 101 Figure 60 Block diagram of closed loop system after pole zero cancellation 101 ky 7 104 UM0483 Note 8 105 AC IM IFOC software library V1 0 features CPU running at 72 MHz e Supported speed feedback Tachogenerator Quadrature incremental encoder e Current sampling method 2isolated current sensors ICS Sshuntresistors placed on the bottom of the three inverter legs e DAC functionality for tracing the most important software variables e Current regulation for torque and flux control PID sampling frequency adjustable up to the PWM frequency Speed control mode for speed regulation e Torque control mode for torque regulation e 16 bit space vector PWM generation frequencies PWM frequency can be easily adjusted Centered PWM pattern type 11 bits resolution at 17 6 kHz Free C source code and spreadsheet for look up table generation CPU load below 30 IFOC algorithm refresh frequency 14 4 kHz Software library developed in accordance with MISRA 2004 C rules Code size 21 KB three shunt resistors for current reading tachogenerator for speed feedb
54. e all release notes to be aware of any new features that might be of interest for your project Registration mechanisms are available on ST web sites to automatically obtain updates File structure The AC IM IFOC software library contains the workspace for the IAR toolchain Once the files are unzipped the following library structure appears as shown in Figure 3 Figure3 File structure C3 STM32 FOC Firmware Libraries v1 0 C3 STM32 FOC ACIM E C EWARM inc src C3 STM32 FOC PMSM Q E C STM32F10xFWLib The STM32 FOC Firmware Libraries v1 0 folder contains the firmware libraries for running 3 phase AC induction motors with sensors and 3 phase PMSM motors with sensors or sensorless The STM32F10xFWLib folder contains the standard library for the STM32F103xx The inc folder contains the header and the src folder contains the source files of the motor control library Finally EWARM folder contains the configuration files for the IAR toolchain Starting the IAR toolchain When you have installed the toolchain you can open the workspace directly from the dedicated folder by double clicking on the STM32_FOC_ACIM eww file The file location is STM32_ FOC ACIM SR EWARM STM32 FOC_ACIM eww UM0483 Getting started with tools 1 4 1 4 1 Customizing the workspace for your STM32F103xx derivative The AC IM IFOC software library was written for the STM32F103VB Howeve
55. e defined in all cases define ROTOR TIME CONSTANT Define here in us the rotor open circuit time constant of the motor 1 B La tL where L is the magnetizing inductance L is the rotor leakage inductance L is the rotor inductance r is the rotor resistance define POLE PAIR NUM Define here the stator winding pole pair number define RATED FREQ Define here in 0 1Hz the right hand boundary of the constant torque region see Figure 7 in that region we have rated current rated flux rated torque rated power define NOMINAL FLUX Define here the required magnetizing current im positive peak value expressed in q1 15 format see Section A 3 on page 95 define NOMINAL_TORQUE Defines the maximum value for the motor s rated torque expressed in q1 15 format 21 105 Getting started with the library UM0483 Note 2 3 22 105 Figure 7 Torque vs speed characteristic curve 1 2 Constant Torque region Constant Power region Constant Power Speed j region 0 4 Torque Per Unit eo o 0 2 T T T T T T T T TH T T T T T T TTT TTHTHTHTHTT THTT HEHTTHT HTHTTHT IH N N N Speed Per Unit 0 The following parameters are required only to enter the field weakening operation constant power region begins beyond the RATED FREQ boundary mentioned above tdefine FLUX REFERENCE TA
56. e frequency 1 define F 1 50 5 Hz mechanical define Ki F 1 2000 Intermediate frequency 1 coefficient settings define Kp F 1 1000 define Kd F 1 2500 Settings for intermediate frequency 2 define F 2 200 20 Hz mechanical define Ki F 2 1000 Intermediate frequency 2 coefficient settings define Kp F 2 750 define Kd F 2 1200 Settings for max frequency define Freq Max 500 50 Hz mechanical define Ki Fmax 500 Frequency max coefficient settings define Kp Fmax 500 define Kd Fmax 500 Once the motor is running integer proportional and derivative coefficients are computed following a linear curve between F min and F 1 F 1 and F 2 F 2 and F max see Figure 49 Note that F min F 1 F 2 F max are mechanical frequencies with 0 1 Hz resolution for example F 1 1234 means F_1 123 4Hz Figure 49 Linear curve for coefficient computation Ki Kp Kd KEE 2 KD F2 Kd E2 I ex s Ki Fmax Kp Fmax Kd Fmax Ki F1 Kp F1 Kda Fi f Ki_Fmin Kp_Fmin Kd_Fmin A Rotor mechanical F_min F 1 F2 F max frequency 83 105 Library functions UM0483 4 9 4 9 1 4 9 2 84 105 Disabling the linear curve computation routine stm32 10x_Timebase module If you want to disable the linear curve computation you must comment out the PID_Speed_Coefficients_update routine In this case the default values for Ki Kp Kd for torqu
57. e rotor flux exactly on the d axis we will have d 0 Ag X With this choice the electromagnetic torque can be written as 3 p Lm Aro ur Te ia ee p A las i e as a product of a flux and a current component P number of stator poles Let us investigate further on the rotor flux Ag Considering the d axis rotor flux equation 445 Lyig Lu ar i iM iore m ds then the equation for is is ij 1 r Combining the latter with the d axis rotor voltage equation leads to di dt fr Ar Ar L x ar Linlds ar Ar d Adr 1 Mar 1 Ar x T XI where 1 is the rotor time constant 1 L ry ThefSlore a lag in flux response is caused to this first order transfer function between YE and Agr The Calclm routine performs a numerical integration using Euler s method which for a first order ODE written as y f ty may be summarized in this way y y At f t y where t is the sampling time Putting the equation above in the explicit form we have s lx m A A A Lim Jnet omn tr ems On the other hand under the same conditions the q axis rotor flux equation becomes Ac sib es KU i 0 59 105 Library functions UM0483 4 4 4 60 105 ll i i igs i So the equation for igr is ig L las Combining the last with the q axis rotor voltage equation leads to vu r L Ar ree od ak Ar a ry m Qj O 0 M o PAM las Adr dr This equation im
58. eRef TB_ClearFlag If Encoder is used ENC Get Average Speed If Tacho is used TAC_GetRotorFreqinHz This is an interrupt routine Routines for monitoring and handling the system critical parameters MC_MotorControl_Layer module Overview This module brings together additional functions that take into account various tasks related to preliminary motor operations like software initializations ADC calibrations parameter monitoring and critical fault checks and managements List of available functions MCL_Init on page 89 MCL_Init_Arrays on page 89 MCL_Chk_OverTemp on page 89 MCL_Chk_BusVolt on page 90 MCL_SetFault on page 90 MCL_ChkPowerStage on page 90 MCL_ClearFault on page 90 MCL Compute BusVolt on page 91 MCL Compute Temp on page 91 UM0483 Library functions MCL_Init Synopsis void MCL_Init void Description This function implements the motor control initializations to be performed at each motor startup it affects the initialization of PID regulators ADC calibration speed sensors and high side driver boot capacitors Functions called PID_Reset_integral_terms ENC_Clear_Speed_Buffer or alternatively TAC_InitTachoMeasure IFOC Init TB Set StartUP Timeout TIM1_CtrlPWMOutputs TB StartUp Timeout IsElapsed SVPWM SShuntCurrentReadingCalibration or alternatively SVPWM lcsCurrentReadingCalibration Note When in Speed control mode the Torque profile in this function is initialized for motor startup se
59. ead Carefully Information in this document is provided solely in connection with ST products STMicroelectronics NV and its subsidiaries ST reserve the right to make changes corrections modifications or improvements to this document and the products and services described herein at any time without notice All ST products are sold pursuant to ST s terms and conditions of sale Purchasers are solely responsible for the choice selection and use of the ST products and services described herein and ST assumes no liability whatsoever relating to the choice selection or use of the ST products and services described herein No license express or implied by estoppel or otherwise to any intellectual property rights is granted under this document If any part of this document refers to any third party products or services it shall not be deemed a license grant by ST for the use of such third party products or services or any intellectual property contained therein or considered as a warranty covering the use in any manner whatsoever of such third party products or services or any intellectual property contained therein UNLESS OTHERWISE SET FORTH IN ST S TERMS AND CONDITIONS OF SALE ST DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY WITH RESPECT TO THE USE AND OR SALE OF ST PRODUCTS INCLUDING WITHOUT LIMITATION IMPLIED WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND THEIR EQUIVALENTS UNDER THE LAWS OF ANY JURISDICTION OR
60. ent components iqs and ids to be used as reference values by the IFOC_Model function in Speed control mode see Torque amp Flux optimization block in Figure 40 Speed setpoint and actual rotor speed y are compared in a PID control loop whose output is iqs This component together with the previous flux reference and the rotor speed a is used to work out the stator frequency that has to be generated With this information two lookup tables described in MC ACmotor prm Section 2 2 5 defined by taking into account the field weakening strategy explained in Section 4 4 4 are run through in order to get the optimal flux reference ids and the saturation value of the torque current component iqs max that allow to reach the desired speed under the obvious limitations of rated torque and rated power Input None Returns None Functions called PID Speed Regulator mul q15 q15 q31 div q31 q15 q 5 Figure 40 Torque and flux optimization block IFOC drive Speed reference or profile generator optimization Ay 3 phase induction motor actual rotor speed or Speed reading M ai14787 57 105 Library functions UM0483 CalciIm Synopsis Description Input Returns Functions called s16 Calclm s16 hld input The purpose of this routine is to supply to the calling function the estimated value of the rotor flux as a response to var
61. enu in LCD is shown for selecting the two variables to be output on the PWM channels Refer to Section 2 3 for more details Once these settings have been done only the required blocks will be linked in the project this means that you do not need to exclude c files from the build When using shunt resistors for current measurement ensure that the REP RATE parameter in MC Control Param h is set properly see Section 2 2 2 and Section A 2 Selecting the update repetition rate based on PWM frequency for 3 shunt resistor configuration on page 93 for details 15 105 Getting started with the library UM0483 2 2 2 16 105 Drive control parameters MC_Control_Param h The MC Control Param h header file gathers parameters related to Power device control parameters on page 16 Flux and torque PID regulators sampling rate on page 16 Power board protection thresholds on page 16 Speed regulation loop frequency on page 17 Speed controller setpoint and PID constants initial values on page 17 Torque and flux controller setpoints and PID constants on page 18 Startup torque ramp parameters on page 18 Linear variation of PID constants according to mechanical speed on page 18 Power device control parameters define PWM FREQ Define here in Hz the switching frequency in parallel uncomment the maximum allowed modulation index definition MAX MODULATION XX PER CENT corresponding to the PWM
62. epends on the selected PWM frequency a number of look up tables are stored in MC Clarke Park c with MMI ranging from 92 to 100 Once you have selected the required PWM switching frequency you should uncomment the Max Modulation Index definition corresponding to the selected PWM frequency in the MC Control Param h definitions list shown below define MAX MODULATION 100 PER CENT up to 11 4 kHz PWM frequency define MAX MODULATION 99 PER CENT up to 11 8 kHz define MAX MODULATION 98 PER CENT up to 12 2 kHz define MAX MODULATION 97 PER CENT up to 12 9 kHz define MAX MODULATION 96 PER CENT up to 14 4 kHz define MAX MODULATION 95 PER CENT up to 14 8 kHz define MAX MODULATION 94 PER CENT up to 15 2 kHz define MAX MODULATION 93 PER CENT up to 16 7 kHz define MAX MODULATION 92 PER CENT up to 17 1 kHz define MAX MODULATION 91 PER CENT up to 17 5 kHz For information on selecting the PWM switching frequency you will find advice in Section A 2 on page 93 To determine the max modulation index corresponding to the PWM switching frequency refer to Table 2 on page 49 Encoder feedback processing stm32 10x encoder module List of available functions and interrupt service routines The following is a list of available functions as listed in the stm32 10x_encoder h header file
63. ge the default ones refer to MB459 included in the STM3210B MCKIT kit and correspond to 19 V for the lower voltage and 350 V for the maximum voltage If the bus voltage exceeds ky UM0483 Getting started with the library the upper threshold an overvoltage fault event is validated If the bus voltage is below the lower threshold an undervoltage fault event is triggered If either of the two faults occurs the motor is stopped and the display shows an error message Note REP_RATE must be an odd number if currents are measured by shunt resistors see Section A 2 Selecting the update repetition rate based on PWM frequency for 3 shunt resistor configuration on page 93 for details its value is 8 bit long Speed regulation loop frequency define PID SPEED SAMPLING TIME The speed regulation loop frequency is selected by assigning one of the defines below define PID SPEED SAMPLING 500us 0 min 500us define PID SPEED SAMPLING 1ms a define PID SPEED SAMPLING 2ms 3 4 1 500gus 2ms define PID SPEED SAMPLING _5ms 9 define PID SPEED SAMPLING 10ms 19 define PID SPEED SAMPLING 127ms 255 max 255 1 500us 127ms Speed controller setpoint and PID constants initial values define PID SPEED REFERENCE Define here in 0 1Hz the mechanical rotor speed setpoint at startup in closed loop mode e define PID SPEED KP DEFAULT The pr
64. hClockCmd GPIO Structlnit GPIO Init GPIO PinRemapConfig TIM1 Delnit TIM1 TimeBaseStructlnit TIM1 TimeBaselnit TIM1 OCStructlnit TIM1_OC1 Init TIM1 OCa2lnit TIM1 OCSInit TIM1_BDTRConfig TIM1 SelectOutputTrigger TIM1_ClearlTPendingBit TIM1 ITConfig TIM1 Cmd ADC Delnit ADC Cmd ADC Structlnit ADC Init ADC StartCalibration ADC GetCalibrationStatus ADC InjectedSequencerLengthConfig ADC_InjectedChannelConfig ADC ExternalTrigInjectedConvCmd NVIC_PriorityGroupConfig NVIC Structlnit NVIC Init Motor control library SVPWM lIcsCurrentReadingCalibration SVPWM IcsCurrentReadingCalibration Synopsis Description Input Returns Note Functions called void SVPWM IcsCurrentReadingCalibration void The purpose of this function is to store the two analog voltages corresponding to zero current values for compensating the offset introduced by both ICS and amplification network None None This function is called by MCL Init which is executed at every motor startup It reads the analog voltage on the A D channels used for current reading before the PWM outputs are enabled so that the current flowing through the inverter is zero Standard Library ADC ITConfig ADC ExternalTrigInjectedConvConfig ADC ExternalTrigInjectedConvCmd ADC InjectedSequencerLengthConfig ADC InjectedChannelConfig ADC SoftwareStartlnjectedConvCmd ADC_GetFlagStatus ADC GetlnjectedConversionValue Motor Control library SVPWM
65. he best results Caution This routine returns the mechanical frequency of the rotor To find the electrical speed use the following conversion electrical frequency mechanical frequency number of pole pairs ky UM0483 Library functions TAC GetRotorFreq Synopsis u16 TAC_GetRotorFreq void Description This routine returns rotor frequency with a unit that can be directly integrated accumulated to get the rotor angular position in the main control loop Input None Output Rotor mechanical frequency with rad PWM period unit 21 rad OXFFFF assuming the control loop is executed in each and every PWM interrupt service routine Functions called GetAvrgTachoPeriod GetLastTachoPeriod both private functions Note Result is zero if speed is too low glitches at start for instance Excessive speed or glitches will result in a pre defined value returned see Section 2 2 4 on page 19 Maximum expectable accuracy depends on CKTIM 72 MHz will give the best results GetLastTachoPeriod Synopsis u32 GetLastTachoPeriod void Description This routine returns the rotor period based on the last tacho capture Input None Output Tacho signal period unit is 1 CKTIM period unsigned 32 bit format Functions called None Note This function is private to the stm32f10x_tacho c module GetAvrgTachoPeriod Synopsis u32 GetAvrgTachoPeriod void Description This routine returns the rotor period based on the average of the fou
66. he latest speed measurement if it is out of the range specified in MC encoder param h then the error counter is incremented and the speed is saturated Furthermore if the error counter is higher than MAXTMUM ERROR NUMBER the boolean variable storing the error status is set Finally the new average value is computed based on the latest SPEED BUFFER SIZE speed measurement ENC Calc Rot Speed None None ENC ErrorOnFeedback Synopsis Description Functions called Input Returns bool ENC ErrorOnFeedback void This function simply returns the status of the boolean variable containing the speed measurement error status which is updated every SPEED MEAS TIMEBASE ms by the ENC Calc Average Speed function In the proposed firmware library this function is called in Run state by the main to check for possible faults of the speed feedback such as disconnected encoder wires None None boolean TRUE if an error occurred FALSE otherwise UM0483 Library functions TIMx IRQHandler interrupt routine Synopsis void TIMx IRQHandler void Description This is the encoder timer TIMER 2 3 or 4 update routine An interruption is generated whenever an overflow underflow of the counter value occurs TIMx CNT The Encoder Timer Overflow variable is then incremented Functions called None Note This is an interrupt routine See also
67. iations of the input current value in see uncompensated flux response controller block in Figure 38 and Figure 39 See Section 4 4 3 for in depth information about the computations implemented Stator current ig in q1 15 format Magnetizing current im defined as rotor flux X divided by magnetizing inductance L in q1 15 format mul q15 q15 q31 MC qmath h CalcRotFlxSlipFreq Synopsis s32 CalcRotFIxSlipFreq s16 hlq input s16 hlm input Description This function estimates the rotor flux slip frequency r central block in Figure 38 and Figure 39 as result of currents d and im Qa Las See Section 4 4 3 for an in depth comprehension of the implemented computations Input Stator current igs and magnetizing current im both in q1 15 format Returns Rotor flux slip frequency expressed in pulses per PWM period Functions called 4 4 3 65536 65536 pulses 2n radiants mul_q15_q15_q31 div q31 q15 q15 MC_qmath h Detailed explanation about indirect field oriented control IFOC Consider the voltage equations of an induction machine being transformed on a reference frame q d that is synchronous with the rotor flux A about reference frame theory see 1 in Appendix A 7 References on page 102 58 105 r di r qr UM0483 Library functions where EA I ud i SLi LU i i Lulu iu a Lit i By choosing the phase of the reference system in such a way to arrange th
68. if sensor output signal is wired to TimerX Input Capture 2 define MAX SPEED FDBK This parameter defines the frequency above which speed feedback is not realistic in the application this allows to discriminate glitches for example The unit is 0 1Hz By default it is set to 6400 640 0Hz which corresponds to approximately 20000 RPM for a two pole pair motor define MAX SPEED This parameter is the value returned by the function TAC_GetRotorFreqInHz if measured speed is greater than MAX SPEED FDBK The default value is 640Hz but it can be 0 or FFFF depending on how this value is managed by the upper layer software define MAX PSEUDO SPEED This parameter is the value returned by the function TAC_GetRotorFreq if measured speed is greater than MAX SPEED FDBK The unit is rad pwm period 2n rad OxFFFF See Section 4 7 4 Converting Hertz into pseudo frequency on page 78 for more details define MIN SPEED FDBK This parameter is the frequency below which speed feedback is not realistic in the application this allows to discriminate too low frequency This value is set to 1 Hz by default and depends on sensor and signal conditioning stage characteristics Typically the tacho signal is too weak at very low speed to trigger input capture on the MCU The MC tacho prm h file includes two formulas that allow to compute the minimum sensed speed when speed is inc
69. ing flow diagrams Figure 55 and Figure 56 show the decision tree for the computation of the torque flux and speed regulation routines Figure 55 Torque flux control loop block diagram Measured Torque Flux cp Target Torque Flux Torque Flux error signed 16 bit Proportional Kp x Torque Flux Error Is PI output saturated Integral Integral Ki x Torque Flux Error Integral term frozen If enabled Clamp Output value to See Differential Kd x Error Torque Flux n A important Previous Error Torque Flux signed int domain note in section 2 2 1 Output Proportional 2 13 Integral 2 16 Differential terms 2 13 Is Output lt PI D lower lim or gt PI D upper limit Clamp Output value to unsigned PI D lower limit PI D upper limit Set Saturated Output Flag Reset Saturated Output Flag return Output value signed 16 bit UM0483 Additional information Figure 56 Speed control loop block diagram Current speed Target speed Speed error signed 16 bit Proportional Kp x Speed Error Is PI output saturated Integral Integral Ki x Slip Error a Integral term frozen If enabled Clamp Output value to See Differential Kd x Error Speed signed int domain Previous Error Speed important note in section 2 2 1 Output Proportional 2 8 Integral 2 14 Differe
70. ion is to store the three analog voltages corresponding to zero current values for compensating the offset introduced by the amplification network None None This function is called by MCL Init which is executed at every motor startup The function reads the analog voltage on A D channels utilized for current reading before TIM1 outputs are enabled so that the current flowing through the inverter is zero Those values are then stored into Phase x Offset variables Standard library ADC ITConfig ADC_ExternalTrigInjectedConvConfig ADC ExternalTrigInjectedConvCmd ADC InjectedSequencerLengthConfig ADC InjectedChannelConfig ADC SoftwareStartlnjectedConvCmd ADC GetFlagStatus ADC GetlnjectedConversionValue ADC SoftwareStartlnjectedConvCmd Motor control library SVPWM InjectedConvConfig SVPWM 3ShuntGetPhaseCurrentValues Synopsis Description Input Returns Note Functions called Curr Components SVPWM 3ShuntGetPhaseCurrentValues void This function computes current values of Phase A and Phase B in q1 15 format starting from values acquired from the A D Converter peripheral None Curr Components type variable In order to have a q1 15 format for the current values the digital value corresponding to the offset must be subtracted when reading phase current A D converted values Therefore the function must be called after SVPWM_3ShuntCurrentReadingCalibration None UM0483 Library functions S
71. is done for K coefficients Figure 58 shows the closed loop system in which the motor phase is modeled using the resistance inductance equivalent circuit in locked rotor condition Block A converts the Voltage command software digital value into the applied stator voltage V and block B converts the real motor current into the Measured current software digital value Figure 58 Closed loop block diagram Voltage command Target current Measured current ai14851 The transfer functions of the two blocks A and B are expressed by the following formulas ky UM0483 Additional information 16 Vp aDC R A 2 A AR and B c ee respectively 2 By putting Kp K Ls Rs it is possible to perform pole zero cancellation as described in Figure 59 Figure A6 3 Figure 59 Pole zero cancellation Voltage command Target current Measured current ai14852 In this condition the closed loop system is brought back to a first order system and the dynamics of the system can be assigned using a proper value of K See Figure 60 Figure 60 Block diagram of closed loop system after pole zero cancellation Target n current V l Target 1 1 current Hos R B 1 Ss K AB B ai14853 It is important to note that the Kj and Kp parameters used inside the PI alg
72. its MCL Compute Temp Synopsis u8 MCL Compute Temp void Description This function computes the power stage heatsink temperature in Celsius degrees Returns An integer representing a temperature value expressed in Celsius degrees Application layer Besides the implementation of the motor control state machine the application layer main c module includes the configuration and initialization of basic peripherals Moreover in this layer the LCD display and user input keys are managed by means function calls belonging to two other modules These modules are briefly described below MC Keys c module Centralizes all information regarding the keyboard reading Any action on the keyboard is processed in the Keys process routine MC Display module Centralizes all information regarding the LCD display management e stm32f10x lcd module Contains some dedicated routines for the control of the LCD embedded with the starter kit 91 105 Additional information UM0483 Appendix A Additional information A 1 92 105 Adjusting CPU load related to IFOC algorithm execution The advanced control timer TIM1 peripheral has the built in capability of updating PWM registers only after a given number of PWM semi periods This feature is handled by a programmable repetition counter It is particularly useful to adjust the CPU load related to IFOC algorithm execution for a given PWM frequency refer to STM32F103xx reference
73. kefile and linking command files are automatically generated When rebuilding the library the configuration files are updated accordingly Figure 8 Adding anew module AR Embedded Workbench IDE BS SIE File Edit View Project Tools Window Help n uWgisiseel il ACY SER ed Mee gt EN Private funcblang nnnm estt 66 E ERE EPA geo tol B 5 5RRRRRRERRRRRESRRRERRERERRRRRRRRRRRRERERRERRRRER ERE kk RR E EWARM es 68 Function Name main include Make Ha C3 source Compile 70 Input None i main c Rebuild All 71 Output None B MC Clarke Park c Clean 72 Return None 1 i 1 i i i i H i 1 H 69 Description Main program i i 1 1 i f 73 eoe deese eode ode dee ede de ee eode e de e e e ede ee de ede e e e ede ee e de de eee ede ee e e e e t x xt xx i i 74 void main void Add main c 2 MC IFOC Drive c MC Keys c MC_MotorControl_ MC PID regulator Source Code Control a ee ee Remove 79 endif 80 81 RCC Configuration 82 GPIO Configuration stm32fl x encode 83 NVIC Configuration i stm3 2f10x lcd c stm32fl x MCdac Setas Actve E stm32fl Ox_svpwm_Jsnont E stm32f1 0x svpwm ics c F stm32f10x tacho c 2 stm32f10x Timebase c File Properties ITTTETET 65 ifdef THREE SHUNT 86 SVPWM_3ShuntInit 3TM321 OxPWLIB 87 elif defi
74. lIcslnjectedConvConfig 51 105 Library functions UM0483 SVPWM_IcsGetPhaseCurrentValues Synopsis Curr Components SVPWM_IcsGetPhaseCurrentValues void Description This function computes current values of Phase A and Phase B in q1 15 format from the values acquired from the A D converter Input None Returns Curr Components type variable Note In order to have a q1 15 format for the current values the digital value corresponding to the offset must be subtracted when reading phase current A D converted values Thus the function must be called after SVPWM lIcsCurrentReadingCalibration Functions called None SVPWM IcsCalcDutyCycles 4 3 3 52 105 Synopsis void SVPWM lIcsCalcDutyCycles Volt Components Stat Volt Input Description After execution of the IFOC algorithm new stator voltages component Va and Vg are computed The purpose of this function is to calculate exactly the three duty cycles to be applied to motor phases from the values of these voltage components Refer to Section 4 2 3 for details about the theoretical approach of SVPWM and its implementation Input Va and Vg Returns None Note None Functions called None Current sampling in isolated current sensor topology and integrating general purpose A D conversions The three currents l4 lo and I5 flowing through a three phase system follow the mathematical relationship 14 lo 1g 0 Therefore to reconstruct the currents flowing through a
75. ld oriented conditions can control machine torque and flux respectively are defined outside this function in Speed control mode they are provided by means of speed and flux regulators by the IFOC_CalcFluxTorqueRef function while in Torque control mode they are settled by the user Therefore as a current source is required the function has to run the power converter as a CR PWM For this purpose it implements a high performance synchronous d q frame current regulator whose operating frequency is defined as explained in Section 2 2 2 by the parameter REP RATE in conjunction with PWM FREQ Triggered by ADC JEOC ISR the function loads stator currents read by ICS or shunt resistors and carries out Clark and Park transformations converting them to ig and igs see Figure 6 Then these currents are fed to PID regulators together with reference values igs and ig The regulator output voltages Naar and vM then must be transformed back to a stator frame through Reverse Park conversion and finally drive the power stage In order to correctly perform Park and Reverse Park transformation it is essential to accurately estimate the rotor flux position 9 because currents have to be oriented in phase and in quadrature with rotor flux To manage this task function Calclm is called to provide Im that is the estimated value of the rotor flux as a response to the variation of input current i see Calclm function
76. led is displayed on the LCD In this case it is strongly advised to check speed sensor feedback connections first and then if necessary to increase STARTUP FINAL TORQUE if the load torque is too high With reference to Figure 21 note that parameters TACHO SPEED VAL ENCODER CL ENABLE STARTUP FINAL TORQUE STARTUP RAMP DURATION and STARTUP TIMEOUT are fully configurable so that you can customize the startup depending on the motor and load conditions Parameters definitions are done in the MC Control Param h header file Figure 21 Speed control startup strategy Torque reference Mak anl Lu eA E eme ttd ces Uu m eo tic imn et torque STARTUP FINAL STARTUP RAMP DURATION STARTUP TIMEOUT t Speed Target speed 7 set by joystick TACHO SPEED VAL ______ ENCODER CL ENABLE Closed Loop t enabled Output IFOC variables using a 2 channel DAC In the stm32 10x_MCconf h configuration file if the DAC FUNCTIONALITY option is uncommented two variables can be output by using the PWM outputs of the TIM3 timer channels 3 and 4 on the PBO and PB1 microcontroller pins The PWM duty cycles are then mapped to the actual value of the variable the user would like to see By using an external RC low pass filter the averaged value of the PWM signal will represent the digital value of ky UM0483 Running the demo program
77. lows the system to measure stator currents correctly using either cheap shunt resistors or market available isolated current hall sensors ICS e Thespeed reading block handles tachogenerator or incremental encoder signals in order to acquire properly rotor angular velocity or position 13 105 Getting started with the library UM0483 2 2 14 105 The PID controller block implements a proportional integral and derivative feedback controller to achieve speed torque and flux regulation Figure 6 FOC structure rotor flux stator stator d gframe d q frame a b c frame IFOC model re AEDEM X NC COLE command i ias Reverse pwm signal Flux ParkT fva vB CALC va vb vc command ods amp circle limitation Clarke Current reading a Speed reading 9 calculation Saucen sete yas acca carn Edi Su xiu eui Eee ue teu ue eine MER CERES ae S 2i14787 How to customize hardware and software parameters It is quite easy to set up an operational evaluation platform with a drive system that includes the STM3210B MCKIT featuring the STM32F103xx microcontroller where this software runs and an AC induction motor This section explains how to quickly configure your system and if necessary customize the library accordingly Follow these steps to accomplish this task 1 Gather all the information that is needed regarding
78. m KANAN KANE ee oe Yon m Rn n 85 4 10 2 List of available functions and interrupt service routines 86 4 11 Routines for monitoring and handling the system critical parameters MC MotorControl Layer module 88 4411 LOVEIVIOW i soris mete caedes rl cot geb de Een edel Re erben s 88 4 11 2 List of available functions 0 0 02 00 eee 88 4 12 Application layer issues oko vh er EE EE See ee Ree Sees 91 Appendix A Additional information eeslseleeeeeeeee 92 A 1 Adjusting CPU load related to IFOC algorithm execution 92 A 2 Selecting the update repetition rate based on PWM frequency for 3 shunt resistor configuration 000 93 A 3 JFixed point numerical representation lille 95 A 4 Tacho based speed measurement flow charts 04 96 AS JPIDDblockdiagrams s s sasa zu c Res ce Ee eer RR e Ere geese 98 A 6 A priori determination of flux and torque currents Pl gains 100 A 7 References 0 00 ccc eee 102 REVISION history sistas aa dE dE RERO RA REESE Y R3 CER CR QR code log a 103 4 104 UM0483 List of tables List of tables Table 1 Sector identification 0 0 n 43 Table 2 PWM frequency vs maximum duty cycle relationship llle 49 Table 3 PWM frequency vs maximum duty cycle relationship llli 67 Table 4 Document revision history 0 cece eee ae 103 ky 5 105 Lis
79. matched with inverter current rating motor rated magnetizing current peak amplitude cell B3 Ampere magnetizing inductance Lm cell B4 Henry leakage inductance Ljs Li cell B5 Henry stator resistance rs cell B6 Ohm rotor resistance r cell B7 Ohm maximum measurable current Imax peak amplitude cell BB Ampere As a result of data processing the following information can be obtained e highest frequency of constant torque region i e the maximum allowable frequency before entering field weakening content of cell B13 should be inserted as parameter RATED FREQ in MC ACMotor Prm h see Section 2 2 5 reference values of igs in q1 15 format according to increasing stator frequency column P should be copied as FLUX REFERENCE TABLE in MC ACMotor Prm h e saturation values of current component igs in q1 15 format according to increasing stator frequency column Q should be copied as TORQUE REFERENCE TABLE in MC ACMotor Prm h 61 105 Library functions UM0483 4 5 4 5 1 4 5 2 62 105 Reference frame transformations MC_Clarke Park module Overview This module intended for AC machines induction synchronous and PMSWM is designed to perform transformations of electric quantities between frames of reference that rotate at different speeds Based on the arbitrary reference frame theory the module provides three functions named after two pioneers of electric machine analysi
80. members of the variable Curr Input which is a structure of type Curr Components Stator currents i and ig in q1 15 format as members of a structure of type Curr Components mul q15 q15 q31 Curr Components Park Curr Components Curr Input s16 Theta The purpose of this function is to transform stator currents i and ig which belong to a stationary o B reference frame to a rotor flux synchronous reference frame q d properly oriented so as to obtain igs and igs See Section 4 5 3 for details Stator currents i and ig in q1 15 format as members of the variable Curr_Input which is a structure of type Curr_Components rotor flux angle 05 65536 pulses per revolution Stator currents is and igs in q1 15 format as members of a structure of type Curr Components mul q15 q15 q31 63 105 Library functions UM0483 4 5 3 64 105 Rev_Park Synopsis Volt_Components Rev_Park Volt_Components Volt_Input Description This function transforms stator voltage vg and vg belonging to a rotor flux synchronous rotating frame to a stationary reference frame so as to obtain v and ve See Section 4 5 3 for details Input Stator voltages vg and Vas in q1 15 format as members of the variable Volt_Input which is a structure of type Volt_Components Returns Stator voltages v and vg in q1 15 format as members of a structure of type Volt Components Functions called mul q15 q15 q31 Rev Park Circle Limitati
81. n by moving in the joystick up down the active Control mode is selected in this example Torque control After sending the Start motor command by pressing the Joy or Key keys this parameter can no longer be accessed until the motor is stopped 25 105 Running the demo program UM0483 26 105 Figure 12 LCD screen for Target Iq settings STM32 Motor Control ACIM IFOC ver 1 0 Torque ControlMode Target Feedback Iq 08000 00000 Id 093834 00000 Speed rpm 00000 Move t Change From the previous screen Figure 1 1 if the joystick is moved to the right the Target Iq current component is selected The parameter can now be changed by moving the joystick up down After sending the Start motor command the Target Iq can be changed in runtime while the measured Iq current component is shown in the Feedback field Figure 13 LCD screen for Target Id settings STM32 Motor Control ACIM IFOC ver 1 0 Torque ControlMode Target Feedback Iq 08000 00000 Id 09834 00000 Speed rpm 00000 Move t Change From the previous screen Figure 12 if the joystick is moved to the right the Target Id current component becomes selected The parameter can now be changed by moving the joystick up down After the Start motor command the target can be changed in runtime while the measured Id current component is shown in the Feedback field Together the Target Iq and Id currents constitute the referen
82. n c module the DBG gt CR DBG_TIM1_STOP instruction performs the above described task Figure 27 DBG TIM1 STOP bit in TIM1 control register extract from STM32 reference manual DBGMCU CR Address 0xE0042004 Only 32 bit access supported POR Reset 0x00000000 not reset by system reset 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 DBG I2C 2 SMBU Reserved S TIMEO UT Res rw 15 14 13 12 11 10 9 8 7 6 5 4 8 2 1 0 De MG DBG DBG DBG DBG DEG DBG DBG TRACE TRAGE DBG pag pre Soe CAN Tima_ TIMS TIM2_ TIMI WWDG IWDG MODE EN Reserved stanDe DPG DPG QUE STOP STOP STOP STOP STOP STOP STOP 1 0 Y rw rw rw rw rw nw rw rw rw nw rw Res rw rw rw z 37 105 Library functions UM0483 4 4 1 4 2 4 2 1 38 105 Library functions Function description conventions Functions are described in the format given below Synopsis Lists the prototype declarations Description Describes the functions specifically with a brief explanation of how they are executed Input Gives the format and units Returns Gives the value returned by the function including when an input value is out of range or an error code is returned Note Indicates the limits of the function or specific requirements that must be taken into account before implementation Caution Indicates important points that must be take
83. n into account to prevent hardware failures Functions called Lists called functions Useful to prevent conflicts due to the simultaneous use of resources Code example Indicates the proper way to use the function and if there are certain prerequisites interrupt enabled etc Some of these sections may not be included if not applicable for example no parameters or obvious use Current reading in three shunt resistor topology and space vector PWM generation stm32 10x svpwm 3shunt module Overview Two important tasks are performed in the stm32 10x svpwm 3shunt module Space vector pulse width modulation SVPWM e Current reading in three shunt resistor topology In order to reconstruct the currents flowing through a three phase load with the required accuracy using three shunt resistors it is necessary to properly synchronize A D conversions with the generated PWM signals This is why the two tasks are included in a single software module UM0483 Library functions 4 2 2 List of available functions The following is a list of available functions as listed in the stm32 10x_svpwm_3shunt h header file e SVPWM_3ShuntInit on page 39 SVPWM_3ShuntCurrentReadingCalibration on page 40 SVPWM_3ShuntGetPhaseCurrentValues on page 40 SVPWM_3ShuntCalcDutyCycles on page 41 SVPWM_3ShuntAdvCurrentReading on page 41 SVPWM_3ShuntInit Synopsis Description Input Returns Note Functions called void SVPWM 3Sh
84. n is slower and the integral action on the output is delayed Inversely decreasing the loop time increases its effects accumulation is faster and the integral action on the output is increased This is why this parameter has to be adjusted prior to setting up any coefficient of the PID regulator In order to keep the CPU load as low as possible and as shown in equation 1 in Figure 47 the sampling time is directly part of the integral coefficient thus avoiding an extra multiplication Figure 48 describes the link between the time domain and the discrete system 81 105 Library functions UM0483 Note 4 8 5 82 105 Figure 48 Time domain to discrete PID equations Time domain f t Kp x ErroOfsys t Kix J o Errors s dt Kyx S Errors 0 T Discrete Discrete f X Kyx Error s Kx DYErrorsys Kgx Error Error 0 sampling done at Fs 1 Ts frequency pe kx To K In theory the higher the sampling rate the better the regulation In practice you must keep in mind that e The related CPU load will grow accordingly e For speed regulation there is absolutely no need to have a sampling time lower than the refresh rate of the speed information fed back by the external sensors this becomes especially true when a tacho generator sensor is used while driving the motor at low to medium speed As discussed in Section 2 2 2 on page 16 the speed regulation loop sampling time can be c
85. ned ICS SENSORS STM32 FOC ACIM sR E cuu tis Build Find in Files Debug Log CO i_ lt _ lt Add one or more files to the project z 23 105 Running the demo program UM0483 3 24 105 Running the demo program This section assumes that you are using the STM3210B MCKIT motor control kit The demo program is intended to provide examples on how to use the software library functions it includes both Torque control and Speed control operations with the possibility of varying different parameters on the fly The default configuration allows the use of three shunt resistor for stator current reading and tacho generator for speed feedback Refer to Section 3 4 on page 32 for setting up the system when using ICS and to Section 3 5 on page 34 if using quadrature incremental encoder After the MCU initialization phase the LCD graphical display shows the main window Use the joystick and the button labelled KEY to navigate between the menus Key assignments are shown in Figure 9 Figure 9 Key function assignments DATA a FUNCTION e b FUNCTION o b d a c o adt ENTER KEY connected to PB3 DATA A simple state machine handles the motor control tasks in the main loop as well as basic monitoring of the power stage This state machine does not differentiate Torque control mode from Speed control mode It is described in Figure 10 The power stage is monitored
86. ng fqx fax fox are their transformations directed along paths orthogonal to each other the equations of transformation to a reference frame rotating at an arbitrary angular velocity can be expressed as UM0483 Library functions cos cos o 22 cos o 27 fox 3 fax f 2 201 ai 2n f qdox dx 3 sinO sin iniu sin M bx fox fex mi 1 1 2 2 where 9 is the angular displacement of the q d reference frame at the time of observation and 0g that displacement at tO see Figure 43 Figure 43 Transformation from an abc stationary frame to a rotating frame q d ai14793 With Clark s transformation stator currents ias and ips which are directed along axes each displaced by 120 degrees are resolved into currents i and lg on a stationary of reference frame Appropriate substitution into the general equations given above yields la las las 2lps lg B In Park s change of variables stator currents i and ig which belong to a stationary o B reference frame are resolved to a rotor flux synchronous reference frame properly oriented so as to obtain ig and igs Consequently with this choice of reference m r thus igs 15c0s0 igsin0 igs S N ig coso On the other hand reverse Park transformation takes back stator voltage v and vq belonging to a rotor flux synchronous rotating frame to a stationary reference frame so as to obtain v and vg
87. nimum duty cycle period of about 5 21 x 2 us That means a maximum achievable IFOC execution rate of about 19 kHz This allows to set the repetition counter REP RATE equal to 1 Moreover the above stated execution rate is beyond the maximum PWM frequency supported by the firmware For a PWM frequency above 19 kHz a repetition counter of 3 must be used REP RATE 3 UM0483 Additional information A 3 Fixed point numerical representation The AC IM IFOC software library uses fixed point representation of fractional signed values Thus a number nis expressed as n m f where mis the integer part magnitude and f the fractional part and both m and fhave fixed numbers of digits In terms of two s complement binary representation if a variable n requires QI bits to express as powers of two its magnitude of which 1 bit is needed for the sign QF bits as inverse powers of two for its fractional part then we have to allocate QI QF bits for that variable Therefore given a choice of QI and QF the variable representation has the following features e Range 2 Ql 1 lt n lt 2 Qht _ 2CQr e Resolution 1 29F The equation below converts a fractional quantity q to fixed point representation n n floor q 2 A common way to express the choice that has been made is the q QI QF notation So if a variable is stored in q3 5 format it means that 3 bits are reserved for the magnitude
88. nit TIM ClearFlag TIM ITConfig Note The timer starts counting at the end of the routine See also STM32F103xx datasheet general purpose timer TIMx TAC InitTachoMeasure Synopsis void TAC InitTachoMeasure void Description This function clears the software FIFO where the latest speed data are stored This function must be called every time the motor is started to initialize the speed measurement process Input None Output None Functions called TIM ITConfig TIM Cmd Note The first measurements following this function call are done without filtering the rolling average mechanism is disabled See also STM32F103xx datasheet general purpose timer TIMx TAC GetRotorFreqinHz Synopsis u16 TAC_GetRotorFreqInHz void Description This routine returns the rotor frequency with 0 1Hz definition The result is given by the following formula Frotor K X Fosc Capture number of overflow x FFFF where K depends on the number of motor and tacho pole pairs Input None Output Rotor mechanical frequency with 0 1 Hz resolution unsigned 16 bits direction cannot be determined using a tacho Functions called GetAvrgTachoPeriod GetLastTachoPeriod both private functions Note Result is zero if speed is too low glitches at start for instance Excessive speed or glitches will result in a pre defined value returned see Section 2 2 4 on page 19 Maximum expectable accuracy depends on CKTIM 72 MHz will give t
89. ns and vice versa by moving the joystick up or down when the motor is stopped From the menu screen shown in Figure 16 moving the joystick to the right selects the Target speed The parameter can then be incremented decremented by moving the joystick up down respectively The motor is then started by pressing the joystick With the motor on it is still possible to modify the target speed while checking its actual value in the Feedback field Figure 17 LCD screen to set the Target speed STM32 Motor Control ACIM IFOC ver 1 0 Speed Control Mode Target Feedback 03000 rpm 00000 lt gt Move t 1 Change Figure 18 Figure 19 and Figure 20 show the three PID screens from which the coefficient parameters can be entered The screens also display the targets and feedbacks for each value of speed torque and flux From the screens shown in Figure 18 Figure 19 and Figure 20 move the joystick left or right to alternately select the P or D coefficients when present The selected coefficient can then be changed incremented or decremented by moving the joystick up down UM0483 Running the demo program Figure 18 LCD screen for setting P term of Speed PID STM32 Motor Control ACIM IFOC ver 1 0 Speed P I 08000 01000 Target 03000 rpm Feedback 00000 rpm Move t Change Figure 19 LCD screen to set the P term of the Torque PID STM32 Motor Control ACIM IFOC ver 1
90. ntial terms 2 8 Is Output lt PI D lower li or PI D upper limit Clamp Output value to unsigned PI D lower limit PI D upper limit Set Saturated Output Flag Reset Saturated Output Flag return Output value signed 16 bit 99 105 Additional information UM0483 A 6 100 105 A priori determination of flux and torque currents PI gains The purpose of this appendix is to provide a criterion for the computation of the initial values of torque flux PI parameters K and Kp Successive fine tuning is then performed in the practical system To calculate these starting values it is required to know the electrical characteristics of the motor in terms of stator resistance R and inductance L plus the electrical characteristics of the hardware board that is shunt resistor Rshunt current sense amplification gain Ay and direct current bus voltage Vg DC The derivative action of the controller is not considered using this method Figure 57 shows the PI controller block diagram used for torque or flux regulation Figure 57 Block diagram of PI Controller Target Voltage command current Measured current ai14850 For this analysis it is assumed that the driving strategy is isotropic with respect to the q and d axis so it can be assumed that the starting values of Kp are the same for the torque regulator and the flux regulator The same assumption
91. omponent a For the meaning of each value please refer to Section 2 1 where the theory of the IFOC algorithm is treated 31 105 Running the demo program UM0483 3 4 Caution 3 4 1 32 105 Setting up the system when using ICS sensors The default configuration provides for the use of three shunt resistors and tacho generator Section 3 4 1 describes how to change the firmware configuration from three shunt resistors to two ICS stator current reading This section gives you information about how to provide the STM32F103xx with ICS feedback signals and to properly customize the firmware When using two ICS for stator current reading you must ensure that the conditioned sensors output signal range is compatible with the STM32F103xx supply voltage Connecting the two ICS sensors to the motor and to STM32F103xx In order for the implemented IFOC algorithm to work properly it is necessary to ensure that the software implementation of the stm32 10x_svpwm_ics module and the hardware connections of the two ICS are consistent As illustrated in Figure 23 the two ICS must act as transducers on motor phase currents coming out of the inverter legs driven by STM32F103xx TIM1 signals PWM1 Phase A and PWM2 Phase B In particular the current coming out of inverter Phase A must be read by an ICS whose output has to be sent to the analog channel specified by the PHASE A ADC CHANNEL parameter in MC pwm ics prm h Likewise the curren
92. on Synopsis void RevPark Circle Limitation void Description After the two new values V4 and V4 of the stator voltage producing flux and torque components of the stator current have been independently computed by flux and torque PIDs it is necessary to saturate the magnitude of the resulting vector equal to v va before passing them to the Rev_Park function The purpose of this routine is to perform the saturation Refer to Section 4 5 4 Circle limitation on page 66 for more detailed information Input None Returns None Note The limitation of the stator voltage vector must be done in accordance with the PWM frequency as shown in Table 2 PWM frequency vs maximum duty cycle relationship on page 49 Functions called None Detailed explanation about reference frame transformations Induction machines show very complex voltage equations because of the time varying mutual inductances between stator and rotor circuits By making a change of variables that refers stator and rotor quantities to a frame of reference rotating at any angular velocity it is possible to reduce the complexity of these equations This strategy is often referred to as the Reference Frame theory see 1 in Appendix A 7 References on page 102 Supposing fax fbx fox are three phase instantaneous quantities directed along axis each displaced by 120 degrees where x can be replaced with s or r to treat stator or rotor quantities see Figure 43 supposi
93. on page 15 for the flux regulation Input PID FluxTYPDEF see MC type h for structure declaration signed 16 bits Output Signed 16 bits Functions called None Note Default values for the PID flux regulation are declared and can be modified in the MC Control Param h file see Section 2 2 2 on page 16 See also Figure 55 on page 98 shows the PID block diagram PID Torque Regulator Synopsis s16 PID Torque regulator PID TorqueTYPEDEF PID Torque s16 glq input Description The purpose of this function is to compute the proportional integral and derivative terms if enabled see Id Ig DIFFERENTIAL TERM ENABLED in Section 2 2 1 on page 15 for the torque regulation Input PID TorqueTYPDEF see MC type h for structure declaration signed 16 bits Output signed 16 bits Functions called None Note Default values for the PID torque regulation are declared and can be modified in the MC Control Param h file see Section 2 2 2 on page 16 See also Figure 55 on page 98 shows the PID block diagram PID Speed Regulator Synopsis s16 PID Speed regulator PID SpeedTYPEDEF PID Speed s16 speed Description The purpose of this function is to compute the proportional integral and derivative terms if enabled see SPEED DIFFERENTIAL TERM ENABLED in Section 2 2 1 on page 15 for the speed regulation Input PID SpeedTYPDEF see MC type h for structure declaration signed 16 bits 79 105 Library functions UM0483 4 8 3 80 1
94. onstruct the currents flowing through a three phase load with the required accuracy using two ICS it is necessary to properly synchronize A D conversions with the generated PWM signals This is why the two tasks are included in a single software module List of available functions and interrupt service routines The following is a list of available functions as listed in the stm32 10x_svpwm_ics h header file e SVPWM lcslnit on page 50 e SVPWM lcsCurrentReadingCalibration on page 51 e SVPWM lcsGetPhaseCurrentValues on page 52 e 3SVPWM lcsCalcDutyCycles on page 52 SVPWM IcsInit Synopsis void SVPWM_IcsInit void Description The purpose of this function is to set up microcontroller peripherals for performing ICS reading and center aligned PWM generation The function initializes NVIC ADC GPIO and TIM1 peripherals In particular ADC and TIM1 peripherals are configured to perform two pairs of simultaneous injected A D conversions every time PWM registers are updated event called U event The first pair of conversions reads the current values while the second one acquires the bus voltage and the voltage on the temperature sensor Refer to Section 4 3 3 for further information on A D conversion triggering in ICS configuration Input None Returns None Note It must be called at main level UM0483 Library functions Functions called Standard library RCC_ADCCLKConfig RCC_AHBPeriphClockCmad RCC_APB2Perip
95. oportional constant of the speed loop regulation signed 16 bit value adjustable from 0 to 32767 e define PID SPEED KI DEFAULT The integral constant of the speed loop regulation signed 16 bit value adjustable from 0 to 32767 e define PID SPEED KD DEFAULT The derivative constant of the speed loop regulation signed 16 bit value adjustable from 0 to 32767 ky 17 105 Getting started with the library UM0483 18 105 Torque and flux controller setpoints and PID constants define PID_TORQUE_REFERENCE The torque reference value in open loop at startup signed 16 bit value define PID_TORQUE_KP_DEFAULT The proportional constant of the torque loop regulation signed 16 bit value adjustable from 0 to 32767 define PID_TORQUE_KI_DEFAULT The integral constant of the torque loop regulation signed 16 bit value adjustable from 0 to 32767 define PID_TORQUE_KD_DEFAULT The derivative constant of the torque loop regulation signed 16 bit value adjustable from 0 to 32767 define PID_FLUX_REFERENCE Flux reference its default value is equal to NOMINAL_FLUX defined in the MC_ACmotor_prm h header file see Section 2 2 5 define PID_FLUX_KP_DEFAULT The proportional constant of the flux loop regulation signed 16 bit value adjustable from 0 to 32767 define PID_FLUX_KI_DEFAULT The integral constant of the flu
96. orithms will be scaled by a constant factor equal to 256 So the computed values of Kp and K must be multiplied by this factor when used in the MC Control Param h file Moreover in the computation of the integral part the PI algorithm does not include the PI sampling time T See the following formula t n n kif ecd kT Y e kT K Y e kT 0 kei k 1 Since the integral part of the controller is computed as the sum of successive errors it is required to include T in computation of the Kj So the final formula can be expressed as Kp Lee 256 Re 256 s ot jua ten Vb DC R A AB Bus shunt op 3 3 For example it is possible to set the bandwidth of the closed loop system equal to 1500 rad s so that the time constant of the current control system is 0 66 ms ky 101 105 Additional information UM0483 The Ao measured for the MB459 is 2 57 It is then possible to compute the values of the parameters knowing the motor parameters Rs Ls VgysDC and Repynt A 7 References e 1 PC Krause O Wasynczuk S D Sudhoff Analysis of Electric Machinery and Drive Systems Wiley IEEE Press 2002 e 2 T A Lipo and D W Novotny Vector Control and Dynamics of AC Drives Oxford University Press 1996 102 105 ky UM0483 Revision history Revision history Table 4 Document revision history Date Revision Changes 08 Jan 2008 1 Initial release 103 105 UM0483 Please R
97. otors the first is proportional to mechanical torque the second to the rotor flux In more detail in the context of FOC rotor flux position is indirectly calculated starting from transformed equations of the machine by means of known motor parameters and stator current measurements this is why the controller is an indirect controller and hence the phrase IFOC drive In other words it can be stated that IFOC drive is halfway between dynamic controllers like speed and position and machine core So the system may well be depicted as in Figure 5 if introduced in a loop for speed control Figure 5 FOC drive placed in a speed loop Torque controller Flux controller or 3 phase noe induction motor NJ actual rotor speed ai14787 Basic information on field oriented structure and library functions is represented in Figure 6 e The 0 calculation block estimates rotor flux angle which is essential to transformation blocks park reverse park to perform field orientation so that the currents supplied to the machine can be oriented in phase and in quadrature to the rotor flux vector More detailed information about the reference frame theory and FOC structure is available in Section 4 4 3 on page 58 e The space vector PWM block SVPWM implements an advanced modulation method that reduces current harmonics thus optimizing DC bus exploitation e The current reading block al
98. plemented in the CalcRotFIxSlipFreq function see CalcRotFIxSlipFreq on page 58 is at the foundation of indirect field oriented control it tells us that the rotor flux slip frequency ay may be simply calculated from stator current components relying on knowledge of the rotor time constant of the machine If rotor angle or rotor speed is known see Figure 38 and Figure 39 respectively then we have managed to determine the rotor flux position 05 This information is essential to achieve optimum control Detailed explanation about field weakening operation Many applications need to operate induction machines above their rated speed this is achieved by means of field weakening The conventional method for the field weakening operation is to vary the rotor flux reference in proportion to the inverse of the rotor speed o In this approach if maximum inverter modulation index is required when attaining rated speed and rated power then the voltage margin enough to regulate current beyond that point is not available this is caused by increased voltage drop across the stator leakage inductance That s why when 1 a method is implemented the inverter voltage is generally limited at 95 of its means The AC IM IFOC software library however makes use of a maximum torque capability scheme see 2 in Appendix A 7 References on page 102 which aims to exploit the system resources completely In both cases DC bus voltage limitation Vp
99. pology requires low side switches to be on when performing current reading A D conversions the REP_RATE parameter must be an odd number in this case Considering that the raw IFOC algorithm execution time is about 21 us when in three shunt resistor stator current reading configuration the related contribution to CPU load can be computed as follows FPwM REP RATE 1 2 o FpWM Refresh Rate 6 6 CPU Load 21 10 100 21 10 100 Selecting the update repetition rate based on PWM frequency for 3 shunt resistor configuration Beyond the well known trade off between acoustical noise and power dissipation consideration should be given to selecting the PWM switching frequency using the AC IM IFOC software library As discussed in Section 4 2 5 on page 45 depending on the PWM switching frequency a limitation on the maximum applicable duty cycle could occur if using three shunt resistor configuration for current reading Table 2 PWM frequency vs maximum duty cycle relationship on page 49 summarizes the performance of the system when the software library is used in conjunction with STM3210B MCKIT hardware The MB459 board is an evaluation platform it is designed to support different motor driving topologies PMSM and AC induction and current reading strategies single and three shunt resistors Therefore the figures given in Table 2 on page 49 should be understood as a starting point and not as a best case Moreover
100. pon L 1 1 1 Low side phase B D am ma SERMEEEEN High side phase B 8 f DO Current feedback phase B p E it i E ampling start i AL i Current feedback phase C Se RAA 9 Sampling end i S i f 1 Space available for sampling m uw ai14838 Case 4 ADuty y lt DT Ty Ts 2 and ADuty p lt DT TRt Ts In this case the duty cycle applied to Phase A is so short that no current sampling can be performed between the two low side commutations Furthermore if the difference in duty cycles between Phases B and A is not long enough to allow the A D conversions to be performed between Phase B low side switch on and Phase A high side switch off it is impossible to sample the currents See Figure 36 To avoid this condition it is necessary to reduce the maximum modulation index or decrease the PWM frequency Figure 36 ADuty lt DT Ty Ts 2 and ADuty p lt DT TptTs ADutyAB 4 Low side phase A AW High side phase A 3 ni F Low side phase B i High side phase B Current feedback phase B 0 8 Current feedback phase C No space available for sampling ial ai14839 The following parameters have been set as default in the firmware They are related to the MB459 board e DT 0 8 us e Ty 2 55 us e Ts 0 7 us e TR 2 55 Us UM0483 Library functions The maximum applica
101. r it works equally successfully with all the products in the STM32F103xx performance line family Using a different sales type may require some modifications to the library according to the available features some of the I O ports are not present on low pin count packages Refer to the MCU datasheet for further details Also depending on the memory size the workspace may have to be configured to fit your STM32F103xx MCU derivative Inkarm xxx xcl file internal Flash or RAM based project The IAR config folder contains 3 files e Inkarm flash xcl e Inkarm ram xcl These files are used as an extended command linker file and contain linker options Memory areas start address size and other parameters are declared here Refer to the Cortex M3 Technical Reference Manual for more information The default extended linker file used in the standard library to configure the device for internal Flash based resident firmware is Inkarm flash xc1 An extract of this file showing the definitions of heap and stack size is provided below Depending on the project requirements it may be necessary to manually edit the segment sizes Code memory in FLASH DROMSTART 0x8000000 DROMEND 0x801FFFF Data in RAM DRAMSTART 0x20000000 DRAMEND 0x20004FFF f FRCRCKCKCkCkckckckckckck ck ckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckckck ck ck ck ckckck kckck ch ck ck ko ckck ck ck kk
102. r last tacho captures Input None Output Tacho signal period unit is 1 CKTIM period unsigned 32 bit format Functions called None Note This function is private to the stm32f10x_tacho c module ky 73 105 Library functions UM0483 74 105 TAC IsTimedOut Synopsis bool TAC_IsTimedOut void Description This routine indicates to the upper layer software that tacho information has disappeared or that the period of the signal has drastically increased Input None Output Boolean TRUE in case of time out Functions called None Note The time out duration depends on tacho timer pre scaler which is variable the time out is higher at low speed The boolean will remain set to TRUE until the TAC_ClrTimeOut is called TAC ClrTimeOut Synopsis void TAC_ClrTimeOut void Description This routine clears the flag indicating that information is lost or that speed is decreasing sharply Input None Output None Note This function must be called to re arm the time out detection mechanism and re start rotor frequency measurements the returned frequency is 0 as long as the timeout flag is set TAC GetCaptCounter Synopsis u16 TAC_GetCaptCounter void Description This routine gives the number of tacho capture interrupts since the last call to the TAC_ClrCaptCounter function Input None Output Unsigned 16 bit integer This variable cannot roll over this is prevented in the tacho capture routine itself it will
103. ramming AC motor drives and power inverter hardware In depth know how of STM32F103xx functions is only required for customizing existing modules and for adding new ones for a complete application development Figure 1 shows the architecture of the firmware It uses the STM32F103xx standard library extensively but it also acts directly on hardware peripherals when optimizations in terms of execution speed or code size are required Figure 1 Firmware architecture Application layer E flux and STM32F103xx IFOC drive drive User standard czar peed E library LA E svewn STM32F103xx motor control library STM32F103xx peripherals ai14767 Rev 1 1 104 www st com Contents UM0483 Contents 1 Getting started with tools 00 cee ee 9 1 1 Working environment 42e aga ho OR Ra vor OR OREGON 9 1 2 Software 1001S 2 35 ce owe ER UR RERO EEE UR EO EE CC RR ed 9 1 3 Library source code cc 48s sue Ra 9E REG n X dc ed e RO 10 1 3 1 Download 452r m ae a Ra Riek ace UR P AUR s Rare eren 10 1 3 2 File SUUCIUIC voe les ad ie hbe give e RRGUR CE XO UR Pose ex 10 1 3 3 Starting the IAR toolchain 0 00 c eee eee 10 1 4 Customizing the workspace for your STM32F103xx derivative 11 1 4 1 Inkarm xxx xcl file internal Flash or RAM based project 11 1 4 2 Extended linker file setting llle 12 2 Getting started with the library eee eee 13 2
104. reasing during startup or decreasing during motor stop define MAX RATIO Maximum possible TIMER clock prescaler ratio This defines the lowest speed that can be measured when counter OxFFFF It also prevents the clock prescaler from decreasing excessively when the motor is stopped This prescaler is automatically adjusted during each and every capture interrupt to optimize the timing resolution UM0483 Getting started with the library define MAX OVERFLOWS This is the maximum number of consecutive timer overflows taken into account It is set by default to 10 if the timer overflows more than 10 times meaning that the tacho period has been increased by a factor of 10 at least the number of overflows is not counted anymore This usually indicates that information is lost tacho time out or that the speed is decreasing very sharply The corresponding duration depends on the tacho timer prescaler which is variable the higher the prescaler at low speed the longer the timeout period define SPEED FIFO SIZE This is the length of the software FIFO in which the latest speed measurements are stored This stack is necessary to compute rolling averages on several consecutive data 2 2 5 AC induction motor parameters MC ACmotor param h The MC ACmotor param h header file holds motor parameters which are essential to properly operate the IFOC vector drive The following parameters must b
105. rol ACIM IFOC ver 1 0 FAULT 1 Bus Under Voltage Press Sel to return to menu Actual values of DC bus voltage and IGBT heatsink temperature In case of overtemperature and bus overvoltage undervoltage the system is autoprotected it warns the user about the fault event while blocking motor operations The user may however be interested in seeing how these values change during the motor control run phase For this purpose an LCD screen was added that continuously shows the DC bus voltage level in volts and the power switch heat sink temperature in Celsius degrees Figure 26 LCD screen to monitor power stage status STM32 Motor Control ACIM IFOC ver 1 0 Power Stage Status DC bus 310 Volt 023 Celsius Move Note on debugging tools The third party JTAG interface should always be isolated from the application using the MB535 JTAG opto isolation board it provides protection for both the JTAG interface and the PC connected to it During a breakpoint when using the JTAG interface for the firmware development the motor control cell clock circuitry should always be enabled if disabled a permanent DC current may flow in the motor because the PWM outputs are enabled which could cause permanent damage to the power stage and or motor A dedicated bit in the DBGMCU SR ky UM0483 Running the demo program register the DBG_TIM1_STOP bit must be set to 1 See Figure 25 In the mai
106. s E Clarke and R H Park These functions implement three variable changes that are required to carry out field oriented control FOC e Clarke transforms stator currents to a stationary orthogonal reference frame named q d see Figure 42 e then from that arrangement Park transforms currents to a frame that rotates at an arbitrary speed which in IFOC drive is synchronous with the rotor flux e Reverse Park transformation brings back stator voltages from a rotating frame q d to a stationary one e Themodule also includes a function to correct the voltage vector command the so called circle limitation Figure 42 Clarke Park and reverse Park transformations Clarke Q Reverse Park ai14794 List of available C functions Clarke on page 63 Park on page 63 Hev Park on page 64 Hev Park Circle Limitation on page 64 UM0483 Library functions Clarke Synopsis Description Input Returns Functions called Park Synopsis Description Input Returns Functions called Curr_Components Clarke Curr_Components Curr_Input This function transforms stator currents ig and ips which are directed along axes each displaced by 120 degrees into currents iy and ig in a stationary o D reference frame o B axes are directed along paths orthogonal to each other See Section 4 5 3 for the details Stator currents ias and ips in q1 15 format as
107. t coming out of inverter Phase B must be read by the other ICS and its output has to be sent to the analog channel specified by the PHASE B ADC CHANNEL parameter in MC pwm ics prm h About the positive current direction convention a positive half wave on PHASE X ADC CHANNEL is expected corresponding to a positive half wave on the current coming out of the related inverter leg see direction of in Figure 23 Figure 23 ICS hardware connections Phase A Phase B UM0483 Running the demo program 3 4 2 Caution Selecting PHASE_A_ADC_CHANNEL and PHASE B ADC CHANNEL Default settings for PHASE A ADC CHANNEL and PHASE B ADC CHANNEL are respectively ADC_CHANNI EL11 and ADC_CHANNEL12 You can change the default settings if the hardware requires it by editing the MC pwm ics prm h file LI Ib dVMNMMMllMlMMltllllll ll Current reading parameters LIB ME Et dY Y Y IAAT TT TTT define PHASE A ADC CHANNEL ADC Channel 11 define PHASE A GPIO PORT GPIOC define PHASE A GPIO PIN GPIO Pin 1 define PHASE B ADC CHANNEL ADC Channel 12 define PHASE B GPIO PORT GPIOC define PHASE B GPIO PIN GPIO Pin 2 The proper GPIOs must be initialized as analog inputs An example for ADC channel 8 is given below ADC Channel 8 pin configuration GPIO InitStructure GP 1 GPIO InitStructure GP 1 GPIO Init GP LOC amp GP
108. t of figures UM0483 List of figures Figure 1 Figure 2 Figure 3 Figure 4 Figure 5 Figure 6 Figure 7 Figure 8 Figure 9 Figure 10 Figure 11 Figure 12 Figure 13 Figure 14 Figure 15 Figure 16 Figure 17 Figure 18 Figure 19 Figure 20 Figure 21 Figure 22 Figure 23 Figure 24 Figure 25 Figure 26 Figure 27 Figure 28 Figure 29 Figure 30 Figure 31 Figure 32 Figure 33 Figure 34 Figure 35 Figure 36 Figure 37 Figure 38 Figure 39 Figure 40 Figure 41 Figure 42 Figure 43 Figure 44 Figure 45 Figure 46 Figure 47 Figure 48 6 104 Firmware architecture llli 1 JTAG interface for debugging and programming illii 9 Elle Str cture tu eb RSS eres a V Sa a e ao VO VUE NURSE rece nod dide 10 Extended linker file setting liil 12 FOC drive placed in a speed loop 60 eee ee 13 FOC SUCIS EE 14 Torque vs speed characteristic curve 0 000 cee ees 22 Adding anew module 0 et tenets 23 Key function assignments 0 llle eae 24 Main State Machine 3s seg noe Rete teen doa xe a Rc ew eae dee ee ad 25 LCD screen for Torque control mode settings 000 cece eee eee 25 LCD screen for Target Iq settingS 0 0 00 ccc eee 26 LCD screen for Target Id settingS 0 0 0 0 e eee tee 26 LCD screen to set the P term of the Torque PID 0 000 e eee ene eee 27 Torque control startup str
109. t until STARTUP TIMEOUT Finally when no valid speed information comes from the motor and STARTUP TIMEOUT is elapsed the main state machine goes into FAULT state for two seconds and the error message Startup failed is displayed on the LCD In this case it is strongly advised to check speed sensor feedback connections first and then if necessary to increase the final ramp torque reference in case the load torque is too high In Torque control mode operation a constant torque reference is produced Depending on the load torque applied this could lead to constant acceleration of the motor making the speed rise up to the motor s physical limits Figure 15 Torque control startup strategy Torque reference set L by Joystick STARTUP RAMP DURATION STARTUP TIMEOUT t 27 105 Running the demo program UM0483 3 2 28 105 Speed control mode Figure 16 Figure 17 Figure 18 show a list of some LCD menus used to set motor control parameters in the Speed control mode The parameter in red is the one that is being selected and whose value can be modified by acting on the joystick key Figure 16 LCD screen for Speed control settings STM32 Motor Control ACIM IFOC ver 1 0 Speed Control Mode Target Feedback 03000 rpm 00000 Move t Change From the menu screen shown in Figure 11 it is possible to switch from Torque control to Speed control mode operatio
110. the software variable reproduced by a scope in real time This advanced feature makes it easier to debug the IFOC algorithm efficiency as the actual values processed by the firmware can be graphically traced in the time domain at the current control loop frequency Moreover when the DAC functionality is enabled it is possible to choose the two variables to check by using a menu screen on the LCD display Figure 22 shows the corresponding menu screen Figure 22 LCD screen to select and view IFOC variables STM32 Motor Control ACIM IFOC ver 1 0 Signal on PBO Measured Rotor Speed Signal on PB 1 Iq ref lt gt Move t 1 Change As usual by pushing on the joystick key to the right left it is possible to navigate between the two DAC channels PBO and PB1 and then to change the variables to be output by moving the key up down The list below shows all the IFOC values that can be selected for each channel Measured rotor speed measured rotor speed Measured el angle measured electrical angle position of rotor flux Vg Reverse Parke voltage component Va Reverse Parke voltage component Vg flux PID controller output voltage component Vq torque PID controller output voltage component lg ref flux command lg ref torque command lg measured flux component lg measured torque component lg Clarke current component I Clarke current component lg Stator current component b la stator current c
111. the third one being computed from the relation given in Section 4 2 4 Thus depending on the space vector sector the A D conversion of voltage V will be performed only on the two phases where the duty cycles applied to the low side switches are the highest In particular by looking at Figure 29 you can deduct that in sectors 1 and 6 the voltage on the Phase A shunt resistor can be discarded likewise in sectors 2 and 3 for Phase B and finally in sectors 4 and 5 for Phase C Moreover in order to properly synchronize the two stator current reading A D conversions it is necessary to distinguish between the different situations that can occur depending on PWM frequency and applied duty cycles The explanations below refer to space vector sector 4 They can be applied in the same manner to the other sectors 45 105 Library functions UM0483 46 105 Case 1 Duty cycle applied to Phase A low side switch is larger than DT Ty Where e DT is dead time e Ty is the duration of the noise induced on the shunt resistor voltage of a phase by the commutation of a switch belonging to another phase Tsis the sampling time of the STM32F10xxx A D converter the following consideration is made under the hypothesis that Ts lt DT Ty Refer to the STMS2F10xxx reference manual for more detailed information This case typically occurs when SVPWM with low lt 60 modulation index is generated see Figure 32 The modulation index is the
112. tions s sssaaa eeaeee 38 4 2 Current reading in three shunt resistor topology and space vector PWM generation stm32f10x_svpwm_3shunt module 38 4 2 1 OVEIVICW aaraa cis E E rre a ha E de N 38 4 2 2 List of available functions s saaa aunan 39 4 2 3 Space vector PWM implementation nananana aaa 42 4 2 4 Current sampling in three shunt topology and general purpose A D CONVEISIONS cscs maata ae aaa a a eae E aE reared dian amas 43 4 2 5 Tuning delay parameters and sampling stator currents in three shunt resistor topology 00 0c eee a a en 45 4 3 Isolated current sensor reading and space vector PWM generation stm32f10x_svpwm_ics module 50 4 3 1 OVGtVIeW soeren te are ed roAa C ela PM n N 50 4 3 2 List of available functions and interrupt service routines 50 4 3 3 Current sampling in isolated current sensor topology and integrating general purpose A D conversions 00 0c eee eee eee 52 4 4 Induction motor IFOC vector control MC_IFOC_Drive module 53 4 4 1 OVervieW vices de eme e hh eR RR eG ee Klee ee eerie aw d 53 4 4 2 List of available C functions 0 0 0 0 00 eee 54 4 4 3 Detailed explanation about indirect field oriented control IFOC 58 4 4 4 Detailed explanation about field weakening operation 60 4 5 Reference frame transformations MC_Clarke_Park module 62 4 5 1 OV6etVIOeW 4 1 d aed aac ha deen IRE ae E ale Ps i n 62 4 5
113. ttings See also Section 3 2 Speed control mode on page 28 MCL Init Arrays Synopsis void MCL Init Arrays void Description This function initializes the arrays used for temperature and bus voltage measurements to avoid erroneous fault detection after an MCU reset MCL Chk OverTemp Synopsis bool MCL Chk OverTemp void Description This function checks for overtemperature fault occurrences on the heatsink connected to the power stage switches The thresholds for temperature and hysteresis values are defined by the user Returns Returns TRUE if the voltage on the thermal resistor connected to ADC channel ADCIN 10 has reached the threshold level or if it has not yet returned to the threshold level minus the hysteresis value after an overheat detection Functions called ADC GetlnjectedConversionValue See also Section 3 6 Fault messages on page 35 on how to set temperature thresholds Ti 89 105 Library functions UM0483 Note 90 105 MCL Chk BusVolt Synopsis Description Returns Functions called See also MCL SetFault Synopsis Description Input Functions called BusV_t MCL_Chk_BusVolt void This function checks for over and or undervoltage faults on inverter DC bus The thresholds for under and overvoltages are defined by the user It returns a BusV_t type variable reporting the fault value ADC GetlnjectedConversionValue Section 3 6 Fault messages on page 35 on how to set DC
114. ty lt D Ty and ADuty ap lt Dr TRtTs With the increase in modulation index ADuty can assume values smaller than Dy7 Ty Sampling synchronized with the counter overflow could be impossible In this case the two currents can be sampled between the two Phase A low side commutations after the counter overflow Consider that in order to avoid the acquisition of the noise induced on the phase B current feedback by phase A switch commutations it is required to wait for the noise to be over Ty See Figure 34 Figure 34 DT Ty Ts 2 lt ADuty lt Dr Ty and ADutyap lt Dt TRt Ts ADutyAB ADutya lt r Low side phase A yg High side phase a qu eS LowsidephaseB PT MihededneeB J o MS 1 Mh i Current feedback phase ho ume So i A l T 9 Sampling start n 9 Sampli d SIN Eti AN amping en Ej Space available for sampling Current feedback phase C 1 ai14837 Case 3 ADutyA lt DT Ty Ts 2 and ADuty p gt DT TRtTs In this case the two currents can be sampled between Phase B low side switch on and Phase A high side switch off The choice was therefore made to sample the currents Ts us before of phase A high side switch off see Figure 35 ky 47 105 Library functions UM0483 48 105 Figure 35 ADutyA lt DT Ty Ts 2 and ADuty p gt DT Tpt Ts 1g ADutyaB i ADutyAB Low side phase A E a High side phase A i
115. untlnit void The purpose of this function is to set up microcontroller peripherals for performing 3 shunt resistor topology current reading and center aligned PWM generation The function initializes NVIC ADC GPIO TIM1 peripherals In particular the ADC and TIM1 peripherals are configured to perform two synchronized A D conversions per PWM switching period Refer to Section 4 2 3 for further information None None It must be called at main level Standard library RCC ADCCLKConfig RCC AHBPeriphClockCmd RCC_APB2PeriphClockCmd GPIO Structlnit GPIO Init GPIO PinRemapConfig TIM1 Delnit TIM1 TimeBaseStructlnit TIM1 TimeBaselnit TIM1 OCStructlnit TIM1 OCllInit TIM1 OCa2lnit TIM1 OC3lnit TIM1 OC1PreloadConfig TIM1 OC2PreloadConfig TIM1 OC3PreloadConfig TIM1 BDTRConfig TIM1 SelectOutputTrigger TIM1_ClearlTPendingBit TIM1 ITConfig TIM1 Cmd ADC Delnit ADC Cmd ADC Structlnit ADC Init ADC StartCalibration ADC GetCalibrationStatus ADC RegularChannelConfig ADC_InjectedSequencerLengthConfig ADC InjectedChannelConfig ADC_ExternalTrigInjectedConvCmd NVIC PriorityGroupConfig NVIC Structlnit NVIC Init Motor control library SVPWM 3ShuntCurrentReadingCalibration 39 105 Library functions UM0483 40 105 SVPWM_3ShuntCurrentReadingCalibration Synopsis Description Input Returns Note Functions called void SVPWM_3ShuntCurrentReadingCalibration void The purpose of this funct
116. using the ADC peripheral and the TIM1 peripheral break input BKIN to watch the following conditions e Heatsink overtemperature ADC channel ADC_IN10 and BKIN input e DC bus over undervoltage on ADC channel ADC INS Overcurrent protection BKIN input Any of these three conditions causes the TIM1 motor control outputs PWM signals to be stopped and the state machine to go into Fault state until the user presses the joystick key After the user has pressed the key the state machine goes into Idle state only if the cause of the fault does not persist anymore Depending on the source of the fault an error message is also displayed on the LCD during Fault state UM0483 Running the demo program Figure 10 Main c state machine Button pushed Fault condition Initialization over and joystick key pressed Motor still Hardware or startup faul Hardware Button pushed Button pushed ai14768 3 1 Torque control mode Figure 11 Figure 12 and Figure 13 show a list of some LCD menus used to set motor control parameters in the Torque control mode The parameter in red is the one that is being selected and whose value can be modified by acting on the joystick key Figure 11 LCD screen for Torque control mode settings STM32 Motor Control ACIM IFOC ver 1 0 Torque Control Mode Target Feedback Iq 08000 00000 Id 093834 00000 Speed rpm 00000 lt gt Move t 1 Change In this conditio
117. ustomized by editing the PTD SPEED SAMPLING TIME parameter in the MC Control Param h header file The flux and torque PID regulator sampling rates are given by the relationship 2 PWM FREQ Fl PID li ux and torque sampling rate REP RATE 1 REP RATE must be an odd number if currents are measured by shunt resistors see also Section A 2 on page 93 its value is 8 bit long Adjusting speed regulation loop Ki Kp and Kd vs motor frequency Depending on the motor frequency it might be necessary to use different values of Kp Ki and Kd These values have to be input in the code to feed the regulation loop algorithm A function performing linear interpolation between four set points PID Speed Coefficient update is provided as an example in the software library see MC_PID_regulators c and can be used in most cases as long as the coefficient values can be linearized If that is not possible a function with a larger number of set points or a look up table may be necessary To enter the four set points once the data are collected edit the MC Control param h file and fill in the field dedicated to the Ki Kp and Kd coefficient calculation as shown below UM0483 Library functions z Settings for min frequency define Freq Min 10 1 Hz mechanical define Ki_Fmin 1000 Frequency min coefficient settings define Kp Fmin 2000 define Kd Fmin 3000 Settings for intermediat
118. x loop regulation signed 16 bit value adjustable from 0 to 32767 define PID_FLUX_KD_DEFAULT The derivative constant of the flux loop regulation signed 16 bit value adjustable from 0 to 32767 Startup torque ramp parameters See Section 3 1 Torque control mode and Section 3 2 Speed control mode on page 28 for details define STARTUP TIMEOUT Define here in ms the overall time allowed for startup define STARTUP RAMP DURATION Define here in ms the duration of the torque ramp up define STARTUP FINAL TORQUE Define here in q1 15 format the final reference value for torque ramp up Speed control mode only define TACHO SPEED VAL Define here in 0 1Hz the lowest speed for tachogenerator reading validation Linear variation of PID constants according to mechanical speed Refer to Section 4 8 5 Adjusting speed regulation loop Ki Kp and Kd vs motor frequency on page 82 UM0483 Getting started with the library 2 2 3 Incremental encoder parameters MC_encoder_param h The MC encoder parameter h header file is to be filled out if position speed sensing is
119. xtensively discussed in technical literature This section provides a basic reminder of the theory PID regulators are useful to maintain a level of torque flux or speed according to a desired target UM0483 Library functions Note 4 8 4 Figure 47 PID general equation torque f rotor position torque and flux regulation for maximum flux f rotor position f system efficiency torque f rotor speed torque regulation for speed regulation 3 P j of the system Where Error Error of the system observed at time t T ySr ErTOfsy Error of the system observed at time t T Tsampling T f X Kp x Errorsy Kix 3Error Kyx Errors Erroreys__ 1 0 AT va Derivative term can be disabled Equation 1 corresponds to a classical PID implementation where e Kj is the proportional coefficient Kiis the integral coefficient e Kais the differential coefficient As mentioned in Figure 47 the derivative term of the PID can be disabled independently through a compiler option see stm32 10x_MCconf h file for the torque flux or the speed regulation a PI can then be quickly implemented whenever the system doesn t require a PID control algorithm Regulator sampling time setting The sampling time needs to be modified to adjust the regulation bandwidth As an accumulative term the integral term is used in the algorithm increasing the loop time decreases its effects accumulatio
120. y cycle relationship PWM frequency Max duty cycle Max modulation Index Up to 11 4 kHz 100 100 12 2 kHz 99 98 12 9 kHz 98 5 97 13 7 kHz 98 96 14 4 kHz 98 96 15 2 kHz 97 94 16 kHz 96 5 93 16 7 kHz 96 5 93 17 5 kHz 95 5 91 Note The figures above were measured using the MB459 board This evaluation platform is designed to support several motor driving topologies PMSM and AC induction and current reading strategies single and three shunt resistors Therefore the figures provided in should be understood as a starting point and not as a best case The RevPark_Circle_Limitation function performs the discussed stator voltage components saturation as illustrated in Figure 44 Figure 44 Circle limitation working principle S16_MAX r MMI S16 MAX ai14845 Va and Vq represent the saturated stator voltage component to be passed to the Reverse Park transformation function while Vg and V are the outputs of the PID current controllers From geometrical considerations it is possible to draw the following relationship Vy MMI S16 MAX Vja 2 ee ES V V MMI 16 MAX gt V Ti 67 105 Library functions UM0483 4 6 4 6 1 68 105 In order to speed up the computation of the above equations while keeping an adequate resolution the value MMI S16 MAX UIS KI is computed and stored in a look up table for different values of V Furthermore considering that MMI d

Download Pdf Manuals

image

Related Search

Related Contents

manual del usuario  3Com NBX 100 Owner's Manual  Déménagement, mode d`emploi  F77 Appl_Ref_Manual - Stratos Global Corporation  1 2 3 4 5 6 7 8 9 10 11 12 13 A B CP 581 SIMATIC  Klipsch R-15M loudspeaker  き貴重苦チ重森建吉も昇吾栄望富らなし離  

Copyright © All rights reserved.
Failed to retrieve file