This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
AN1012PIC16HV785: Programmable Lithium and Nickel Battery Charger
Features
• User-Configurable Battery Charger for Lithium, Nickel and Lead Battery Packs
• Based on PIC16F785 with Integrated Shunt Regulator
• Firmware and Support Tools for easy design• 10-bit ADC for Voltage, Current and Temperature
Measurement:- Accurate voltage regulation (+/-1%)- Accurate current regulation (+/-5%)
The PIC16HV785 provides an unprecedented level ofconfigurability for charging Lithium Ion/Lithium Polymerbattery packs. Its precise, 10-bit Analog-to-Digital con-verter and high-frequency Pulse-Width Modulatorenable the PIC16HV785 to provide optimum control ofcharging algorithms for lithium battery chemistries.Special features include an internal voltage regulatorand an internal clock oscillator that reduce externalcomponent count. The PIC16HV785 can be configuredas either a Switch mode or a linear charger. In Switchmode, it will support either primary or secondary sidecontrol. In Linear mode, it can be designed intoapplications requiring low-power supply noise.
MULTI-STEP CHARGING
To insure the proper treatment of lithium chemistriesduring extreme temperature and voltage conditions,multi-step charging is required. The PIC16HV785starts the charging cycle upon sensing the presence ofa battery pack and a valid charging supply. Duringcharge qualification, the battery’s temperature and volt-age are measured to determine the appropriate initialstate. The initial states include Charge Suspend, Pre-charge and Current Regulation. Charge Suspend haltscharging when the user-defined preset conditions forcharging are not met. Precharge allows for the recov-ery of deeply discharged batteries by applying a lowcharge (or C) rate. Current Regulation providesconstant current, voltage limited charge. Uponreaching the target voltage during Current Regulation,the Voltage Regulation state is entered. Chargingcontinues at a constant voltage until the currentdecreases to the user-specified minimum currentthreshold. The user-specified minimum currentthreshold can be configured for various chargingtemperatures. At this threshold, charging is terminatedand the End-of-Charge state is reached.
USER-CONFIGURABLE PARAMETERS
The PIC16HV785 supports user-configurable parame-ters that allow for customizing the charging profile with-out changing the charger’s hardware design. Thisfeature allows for the maximum reuse of hardware,thus reducing time-to-market. These parametersinclude:
• Battery Temperature:- Minimum/maximum temperature for charge
initiation- Maximum temperature allowed during charge
• Battery Voltage:
- Minimum/maximum voltage for charge initiation- Target voltage during voltage regulation- Voltage at which the charger will restart
charging after completion of a valid charge cycle• Charge Current:
- Target current during current regulation- Taper current threshold for End-of-Charge
during voltage regulation- Target current during precharge
• Time:
- Precharge time limit- Current regulation time limit- Voltage regulation time limit
• Status Display:- Duty cycle for the two LEDs denoting charge
states can be modified
These parameters are configured through thePowerTool™ 200 Development Software for thePIC16HV785.
SPECIAL FEATURES
The PIC16HV785 includes a voltage regulator, a volt-age reference, an internal clock oscillator and ahigh-frequency Pulse-Width Modulator.
• The internal voltage regulator has a maximum input voltage of 18V and eliminates the need for external references
• The precise, internal 8 MHz clock oscillator eliminates the need for external oscillator circuits
• The high-speed Pulse-Width Modulator is used for power regulation and can support frequencies up to 500 kHz
The PIC16HV785 is a configurable, Switch modecharger which is comprised of a PIC16F microcontrol-ler core and precision analog circuitry. This sectionexplores the hardware features in relation to genericSwitch mode charging. The PIC16HV785 hardware isa PIC16F785 device with an integrated shunt regulator,to allow the device to be powered directly from a bat-tery stack, or from charger voltage. It is available in a20-pin PDIP, SOIC or SSOP package. See thePIC16F785 data sheet for more hardware description.Hardware features include:
• Operational Amplifier module with two independent op amps
• Two-Phase Asynchronous Feedback PWM• Voltage Regulator• 10-bit A/D Converter
• In-Circuit Serial Programming™ (ICSP™) via two pins
Hardware Features
The PIC16HV785 features are well-suited for Switchmode battery charging. The PIC16HV785 device’sblock diagram (Figure 1) is to be used in conjunctionwith the Switch mode charger example (Figure 10,page 9).
• Current/Voltage Measurement Block – The Current/Voltage Measurement Block consists of a 10-bit Analog-to-Digital converter, operational amplifiers and a comparator. The output of this block is fed into the charge control module (refer to Figure 1).The inputs into this block are to be connected asdescribed in Figure 10. The following signals areinputs into this block:
- LOOPFBK: to comparator- LOOPIN: to op amp and ADC- CTRLIN: to op amp
- IFBINB: to op amp- IFBINA: to op amp- BATID: to ADC
- TEMP: to ADC- CHGFBK: to comparatorThe following signals are outputs from this block:
- IFBOUT: from op amp
• Charge Control Module – The charge control module generates a Pulse-Width Modulated signal called CHGOUT. Its frequency is config-urable and can be set up to 1 MHz. This signal is connected to an external DC/DC buck converter.
• Voltage Regulator – The integrated voltage regulator is designed to work with unregulated DC supplies.
• The precision internal 8 MHz clock oscillator eliminates the need for external oscillator circuits.
• In-circuit configurability utilizing 256 bytes of on-board EEPROM.
• Power on Reset – The POR insures the proper start-up of the PIC16HV785 when voltage is applied to VDD.
• Brown-out Reset – The BOR is activated when the input voltage falls to 2.1V; the PIC16HV785 is reset.
In this schematic, the PIC16HV785 is being used tocontrol a step-down buck converter. A buck converteruses a square wave pulse train to turn on and off aswitch that provides current into an inductor. The ratioof output voltage to input voltage is the duty cycle of thepulse. Current and voltage feedback are used to con-trol the duty cycle to regulate the output voltage andcurrent.
Buck Converter
The inductor L1, the capacitor COUT and diode D1 com-prise the buck converter. The MOSFET Q1 is theswitch that applies the charger voltage when turned on.It is driven by a pulse train applied by the PIC16HV785.
FIGURE 2: BUCK CONVERTER
In the above diagram, when a constant voltage isapplied to VIN and a pulse train of constant frequencyand duty cycle is applied to the age of the MOSFET, theresult is a constant voltage at VOUT which is a fractionof VIN equal to the duty cycle of the pulse.
The voltage drop across the inductor is:
EQUATION 1:
With the voltage regulated at VOUT, the drop across theinductor is VIN – VOUT, thus the current through theinductor is:
EQUATION 2:
This integral taken over one pulse cycle can be brokendown into pulse on and pulse off time. When the pulse ison, VIN = VCHARGE, and when the pulse is low, VIN = 0.Since the current is the same at the beginning of eachcycle, the equation becomes:
EQUATION 3:
When the pulse goes high, the current through theinductor increases as a response. When the pulsegoes low, the current decreases. The graph (Figure 3)shows the current through the inductor as a responseto the input pulse, and the resulting voltage drop acrossthe inductor.
When the current through the inductor is increasing, asa result of the pulse going high, the voltage drop acrossthe inductor is positive (di/dt is positive). This drop issubtracted from the applied charge voltage to produceVOUT. When the current through the inductor isdecreasing (di/dt is negative), the voltage drop acrossthe inductor is negative, adding to the zero inputvoltage to produce VOUT.
FIGURE 3: BUCK CONVERTER WAFEFORMS
Feedback Circuits
The circuit uses feedback for two purposes. One is toprovide the ramp waveform that defines the PWM dutycycle. The other is the current sense that is comparedto a reference voltage to determine if the current isbeing regulated at the correct level. This is also fedback into the PWM to modulate the duty cycle.
The CHGFBK pin (pin 16) receives the ramp sawtoothwaveform that controls the duty cycle of the PWM signal.This sawtooth needs to be generated externally by anRC network connected to the PWM output. The RC net-work uses the frequency of the PWM to generate thesawtooth waveform. When the PWM is triggered high,the sawtooth starts to ramp up. When the sawtoothreaches a certain point (determined internally by refer-ence voltage and current feedback), the PWM output issent low, also driving the sawtooth low. The sawtoothstarts up again when the internal oscillator sends thePWM high again.
The RC circuit can be placed on the output of the PWMsignal. A clamping diode can be used to control thetotal voltage drop.
FIGURE 4: SAWTOOTH GENERATOR
The voltage at CHGFBK will ramp up when the PWMoutput at CHGOUT triggers high. When the ramp atCHGFBK exceeds the internal comparator level of ref-erence voltage, the PWM will trigger CHGOUT low. Theconstant frequency sawtooth will determine the pulsewidth as a function of internal reference voltage.
FIGURE 5: SAWTOOTH AND PWM WAVEFORMS
CURRENT FEEDBACK
The aforementioned reference voltage is determined bycurrent feedback in order to regulate the current. A sec-ond PWM, which is under firmware control, is used tocreate a DC level to which to compare the sensed cur-rent. The voltage drop across a current sense resistor isapplied to pin 13 (IFBINA) and is internally amplified by anop amp. The output of this op amp is available on pin 14(IFBOUT). The output on pin 14 is then fed into pin 8(LOOPIN) which is the input to another op amp. Theother input of this op amp is a DC level that is created bythe firmware controlled PWM. The firmware controlledPWM is output on pin 5 (CTRLOUT) and fed into an RCcircuit whose time constant is high enough to create arough DC level. This DC level will vary with the dutycycle of the firmware controlled PWM. This DC level isthen applied to pin 9 (CTRLIN). This DC level is com-pared to the current feedback by op amp 1. The outputof op amp 1 is fed to the main internal comparator whereit is compared to the sawtooth waveform to determinethe duty cycle of the main PWM, which regulates currentthrough the buck converter.
FIGURE 6: FEEDBACK DIAGRAM
The actual circuit implementation, including op ampfeedback RC networks, is shown below.
The PIC16HV785 has a built-in shunt regulator to allowthe device to be powered directly by the charging volt-age. The integrated voltage regulator is designed towork with unregulated DC supplies. While there is, theo-retically, no limit to the charging voltage, there are guide-lines that should be followed. A series limiting resistor(RVDD) should be placed between the unregulated sup-ply and the VDD pin. The value for this series resistor(RVDD) must be between RMIN and RMAX as shown inthe following equation:
EQUATION 4:
Overvoltage Protection
The PIC16HV785 has a comparator that is gated to thePWM which compares the reference voltage to anexternal divided voltage applied to pin 18 (VOVP). Whenthe voltage on pin 18 exceeds the reference voltage,the PWM is turned off. The external voltage dividershould be chosen such that the preferred overvoltagesafety point is used.
FIGURE 8: OVERVOLTAGE CIRCUIT
A/D Inputs
The internal A/D converter is used to measure thecharging voltage on pin 3 (VIN), the current on pin 13(IFBINA) and optionally, the temperature on pin 19(TEMP) if there is a thermistor present. An externalvoltage divider is used on pin 3 to measure the chargevoltage.
FIGURE 9: A/D INPUTS
Where:RMAX = maximum value of series resistor (ohms)
RMIN = minimum value of series resistor (ohms)Vs(MIN) = minimum value of charger DC supply (VDC)Vs(MAX) = maximum value of charger DC supply (VDC)
I(led) = total current drawn by all LEDs when illuminated simultaneously
Note: The 1.05 and .95 constants are included tocompensate for the tolerance of 5% resis-tors. The 16 mA constant is the anticipatedload presented by the PIC16HV785, includ-ing the loading, due to external componentsand a 4 mA minimum current for the shuntregulator itself. The 50 mA constant is themaximum acceptable current for the shuntregulator.
To ensure the proper treatment of lithium chemistriesduring extreme temperature and voltage conditions,multi-step charging is required. The PIC16HV785measures key voltage, temperature and timeparameters. It compares them to user-defined voltage,temperature and time limits.
CHARGE PENDING STATE – BEGINNING THE CHARGE CYCLE
The PIC16HV785 is initially set in the Charge Pendingstate. In this state, the presence of a battery pack mustbe sensed in order to begin the charging cycle. ThePIC16HV785 comes up in the Charge Pending stateafter a Reset, independent of the previous state.
CHARGE QUALIFICATION STATE
During Charge Qualification, the battery’s temperatureand voltage are measured to determine the nextcharging state. There are four possible next states.
1. If the battery’s temperature is outside of the limitsfor charge initiation (StartTMax, TempMin), thenthe next state is Charge Suspend.
2. If the battery’s voltage is less than the prechargethreshold (PCVolt) and its temperature is withinthe limits for charge initiation (StartTMax,TempMin), then the next state is Precharge.
3. If the battery’s voltage is above the prechargethreshold (PCVolt) and its temperature is withinthe limits for charge initiation (StartTMax,TempMin), then the next state is CurrentRegulation.
4. If the battery’s voltage is above the voltage atwhich charging will restart (Vrchg), then the nextstate is Charge Complete.
PRECHARGE STATE
The Precharge state allows for the recovery of a deeplydischarged battery pack by applying a low charge rate.In this state, a user-configured precharge current isapplied to the battery, resulting in an increase in thebattery’s voltage. There are three possible next states:
1. If the battery’s voltage is above the prechargethreshold (PCVolt) and the battery’s temperatureis within the limits for charge initiation (StartTMax,TempMin), then the next state is CurrentRegulation.
2. If the Precharge state time limit is exceeded(PCTimeMax) and the battery’s voltage remainsless than the precharge threshold (PCVolt),then the next state is Charge Suspend.
If the Precharge state time limit is exceeded(PCTimeMax) and the battery’s temperature isgreater than the maximum temperature forcharge initiation (StartTMax), then the next stateis Charge Suspend.
If the Precharge state time limit is exceeded(PCTimeMax) and the battery’s temperature isless than the minimum temperature for chargeinitiation (StartTMin), then the next state isCharge Suspend.
3. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
CHARGE SUSPEND STATE
In the Charge Suspend state, no current is applied tothe battery pack. There are two possible next states:
1. If the battery’s temperature is within the limits forcharge initiation (StartTMax, TempMin) and itsvoltage is less than the voltage at which charg-ing would restart (VRVrech), then the next stateis Precharge.
2. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
CURRENT REGULATION STATE
The Current Regulation state can be entered from thePrecharge state or Charge Qualification state. Batterycharging is initiated. This state provides constantcurrent, voltage limited charging. The charge current isreferred to as CRCurrent or the regulation current.While the current is applied, the battery’s voltageincreases until it reaches a voltage limit referred to asCRVTarg or regulation voltage. Charging continues,during which battery voltage and temperature aremonitored. There are three possible next states.
1. If the battery’s voltage reaches or exceeds thevoltage limit (CRVTarg) and its temperatureremains below the maximum allowable duringcurrent regulated charging (TempMax), then thenext state is Voltage Regulation.
2. If the battery exhibits any one of the followingconditions, then the next state is Charge Suspend:- Battery voltage exceeds upper voltage limit
for charging (Vmax)- Battery temperature exceeds upper
temperature limit for charging (TempMax)- Battery temperature is below the lower
temperature limit for charging (TMIN)
If the time in the Current Regulation stateexceeds the time limit (CRTimeMax), then thenext state is Charge Suspend.
3. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
Voltage Regulation provides charging at a constantvoltage while the charge current decreases (or tapers)to the user-specified minimum current threshold(VRIMin). There are three possible next states.
1. When the charge current reaches the tapercurrent threshold for End-of-Charge (VRIMin)and the battery’s voltage remains at the regu-lated voltage value (CRVTarg), then the batteryhas reached the Charge Complete state.
2. If the battery exhibits any one of the followingconditions, then the next state is ChargeSuspend.- Battery voltage exceeds upper voltage limit
for charging (Vmax)- Battery temperature exceeds upper
temperature limit for charging (TempMax)If the time in the Voltage Regulation stateexceeds the time limit (VRTimeMax), then thenext state is Charge Suspend.
3. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
CHARGE CYCLE COMPLETE STATE
When the current is less than the taper current threshold(VRIMin) and the voltage is greater than the target volt-age (CRVTarg), End-of-Charge is triggered. At thisthreshold, charging is terminated and the End-of-Chargestate is reached. The PIC16HV785 can renew thecharge cycle by entering the Charge Pending statewhen: 1) the battery is removed, or 2) if the battery’s volt-age falls below the recharge threshold voltage(VRVrech).
To ensure the proper treatment of nickel chemistriesduring extreme temperature and voltage conditions,multi-step charging is required. The PIC16HV785measures key voltage, temperature and timeparameters. It compares them to user-definedvoltage, temperature and time limits.
CHARGE PENDING STATE – BEGINNING THE CHARGE CYCLE
The PIC16HV785 is initially set in the Charge Pendingstate. In this state, the presence of a battery pack mustbe sensed in order to begin the charging cycle. ThePIC16HV785 comes up in the Charge Pending stateafter a Reset, independent of the previous state.
CHARGE QUALIFICATION STATE
During charge qualification, the battery’s temperatureand voltage are measured to determine the nextcharging state. There are four possible next states.
1. If the battery’s temperature is greater than thecharge limit (MaxTmp), or the voltage is greaterthan the charge limit (MaxVolt), then the nextstate is Trickle Charge.
2. If the battery’s voltage is less than the prechargethreshold (PCVolt), or its temperature is outsideof the limits for fast charge (PCTempLo,PCTempHi), then the next state is Precharge.
3. If the battery’s voltage is above the prechargethreshold (PCVolt) and its temperature is withinthe limits for fast charge (PCTempLo,PCTempHi), then the next state is Fast Charge.
PRECHARGE STATE
The Precharge state allows for the recovery of a deeplydischarged battery pack by applying a low charge rate,or a slow recharge of a battery when the temperature istoo high or too low to accept a fast charge. In this state,a user-configured precharge current is applied to thebattery, resulting in an increase in the battery’s voltage.There are three possible next states.
1. If the battery’s voltage is above the prechargethreshold (PCVolt) and the battery’s tempera-ture is within the limits for charge initiation(PCTempLo, PCTempHi), then the next state isFast Charge.
2. If the Precharge state time limit is exceeded(PCTimeMax) while still in Precharge state,then the next state is Trickle Charge.
3. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
FAST CHARGE STATE
In Fast Charge state, the full charging current is appliedto the battery. There are three possible next states.
1. The charger will enter Trickle Charge stateunder any of the following conditions:• The voltage exceeds MaxVolt.• The temperature exceeds MaxTmp.
• The time exceeds FCTimeMax.• -dV (minus delta V) full trigger is detected and
time is greater than FCTimeMin.• dT/dt full trigger is detected and time is greater
than FCTimeMin and Top Off state is disabled.2. The charger will enter Top Off state when dT/dt
full trigger is detected and time is greater thanFCTimeMin and Top Off state is enabled.
3. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
TOP OFF STATE
In the Top Off state, the dT/dt trigger has been reachedand a lower amount of current is delivered to top off thebattery. There are two possible next states.
1. The battery will exit Top Off state and enterTrickle Charge under the following conditions:
• The voltage exceeds MaxVolt• The temperature exceeds MaxTmp• The time exceeds TPTimeMax
2. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
TRICKLE CHARGE STATE
Trickle Charge state provides a very small constantcurrent to maintain a full charge on the battery. Thereare two possible next states.
1. The battery will enter Charge Complete state ifthe voltage exceeds MaxVolt or the timeexceeds TPTimeMax.
2. If the battery pack is taken away, then thePIC16HV785 enters the Charge Pending state.
CHARGE CYCLE COMPLETE STATE
When the charge is complete, all charge current termi-nates. The battery will re-enter Trickle Charge modewhen the voltage is less than Vrech and voltagerecharge is enabled. Charge complete is determinedby the dT/dt method or the -dV method.
1. dT/dt: When the rate of change of the temperatureincreases suddenly, the temperature increases bygreater than dTDelta in time dTTime and thecharging can be declared complete.
2. -dV: When the voltage changes suddenly in thenegative direction, drops by dVDetect suddenlyafter rising throughout the charge cycle, thecharging can be declared complete.
The PIC16HV785 device’s configurable parametersallow for flexible changes in designing battery charg-ers. The parameters are categorized as follows:
• Configuration• Lithium Charging
• Nickel Charging• LED Display Configuration• Look-up Tables
Configuration Parameters
The configuration parameters provide an identity to thebattery pack and provide its basic characteristics to thePIC16HV785.
Lithium Charging
The lithium parameters govern precharge conditions,current regulation conditions and voltage regulationconditions, as well as when the battery is full and whencharging should be suspended.
Nickel Charging
The nickel parameters govern when the cells should betrickle charged, fast charged, topped off, and when thecells are full based on negative voltage drop ortemperature rate of change.
LED Display Configuration
The PIC16HV785 supports a 2-LED charging state dis-play. These LEDs can be configured to identify theseven unique charger states
Look-up Tables
The look-up tables are grids of data that performthermistor measurement linearization and PWMadjustment based on feedback measurements.
BandgapCF 2 248 integer Internal band gap calibration factor.
BattDetectVolt 2 50 mV Voltage threshold for battery detection.
BattIDMax 1 255 A/D full scale divided by
255
BATID input pin value maximum. When using BATID pin battery detection, voltage on BATID pin must be between BattIDMax and BattIDMin for battery present.
BattIDMin 1 0 A/D full scale divided by
255
BATID input pin value minimum. When using BATID pin battery detection, voltage on BATID pin must be between BattIDMax and BattIDMin for battery present.
Capacity (mAh) 2 2000 mAh Full-charge capacity of the battery pack. For reference only.
CurrentCF 2 2553 integer Current calibration factor.
DevName — PIC16HV785
ASCII Device name. For reference only.
MfgName — Microchip AXCII Manufacturer’s name. For reference only.
Mode2 1 00100000b binary Configuration Register:bit 7: 1 = Disable auto-offset calibrationbit 6: 1 = Enable clock output on BATID pin after Resetbit 5: 1 = Use constant temperature from EEPROMbit 4: 1 = NiMh algorithm 0 = Li Ion algorithmbit 3: Unusedbit 2: 1 = Disable voltage recharge trigger (VRVrech)bit 1: 1 = Disable voltage cutoff in regulatorbit 0: 1 = Disable PWM auto-shutdown
OscTrim 1 0 integer Oscillator trim calibration value.
PWMFreq 1 15 integer LUT value which determines the PWM frequency.
PatternID 2 0x102 integer ID for parameter set.
SHUNT 1 100 mOhms Shunt resistor value.
SeriesCells 1 4 integer Number of series connected cells in the battery pack.
Tdefault 1 112 code Default temperature when using constant temperature in EEPROM(°C * 10 + 200)/4.
TempCF 2 8192 integer Temperature calibration value.
TimerEOCRecheck 1 20 .25 sec. Recheck timer for End-of-Charge condition.
TimerStChng 1 20 .25 sec. Recheck timer for state change.
VoltageCF 2 5121 integer Voltage calibration value.
Li Ion Charging Parameters
CRCurrent 2 800 mA Charging current during current regulation.
CRTimeMax 1 0 4 min. Current regulation time limit.
CRVTarg 2 4200 mV Target cell voltage in current regulation. This is set to the fully charged voltage of one cell, typically, as specified by the cell manufacturer.
PCCurrent 2 200 mA Charging current during precharge.
PCTempThresh 1 175 code Maximum temperature required to enable charging with precharge conditions (°C * 10 + 200)/4.
PCTimeMax 1 60 4 min. Duration of precharge.
PCVolt 2 3000 mV Cell voltage under which precharge occurs.
StartTMax 1 code Maximum temperature under which charging may begin (°C * 10 + 200)/4.
TempMax 1 200 code Maximum temperature under which charging is allowed to continue (°C * 10 + 200)/4.
TempMin 1 50 code Minimum temperature over which charging is allowed to continue or start (°C * 10 + 200)/4.
Vmax 2 4300 mV Voltage which triggers Charge Suspend mode when exceeded.
VRIMin 2 50 mA Voltage regulation fully charged current. This is the value of the taper current which will determine that the battery is fully charged.
VRTimeMax 1 90 4 min. Voltage regulation time limit.
VRVrech 2 4100 mV Voltage regulation recharge cell voltage. Charger will begin recharging if cell voltage of pack falls below SeriesCells * VRVrech.
Vsafety 2 4350 mV Charger will shut down immediately when voltage exceeds Vsafety.
Nickel Parameters
ChargeVolt 2 2000 mV Charge voltage.
DischVolt 2 1000 mV Discharge target voltage.
FCCurr 2 2000 mA Fast charge current.
FCTimeMax 1 0 4 min. Fast charge time limit.
FCTimeMin 1 0 4 min. Fast charge time minimum.
MaxTmp 1 175 code Maximum temperature for charging (°C * 10 + 200)/4.
During initialization, the firmware will define constants,allocate resources and configure registers. Thisincludes mapping the GPIO, setting up the timers, set-ting the initial PWM frequency, outputting the optionalBATID frequency check signal, configuring the LEDpins and configuring the HVOUT pin.
Once the resources are configured, RAM is clearedand the main loop is entered.
Four of the initialization functions are described below:
1. Programming the initial PWM frequency.2. Configuring the BATID pin as an analog input
and output of the clock frequency.3. Configuring the LED2 pin as LED or
communication.4. Configuring the HVOUT pin for one of its multiple
functions.
The initial PWM frequency is configured by writing toPWMFreq, where the following table determines thePWM frequency as a function of the bits in the PWMPregister.
The BATID pin is used to determine if a battery is presentby measuring the voltage on the pin and comparing it tothe proper EEPROM parameters. Alternatively, after aReset and during initialization, this pin can be configuredby the Mode2 parameter to output a single burst of256 clocks in order to determine the frequency of theinternal oscillator.
The LED2 pin is configured as either an LED driver oras the communication pin. See the “Communication”section for more information.
The HVOUT pin is a general purpose, open-drain outputthat can be configured as one of three mutually exclu-sive functions, as chosen by the Mode and Mode3parameters.
Mode<6> = 1: Charge Current Switch
Used as an indication of charge current flowing.
HVOUT = 1: Charge current flowing
HVOUT = 0: No charge current flowing
Mode3<7> = 1: Enable External Discharge Circuit
An option in Nickel charging is to provide a load to dis-charge a battery immediately prior to charging. Thiscan help in detection of End-of-Charge conditions.
If the charger cannot satisfactorily regulate a low-leveltrickle charge current, an external trickle charge circuitmay be used. The HVOUT pin, in this case, can controlthe trickle charge circuit when the Trickle Charge stateis entered.
HVOUT = 1: Default
HVOUT = 0: Trickle charge circuit enabled
Main Loop
The main loop cycles through the following functions:
• Performs A/D measurements
• Checks measurements against triggers and determines the charge state
• Adjusts the PWM to regulate current• Operates the LEDs• Maintains the timers
• Performs EEPROM reads and writes• Performs communication transactions
The actual subroutines are:
• adc_svc: Receive the finished A/D conversions, process the data with calibration constants, etc., and store in RAM
• adc_start: Start a new set of conversions to be completed for the next cycle
• check_triggers: Compare the A/D results with parameters to determine what state the charging should be in
• chg_state_svc: Put the charger into the proper state based on A/D results
• regulate: Adjust the PWM to regulate current based on charge state and feedback measurements
• led_svc: Operate two LEDs to display the charge state
• timer_svc: Maintain the firmware timers• ee_write_buf: Background process to write the
data block in the RAM buffer into EEPROM• ccmd_svc: React to communication commands
• status_build: Build the status byte communication register
Triggers and Charge States
Once data is received from the A/D, it is compared tothe parameters using charge state formulas to deter-mine the proper charge states, as explained above inthe functional descriptions.
Regulating the PWM
The PWM duty cycle is adjusted by the firmware inresponse to the charge state and the feedback measure-ments. It is increased or decreased to keep the voltageand current as close to the charge requirements as pos-sible without exceeding those requirements. The feed-back measurements of voltage and current arecompared to the required voltage and current of the par-ticular charge state the device is in. The PWM is eitherkept the same, increased or decreased a little, orincreased or decreased a lot as a function of thedifference between the feedback measurements andthe requirements.
As Table 4 shows, if the voltage feedback is no greaterthan Vh more than the requirement, and no less thanVl lower than the requirement, the PWM is unchanged.If the feedback voltage exceeds the required voltage bymore than Vl, the PWM is decreased by PWMAdjust4,etc.
Table 4 shows the PWM adjustment factors as afunction of current difference and voltage differencewhen comparing feedback to requirements:
TABLE 4: PWM ADJUSTMENT FACTORS
LED Control
Two LED Configuration registers (one for each LED)determine how the LEDs are displayed when controllingon/off, flashing, flash counts and on/off times.
TABLE 5: LED CONFIGURATION REGISTERS
EEPROM parameters are used to define the settingsabove for each charge state. The LED1State1-8 andLED2State1-8 parameters are used to program theabove configuration parameters based on what statethe charger is in.
A/D Starting and Processing
The A/D operations consist of starting the A/D readingson up to 5 channels, retrieving the data and calibratingthe data.
To start the readings, the firmware programs the A/DControl registers (see the “PIC16F785 Data Sheet”(DS41249)) to perform the required measurements. Upto five channels are used for the charger function. Theyinclude the following:
• Reference Voltage• Current
• Voltage• Temperature• BATID
When conversions are complete, flags are set so thefirmware can perform the calibration and processing.For filtering purposes, the average of 16 consecutivereadings are used for valid data.
REFERENCE VOLTAGE
The band gap reference voltage (VR) is calibrated ortranslated from the raw A/D measurement (A/DRAW) asfollows:
EQUATION 5:
Since the reference voltage is fixed, this calibrationfactor is used to compensate for a variance in VDD. It isused to correct any readings that use VDD as areference.
Current Zones
< -Cll < -Cl -Chl to +Chl > Ch > Chh
Vo
ltag
e Z
on
es > Vhh -PWMAdjust1 -PWMAdjust1 -PWMAdjust1 -PWMAdjust1 -PWMAdjust1
The current reading is calibrated or translated from theraw A/D measurement (A/DRAW) as follows:
EQUATION 6:
The CurrentCF is determined by examiningEquation 6 at full scale, for example:
EQUATION 7:
Representing the decimal fraction as a ratio using apower of 2:
EQUATION 8:
VOLTAGE
The voltage reading is calibrated or translated from theraw A/D measurement (A/DRAW) as follows:
EQUATION 9:
Table 6 shows the typical VoltageCF values for thePS2070 evaluation module with a different number ofcells and different voltage dividers selected:
TABLE 6: TYPICAL VoltageCF VALUES FOR PS2070
BATID
The BATID pin is measured in raw A/D units, scaled to 0to 255, and compared to EEPROM parameters that arein raw A/D units, scaled to 0 to 255, so no calibration isperformed.
TEMPERATURE
The current reading is calibrated or translated from theraw A/D measurement (A/DRAW) as follows:
EQUATION 10:
TempCF is typically 8192 and is set by comparing aknown temperature to the measured temperature.
The temperature response of the thermistor is thensubjected to linearization by a look-up table asdescribed in the next section.
Thermistor Linearization
The thermistor reading is subjected to piecewise linearinterpolation using a look-up table of line equations.Since the variance of voltage with temperature for thethermistor is not always along the same line (sameslope and intercept), multiple line equations must beused for interpolation depending on where the mea-surement is. The look-up table was developed by ratingraw A/D values; that is why TempCF can typically beset to 1.
When referenced to VR:
Current = A/DRAW * CurrentCF/65536
When referenced to VDD:
Current = (A/DRAW * VR/16384) * CurrentCF/65535
Current(full scale) = VREF/AMPgain/SHUNT =
5000/19.6/0.100 = 2551 mA
2551 = 1023 * CurrentCF
CurrentCF = 2.494
CurrentCF Base = 1024
CurrentCF = 2553
When referenced to VR:Voltage = A/DRAW * VoltageCF/1024
When referenced to VDD:Voltage = (A/DRAW * VR/16384) * VoltageCF/1024
Where VoltageCF is determined as follows:Voltage = A/DRAW * VoltageCF’
A/DRAW = (Voltage * Cells) * R/VREF * 1023
Where:R = Resistor Divider Ratio
VREF = 5000 mV
This means:
Voltage = VoltageCF’ * Voltage * Cells * R/VREF * 1023
or
VoltageCF’ = VREF/(Cells * R * 1023)
and using integer arithmetic:
VoltageCF = VoltageCF’ * 1024
So that:
Voltage = VoltageCF * A/DRAW /1024
Cells R# R1 R2 R Ratio VoltageCF
1 1 0.232 10.0 0.9773 5121
2 2 10.500 10.0 0.4878 5130
3 3 20.500 10.0 0.3279 5088
4 4 30.900 10.0 0.2445 5117
Temperature = A/DRAW * TempCF/8192
Where temperature is in the internal units of: (°C + 20) * 10
The look-up table is a series of slopes and Y-interceptscorresponding to regions of temperature A/D readings.T_LUT_N represents the number of entries in the table,in this case eight entries.
TABLE 7: THERMISTOR LINEARIZATION
The typical values are:
TABLE 8: A/D TEMPERATURE READINGS
CommunicationCommunication for memory reads and writes, typicallyused for changing parameters, is performed using theLED2 I/O pin (pin 2). Pin 2 is configured during Resetinitialization to either be the communication pin or anLED driver. If pin 2 is driven low during initialization,pin 2 will become the LED driver. If pin 2 is driven highduring initialization, communication will be enabled andpin 2 will be the communication pin.
The communication protocol is the Single Pin Serial(SPS) protocol. SPS communication is an asynchronousreturn-to-one protocol. The signal requires an externalpull-up resistor. The timing of the driven low pulsesdefines the communication. A Break cycle starts a com-mand from the host to the PIC16HV785. The commandis eight bits long. After this, eight data bits are eitherwritten to the PIC16HV785, or read from thePIC16HV785.
A Break cycle is defined by a low period of time equalto or greater than time tb, then returned high for a timegreater than or equal to tbr.
The data bits consist of three sections each:
1. Start: low for at least time tstr.2. Data: data high or low valid by time tdsuh/v and
held until time tdh/v.3. Stop: high by time tssuh/v and held until time tcyc.
All transactions either read or write an 8-bit register.Each register has a 7-bit address, plus a read/write bit,for a total of 8 bits. Bit 7 is the read/write bit. When bit 7is ‘1’, the register is written. When bit 7 is ‘0’, the regis-ter is read. Of the possible 128 addressable registers,only 10 are implemented.
A read transaction will receive a single byte of data. Awrite transaction can write multiple 8-bit data values toa register:
7 VERSION 1 = Load Data registers (Register 4 and Register 5) with firmware version number
6 PWM_SET 1 = Load control PWM with contents of Data registers
5 REG_ON 1 = Enable regulation module
4 EE_RQ 1 = Request EEPROM write of data block in RAM
3 Unused
2 RESET 1 = Reset firmware (branch to Reset vector from Idle loop)
1 FORCE_CHGSTATE 1 = Force branch to Charge Controller state
0 SIM_RQ 1 = Load simulation data previously written to RAM
Bit Name Description
7:0 DATA_LO Generic data used in memory reads and writes (LSB)
Bit Name Description
7:0 DATA_HI Generic data used in memory reads and writes (MSB)
Bit Name Description
7:0 Unused
Bit Name Description
7:0 UNLOCK Unlock code is written here
Bit Name Description
7:0 MEM_ACCESS Data written to Register 8 is actually sent to the memory address contained in Register 0 and the bank indicated by Register 2 (bits<1:0>)
Bit Name Description
7:0 MEM_ACCESS_IA Data written to Register 8 is actually sent to the memory address contained in Register 0 and the bank indicated by Register 2 (bits<1:0>); Register 0 will be post-incremented
Host driven operations refer to a host communicatingwith the PIC16HV785 in order to read or write memorylocations. This is typically done during programming,parameter changing, or troubleshooting. The four basicfunctions are EEPROM read, EEPROM write, RAMread and RAM write. The host will employ the SinglePin Serial protocol and the registers described in the“Register Descriptions” section to accomplish thefunctions.
RAM READ
There are three steps to the RAM read:
1. Select the bank: Set Communication Register 2(bit 0 = 0); select bank 0/1 since bank 2/3 is notimplemented.
2. Select the address: Set CommunicationRegister 0 to the starting RAM address.
3. Read the data: Read the contents of theMemory Access register (Register 8 orRegister C). When using Register C, theaddress will auto-increment, so step 3 can berepeated to receive more data.
RAM WRITE
There are three steps to the RAM write:
1. Select the bank: Set Communication Register 2(bit 0 = 0); select bank 0/1 since bank 2/3 is notimplemented.
2. Select the address: Set CommunicationRegister 0 to the starting RAM address.
3. Write the data: Write the data to the MemoryAccess register (Register 8 or Register C). Whenusing Register C, the address will auto-increment,so step 3 can be repeated to write more data.
EEPROM READ
There are three steps to the EEPROM read:
1. Select the bank: Set Communication Register 2(bits<1:0> = 10); select bank = EEPROM.
2. Select the address: Set CommunicationRegister 0 to the starting EEPROM address.
3. Read the data: Read the contents of the Mem-ory Access register (Register 8 or Register C).When using Register C, the address will auto-increment, so step 3 can be repeated to receivemore data.
EEPROM WRITE
The EEPROM write follows a more secure protocol inwhich a “control packet” of data is written to a RAMbuffer first. The RAM buffer begins at address 0xA0. Acontrol bit is then set to trigger the writing of the data inthe control packet to EEPROM. The control packettakes the following form:
TABLE 10: EEPROM WRITE CONTROL PACKET
The total procedure is a five step process:
1. Suspend normal operation: Set CommunicationRegister 2 = 0x20 (bit 5 = 1).
2. Check if the EEPROM is busy: DoesCommunication Register 1 (bit 7 = 1)?
3. If not busy, write the control block data to RAM,beginning at address 0xA0, using RAM writeprocedure.
4. When all data is written, trigger EEPROM write;set Communication Register 3 (bit 4 = 1).
5. Issue a firmware Reset: Set CommunicationRegister 3 (bit 2 = 1).
The software supplied herewith by Microchip Technology Incorporated (the “Company”) is intended and supplied to you, theCompany’s customer, for use solely and exclusively with products manufactured by the Company.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 civilliability 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 FORSPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
FIRMWARE SOURCE CODE
Define Constants, Registers and EEPROM Locations
The following section defines variables used by thefirmware to control the charging regime. The EEPROMparameters described in the functional description areassigned addresses and variable names. Note that theinternal firmware variable names for these parameters
may not match the names used in the functionaldescriptions above. The names in the functionaldescriptions match the names in the PowerTool™ 200software. The software and data sheet names havebeen given names that are more user-friendly.
The mode bits are defined which become user-select-able functions and charge features as described in thefunctional descriptions. Variable names are defined forhardware interface registers, such as A/D control anddata, timers, PWM configuration and GPIO.
org 0x20 ; *** bank 0r_mode res 1 ; operational mode registerr_chg_state res 1 ; charge controller "state"r_adc_0 equ $ ;r_adc_0_L res 1 ; adc result - channel 0r_adc_0_H res 1 ;r_adc_1 equ $ ;r_adc_1_L res 1 ; adc result - channel 1r_adc_1_H res 1 ;r_adc_2 equ $ ;r_adc_2_L res 1 ; adc result - channel 2r_adc_2_H res 1 ;r_adc_3 equ $ ;r_adc_3_L res 1 ; adc result - channel 3r_adc_3_H res 1 ;
r_adc_4 equ $ ;r_adc_4_L res 1 ; adc result - channel 4r_adc_4_H res 1 ;r_pwm_L res 1 ; pwm settingr_pwm_H res 1 ; pwm settingr_reg_c res 2 ; regulation target: current (mA)r_reg_v res 2 ; regulation target: voltage (mV)r_comm_reg equ $ ; comm "registers" r_comm_reg_0 res 1 ; indirect address registerr_comm_reg_1 res 1 ; statusr_comm_reg_2 res 1 ; config flagsr_comm_reg_3 res 1 ; command flagsr_comm_reg_4 res 1 ; data lor_comm_reg_5 res 1 ; data hir_comm_reg_6 res 1 ;r_comm_reg_7 res 1 ;r_sim res 1 ;r_chg_timer_a res 1 ; hysteresis timerr_chg_timer_b res 1 ; hysteresis timerr_chg_timer_c res 1 ; hysteresis timerr_chg_timer_d res 1 ; hysteresis timerr_temp_1 res 1 ; location sensitive (init ram clear)r_temp_2 res 1 ; r_temp_3 res 1 ; r_temp_4 res 1 ; r_tempi_1 res 1 ; temporary reg for isrr_timer_a1 res 1 ;r_timer_b res 1 ;r_timer_b1 res 1 ;r_timer_c res 1 ;r_timer_d res 1 ;r_timer_d1 res 1 ;r_led_config_1 res 1 ;r_led_contrl_1 res 1 ;r_led_config_2 res 1 ;r_led_contrl_2 res 1 ;r_adc_control res 1 ; adc controlr_adc_raw_L res 1 ;r_adc_raw_H res 1 ;
r_count_1 res 1 ;r_accD_L res 1 ; math - accumulator - Dr_accD_H res 1 ;r_accC_L res 1 ; math - accumulator - Cr_accC_H res 1 ;r_accB_L res 1 ; math - accumulator - Br_accB_H res 1 ;r_accA_L res 1 ; math - accumulator - Ar_accA_H res 1 ;
r_comm_count res 1 ;r_comm_data res 1 ;r_comm_flags res 1 ;r_comm_data_cmnd res 1 ;
r_mode2 res 1 ;
org 0x60r_adc_accum res 2 ;r_adc_accum_count res 1 ;r_adc_avg res 2 ;r_adc_avg_shadow res 2 ;r_adc_1_ofs res 1 ;r_adc_2_save res 2 ;r_adc_3_save_a res 2 ;
r_mode3 res 1 ;r_timer_d2 res 1 ;;-----------------------------------------------------------;--- registers: bank0,1,2,3 (common);-----------------------------------------------------------
org 0x70 ; *** bank 0 (common area)r_shadow_1 res 1 ;r_shadow_2 res 1 ;r_shadow_3 res 1 ;;r_shadow_4 res 1 ;r_flags_1 res 1 ; assorted bit flagsr_flags_2 res 1 ; assorted bit flagsr_flags_3 res 1 ; assorted bit flagsr_flags_4 res 1 ; assorted bit flagsr_flags_5 res 1 ; assorted bit flagsr_flags_6 res 1 ; assorted bit flagsr_isr_w res 1 ; interrupt contextr_isr_status res 1 ; interrupt contextr_isr_pclath res 1 ; interrupt contextr_isr_fsr res 1 ; interrupt contextr_ee_data res 1 ; eeprom datar_ee_addr res 1 ; eeprom addressr_tempc_1 res 1 ;
#define flag0_mode_pchg_always r_mode, 7 ; always start with pchg#define flag0_mode_gpio_cutoff r_mode, 6 ; enable gpio cutoff logic#define flag0_mode_bpres_battid r_mode, 2 ; use battid for batt present#define flag0_mode_bpres_v r_mode, 1 ; battery present on voltage sense#define flag0_mode_bpres_always r_mode, 0 ; battery present - always
#define flag0_mode_cofs_dis r_mode2, 7 ; current offset - disable#define flag0_mode_oscout r_mode2, 6 ; enable oscillator out on battid#define flag0_mode_temp_k r_mode2, 5 ; use constant temperature 25degC#define flag0_mode_nm r_mode2, 4 ; nickel metal hydride algorithm#define flag0_mode_vrchg_dis r_mode2, 2 ; voltage recharge - disable#define flag0_mode_vregco_dis r_mode2, 1 ; regulation voltage cutoff - disable#define flag0_mode_pwmas_dis r_mode2, 0 ; pwm auto shutdown - disable
;*** WARNING: DO NOT MOVE: flag_led_2_save;*** WARNING: DO NOT MOVE: flag_led_1_save;#define flag_led_2_save r_flags_4, 7;#define flag_led_1_save r_flags_4, 6#define flag_adc_3_sim r_flags_4, 7
org 0xa0 ; *** bank 1r_buf1 equ $ ; sim data, ee write buf datar_ee_buf equ $ ;r_ee_buf_adr res .1 ;r_ee_buf_cnt res .1 ;r_ee_buf_dta res .29 ;r_ee_buf_ptr res .1 ;
org 0xb0r_buf2 res .16 ; overlaps 2nd half of r_buf1
isr_x: ;movf r_isr_fsr, w ;movwf r_fsr ;movf r_isr_pclath, w ;movwf r_pclath ;swapf r_isr_status, w ;movwf r_status ;swapf r_isr_w, f ; swapf r_isr_w, w ;
This routine runs whenever the part is first powered upor reset. This includes initial hardware configurations,such as oscillator, GPIO ports and voltage referenceconfigurations. It sets the initial PWM frequency,checks for communication and outputs the clock on theBATID pin if requested.
This routine is run in response to communicationactivities that use the control bits in the Communicationregisters to modify behavior. All of the communicationfunctions, as described in the functional descriptions oncommunication, are implemented below, including all
of the functionality in each bit of the Communicationregisters. Functions include reading the firmware ver-sion, setting the PWM, turning on regulation, forcingthe branch to the charge controller state machine andrunning simulation.
;---------------------------------------;--- comm command service;---------------------------------------ccmd_svc: ;
This routine builds the Communication Statusregister – Communication Register 1. This includes bit-maps for signifying that EEPROM write is in progress,EEPROM write resulted in an error, regulation is active,charge controller is active and data simulation is active.
During the “regulate” phase of the main loop, this rou-tine is used to load the PWM in response to changingPWM values. The values are typically changed
because the charge state changed or the feedbackmeasurements are not close enough to requirements.This routine loads the PWM with the new value.
This routine writes the RAM EEPROM buffer to theEEPROM. As described in “Host Driven Operations”,an EEPROM write is performed by writing a control block
to a RAM buffer. A Communication register bit is then setto execute this routine to copy the RAM buffer to theEEPROM.
;-----------------------------------------------------------;--- ee buffer write;-----------------------------------------------------------ee_write_buf: ; bsf r_status, RP0 ; *** bank=1 btfsc flag_ee_busy ; busy ? goto ee_write_buf_busy ; --- yes, skip ... btfss flag_ee_rq ; request pending ? goto ee_write_buf_x ; --- no, exit ...ee_write_buf_prep: ; movlw r_ee_buf ; prep for checksum check movwf r_fsr ; bcf r_status, IRP ; movf r_ee_buf_cnt, w ; addlw .2 ; call chksum ; calc checksum xorwf r_indf, w ; compare to chksum in buffer btfss r_status, Z ; checksum ok ? goto ee_write_buf_err ; --- no, process error ... movlw r_ee_buf_dta ; movwf r_ee_buf_ptr ; bsf flag_ee_busy ; --- yes, set "busy" flag bcf flag_ee_err ;ee_write_buf_busy: ; bsf r_status, RP1 ; *** bank=3 btfsc r_eecon1, WR ; ee write in progress ? goto ee_write_buf_x ; --- yes, exit ... bcf r_status, RP1 ; *** bank=1 movf r_ee_buf_cnt, f ; btfsc r_status, Z ; goto ee_write_buf_done ;ee_write_buf_next: ; movf r_ee_buf_ptr, w ; movwf r_fsr ; movf r_indf, w ; w = data movwf r_ee_data ; movf r_ee_buf_adr, w ; call ee_write_waddr ; (sets bank=0) bsf r_status, RP0 ; *** bank=1 decf r_ee_buf_cnt, f ; decrement count incf r_ee_buf_adr, f ; increment ee pointer incf r_ee_buf_ptr, f ; increment buffer pointer goto ee_write_buf_x ;ee_write_buf_err: ; bsf flag_ee_err ;ee_write_buf_done: ; bcf flag_ee_busy ; bcf flag_ee_rq ;ee_write_buf_x: ; bcf r_status, RP1 ; bcf r_status, RP0 ; return ;
; call:; fsr pointer to buffer ; (r_status[IRP] should be set appropriately); w count; uses:; r_temp_1; return:; fsr points to buffer[count]; w checksum;---------------------------------------chksum: movwf r_tempc_1 ; movlw .0 ;chksum_loop: ; addwf r_indf, w ; add data byte incf r_fsr, f ; increment pointer decfsz r_tempc_1, f ; loop ... goto chksum_loop ; return ;
Thermistor Temperature Processing (Subroutine of ADC_Service)
As described in the functional descriptions, thetemperature measurement of the A/D converter uses alinearization scheme composed of a look-up table ofline equations. This routine uses the look-up tables topiecewise linearly interpolate the temperature reading.
;---------------------------------------;--- thermistor temperature index; ; call:; w key;; exit:; w ram location; r_temp_3 vector length (limited); r_temp_4 key;---------------------------------------therm_index: ; movwf r_temp_4 ; save key
This set of subroutines implements all the communica-tion functions: enabling or disabling communicationdepending on start-up state of the communicationGPIO, and receiving and transmitting the data.
Two GPIOs can be used to perform charge state feed-back with an LED display. Each LED can beprogrammed to be on, off or flashing, and the on/off/flash times can be programmed using the parameters
described in the functional description. This routineuses the charge state and the LED configurationparameters to drive the GPIO to control the LEDproperly.
This routine receives the raw A/D data for voltage,current, temperature and BATID and calibrates andconverts it to a form usable by the algorithm, asdescribed in the calibration section in the firmwaredescriptions.
;-----------------------------------------------------------;--- adc_svc() - service adc conversion;-----------------------------------------------------------adc_svc: ; btfss r_adc_control, 7 ; conversion started ? goto adc_svc_x ; --- no, exit ... btfsc r_adcon0, GO ; conversion complete ? goto adc_svc_x ; --- no, exit ... bcf r_adc_control, 7 ; clear "conversion started" flag
;---------------------------------------;--- fetch "raw" result;--------------------------------------- bsf r_status, RP0 ; *** bank=1 movf r_adresl, w ; bcf r_status, RP0 ; *** bank=0 movwf r_adc_raw_L ; movf r_adresh, w ; movwf r_adc_raw_H ; load raw data
movlw r_adc_raw_L ; call math_load_B ; accB = raw movlw r_adc_accum ; accA = running accum call math_add_16_load_A ; accB = raw + accum movlw r_adc_accum ; call math_move_B ; move result to register: accum incf r_adc_accum_count, f ; btfss r_adc_accum_count, 4 ; accum complete ? goto adc_svc_x ; --- no, exit ...
This routine monitors the A/D status to see when a newreading should be performed, then programs the A/Dregisters to perform the correct measurements usingthe correct channels and resolutions.
As a result of the trigger checks, this routine enters thecharger into the correct charge state, as described inthe functional descriptions. Charge Suspend, Fast
Charge, Trickle Charge, etc., are entered whenappropriate. See Lithium and Nickel charge statedescriptions in the functional description sections.
;-----------------------------------------------------------;-----------------------------------------------------------;--- charge state service;-----------------------------------------------------------;-----------------------------------------------------------chg_state_svc: ; btfss flag_chg_state_timer ; sevice timer expired ? goto chg_state_svc_x_ ; --- no, exit ... bcf flag_chg_state_timer ; btfss flag_adcset_0_rdy ; adc data ready ? goto chg_state_svc_x ; --- no, exit ... bcf flag_adcset_0_rdy ;
;--- charge state service enabled ?chg_state_on: ; btfsc flag0_creg_chgcon_off ; goto chg_state_svc_x ;chg_state_on_x: ;
check_nm_dv_negative: ; movlw EE_CHGN_V_DV ; call load_A_ee ; call math_add_16 ; add dV threshold to dV result from above btfss r_accB_H, 7 ; still negative ? goto check_nm_dv_x ; --- yes, change not enough - exit bsf flag_temp_1 ; --- no, change is enough - set carry goto check_nm_dv_x ;
check_nm_dv_newmax: ; movf r_adc_2, w ; movwf r_adc_2_save ; movf r_adc_2+1, w ; movwf r_adc_2_save+1 ;
EXAMPLE 2: NICKEL CHARGE STATE SEQUENCE FLOWCHART EQUATIONS
State Transition Criteria:[12] => Transition from state 1 to state 2[x1] => Transition from any state to state 1
[x0] = BP* or ResetHighest priority and true for all states – for clarity, not included in all equations below.
STATE-0[01] = [x0]*
STATE-1AA = (MODE_EXTDCHG_EN and (V > VDCHG))[17] = AA* and ((V > VMAX) or (T > TMAX) or MODE_SLOCHG)[12] = AA* and [17]* and ((T < TPCHG_LO) or (T > TPCHG_HI) or (V < VPCHG))[13] = AA* and [17]* and [12]*
STATE-2[27] = ((V > VMAX) or (T > TMAX) or (TI_1 > TIPCHG_MAX))[23] = [27]* and (TI_2 > TIPCHG_MIN) and (T > TPCHG_LO) and (T < TPCHG_HI) and (V > VPCHG)
STATE-3AA = (V > VMAX) or (T > TMAX) or (TI_1 > TIFCHG_MAX)[37] = AA or ((TI_2 > TIFCHG_MIN) and ((DTDT_DETECT and MODE_TOPOFF_EN*) or (MDV_DETECT)) )[34] = AA* and (TI_2 > TIFCHG_MIN) and (DTDT_DETECT and MODE_TOPOFF_EN)
STATE-4[47] = (V > VMAX) or (T > TMAX) or (TI_1 > TITOPOFF_MAX)
STATE-5[57] = MODE_VRCHG_EN and (V < VMAX) and (T < TMAX) and (V < VRCHG) STATE-7[75] = (V > VMAX) or (TI_1 > TITRICKLE_MAX)
This routine performs the initialization of variablesrequired by each individual charge state. Each chargestate will have a different set of triggers and variablesthat are required for exiting.
movwf r_chg_state ; save state movf r_chg_state, w ; configure led1 addlw EE_LED1_CFG ; call ee_read_waddr ; call led_init_1 ; movf r_chg_state, w ; configure led2 addlw EE_LED2_CFG ; call ee_read_waddr ; call led_init_2 ;
movlw EE_CHG_TIME_0 ; call ee_read_waddr ; w = theshold from ee movwf r_chg_timer_a ;
return ;;-----------------------------------------------------------Check TriggersThis routine checks all the triggers that are required to exit the current charge state and enter into a different one. The triggers, variables, and equations for each state are described in the functional description. ;-----------------------------------------------------------;--- load_timer_d1() - load timer and reset pre-scaler;-----------------------------------------------------------load_timer_d1_ee: ; call ee_read_waddr ;load_timer_d1: ; movwf r_timer_d1 ; clrf r_timer_d ; bcf flag_chg_ti1_done ; return ;
This routine checks all the triggers that are required toexit the current charge state and enter into a differentone. The triggers, variables and equations for eachstate are described in the functional descriptions.
;-----------------------------------------------------------;--- load_timer_d1() - load timer and reset pre-scaler;-----------------------------------------------------------load_timer_d1_ee: ; call ee_read_waddr ;load_timer_d1: ; movwf r_timer_d1 ; clrf r_timer_d ; bcf flag_chg_ti1_done ; return ; ;-----------------------------------------------------------;--- load_timer_d2() - load timer and reset pre-scaler; used as a "holdoff" or "minimum" timeout; therefore,; if setpoint==0, "done" flag set immediately; if setpoint<>0, "done" flag set when timer expires;-----------------------------------------------------------load_timer_d2_ee: ; call ee_read_waddr ;load_timer_d2: ; movwf r_timer_d2 ; clrf r_timer_d ; bcf flag_chg_ti2_done ; movf r_timer_d2, f ; btfsc r_status, Z ; bsf flag_chg_ti2_done ; set "done" if ==0 return ; ;---------------------------------------;--- check timer a;--- check timer b;--- check timer c;--- check timer d; status[Z]=1 if timer=0;---------------------------------------check_chg_timer_a: ; movlw r_chg_timer_a ; goto check_chg_timer_ ;check_chg_timer_b: ; movlw r_chg_timer_b ; goto check_chg_timer_ ;check_chg_timer_c: ; movlw r_chg_timer_c ; goto check_chg_timer_ ;check_chg_timer_d: ; movlw r_chg_timer_d ; goto check_chg_timer_ ;
check_chg_timer_: ; movwf r_fsr ; movf r_indf, f ; btfss r_status, Z ; decfsz r_indf, f ; nop ; return ;
The regulate routine controls the PWM so that therequired voltage and current are always delivered tothe battery. The charge state and the feedback mea-
surements are used to determine if the PWM needs tobe adjusted. If it does, then PWM_adjust is called tocalculate the correct new value, and PWM_set is calledto write that value to the PWM Control register.
;-----------------------------------------------------------;--- regulate();-----------------------------------------------------------#define REG_V_H2 .25 ; voltage - upper limit 2#define REG_V_H1 .6 ; voltage - upper limit 1#define REG_V_L1 .6 ; voltage - lower limit 1#define REG_V_L2 .50 ; voltage - upper limit 2
math_mul_16_loop: ; rrf r_accD_H, F ; shift operand2 lsb into C rrf r_accD_L, F ; btfss r_status, C ; C = 1? goto math_mul_16_shift ; --- no, go shift ...
math_mul_16_add: ; call math_add_16 ;
math_mul_16_shift: ; rrf r_accB_H, F ; SHIFT result accumulator rrf r_accB_L, F ; rrf r_accC_H, F ; rrf r_accC_L, F ; decfsz r_count_1, F ; goto math_mul_16_loop ; loop
;-----------------------------------------------------------;--- div32; operands:; dividend - accA,accB; divisor - accC;; result:; quotient - accB; remainder - accA; overflow - WREG=0 else WREG=1 ?;-----------------------------------------------------------math_div_32: ; movf r_accC_L, W ; subwf r_accA_L, W ; movf r_accC_H, W ; btfss r_status, C ; incf r_accC_H, W ; subwf r_accA_H, W ; btfsc r_status, C ; retlw 0 ; overflow or division by zero
movlw .16 ; movwf r_count_1 ;math_div_32_loop: ; bcf r_status, C ; rlf r_accB_L, F ; shift dividend (accA,accB << 1) rlf r_accB_H, F ; rlf r_accA_L, F ; rlf r_accA_H, F ;
btfsc r_status, C ; if carry, go subtract goto math_div_32_sub ;
movf r_accC_L, W ; subwf r_accA_L, W ; movf r_accC_H, W ; btfss r_status, C ; incf r_accC_H, W ; subwf r_accA_H, W ; btfss r_status, C ; if smaller than divisor, skip to next goto math_div_32_next ;
math_div_32_sub: ; movf r_accC_L, W ; subtract divisor from high subwf r_accA_L, F ; movf r_accC_H, W ; btfss r_status, C ; incf r_accC_H, W ; subwf r_accA_H, F ; bsf r_accB_L, 0 ;
math_div_32_next: ; decfsz r_count_1, F ; goto math_div_32_loop ; retlw 1 ; no more overflow possible
This sets the default values for the EEPROM parameters.Note that the internal names of EEPROM parametersmay vary from the data sheet and PowerTool 200 names.The PowerTool 200 names are used in the functionaldescription sections.
org 0x2100 DE 0x01, 0x00 ; pattern DE .1 ; ncells DE "microchp" ; manuf name DE "16HV785 " ; device name DE low .800, high .800 ; capacity DE .19 ; pwm DE 0x01 ; mode DE 0x20 ; mode2 DE .00 ; oscillator trim
org 0x2120 DE 0x08, 0x18, 0x28, 0x38 ; LED1 CONFIG DE 0x48, 0x58, 0x68, 0x78 ; LED1 CONFIG (cont) DE 0x08, 0x18, 0x28, 0x38 ; LED2 CONFIG DE 0x48, 0x58, 0x68, 0x78 ; LED2 CONFIG (cont)
org 0x2134 DE .12, .10, .05, .01 ; regulation: pwm adj values DE .19, .06, .06, .44 ; regulation: voltage zone thresholds DE .5 ; regulation: current zone thresholds DE low .4350, high .4350 ; regulation: v_safety (lion)
org 0x2143 DE low .2000, high .2000 ; chg_v_min DE low .4250, high .4250 ; chg_v_max DE low .4000, high .4000 ; chg_v_rchg DE low .4200, high .4200 ; chg_v_reg DE low .3000, high .3000 ; chg_v_pchg DE low .0050, high .0050 ; chg_v_min_bp DE .50 ; chg_t_min DE .175 ; chg_t_chgi DE .200 ; chg_t_chg DE .75 ; chg_t_pchg DE low .100, high .100 ; chg_c_pchg DE low .800, high .800 ; chg_c_reg DE low .50, high .50 ; chg_c_min DE .0 ; chg_ti_pchg DE .0 ; chg_ti_creg DE .0 ; chg_ti_vreg DE .20, .20, .00, .00, .00, .00 ; chg_time DE .128, .255 ; battid_min, _max
org 0x216c DE low .0248, high .0248 ; adc_cal_0 (reference) DE low .2553, high .2553 ; adc_cal_1 (current) DE low .5121, high .5121 ; adc_cal_2 (voltage) DE low .8192, high .8192 ; adc_cal_3 (temperature) DE low .6407, high .6407 ; adc_cal_4 (battid) DE .100 ; shunt DE .112 ; temperature default
org 0x217C DE .8 ; TLUT - length DE .38, .48, .61, .79 ; TLUT - temp axis DE .105, .183, .207 ; TLUT - temp axis (cont) DE low -.23362, high -.23362 ; TLUT - slope - 0 DE low .1418, high .1418 ; TLUT - yint - 0 DE low -.19864, high -.19864 ; TLUT - slope - 1 DE low .1352, high .1352 ; TLUT - yint - 1 DE low -.15709, high -.15709 ; TLUT - slope - 2 DE low .1255, high .1255 ; TLUT - yint - 2 DE low -.12572, high -.12572 ; TLUT - slope - 3 DE low .1162, high .1162 ; TLUT - yint - 3 DE low -.10206, high -.10206 ; TLUT - slope - 4 DE low .1071, high .1071 ; TLUT - yint - 4 DE low -.8631, high -.8631 ; TLUT - slope - 5 DE low .990, high .990 ; TLUT - yint - 5 DE low -.10154, high -.10154 ; TLUT - slope - 6 DE low .1127, high .1127 ; TLUT - yint - 6 DE low -.12875, high -.12875 ; TLUT - slope - 7 DE low .1402, high .1402 ; TLUT - yint - 7
org 0x21AA;debug; DE 0x1A ; mode_3 DE 0x3A ; mode_3 DE low .2544, high .2544 ; adc_cal_2 (voltage) nimh DE low .2000, high .2000 ; chgn_v DE low .1000, high .1000 ; chgn_v_dchg DE .175 ; chgn_t_max (175=50degC, 200=60degC) DE low .1800, high .1800 ; chgn_v_max DE low .100, high .100 ; chgn_c_pchg DE .75 ; chgn_t_pchg_lo (75=10degC) DE .162 ; chgn_t_pchg_hi (162=44.8degC) DE low .0800, high .0800 ; chgn_v_pchg DE .0 ; chgn_ti_pchg_mn DE .0 ; chgn_ti_pchg_mx DE low .2000, high .2000 ; chgn_c_fchg DE .0 ; chgn_ti_fchg_mn DE .0 ; chgn_ti_fchg_mx DE .120 ; chgn_ti_dtdt (temp rise time criteria) DE .10 ; chgn_t_dtdt (temp rise criteria) DE low .10, high .10 ; chgn_v_dv (-delta voltage) DE low .200, high .200 ; chgn_c_topoff DE .11 ; chgn_ti_topoff (11=45min, i.e. 66% eff, 5% cap, c/10) DE low .1300, high .1300 ; chgn_v_rchg (recharge voltage) DE low .80, high .80 ; chgn_c_trik DE .150 ; chgn_ti_trik (timeout for trickle charge) DE low .1900, high .1900 ; chgn_v_safety
Note the following details of the code protection feature on Microchip devices:
• Microchip products meet the specification contained in their particular Microchip Data Sheet.
• Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions.
• There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property.
• Microchip is willing to work with the customer who is concerned about the integrity of their code.
• Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.”
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of ourproducts. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such actsallow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding deviceapplications and the like is provided only for your convenienceand may be superseded by updates. It is your responsibility toensure that your application meets with your specifications.MICROCHIP MAKES NO REPRESENTATIONS ORWARRANTIES OF ANY KIND WHETHER EXPRESS ORIMPLIED, WRITTEN OR ORAL, STATUTORY OROTHERWISE, RELATED TO THE INFORMATION,INCLUDING BUT NOT LIMITED TO ITS CONDITION,QUALITY, PERFORMANCE, MERCHANTABILITY ORFITNESS FOR PURPOSE. Microchip disclaims all liabilityarising from this information and its use. Use of Microchipdevices in life support and/or safety applications is entirely atthe buyer’s risk, and the buyer agrees to defend, indemnify andhold harmless Microchip from any and all damages, claims,suits, or expenses resulting from such use. No licenses areconveyed, implicitly or otherwise, under any Microchipintellectual property rights.
The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KEELOQ, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC, and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A.
Analog-for-the-Digital Age, Application Maestro, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Linear Active Thermistor, Mindi, MiWi, MPASM, MPLIB, MPLINK, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries.
SQTP is a service mark of Microchip Technology Incorporated in the U.S.A.
All other trademarks mentioned herein are property of their respective companies.
Microchip received ISO/TS-16949:2002 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona, Gresham, Oregon and Mountain View, California. The Company’s quality system processes and procedures are for its PICmicro® 8-bit MCUs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified.