Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.



Published on

Published in: Education, Business, Technology
  • Be the first to comment

  • Be the first to like this


  1. 1. AN857 Brushless DC Motor Control Made Easy get device and exercise the code directly from the MPLAB® environment. The final code can then beAuthor: Ward Brown ported to one of the smaller, less expensive, Microchip Technology Inc. PICmicro microcontrollers. The porting takes minimal effort because the instruction set is identical for all PICmicro 14-bit core devices.INTRODUCTION It should also be noted that the code was bench testedThis application note discusses the steps of developing and optimized for a Pittman N2311A011 brushless DCseveral controllers for brushless motors. We cover sen- motor. Other motors were also tested to assure that thesored, sensorless, open loop, and closed loop design. code was generally useful.There is even a controller with independent voltage andspeed controls so you can discover your motor’s char- Anatomy of a BLDCacteristics empirically. Figure 1 is a simplified illustration of BLDC motor con-The code in this application note was developed with struction. A brushless motor is constructed with a per-the Microchip PIC16F877 PICmicro® Microcontroller, in manent magnet rotor and wire wound stator poles.conjuction with the In-Circuit Debugger (ICD). This Electrical energy is converted to mechanical energy bycombination was chosen because the ICD is inexpen- the magnetic attractive forces between the permanentsive, and code can be debugged in the prototype hard- magnet rotor and a rotating magnetic field induced inware without need for an extra programmer or the wound stator poles.emulator. As the design develops, we program the tar-FIGURE 1: SIMPLIFIED BLDC MOTOR DIAGRAMS 100 A N A com a 101 c S 110 N N a S com b 6 b 3 4 1 C com N S S 001 N c 010 B a c 2 b com C 5 S B 011© 2002 Microchip Technology Inc. DS00857A-page 1
  2. 2. AN857In this example there are three electromagnetic circuits cal connections through the six possible combinations,connected at a common point. Each electromagnetic numbered 1 through 6, at precisely the right momentscircuit is split in the center, thereby permitting the per- will pull the rotor through one electrical revolution.manent magnet rotor to move in the middle of the In the simplified motor of Figure 1, one electrical revo-induced magnetic field. Most BLDC motors have a lution is the same as one mechanical revolution. Inthree-phase winding topology with star connection. A actual practice, BLDC motors have more than one ofmotor with this topology is driven by energizing 2 the electrical circuits shown, wired in parallel to eachphases at a time. The static alignment shown in other, and a corresponding multi-pole permanent mag-Figure 2, is that which would be realized by creating an netic rotor. For two circuits there are two electrical rev-electric current flow from terminal A to B, noted as path olutions per mechanical revolution, so for a two circuit1 on the schematic in Figure 1. The rotor can be made motor, each electrical commutation phase would coverto rotate clockwise 60 degrees from the A to B align- 30 degrees of mechanical rotation.ment by changing the current path to flow from terminalC to B, noted as path 2 on the schematic. The sug- Sensored Commutationgested magnetic alignment is used only for illustrationpurposes because it is easy to visualize. In practice, The easiest way to know the correct moment to com-maximum torque is obtained when the permanent mag- mutate the winding currents is by means of a positionnet rotor is 90 degrees away from alignment with the sensor. Many BLDC motor manufacturers supplystator magnetic field. motors with a three-element Hall effect position sensor. Each sensor element outputs a digital high level for 180The key to BLDC commutation is to sense the rotor electrical degrees of electrical rotation, and a low levelposition, then energize the phases that will produce the for the other 180 electrical degrees. The three sensorsmost amount of torque. The rotor travels 60 electrical are offset from each other by 60 electrical degrees sodegrees per commutation step. The appropriate stator that each sensor output is in alignment with one of thecurrent path is activated when the rotor is 120 degrees electromagnetic circuits. A timing diagram showing thefrom alignment with the corresponding stator magnetic relationship between the sensor outputs and thefield, and then deactivated when the rotor is 60 degrees required motor drive voltages is shown in Figure 2.from alignment, at which time the next circuit is acti-vated and the process repeats. Commutation for therotor position, shown in Figure 1, would be at the com-pletion of current path 2 and the beginning of currentpath 3 for clockwise rotation. Commutating the electri-FIGURE 2: SENSOR VERSUS DRIVE TIMING ...1 6 5 4 3 2 1 6... +V A Float -V +V B Float -V +V C Float -V H Sensor A L H Sensor B L H Sensor C L Code 101 001 011 010 110 100 101 001DS00857A-page 2 © 2002 Microchip Technology Inc.
  3. 3. AN857The numbers at the top of Figure 2 correspond to the At this point we are ready to start building the motorcurrent phases shown in Figure 1. It is apparent from commutation control code. Commutation consists ofFigure 2 that the three sensor outputs overlap in such linking the input sensor state with the correspondinga way as to create six unique three-bit codes corre- drive state. This is best accomplished with a state tablesponding to each of the drive phases. The numbers and a table offset pointer. The sensor inputs will formshown around the peripheral of the motor diagram in the table offset pointer, and the list of possible outputFigure 1 represent the sensor position code. The north drive codes will form the state table. Code developmentpole of the rotor points to the code that is output at that will be performed with a PIC16F877 in an ICD. I haverotor position. The numbers are the sensor logic levels arbitrarily assigned PORTC as the motor drive port andwhere the Most Significant bit is sensor C and the Least PORTE as the sensor input port. PORTC was chosenSignificant bit is sensor A. as the driver port because the ICD demo board alsoEach drive phase consists of one motor terminal driven has LED indicators on that port so we can watch thehigh, one motor terminal driven low, and one motor ter- slow speed commutation drive signals without anyminal left floating. A simplified drive circuit is shown in external test equipment.Figure 3. Individual drive controls for the high and low Each driver requires two pins, one for high drive anddrivers permit high drive, low drive, and floating drive at one for low drive, so six pins of PORTC will be used toeach motor terminal. One precaution that must be control the six motor drive MOSFETS. Each sensortaken with this type of driver circuit is that both high side requires one pin, so three pins of PORTE will be usedand low side drivers must never be activated at the to read the current state of the motor’s three-outputsame time. Pull-up and pull-down resistors must be sensor. The sensor state will be linked to the drive stateplaced at the driver inputs to ensure that the drivers are by using the sensor input code as a binary offset to theoff immediately after a microcontoller RESET, when the drive table index. The sensor states and motor drivemicrocontroller outputs are configured as high imped- states from Figure 2 are tabulated in Table 1.ance inputs.Another precaution against both drivers being active atthe same time is called dead time control. When an out-put transitions from the high drive state to the low drivestate, the proper amount of time for the high side driverto turn off must be allowed to elapse before the low sidedriver is activated. Drivers take more time to turn offthan to turn on, so extra time must be allowed to elapseso that both drivers are not conducting at the sametime. Notice in Figure 3 that the high drive period andlow drive period of each output, is separated by a float-ing drive phase period. This dead time is inherent to thethree phase BLDC drive scenario, so special timing fordead time control is not necessary. The BLDC commu-tation sequence will never switch the high-side deviceand the low-side device in a phase, at the same time.FIGURE 3: THREE PHASE BRIDGE +VM +VM +VM A High B High C High control control control To A To B To C A Low B Low C Low control control control -VM -VM -VM© 2002 Microchip Technology Inc. DS00857A-page 3
  4. 4. AN857TABLE 1: CW SENSOR AND DRIVE BITS BY PHASE ORDER Pin RE2 RE1 RE0 RC5 RC4 RC3 RC2 RC1 RC0 Sensor Sensor Sensor C High C Low B High B Low A High A Low Phase C B A Drive Drive Drive Drive Drive Drive 1 1 0 1 0 0 0 1 1 0 2 1 0 0 1 0 0 1 0 0 3 1 1 0 1 0 0 0 0 1 4 0 1 0 0 0 1 0 0 1 5 0 1 1 0 1 1 0 0 0 6 0 0 1 0 1 0 0 1 0Sorting Table 1 by sensor code binary weight results in Table 2. Activating the motor drivers, according to a state tablebuilt from Table 2, will cause the motor of Figure 1 to rotate clockwise.TABLE 2: CW SENSOR AND DRIVE BITS BY SENSOR ORDER Pin RE2 RE1 RE0 RC5 RC4 RC3 RC2 RC1 RC0 Sensor Sensor Sensor C High C Low B High B Low A High A Low Phase C B A Drive Drive Drive Drive Drive Drive 6 0 0 1 0 1 0 0 1 0 4 0 1 0 0 0 1 0 0 1 5 0 1 1 0 1 1 0 0 0 2 1 0 0 1 0 0 1 0 0 1 1 0 1 0 0 0 1 1 0 3 1 1 0 1 0 0 0 0 1Counter clockwise rotation is accomplished by driving current through the motor coils in the direction opposite of thatfor clockwise rotation. Table 3 was constructed by swapping all the high and low drives of Table 2. Activating the motorcoils, according to a state table built from Table 3, will cause the motor to rotate counter clockwise. Phase numbers inTable 3 are preceded by a slash denoting that the EMF is opposite that of the phases in Table 2.TABLE 3: CCW SENSOR AND DRIVE BITS Pin RE2 RE1 RE0 RC5 RC4 RC3 RC2 RC1 RC0 Sensor Sensor Sensor C High C Low B High B Low A High A Low Phase C B A Drive Drive Drive Drive Drive Drive /6 0 0 1 1 0 0 0 0 1 /4 0 1 0 0 0 0 1 1 0 /5 0 1 1 1 0 0 1 0 0 /2 1 0 0 0 1 1 0 0 0 /1 1 0 1 0 0 1 0 0 1 /3 1 1 0 0 1 0 0 1 0The code segment for determining the appropriate drive word from the sensor inputs is shown in Figure 4.DS00857A-page 4 © 2002 Microchip Technology Inc.
  5. 5. AN857FIGURE 4: COMMUTATION CODE SEGMENT#define DrivePort PORTC#define SensorMask B’00000111’#define SensorPort PORTE#define DirectionBit PORTA, 1Commutate movlw SensorMask ;retain only the sensor bits andwf SensorPort ;get sensor data xorwf LastSensor, w ;test if motion sensed btfsc STATUS, Z ;zero if no change return ;no change - return xorwf LastSensor, f ;replace last sensor data with current btfss DirectionBit ;test direction bit goto FwdCom ;bit is zero - do forward commutation ;reverse commutation movlw HIGH RevTable ;get MS byte to table movwf PCLATH ;prepare for computed GOTO movlw LOW RevTable ;get LS byte of table goto Com2FwdCom ;forward commutation movlw HIGH FwdTable ;get MS byte of table movwf PCLATH ;prepare for computed GOTO movlw LOW FwdTable ;get LS byte of tableCom2 addwf LastSensor, w ;add sensor offset btfsc STATUS, C ;page change in table? incf PCLATH, f ;yes - adjust MS byte call GetDrive ;get drive word from table movwf DriveWord ;save as current drive word returnGetDrive movwf PCLFwdTable retlw B’00000000’ ;invalid retlw B’00010010’ ;phase 6 retlw B’00001001’ ;phase 4 retlw B’00011000’ ;phase 5 retlw B’00100100’ ;phase 2 retlw B’00000110’ ;phase 1 retlw B’00100001’ ;phase 3 retlw B’00000000’ ;invalidRevTable retlw B’00000000’ ;invalid retlw B’00100001’ ;phase /6 retlw B’00000110’ ;phase /4 retlw B’00100100’ ;phase /5 retlw B’00011000’ ;phase /2 retlw B’00001001’ ;phase /1 retlw B’00010010’ ;phase /3 retlw B’00000000’ ;invalid© 2002 Microchip Technology Inc. DS00857A-page 5
  6. 6. AN857Before we try the commutation code with our motor, lets An interesting fact about KT and KV is that their productconsider what happens when a voltage is applied to a is the same for all motors. Volts and Amps areDC motor. A greatly simplified electrical model of a DC expressed in MKS units, so if we also express KT inmotor is shown in Figure 5. MKS units, that is N-M/Rad/Sec, then the product of KV and KT is 1.FIGURE 5: DC MOTOR EQUIVALENT CIRCUIT EQUATION 3: KV * KT = 1 R L BEMF This is not surprising when you consider that the units of the product are [1/(V*A)]*[(N*M)/(Rad/Sec)], which is Motor the same as mechanical power divided by electrical power. If voltage were to be applied to an ideal motor from an ideal voltage source, it would draw an infinite amount ofWhen the rotor is stationary, the only resistance to cur- current and accelerate instantly to the speed dictatedrent flow is the impedance of the electromagnetic coils. by the applied voltage and KV. Of course no motor isThe impedance is comprised of the parasitic resistance ideal, and the start-up current will be limited by the par-of the copper in the windings, and the parasitic induc- asitic resistance and inductance of the motor windings,tance of the windings themselves. The resistance and as well as the current capacity of the power source.inductance are very small by design, so start-up cur- Two detrimental effects of unlimited start-up currentrents would be very large, if not limited. and voltage are excessive torque and excessive cur-When the motor is spinning, the permanent magnet rent. Excessive torque can cause gears to strip, shaftrotor moving past the stator coils induces an electrical couplings to slip, and other undesirable mechanicalpotential in the coils called Back Electromotive Force, problems. Excessive current can cause driver MOS-or BEMF. BEMF is directly proportional to the motor FETS to blow out and circuitry to burn.speed and is determined from the motor voltage con- We can minimize the effects of excessive current andstant KV. torque by limiting the applied voltage at start-up with pulse width modulation (PWM). Pulse width modulationEQUATION 1: is effective and fairly simple to do. Two things to con- sider with PWM are, the MOSFET losses due to switch- RPM = KV x Volts ing, and the effect that the PWM rate has on the motor. BEMF = RPM / KV Higher PWM frequencies mean higher switching losses, but too low of a PWM frequency will mean thatIn an ideal motor, R and L are zero, and the motor will the current to the motor will be a series of high currentspin at a rate such that the BEMF exactly equals the pulses instead of the desired average of the voltageapplied voltage. waveform. Averaging is easier to attain at lower fre- quencies if the parasitic motor inductance is relativelyThe current that a motor draws is directly proportional high, but high inductance is an undesirable motor char-to the torque load on the motor shaft. Motor current is acteristic. The ideal frequency is dependent on thedetermined from the motor torque constant KT. characteristics of your motor and power switches. For this application, the PWM frequency will be approxi-EQUATION 2: mately 10 kHz. Torque = KT x AmpsDS00857A-page 6 © 2002 Microchip Technology Inc.
  7. 7. AN857We are using PWM to control start-up current, so why There are several ways to modulate the motor drivers.not use it as a speed control also? We will use the ana- We could switch the high and low side drivers together,log-to-digital converter (ADC), of the PIC16F877 to or just the high or low driver while leaving the otherread a potentiometer and use the voltage reading as driver on. Some high side MOSFET drivers use athe relative speed control input. Only 8 bits of the ADC capacitor charge pump to boost the gate drive aboveare used, so our speed control will have 256 levels. We the drain voltage. The charge pump charges when thewant the relative speed to correspond to the relative driver is off and discharges into the MOSFET gatepotentiometer position. Motor speed is directly propor- when the driver is on. It makes sense then to switch thetional to applied voltage, so varying the PWM duty high side driver to keep the charge pump refreshed.cycle linearly from 0% to 100% will result in a linear Even though this application does not use the chargespeed control from 0% to 100% of maximum RPM. pump type drivers, we will modulate the high side driverPulse width is determined by continuously adding the while leaving the low side driver on. There are threeADC result to the free running Timer0 count to deter- high side drivers, any one of which could be activemine when the drivers should be on or off. If the addi- depending on the position of the rotor. The motor drivetion results in an overflow, then the drivers are on, word is 6-bits wide, so if we logically AND the driveotherwise they are off. An 8-bit timer is used so that the word with zeros in the high driver bit positions, and 1’sADC to timer additions need no scaling to cover the full in the low driver bit positions, we will turn off the activerange. To obtain a PWM frequency of 10 kHz Timer0 high driver regardless which one of the three it is.must be running at 256 times that rate, or 2.56 MHz. We have now identified 4 tasks of the control loop:The minimum prescale value for Timer0 is 1:2, so weneed an input frequency of 5.12 MHz. The input to • Read the sensor inputsTimer0 is FOSC/4. This requires an FOSC of 20.48 MHz. • Commutate the motor drive connectionsThat is an odd frequency, and 20 MHz is close enough, • Read the speed control ADCso we will use 20 MHz resulting in a PWM frequency of • PWM the motor drivers using the ADC and Timer09.77 kHz. addition results At 20 MHz clock rate, control latency, caused by the loop time, is not significant so we will construct a simple polled task loop. The control loop flow chart is shown in Figure 6 and code listings are in Appendix B.© 2002 Microchip Technology Inc. DS00857A-page 7
  8. 8. AN857FIGURE 6: SENSORED DRIVE FLOWCHART Initialize ADC Yes Ready ? Read new ADC No Set ADC GO Add ADRESH to TMR0 Yes Carry? No Mask Drive Word Output Drive Word No Sensor Change Yes Save Sensor Code CommutateDS00857A-page 8 © 2002 Microchip Technology Inc.
  9. 9. AN857Sensorless Motor Control FIGURE 7: BEMF EQUIVALENT CIRCUITIt is possible to determine when to commutate themotor drive voltages by sensing the back EMF voltage Von an undriven motor terminal during one of the drivephases. The obvious cost advantage of sensorless Bcontrol is the elimination of the Hall position sensors.There are several disadvantages to sensorless control: R• The motor must be moving at a minimum rate to generate sufficient back EMF to be sensed• Abrupt changes to the motor load can cause the BEMF drive loop to go out of lock L• The BEMF voltage can be measured only when the motor speed is within a limited range of the ideal commutation rate for the applied voltage• Commutation at rates faster than the ideal rate BBEMF will result in a discontinuous motor responseIf low cost is a primary concern and low speed motor COM ABEMF Aoperation is not a requirement and the motor load is notexpected to change rapidly then sensorless controlmay be the better choice for your application. CBEMFDetermining the BEMFThe BEMF, relative to the coil common connectionpoint, generated by each of the motor coils, can be Lexpressed as shown in Equation 4 through Equation 6.EQUATION 4: R BBEMF = sin ( α ) CEQUATION 5: Figure 7 shows the equivalent circuit of the motor with  coils B and C driven while coil A is undriven and avail- 2π CBEMF = sin  α - —  able for BEMF measurement. At the commutation fre- 3   quency the Ls are negligible. The Rs are assumed to be equal. The L and R components are not shown in the A branch since no significant current flows in this part of the circuit so those components can be ignored.EQUATION 6:   ABEMF = sin  α - 4π  —  3© 2002 Microchip Technology Inc. DS00857A-page 9
  10. 10. AN857The BEMF generated by the B and C coils in tandem, We will use this result to normalize the BEMF diagramsas shown in Figure 7, can be expressed as shown in presented later, but first lets consider the expectedEquation 7. BEMF at the undriven motor terminal. Since the applied voltage is pulse width modulated, theEQUATION 7: drive alternates between on and off throughout the phase time. The BEMF, relative to ground, seen at the BEMFBC = BBEMF - CBEMF A terminal when the drive is on, can be expressed as shown in Equation 9.The sign reversal of CBEMF is due to moving the refer- EQUATION 9:ence point from the common connection to ground.Recall that there are six drive phases in one electrical [V - (BBEMF - CBEMF )]R BEMFA = - C BEMF + ABEMFrevolution. Each drive phase occurs +/- 30 degrees 2Raround the peak back EMF of the two motor windingsbeing driven during that phase. At full speed theapplied DC voltage is equivalent to the RMS BEMF V - BBEMF + CBEMFvoltage in that 60 degree range. In terms of the peak BEMFA = - CBEMF + ABEMF 2BEMF generated by any one winding, the RMS BEMFvoltage across two of the windings can be expressedas shown in Equation 8. Notice that the winding resistance cancels out, so resistive voltage drop, due to motor torque load, is notEQUATION 8: a factor when measuring BEMF. The BEMF, relative to ground, seen at the A terminal π 2 when the drive is off can be expressed as shown in 3 2  2π   Equation 10. BEMFRMS = — ∫  sin (α) - sin  α - —   dα π π   3  6 EQUATION 10:   3 π 3π BEMFA = ABEMF - CBEMF BEMFRMS = +  π 2 4   BEMFRMS = 1.6554DS00857A-page 10 © 2002 Microchip Technology Inc.
  11. 11. AN857Figure 8 is a graphical representation of the BEMF for-mulas computed over one electrical revolution. Toavoid clutter, only the terminal A waveform, as wouldbe observed on a oscilloscope is displayed and isdenoted as BEMF(drive on). The terminal A waveformis flattened at the top and bottom because at thosepoints the terminal is connected to the drive voltage orground. The sinusoidal waveforms are the individualcoil BEMFs relative to the coil common connectionpoint. The 60 degree sinusoidal humps are the BEMFsof the driven coil pairs relative to ground. The entiregraph has been normalized to the RMS value of the coilpair BEMFs.FIGURE 8: BEMF AT 100% DRIVE BLDC Motor Waveforms (PWM at 100% Duty Cycle) 1.5 1 Vollts (Normalized to DC Drive) B C 0.5 A ABS(B-C) ABS(C-A) 0 ABS(A-B) BEMF(drive on) -0.5 -1 -30 30 90 150 210 270 330 Electrical DegreesNotice that the BEMF(drive on) waveform is fairly linearand passes through a voltage that is exactly half of theapplied voltage at precisely 60 degrees which coin-cides with the zero crossing of the coil A BEMF wave-form. This implies that we can determine the rotorelectrical position by detecting when the open terminalvoltage equals half the applied voltage.What happens when the PWM duty cycle is less than100%? Figure 9 is a graphical representation of theBEMF formulas computed over one electrical revolu-tion when the effective applied voltage is 50% of thatshown in Figure 8. The entire graph has been normal-ized to the peak applied voltage.© 2002 Microchip Technology Inc. DS00857A-page 11
  12. 12. AN857FIGURE 9: BEMF AT 50% DRIVE BLDC Motor Waveforms (PWM at 50% Duty Cycle) 1.5 1 Vollts (Normalized to DC Drive) B C 0.5 A ABS(B-C) ABS(C-A) 0 ABS(A-B) BEMF(drive on) -0.5 -1 -30 30 90 150 210 270 330 Electrical DegreesAs expected the BEMF waveforms are all reduced pro-portionally but notice that the BEMF on the open termi-nal still equals half the applied voltage midway throughthe 60 degree drive phase. This occurs only when thedrive voltage is on. Figure 10 shows a detail of the openterminal BEMF when the drive voltage is on and whenthe drive voltage is off. At various duty cycles, noticethat the drive on curve always equals half the appliedvoltage at 60 degrees.DS00857A-page 12 © 2002 Microchip Technology Inc.
  13. 13. AN857FIGURE 10: DRIVE ON VS. DRIVE OFF BEMF Floating Terminal Back EMF Floating Terminal Back EMF (PWM at 100% Duty Cycle) (PWM at 60% Duty Cycle) 1 1 Voltage (Normalized to DC Drive) Voltage (Normalized to DC Drive) BEMF(drive on) BEMF(drive on) 0.5 0.5 BEMF(drive off) BEMF(drive off) 0 0 30 90 30 90 Electrical Degrees Electrical Degrees Floating Terminal Back EMF Floating Terminal Back EMF (PWM at 75% Duty Cycle) (PWM at 10% Duty Cycle) 1 1 Voltage (Normalized to DC Drive) Voltage (Normalized to DC Drive) BEMF(drive on) BEMF(drive on) 0.5 0.5 BEMF(drive off) BEMF(drive off) 0 0 30 90 30 90 Electrical Degrees Electrical DegreesHow well do the predictions match an actual motor?Figure 11 is shows the waveforms present on terminalA of a Pittman N2311A011 brushless motor at variousPWM duty cycle configurations. The large transients,especially prevalent in the 100% duty cycle waveform,are due to flyback currents caused by the motor wind-ing inductance.© 2002 Microchip Technology Inc. DS00857A-page 13
  14. 14. AN857FIGURE 11: PITTMAN BEMF WAVEFORMS 100% Duty Cycle 50% Duty Cycle 75% Duty Cycle 10% Duty CycleThe rotor position can be determined by measuring thevoltage on the open terminal when the drive voltage isapplied and then comparing the result to one half of theapplied voltage.Recall that motor speed is proportional to the appliedvoltage. The formulas and graphs presented so far rep-resent motor operation when commutation rate coin-cides with the effective applied voltage. When thecommutation rate is too fast then commutation occursearly and the zero crossing point occurs later in thedrive phase. When the commutation rate is too slowthen commutation occurs late and the zero crossingpoint occurs earlier in the drive phase. We can senseand use this shift in zero crossing to adjust the commu-tation rate to keep the motor running at the ideal speedfor the applied voltage and load torque.DS00857A-page 14 © 2002 Microchip Technology Inc.
  15. 15. AN857Open Loop Speed Control The program that we use to run the motor open loop is the same program we will use to automatically adjustAn interesting property of brushless DC motors is that the commutation rate in response to variations in thethey will operate synchronously to a certain extent. This torque load. The program uses two potentiometers asmeans that for a given load, applied voltage, and com- speed control inputs. One potentiometer, we’ll call it themutation rate the motor will maintain open loop lock PWM potentiometer, is directly linked to both the PWMwith the commutation rate provided that these three duty cycle and the commutation time lookup table. Thevariables do not deviate from the ideal by a significant second potentiometer, we’ll call this the Offset potenti-amount. The ideal is determined by the motor voltage ometer, is used to provide an offset to the PWM dutyand torque constants. How does this work? Consider cycle determined by the PWM potentiometer. An ana-that when the commutation rate is too slow for an log-to-digital conversion of the PWM potentiometerapplied voltage, the BEMF will be too low resulting in produces a number between 0 and 255. The PWM dutymore motor current. The motor will react by accelerat- cycle is generated by adding the PWM potentiometering to the next phase position then slow down waiting reading to a free running 8-bit timer. When the additionfor the next commutation. In the extreme case the results in a carry the drive state is on, otherwise it is off.motor will snap to each position like a stepper motor The PWM potentiometer reading is also used to accessuntil the next commutation occurs. Since the motor is the 256 location commutation time lookup table. Theable to accelerate faster than the commutation rate, Offset potentiometer also produces a number betweenrates much slower than the ideal can be tolerated with- 0 and 255. The Most Significant bit of this number isout losing lock but at the expense of excessive current. inverted making it a signed number between -128 andNow consider what happens when commutation is too 127. This offset result, when added to the PWM poten-fast. When commutation occurs early the BEMF has tiometer, becomes the PWM duty cycle threshold, andnot reached peak resulting in more motor current and a controls the drive on and off states described previ-greater rate of acceleration to the next phase but it will ously.arrive there too late. The motor tries to keep up with thecommutation but at the expense of excessive current. Closed Loop Speed ControlIf the commutation arrives so early that the motor can Closed loop speed control is achieved by unlinking thenot accelerate fast enough to catch the next commuta- commutation time table index from the PWM duty cycletion, lock is lost and the motor spins down. This hap- number. The PWM potentiometer is added to a fixedpens abruptly not very far from the ideal rate. The manual threshold number between 0 and 255. Whenabrupt loss of lock looks like a discontinuity in the motor this addition results in a carry, the mode is switched toresponse which makes closed loop control difficult. An automatic. On entering Automatic mode the commuta-alternative to closed loop control is to adjust the com- tion index is initially set to the PWM potentiometermutation rate until self locking open loop control is reading. Thereafter, as long as Automatic mode is stillachieved. This is the method we will use in our applica- in effect, the commutation table index is automaticallytion. adjusted up or down according to voltages read atWhen the load on a motor is constant over it’s operating motor terminal A at specific times. Three voltage read-range then the response curve of motor speed relative ings are applied voltage is linear. If the supply voltage is wellregulated, in addition to a constant torque load, then FIGURE 12: BEMF SAMPLE TIMESthe motor can be operated open loop over it’s entirespeed range. Consider that with pulse width modula-tion the effective voltage is linearly proportional to thePWM duty cycle. An open loop controller can be madeby linking the PWM duty cycle to a table of motor speedvalues stored as the time of commutation for each drivephase. We need a table because revolutions per unittime is linear, but we need time per revolution which isnot linear. Looking up the time values in a table is muchfaster than computing them repeatedly.© 2002 Microchip Technology Inc. DS00857A-page 15
  16. 16. AN857The first reading is taken during drive phase 4 when ter- another speed adjustment will be made. Adjustmentsminal A is actively driven high. This is the applied volt- continue to be made ahead of the motor response untilage. The next two readings are taken during drive eventually, the commutation time is too short for thephase 5 when terminal A is floating. The first reading is applied voltage, and the motor goes out of lock. Thetaken when ¼ of the commutation time has elapsed acceleration timer delay prevents this runaway condi-and the second reading is taken when ¾ of the commu- tion. Since the motor can tolerate commutation timestation time has elapsed. Well call these readings 1 and that are too long, but not commutation times that are2 respectively. The commutation table index is adjusted too short, the acceleration time delay can be longeraccording to the following relationship between the than required without serious detrimental effect.applied voltage reading and readings 1 and 2: Consider what happens in the control loop when the• Index is unchanged if Reading 1 > Applied Volt- voltage to the motor suddenly falls, or the motor load is age/2 and Reading 2 < Applied Voltage/2 suddenly increased. If the change is sufficiently large,• Index is increased if Reading 1 < Applied Voltage/ commutation time will immediately be running too short 2 for the motor conditions. The motor cannot tolerate this,• Index is decreased if Reading 1 > Applied Volt- and loss of lock will occur. To prevent loss of lock, the age/2 and Reading 2 > Applied Voltage/2 loop deceleration timer delay must be short enough for the control loop to track, or precede the changing motorThe motor rotor and everything it is connected to has a condition. If the time delay is too short, then the controlcertain amount of inertia. The inertia delays the motor loop will continue to lengthen the commutation timeresponse to changes in voltage load and commutation ahead of the motor response resulting in over compen-time. Updates to the commutation time table index are sation. The motor will eventually slow to a speed thatdelayed to compensate for the mechanical delay and will indicate to the BEMF sensor that the speed is tooallow the motor to catch up. slow for the applied voltage. At that point, commutation deceleration will cease, and the commutation changeAcceleration and Deceleration Delay will adjust in the opposite direction governed by theThe inertia of the motor and what it is driving, tends to acceleration time delay. Over compensation duringdelay motor response to changes in the drive voltage. deceleration will not result in loss of lock, but will causeWe need to compensate for this delay by adding a increased levels of torque ripple and motor current untilmatching delay to the control loop. The control loop the ideal commutation time is eventually reached.delay requires two time constants, a relatively slow onefor acceleration, and a relatively fast one for decelera- Determining The Commutation Timetion. Table ValuesConsider what happens in the control loop when the The assembler supplied with MPLAB performs all cal-voltage to the motor suddenly rises, or the motor load culations as 32-bit integers. To avoid the roundingis suddenly reduced. The control senses that the motor errors that would be caused by integer math, we willrotation is too slow and attempts to adjust by making use a spreadsheet, such as Excel, to compute the tablethe commutation time shorter. Without delay in the con- entries then cut and paste the results to an include file.trol loop, the next speed measurement will be taken The spreadsheet is setup as shown in Table 4.before the motor has reacted to the adjustment, andTABLE 4: COMMUTATION TIME TABLE VALUES Variable Name Number or Formula Description Phases 12 Number of commutation phase changes in one mechanical revolution. FOSC 20 MHz Microcontroller clock frequency FOSC_4 FOSC/4 Microcontroller timers source clock Prescale 4 Timer 1 prescale MaxRPM 8000 Maximum expected speed of the motor at full applied voltage MinRPM (60*FOSC_4)/Phases*Prescale*65535)+1 Limitation of 16-bit timer Offset -345 This is the zero voltage intercept on the RPM axis. A property normalized to the 8-bit A to D converter. Slope (MaxRPM-Offset)/255 Slope of the RPM to voltage input response curve normalized to the 8-bit A to D converter.DS00857A-page 16 © 2002 Microchip Technology Inc.
  17. 17. AN857The body of the spreadsheet starts arbitrarily at row 13. The range of commutation phase times at a reasonableRow 12 contains the column headings. The body of the resolution requires a 16-bit timer. The timer counts fromspreadsheet is constructed as follows: 0 to a compare value then automatically resets to 0.• Column A is the commutation table index number The compare values are stored in the commutation N. The numbers in column A are integers from 0 time table. Since the comparison is 16 bits and tables to 255. can only handle 8 bits the commutation times will be stored in two tables accessed by the same index.• Column B is the RPM that will result by using the counter values at index number N. The formula in • Column E is the most significant byte of the 16-bit column B is: =IF(Offset+A13*Slope>MinRPM,Off- timer compare value. The formula for column E is: set+A13*Slope,MinRPM). =CONCATENATE("retlw high D”,INT(D13),””).• Column C is the duration of each commutation • Column F is the least significant byte of the 16-bit phase expressed in seconds. The formula for col- timer compare value. The formula for column F is: umn C is: =60/(Phases*B13). =CONCATENATE(“retlw low D”,INT(D13),””).• Column D is the duration of each commutation When all spreadsheet formulas have been entered in phase expressed in timer counts. The formula for row 13, the formulas can be dragged down to row 268 column D is: =C13*FOSC_4/Prescale. to expand the table to the required 256 entries. Col- umns E and F will have the table entries in assembler ready format. An example of the table spreadsheet is shown in Figure 13.FIGURE 13: PWM LOOKUP TABLE GENERATOR© 2002 Microchip Technology Inc. DS00857A-page 17
  18. 18. AN857Using Open Loop Control to Determine To obtain the response offset with Excel®, enter theMotor Characteristics voltage (left column), and RPM (right column) pairs in adjacent columns of the spreadsheet. Use the chartYou can measure the motor characteristics by operat- wizard to make an X-Y scatter chart. When the chart ising the motor in Open Loop mode, and measuring the finished, right click on the response curve and selectmotor current at several applied voltages. You can then the pop-up menu “add trendline. . .” option. Choose thechart the response curve in a spreadsheet, such as linear regression type and, in the Options tab, checkExcel, to determine the slope and offset numbers. the “display equation on chart” option. An example ofFinally, plug the maximum RPM and offset numbers the spreadsheet is shown in Figure 14.back into the table generator spreadsheet to regener-ate the RPM tables.To operate the motor in Open Loop mode:• Set the manual threshold number (ManThresh) to 0xFF. This will prevent the Auto mode from tak- ing over.• When operating the motor in Open Loop mode, start by adjusting the offset control until the motor starts to move. You may also need to adjust the PWM control slightly above minimum.• After the motor starts, you can increase the PWM control to increase the motor speed. The RPM and voltage will track, but you will need to adjust the offset frequently to optimize the voltage for the selected RPM.• Optimize the voltage by adjusting the offset for minimum current.FIGURE 14: MOTOR RESPONSE SCOPE DETERMINATIONDS00857A-page 18 © 2002 Microchip Technology Inc.
  19. 19. AN857Constructing The Sensorless ControlCodeAt this point we have all the pieces required to controla sensorless motor. We can measure BEMF and theapplied voltage then compare them to each other todetermine rotor position. We can vary the effectiveapplied voltage with PWM and control the speed of themotor by timing the commutation phases. Some mea-surement events must be precisely timed. Other mea-surement events need not to interfere with each other.The ADC must be switched from one source to anotherand allow for sufficient acquisition time. Some eventsmust happen rapidly with minimum latency. Theseinclude PWM and commutation.We can accomplish everything with a short main loopthat calls a state table. The main loop will handle PWMand commutation and the state table will schedulereading the two potentiometers, the peak applied volt-age and the BEMF voltages at two times when theattached motor terminal is floating. Figure A-1 throughFigure A-10, in Appendix A, is the resulting flow chartof sensorless motor control. Code listings are inAppendix C and Appendix D.© 2002 Microchip Technology Inc. DS00857A-page 19
  20. 20. AN857APPENDIX A: SENSORLESS CONTROL FLOWCHARTFIGURE A-1: MAIN LOOP Sensorless Control Initialize Yes Is Timer1 Compare Flag Set? Call Commutate No Yes Is Full On Flag Set? No Add PWM Threshold to Timer0 Yes Carry No ? Set Drive-On Clear Drive-On Flag Flag Call DriveMotor Call LockTest Call StateMachineDS00857A-page 20 © 2002 Microchip Technology Inc.
  21. 21. AN857FIGURE A-2: MOTOR COMMUTATION Commutate Is Timer1 Clear on Compare Yes Enabled? No Decrement PhaseIndex Is Yes PhaseIndex =0? PhaseIndex = 6 No Drive Word = Table Entry@PhaseIndex DriveMotor Commutate End© 2002 Microchip Technology Inc. DS00857A-page 21
  22. 22. AN857FIGURE A-3: MOTOR DRIVER CONTROL DriveMotor Get Stored DriveWord No Is DriveOnFlag Set? AND DriveWord with OffMask Yes OR DriveWord with SpeedStatus Output DriveWord to motor drive port DriveMotor EndFIGURE A-4: PHASE DRIVE PERIOD SetTimer High byte of Timer1 compare= High byte Table@RPMIndex Low byte of Timer1 compare= Low byte Table@RPMIndex SetTimer EndDS00857A-page 22 © 2002 Microchip Technology Inc.
  23. 23. AN857FIGURE A-5: MOTOR SPEED LOCKED WITH COMMUTATION RATE LockTest No Is PWM cycle start flag set? Yes Which half On Cycle of PWM cycle is longest? No Is Drive Yes Off Cycle Active? Clear PWM cycle start flag Decrement RampTimer Is No RampTimer Zero? Yes Is No Yes ADCRPM > Manual Threshold? Reset AutoRPM Set AutoRPM Flag Flag LT3 LT2© 2002 Microchip Technology Inc. DS00857A-page 23
  24. 24. AN857FIGURE A-6: MOTOR SPEED LOCKED WITH COMMUTATION RATE (CONT.) LT3 LT2 Is Yes BEMF1 < No VSupply/2 ? Is BEMF2 < Yes VSupply/2 ? No SpeedStatus = SpeedStatus = Speed Too Slow Speed Too Fast RampTimer = RampTimer = AccelerateDelay DecelerateDelay No No AutoRPM? AutoRPM? Yes Yes Decrement RPMIndex Increment RPMIndex Limit to minimum Limit to maximum SpeedStatus = RPMIndex = ADCRPM Speed Locked RampTimer = DecelerateDelay LockTest EndDS00857A-page 24 © 2002 Microchip Technology Inc.
  25. 25. AN857FIGURE A-7: MOTOR CONTROL STATE MACHINE StateMachine Yes State = RPMSetup ? Is No No motor in Phase 1 ? State = Yes RPMSetup Yes ? Start ADC No Is ADC No Done? Change ADC input to Offset Pot Yes ADCRPM = ADC State = RPMRead Result State = OffsetSetup State = Yes OffsetSetup ? Is No No motor in Phase 2 ? Yes State = Yes OffsetRead ? Start ADC No Is ADC No Done? Change ADC input to Motor Terminal A Yes ADCOffset = ADC Result Invert msb of ADC Offset State = OffsetRead PWMThreshold = ADCRPM + ADCOffset Limit PWMThreshold to Max or Min SM4 SM1 SM2 SM3© 2002 Microchip Technology Inc. DS00857A-page 25
  26. 26. AN857FIGURE A-8: MOTOR CONTROL STATE MACHINE (CONT.) SM4 SM1 SM2 SM3 Yes State = VSetup ? Is Yes PWMThreshold Is No No motor = 0? in Phase 4 ? No Yes Yes Is No PWMThreshold Call SetTimer >0xFD? Set Clear FullOnFlag FullOnFlag State = Vldle State = VSetup Clear SpeedStatus Yes State = Vldle ? Set ADC input to PWM Pot Is No No motor drive active ? State = RPMSetup Yes Wait for ADC State = Yes acquisition time VRead ? No Is ADC No Start ADC Done? Yes State = VRead VSupply = ADC Result State = BEMFSetup SM4 SM5 SM3DS00857A-page 26 © 2002 Microchip Technology Inc.
  27. 27. AN857FIGURE A-9: MOTOR CONTROL STATE MACHINE (CONT.) SM4 SM5 SM3 Yes State = BEMFSetup ? Is No No motor in Phase 5 ? State = Yes Yes BEMFSetup ? Is No No this the start Timer1 No of the longest PWM compare? half cycle ? Yes Yes Disable Timer1 Force motor clear on compare drive active Save current Wait for ADC compare word acquisition time (commutation time) Set compare word Start ADC to 1/4 current commutation time Set compare word State = BEMFIdle to 3/4 current commutation time State = BEMFRead Yes State = BEMFRead ? Is No No ADC Done? Yes DeltaV1 = VSupply/2 - ADC result SM4 State = BEMF2Idle SM6 SM3© 2002 Microchip Technology Inc. DS00857A-page 27
  28. 28. AN857 FIGURE A-10: MOTOR CONTROL STATE MACHINE (CONT.) SM4 SM6 SM3 State = Yes BEMF2Idle ? No Timer1 No Compare State = ? Yes BEMF2Read Yes ? Force motor No Is ADC No Done? drive active Yes Wait for ADC DeltaV2 = acquisition time VSupply/2 - ADC result State = RPMSetup Start ADC Change ADC input to PWM Pot Set Timer1 compare word to saved commutation time Change compare mode to clear Invalid State: Timer1 on compare Set ADC input to PWM Pot State = RPMSetup State = BEMF2Read StateMachine EndDS00857A-page 28 © 2002 Microchip Technology Inc.
  29. 29. AN857APPENDIX B: SCHEMATICSFIGURE B-1: SCHEMATIC A - MOTOR DRIVERS© 2002 Microchip Technology Inc. DS00857A-page 29
  30. 30. AN857FIGURE B-2: SCHEMATIC B - CONTROLLERDS00857A-page 30 © 2002 Microchip Technology Inc.
  31. 31. AN857 Software License Agreement The software supplied herewith by Microchip Technology Incorporated (the “Company”) for its PICmicro® Microcontroller is intended and supplied to you, the Company’s customer, for use solely and exclusively on Microchip PICmicro Microcontroller prod- ucts. The software is owned by the Company and/or its supplier, and is protected under applicable copyright laws. All rights are reserved. Any use in violation of the foregoing restrictions may subject the user to criminal sanctions under applicable laws, as well as to civil liability for the breach of the terms and conditions of this license. THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATU- TORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICU- LAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.APPENDIX C: SENSORED CODE;**********************************************************************; *; Filename: sensored.asm *; Date: 11 Feb. 2002 *; File Version: 1.0 *; *; Author: W.R. Brown *; Company: Microchip Technology Incorporated *; *; *;**********************************************************************; *; Files required: *; *; *; *;**********************************************************************; *; Notes: Sensored brushless motor control Main loop uses 3-bit *; sensor input as index for drive word output. PWM based on *; Timer0 controls average motor voltage. PWM level is determined *; PWM level is determined from ADC reading of potentiometer. *; *;********************************************************************** list p=16f877 ; list directive to define processor #include <> ; processor specific variable definitions __CONFIG _CP_OFF & _WDT_OFF & _BODEN_ON & _PWRTE_ON & _HS_OSC & _WRT_ENABLE_OFF & _LVP_ON &_DEBUG_OFF & _CPD_OFF;**********************************************************************;*;* Define variable storage;* CBLOCK 0x20 ADC ; PWM threshold is ADC result LastSensor ; last read motor sensor data DriveWord ; six bit motor drive data ENDC© 2002 Microchip Technology Inc. DS00857A-page 31
  32. 32. AN857;**********************************************************************;*;* Define I/O;*#define OffMask B’11010101’#define DrivePort PORTC#define DrivePortTris TRISC#define SensorMask B’00000111’#define SensorPort PORTE#define DirectionBit PORTA,1;********************************************************************** org 0x000 ; startup vector nop ; required for ICD operation clrf PCLATH ; ensure page bits are cleared goto Initialize ; go to beginning of program ORG 0x004 ; interrupt vector location retfie ; return from interrupt;**********************************************************************;*;* Initialize I/O ports and peripherals;*Initialize clrf DrivePort ; all drivers off banksel TRISA; setup I/O clrf DrivePortTris ; set motor drivers as outputs movlw B’00000011’ ; A/D on RA0, Direction on RA1, Motor sensors on RE<2:0> movwf TRISA ;; setup Timer0 movlw B’11010000’ ; Timer0: Fosc, 1:2 movwf OPTION_REG; Setup ADC (bank1) movlw B’00001110’ ; ADC left justified, AN0 only movwf ADCON1 banksel ADCON0; setup ADC (bank0) movlw B’11000001’ ; ADC clock from int RC, AN0, ADC on movwf ADCON0 bsf ADCON0,GO ; start ADC clrf LastSensor ; initialize last sensor reading call Commutate ; determine present motor position clrf ADC ; start speed control threshold at zero until first ADCreading;**********************************************************************;*;* Main control loop;*Loop call ReadADC ; get the speed control from the ADC incfsz ADC,w ; if ADC is 0xFF we’re at full speed - skip timer add goto PWM ; add Timer0 to ADC for PWM movf DriveWord,w ; force on condition goto Drive ; continuePWMDS00857A-page 32 © 2002 Microchip Technology Inc.
  33. 33. AN857 movf ADC,w ; restore ADC reading addwf TMR0,w ; add it to current Timer0 movf DriveWord,w ; restore commutation drive data btfss STATUS,C ; test if ADC + Timer0 resulted in carry andlw OffMask ; no carry - suppress high driversDrive movwf DrivePort ; enable motor drivers call Commutate ; test for commutation change goto Loop ; repeat loopReadADC;**********************************************************************;*;* If the ADC is ready then read the speed control potentiometer;* and start the next reading;* btfsc ADCON0,NOT_DONE ; is ADC ready? return ; no - return movf ADRESH,w ; get ADC result bsf ADCON0,GO ; restart ADC movwf ADC ; save result in speed control threshold return ;;**********************************************************************;*;* Read the sensor inputs and if a change is sensed then get the;* corresponding drive word from the drive table;*Commutate movlw SensorMask ; retain only the sensor bits andwf SensorPort,w ; get sensor data xorwf LastSensor,w ; test if motion sensed btfsc STATUS,Z ; zero if no change return ; no change - back to the PWM loop xorwf LastSensor,f ; replace last sensor data with current btfss DirectionBit ; test direction bit goto FwdCom ; bit is zero - do forward commutation ; reverse commutation movlw HIGH RevTable ; get MS byte of table movwf PCLATH ; prepare for computed GOTO movlw LOW RevTable ; get LS byte of table goto Com2FwdCom ; forward commutation movlw HIGH FwdTable ; get MS byte of table movwf PCLATH ; prepare for computed GOTO movlw LOW FwdTable ; get LS byte of tableCom2 addwf LastSensor,w ; add sensor offset btfsc STATUS,C ; page change in table? incf PCLATH,f ; yes - adjust MS byte call GetDrive ; get drive word from table movwf DriveWord ; save as current drive word returnGetDrive movwf PCL© 2002 Microchip Technology Inc. DS00857A-page 33
  34. 34. AN857;**********************************************************************;*;* The drive tables are built based on the following assumptions:;* 1) There are six drivers in three pairs of two;* 2) Each driver pair consists of a high side (+V to motor) and low side (motor to ground) drive;* 3) A 1 in the drive word will turn the corresponding driver on;* 4) The three driver pairs correspond to the three motor windings: A, B and C;* 5) Winding A is driven by bits <1> and <0> where <1> is A’s high side drive;* 6) Winding B is driven by bits <3> and <2> where <3> is B’s high side drive;* 7) Winding C is driven by bits <5> and <4> where <5> is C’s high side drive;* 8) Three sensor bits constitute the address offset to the drive table;* 9) A sensor bit transitions from a 0 to 1 at the moment that the corresponding;* winding’s high side forward drive begins.;* 10) Sensor bit <0> corresponds to winding A;* 11) Sensor bit <1> corresponds to winding B;* 12) Sensor bit <2> corresponds to winding C;*FwdTable retlw B’00000000’ ; invalid retlw B’00010010’ ; phase 6 retlw B’00001001’ ; phase 4 retlw B’00011000’ ; phase 5 retlw B’00100100’ ; phase 2 retlw B’00000110’ ; phase 1 retlw B’00100001’ ; phase 3 retlw B’00000000’ ; invalidRevTable retlw B’00000000’ ; invalid retlw B’00100001’ ; phase /6 retlw B’00000110’ ; phase /4 retlw B’00100100’ ; phase /5 retlw B’00011000’ ; phase /2 retlw B’00001001’ ; phase /1 retlw B’00010010’ ; phase /3 retlw B’00000000’ ; invalid END ; directive ’end of program’DS00857A-page 34 © 2002 Microchip Technology Inc.