ATmega Battery Doc2599 PDF
ATmega Battery Doc2599 PDF
Features 8-bit
• Support for up to 4 Li-Ion series-connected battery cells
• Battery protection by dedicated Hardware Microcontrollers
- Deep under voltage protection
- Over-current protection during charging
- Over-current protection during discharging
- Short circuit protection
Application Note
• Charging and discharging current monitoring with 18 bit ADC
- Automatic Precharging after under-voltage situations
- State-of-Charge and State-of-Health status
• SMBus communication
- Full smart battery SMBus support
- Support for In-System Programming through SMBus
- Support for AES encrypted Firmware updates
1 Introduction
Rechargeable Lithium-Ion (Li-Ion) batteries are widely used in portable electronics
such as cell phones, digital cameras and laptop computers. This is mainly due to
the high energy to weight ratio of these batteries. Maximizing the lifetime and
energy storage of Li-Ion batteries requires careful monitoring and control of the
charge and discharge cycles. Incorrect use may even pose a threat to safety, as Li-
Ion batteries can explode under extreme conditions. For these reasons intelligent
batteries – smart batteries – have been introduced.
The Atmel ATmega406 AVR microcontroller has been created with smart battery
applications in mind. The feature set includes high accuracy ADCs, a TWI interface
for SMBus communications, as well as independent hardware features that can
protect the battery from incorrect use. This application note describes the
implementation of a smart battery using the Atmel ATmega406 microcontroller.
Figure 1-1. Smart battery from the author’s laptop
Rev. 2599C-AVR-02/06
2 Scope of implementation
The intent of the software associated with this application note is to provide an
infrastructure for dealing with issues that will be faced when designing a battery pack.
Although a functional battery pack has been implemented, there are likely many
customizations and feature enhancements that can be made. The designer is
encouraged to take what has been provided and personalize it.
The application note describes how the ATmega406 capabilities are employed to
achieve the functionality needed when implementing a smart battery.
The application note software has not implemented battery authentication, which is
desired in applications where the aftermarket represents significant revenue. This is
used to ensure that only an “original” battery can be used with the product.
Authentication is discussed further in section 6.7.
A Table of Contents is found on page 35.
Warning!
Incorrect handling of Li-Ion batteries poses a safety hazard: If Li-Ion batteries
are mistreated they can explode. Use caution when dealing with any aspect of
the design that may adversely impact safety; make sure you fully understand
the behavior of the hardware and the software as a system.
4 Theory of operation
Smart battery systems consists of three elements:
• Smart battery host
• Smart battery pack
• Smart battery charger
2 AVR453
2599C-AVR-02/06
AVR453
Figure 4-1. A typical smart battery system
Power Power
supply control
AC/DC
SMBus
The smart battery host draws power from the smart battery pack (or just ‘smart
battery’) and can obtain information about type, brand, remaining charge status and
much more. Communication between the Host and the Battery is based on the
System Management Bus (SMBus). The smart battery charger is a charger that can
adapt its output based on the requests from the connected smart battery pack. This
information is either transmitted directly from the smart battery to the charger, or
retrieved directly from the smart battery pack by the charger, through the SMBus. The
safety signal communicates critical errors directly from the battery to the charger.
More information about the smart battery system is available in the Smart Battery
System Specification [1].
3
2599C-AVR-02/06
Figure 4-2. Typical charging profile for a Li-Ion battery
Constant-current Constant-voltage
charging charging
4.5 1600
Capacity [mAh]
Voltage
4.0 1200
3.5 800
Capacity
3.0 400
Current
2.5 0
0 0.5 1.0 1.5 2.0 2.5
It is important that the supplied current and voltage do not exceed the manufacturer’s
specifications for the cells, or overheating and cell rupture may result. The
ATmega406 monitors pack current and voltage independently in hardware and can
disconnect the pack from the charger in the event of over-current or over-voltage.
Additionally, if the designer incorporates thermal sensors the ATmega406 can sense
temperature and request the charger to reduce the charging current or voltage if
needed. The ATmega406 device includes an on-chip temperature sensor to provide a
low-cost alternative to external sensors or to serve as a backup in the event of an
external sensor failure.
A key in providing accurate state-of-charge estimates is the ability to monitor
precisely the charge and discharge currents. The ATmega406 device includes a high-
accuracy Coulomb Counter ADC that provides both high sensitivity and high
resolution for this purpose.
Unused
Working voltage span
capacity
End voltage
Time
4 AVR453
2599C-AVR-02/06
AVR453
To make best use of the available cell capacity, it is crucial that the cell voltage can
be accurately measured to allow operation down to as low voltage as possible without
going below the cell’s discharge voltage limit. By having the bottom limit of the
working voltage span as close as possible to the discharge cut-off voltage, the
unused capacity is minimized (see Figure 4-3). For this reason, it is advantageous to
have a high-accuracy ADC to measure the cell voltages. It is also critical to have as
little series resistance as possible in the system to prevent unnecessary voltage
drops. With the redundant safety features present in the ATmega406, it may be
possible to eliminate one or more stages of safety circuitry from the pack, thus
reducing the losses and increasing the pack output. Additionally, it is important to use
a low-resistance device for current measurement. The reference design uses a 5mΩ
resistor for this purpose and is able to measure current flow with a resolution better
than 1mA.
5
2599C-AVR-02/06
4.2 Smart battery definition
There are several types of smart batteries, some smarter than others. The simplest
form of a smart battery provides information about the battery technology and charge
algorithm. The definition provided by the Smart Battery System Forum states that a
smart battery must at least be able to provide State-of-Charge information.
A fundamental need for Li-Ion batteries is short-circuit protection. More sophisticated
packs also include enhanced safety mechanisms to prevent over-charging, over-
discharging, over-temperature and other conditions that are dangerous or could
adversely affect battery longevity.
6 AVR453
2599C-AVR-02/06
AVR453
its own charging, report errors, inform the Host of low-charge conditions, predict
remaining run-time, provide temperate, voltage and current information and
continuously self-correct to maintain prediction accuracy. The SMBus specification
also allows for five separate manufacturer-defined commands. One of these is used
in this reference implementation for performing in-system programming of the
ATmega406 device over SMBus. Another command is used to initiate, delete or
check status of calibration.
7
2599C-AVR-02/06
Factory calibration of the CCADC offset must be performed to ensure maximum
accuracy.
The VADC is used to monitor the individual cell voltages, the chip temperature from
the internal temperature sensor, and can be used to monitor the temperature of the
batteries.
More details about the capabilities and the operation of these ADCs can be found in
the ATmega406 data sheet.
8 AVR453
2599C-AVR-02/06
AVR453
9
2599C-AVR-02/06
5.1 Overview of the software implementation
The software implementation consists of two separate projects: a bootloader, and the
main battery application. The bootloader includes a subset (only enough code to
perform programming tasks over SMBus) of the application program’s SMBus code,
but implemented in a polled manner rather than using interrupts (no interrupts are
used in the bootloader). It also includes a small command interpreter and various low-
level memory programming functions. Optionally, AES or other encryption algorithms
may be added to protect the memory image during transfer.
The application program is more complex. In general, timer interrupts trigger the
VADC to perform periodic scans, and computations are performed on the results to
generate the data required to support the individual SMBus commands. The CCADC
produces its own interrupts when its charge-monitoring data is ready, and calculations
are performed on those results when they become available. SMBus communications
are handled almost entirely by the TWI interrupt’s state machine. Timer0 provides a
periodic timer tick that allows up to eight generic timer event users, and also controls
the duty-cycling and scanning of the LEDs.
The following table details the usage of each peripheral and the interrupts it uses.
10 AVR453
2599C-AVR-02/06
AVR453
5.1.1 Normal Code Execution
The primary code execution begins with a hardware initialization. All peripherals and
interrupt sources are set up, and interrupts are then enabled. SRAM variables are
initialized, and normal execution flow begins.
In addition to normal activity invoked by interrupts, there are two primary mechanisms
used to affect main loop code execution: generic timers and action flags.
The Timer0 Overflow interrupt provides eight generic software timers. When these
timers expire, a corresponding function is called (from within the ISR, so its execution
must be kept very short). This function may restart the timer, enable or disable a
peripheral, or take other small actions. If a larger task must be performed, this
function will assert an Action Flag.
Action flags are monitored in the main loop. When an action flag is asserted, a set of
actions will be taken and the flag will be cleared. To provide longer duration timers
than those available from the Generic Timers directly, one of the Generic Timer
channels asserts an action flag, which in turn tracks longer intervals within the main
loop. Based on these longer timeouts, other more infrequent actions are taken.
One such activity is the initiation of SMBus Master transactions as required by the
SMBus standard. Another activity is the initiation of VADC scanning for measuring
cell voltages, on-chip temperature, and thermistor reading. After a complete scan is
done, the VADC conversion results are used to recalculate these parameters, and
this in turn result in updates to the various SMBus variables.
A mechanism has been established in the VADC Conversion Complete ISR to handle
automatic scanning of all ten VADC channels. Besides taking readings, this scan
automatically manages the disabling and re-enabling of the cell balancing FETs.
Since filters are used on the cell inputs, the cell balancing FETs must be disabled
early enough in the scan to allow the filters to reach full voltage before a cell reading
is taken. The present implementation of the software scans all other channels before
scanning the cells, thus allowing maximum recovery time for the filter’s R-C time
constant. See section 4.1.3 for more details on cell balancing theory.
The Coulomb Counter ADC (CCADC) utilizes several different interrupts, depending
on the pack’s operating mode. Foreground code determines which mode to operate
the Coulomb Counter in, and this further influences the choice of CCADC operating
modes for the purpose of power management. Additionally, the 32kHz Crystal
oscillator supplies clock for the Wakeup timer, which is used in lower-power operating
modes.
As shown in the flowchart in Figure 5-2, the application first initializes all modules and
then enters an eternal loop. In every iteration, the loop first checks if any action flags
are set by the interrupt controlled parts of the application and acts accordingly. Four
times per second the quarter-second flag is set and the loop performs its regular
tasks. Inside the quarter-second flag check, the user can insert custom code to be
executed four times per second. Every fourth time the quarter-second flag is set, once
per second, there is a similar place to insert custom code to be executed once per
second.
When starting the 32kHz oscillator, it takes up to 2 seconds for it to stabilize.
Therefore, when the oscillator is started, a startup delay counter is initialized. The box
'Enable 32kHz oscillator...' in the flowchart takes care of updating this delay counter
and enabling the real-time clock when the startup delay has elapsed.
11
2599C-AVR-02/06
Figure 5-2. Overview of the main loop
Main loop
No No
No
Restart watchdog timer
Multiple of 4
Yes Start new ADC read
ticks, ie. one second
sequence for all channels
elapsed?
No
No
Most of the charge and discharge control, cell balancing and thermal checks are
performed once per second, when a ADC scan sequence is finished. Updated ADC
readings are then available and ready for processing.
12 AVR453
2599C-AVR-02/06
AVR453
Figure 5-3. Flowchart for “Handle ADC scan results”
Handle ADC scan
results
Continue
13
2599C-AVR-02/06
RunningAcc holds the present state of charge at all times. It is possible that this
value may go negative, especially if the pack has not yet been fully calibrated. In
normal operation, when the pack reaches full charge this value will be reset to the
difference between its present value and the MaxBottomAcc value, and
MaxToppAcc will be assigned the result as well, and MaxBottomAcc will be zeroed.
A similar approach is used to recalibrate at full discharge.
While this reference implementation provides all the basic data gathering and
reporting functions needed for a smart battery, software algorithms must be added to
provide accurate capacity estimates as well as specific charging control methods.
14 AVR453
2599C-AVR-02/06
AVR453
Equation 5-1. Calculation to obtain correct cell voltage in mV
[ ]
Temp. 1ο K =
ADCreading ⋅ VPTAT Calib
214
[
Temp. 0.1ο K = ]
ADCreading ⋅ VPTAT Calib ⋅ 10
214
15
2599C-AVR-02/06
used and would yield even more resolution on low-current readings, specifically, up to
6 ⋅ 5mΩ could be used without overflowing the 32-bit accumulator while still allowing
the maximum possible SMBus pack capacity.
Note that any CCADC offset that is present should be removed from each sample
before accumulation. Since such offset may be influenced by temperature, additional
algorithms may be required. Since the resolution of the offset is limited to the step
size of the converter, for smaller currents the error of only being able to use an
integer value for offset becomes a larger portion of the result. This fact may determine
both the value of sense resistor chosen as well as the point where a change is made
from using Accumulator mode to using periodically sampled or estimated
measurements.
Unused
MSB LSB
16 AVR453
2599C-AVR-02/06
AVR453
Figure 5-5. Calibration states
Valid
Startup/
Reset
calibration
values?
YES
Not
NO calibrated NO
Request: Delete
calibration values
Request: Delete
Request: Start
calibration values
calibration
Valid
Request: Start
Running calibration Calibrated YES calibration
values?
Request: Start
calibration
Calibration
success?
Found suitable No
Measure external reference value for BGCCR?
voltage of 4.096V
Yes
SUCCESS FAILED
Please refer to the ATmega406 datasheet for more details on the Bandgap Reference
Calibration registers, BGCRR and BGCCR.
17
2599C-AVR-02/06
5.5.2 CCADC offset calibration
Calibration for current measurement offset, or CCADC offset, is implemented in the
function CalibrateCCoffset() in the file analog.h. The function assumes that
the current through the sense resistor has been zero for at least one second before
initiation calibration. The result from the CCADC is then used to update the offset
calibration values. If the measured offset is outside predefined limits, the calibration
process fails and the offset calibration value is set to a default value of zero.
18 AVR453
2599C-AVR-02/06
AVR453
All word-size data maintained for SMBus commands are kept in the union variable
SV. The header file smbus.h includes two different ways to access this data, either
through the SMBvariables[][] array which provides byte-level access, or the
SMBvar_int[] array which provides word-level access. This approach reduces
code size and improves speed when dealing with flags and byte-wide data.
Table 5-2 provides details on the default value of each of these variables.
Table 5-2. SMBus Commands and Default data values
Command (ID) Data Direction & Size Default Value Data Source
ManufacturerAccess (0x00) R/W Word 0x4060 Initialized at startup
RemainingCapacityAlarm (0x01) R/W Word PACK_DESIGNCAPTYP (1)
/ 10 From battery specs
RemainingTimeAlarm (0x02) R/W Word 10 Per sbdat110, section 4.4.1
BatteryMode (0x03) R/W Word 0 Per sbdat110, section 5.1.4
AtRate (0x04) R/W Word Calculated as needed Per sbdat110, section 5.1.5
AtRateTimeToFull (0x05) Read Word Calculated as needed Per sbdat110, section 5.1.6
AtRateTimeToEmpty (0x06) Read Word Calculated as needed Per sbdat110, section 5.1.7
AtRateOK (0x07) Read Word Calculated as needed Per sbdat110, section 5.1.8
Temperature (0x08) Read Word Calculated as needed On-chip sensor
Voltage (0x09) Read Word Calculated as needed VADC readings
Current (0x0A) Read Word Calculated as needed CCADC Instantaneous
AverageCurrent (0x0B) Read Word Calculated as needed CCADC Instantaneous, avg’d
MaxError (0x0C) Read Word Calculated as needed Per sbdat110, section 5.1.13
RelativeStateOfCharge (0x0D) Read Word Calculated as needed Per sbdat110, section 5.1.14
AbsoluteStateOfCharge (0x0E) Read Word Calculated as needed Per sbdat110, section 5.1.15
RemainingCapacity (0x0F) Read Word Calculated as needed Per sbdat110, section 5.1.16
FullChargeCapacity (0x10) Read Word Calculated as needed Per sbdat110, section 5.1.17
RunTimeToEmpty (0x11) Read Word Calculated as needed Per sbdat110, section 5.1.18
AverageTimeToEmpty (0x12) Read Word Calculated as needed Per sbdat110, section 5.1.19
AverageTimeToFull (0x13) Read Word Calculated as needed Per sbdat110, section 5.1.20
ChargingCurrent (0x14) Read Word or Write to Charger Calculated as needed Per sbdat110, section 5.2.1
ChargingVoltage (0x15) Read Word or Write to Charger Calculated as needed Per sbdat110, section 5.2.2
BatteryStatus (0x16) Read Word or Write to Host 0x0080 Per sbdat110, section 4.4.1
CycleCount (0x17) Read Word 0 Per sbdat110, section 4.4.1
DesignCapacity (0x18) Read Word Calculated as needed From battery specs
DesignVoltage (0x19) Read Word Calculated as needed From battery specs
SpecificationInfo (0x1A) Read Word 0x0031 Per sbdat110, section 5.1.25
ManufactureDate (0x1B) Read Word Calculated at compile time Per sbdat110, section 5.1.26
SerialNumber (0x1C) Read Word User-defined Per sbdat110, section 5.1.27
Reserved (0x1D-0x1F) Read Word N/A N/A
ManufacturerName (0x20) Read String/Block User-defined Per sbdat110, section 5.1.28
DeviceName (0x21) Read String/Block User-defined Per sbdat110, section 5.1.29
DeviceChemistry (0x22) Read String/Block “LION” Per sbdat110, section 5.1.30
ManufacturerData (0x23) Read String/Block User-defined Per sbdat110, section 5.1.31
19
2599C-AVR-02/06
Command (ID) Data Direction & Size Default Value Data Source
Reserved (0x24-0x2E) N/A N/A N/A
OptionalMfgFunction5 (0x2F) R/W Block N/A Bootloader
Reserved (0x30-0x3B) N/A N/A N/A
OptionalMfgFunction4 (0x3C) R/W Word N/A Calibration state
OptionalMfgFunction3 (0x3D) R/W Word N/A N/A
OptionalMfgFunction2 (0x3E) R/W Word N/A N/A
OptionalMfgFunction1 (0x3F) R/W Word N/A N/A
Notes: 1. Typical capacity in mAh for the battery pack. Defined in pack.h.
Local copies of all variables required by the SMBus command set are maintained in
SRAM. In some cases, these values are treated as read-only; in other cases, the
Battery pack, the Host, the Charger or any of these may modify the variables.
Some variables affect other commands and variables. For instance, the
CapacityMode flag will affect all calculations involving mA vs. mW. For more
information, see the Smart Battery Data Specification, section 5.1.4. The AtRate()
function is part of a two-stage procedure for determining time remaining for either
charging or discharging at a given rate. See the Smart Battery Data Specification,
section 5.1.6 for more information on the AtRate() command. The
SpecificationInfo() command contains bits that define scaling parameters for
the pack voltage and current to allow very high capacity and high voltage packs. See
the Smart Battery Data Specification, section 5.1.25 for more information on the
AtRate() command.
20 AVR453
2599C-AVR-02/06
AVR453
Figure 5-7. Flowchart for TWI Interrupt Service Routine
SLAVE-MODE STATES
STOP
Error,
Stop RDATA
RDATA
Timeout Error RCMD Error
Complete
Generate a
No Valid Cmd? Yes TW_Wait4RW
Bus Timeout
Error
NAK Error
REPEATED
START
START
TW_ReplyData
STOP
ACK,
SLA_R
TW_MCMD_W
TW_MSLA_W
ACK (Send buffered
(Send SLA+W)
Cmd, then Data)
No
ACK
Error
MASTER-MODE STATES
When the AVR receives the Command byte, a table look-up is used to check that the
command is valid for SMBus Slave mode. If it is not, a bus timeout error is generated
to inform the sender of the fault. If the command is valid, the bus is re-enabled by
clearing the TWI Interrupt flag (TWINT) and the state machine advances.
21
2599C-AVR-02/06
have been received, a flag is set asking for the foreground code to process the
received command.
Figure 5-8. SMBus Slave Write command examples
S Slave Address W A Command Code A Data Byte A P
Write Byte Protocol format
S Slave Address W A Command Code A Data Byte Low A Data Byte High A P
Write Word Protocol format
In the foreground code, a PEC validation is performed if the byte count indicates that
PEC has been sent. Once it is determined that the data is valid, the command byte is
used as an index into a table of pointers to functions, with each function
corresponding to one and only one command. In most cases the function will write the
received data to the SRAM-based SMBus variables. As needed, other actions will
also be taken. Once the action is completed, the bus is re-enabled and is then ready
for further transactions. If modifications are made to the software, it is important that
the bus is re-enabled in less than 25ms or the Host may assume that the pack is
generating a bus timeout error.
22 AVR453
2599C-AVR-02/06
AVR453
due to the SMBus requirement that a bus master is required to check for bus idle time
of 50µs.
To meet this requirement, the ATmega406 pin-change detection mechanism is used
to monitor for bus idle conditions. This reference implementation assumes that PA6 is
connected to the SMBCLK (SCL) signal. Alternatively, in a user specific
implementation, any I/O signal with pin-change capability can be used instead of PA6.
Note that the SCL line may not be read directly as the SCL and SDA lines are not
shared with general-purpose I/O ports.
A multi-stage method is employed to ensure bus availability (refer to Figure 5-10).
First, the presence of a message in the Transmit Buffer results in execution of the
foreground code that manages Master mode. Next, if the Slave state machine is not
in the IDLE state, no attempt is made to take control of the bus. Next, the SCL line is
checked by reading PA6 to be sure it is not currently at a logical zero condition. At
this point the bus appears to be free, so as the last stage a flag (TEST50US) is
asserted to indicate that the 50µs bus-free test has now begun. During this time the
SCL line is monitored by means of enabling the Pin-Change Interrupt for PA6. The
foreground SMBus Master mode management code is then exited. With a clock
speed of 1MHz, 50µs corresponds to 50 instructions at most. Therefore, when the
code is re-entered it is guaranteed that at least 50µs has passed and handling the
timing of the 50µs by the use of a timer is thus not required.
Figure 5-10. Initiation of Master Transmit from smart battery
SMBus Master Mode
Clears the TEST50US flag if
SMBus is not free for 50µs.
Msg present in Yes SMBus state Yes SMBCLK is idle Yes Test SMBLK idle
SMBus TX buffer? machine IDLE? (logic high) for 50µs
No No No
Start transmission
Yes
Rest of communication is handled by
ISR, which also clears the SMLOCK
flag when transmission is competed. Activate TWI ISR in
state 0x08
When the Pin-Change Interrupt is enabled, any bus activity will trigger the interrupt.
The corresponding ISR will clear the TEST50US flag, indicating that the bus is not
free. Thus, when the foreground code is re-entered, if this flag is not asserted but
there is a message in the buffer, it is understood that the test has failed and must be
started again; thus the flag will again be asserted and the routine will be exited.
23
2599C-AVR-02/06
When the foreground code is eventually called again from the main loop and the
TEST50US flag is still asserted, conditions are good for beginning a transmission.
One last check is performed to ensure that the SMBCLK line is not low and the TWI
ISR State Machine is in the IDLE state. Finally, a START bit is transmitted to take
control of the bus. An additional lock flag (SMLOCK) is also asserted to indicate that
Master mode has been entered by the TWI Hardware, so that the foreground code
will not attempt to repeatedly initiate a transmission for the same message.
If the ATmega406 is successful in taking ownership of the bus, at the completion of
the transmission of the Start bit the TWI ISR will be activated with a Status code of
0x08. As a result, the state machine will now vector into the states related to Master
Mode transmission, and the ISR will handle all further aspects of the transmission.
Alternatively, if the TWI module is unsuccessful in taking over the bus, the TWI ISR
will still be entered but with status codes that are indicative of an error having
occurred. In this latter case, the SMLOCK and TEST50US flags will be cleared to
force another bus takeover attempt in the future.
25
2599C-AVR-02/06
For Slave Read command types, PEC is generated using all bytes from the complete
transaction. This includes the original Slave Address + W, the Command, the Slave
Address + R, and all of the reply data. Depending on whether the slave address is
assigned by the Host system or is fixed, it may be possible to pre-calculate a partial
CRC value based on the Slave address and the command, rather than generating it
on-the-fly each time.
For Slave Write command types, it is not known for certain whether PEC will be
included in the transmission. Therefore the TWI ISR code must accommodate the
presence or absence of PEC, regardless of the state of the UsePEC flag. Upon
completion of the receive operation, it is determined whether the PEC value is
included as part of the received packet. As discussed in the previous section, the
number of expected bytes is determined in advance according to the specific
command, knowing that PEC may or may not be present in addition to this. After all
expected bytes are received, the ISR leaves TWINT asserted and notifies the
foreground code of the presence of a complete packet. The foreground code then
analyzes the packet for errors, and if any are found a timeout error is generated and
the packet is discarded. Otherwise, the command action is carried out and TWINT is
cleared, freeing the bus to allow the Master to send a STOP and return the ISR state
machine to the IDLE state.
In cases where errors are detected by the foreground code, it is necessary to be able
to force the ISR back to the IDLE state. Therefore, the ISR’s state variable has scope
beyond the ISR itself.
26 AVR453
2599C-AVR-02/06
AVR453
The Boot Loader code initially performs a simple check of the Application Section of
the flash memory to determine if it contains a valid program image. In the
low_level_init() function of the bootloader code, if the Reset vector at location
0x0000 contains 0xFFFF, it can be safely assumed that the Application area does not
contain a valid image, and control will stay with the boot loader. Otherwise, a jump to
address 0x0000 is performed, effectively starting the main application code.
Since the SMBus imposes a startup time limit of 500ms, the number of clock cycles
available for the Boot Loader to perform extensive validity checks, like a complete
CRC of the application section, is limited. It is possible to implement a more complete
validation of the Application code and to also perform a very thorough verification in
the primary application, and run this after the SMBus interface is brought into
operation. This is left up to the user to implement.
If the Application Section of flash memory does not contain a valid image, then
execution continues in the Boot Loader’s code. The entry point for the bootloader
when being accessed from the application area is the entry point to the bootloader’s
main() function. Note that if any changes are made to the bootloader code or if it is
recompiled, this address should be verified and the smbus.c code should reflect the
correct address in its handler for OptionalMfgFunction5. Since this could be
entered from either the boot loader or from the application area, all critical variables
for the boot loader are initialized inside of main() to ensure that they are properly
initialized regardless of how main() was entered. It also ensures that all interrupts
are disabled to prevent inadvertent execution of any application-area code. Next, it
initializes the TWI port to prepare it for SMBus communications. Finally, control
passes to the main loop of the loader.
The main loop waits for the only SMBus command that is valid for the boot loader,
namely, OptionalMfgFunction5. Upon receiving this command, it interprets the
contents per the protocol defined below and performs the requested action.
Each SMBus Slave Write command modifies a Status flag based on success or
failure of the command. It is possible, but not necessary, to query this Status flag after
each Slave Write operation, even those that only update a portion of the SRAM data
buffer. For operations that take a relatively long time, such as erasing flash or
EEPROM, the Status flag will also indicate if the device is busy.
All communications are expected to use the standard smart battery address.
Likewise, only command identifier 0x2F, OptionalMfgFunction5, is used for ISP
over SMBus. All Slave Write operations use the Write Block mode and must all
conform to the protocol defined below. Slave Read operations use only the Read
Block protocol and will only return the Status value. It is left to the designer to
implement a Memory Read command if this is desired, but this may expose the
internal memory contents to copying.
Figure 5-11. Boot loader Write command frame (Slave Write).
S Slave Address (0x16) W A OptionalMfgFunction5 (0x2F) A Byte Count A
Data Data A P
27
2599C-AVR-02/06
Note that both EEPROM and Flash memory addresses are given as byte addresses.
For the Slave Write commands, the meaning of the fields varies by the specific
command and the memory type.
Five primary commands are implemented within the OptionalMfgFunction5
command: Write, Erase, Patch, Insert and Verify. Provision is also included for a
Read command, but this should be omitted in final products as it poses a security
hole. Alternatively, one could consider adding an encryption layer.
There are also two secondary commands, Exit and Activate. Activate is used to
switch to bootloader mode while running in the main application, and is ignored if
received while already in the bootloader. Exit is used when all bootloader tasks have
been completed and it is desired to start executing the main application code.
Two additional optional commands may be implemented by the user, the ‘w’ and ‘v’
commands (distinguished by the use of lower-case letters). These commands
indicate that decryption should be performed on the data block (either an entire page
for Flash, or the specified block size for EEPROM) prior to the write or verify
operation. In this way, encrypted data may be transferred to the internal SRAM buffer
but will be decrypted before use, ensuring data security.
Table 5-4. OptionalMfgFunction5 Sub-commands
Command Command fields required Functionality(1)
WRITE (‘W’ / ‘w’) Mem Type: (F)lash / (N)onvolatile EEPROM Write the contents of the internal SRAM buffer to the
Offset: Buffer offset (EEPROM only) specified memory region. Operation may fail based on
Addr High/Low: Start address in Flash/EEPROM settings of the ‘lock’ fuse bits.
Block Size: Bytes to write (EEPROM only)
ERASE (‘E’) Mem Type: (F)lash / (N)onvolatile EEPROM Erase the specified memory region. Operation may fail
Addr High/Low: Start address in Flash/EEPROM based on settings of the ‘lock’ fuse bits. This operation
Block Size: Bytes to erase (EEPROM only) does not affect or make use of the internal SRAM buffer.
PATCH (‘P’) Mem Type: (F)lash / (N)onvolatile EEPROM Loads the internal SRAM buffer with the present
Offset: Buffer offset (EEPROM only) contents of the specified memory region. The buffer may
Addr High/Low: Start address in Flash/EEPROM then be partially overwritten using the INSERT command
Block Size: Bytes to read (EEPROM only) and then written back to memory.
INSERT (‘I’) Offset: Buffer offset Place the specified data into the internal SRAM buffer,
Block Size: Byte count starting at the specified buffer offset. Note that a
Data: Data bytes to write to SRAM buffer complete fill of the buffer is not possible in a single
INSERT operation.
VERIFY(‘V’ / ‘v’) Mem Type: (F)lash / (N)onvolatile EEPROM After loading the internal SRAM buffer, the Verify
Offset: Buffer offset (EEPROM only) command will perform a comparison to the specified
Addr High/Low: Start address in Flash/EEPROM memory region. The Status flag will indicate the
Block Size: Bytes to verify (EEPROM only) good/bad result of the comparison.
READ Not implemented at this time The Read command may be used primarily to read out
the contents of the device’s EEPROM memory so that it
may be restored after a programming operation.
ACTIVATE (‘A’) None, but data Byte Count has to be 1, i.e. Transfer control from Application code to Bootloader. All
equivalent to Word Write. other smart battery functions stop.
EXIT (‘X’) None Transfer control from Bootloader to Application code. All
smart battery functions start again.
Notes: 2. Setting of lock bits may limit the possibilities to read and write to the Flash from the Boot Loader. Please refer to
the datasheet for more details.
28 AVR453
2599C-AVR-02/06
AVR453
W: If Flash is specified, the address is the base of the Flash page to be written, in
bytes. No other information is required as only a complete page can be written to
flash. If EEPROM is specified, then the address is the starting address in EEPROM
space; offset is the starting location within the on-chip SRAM buffer, and the byte
count must be provided in the Block Size parameter.
w: Same as the “W” command, but the contents of the SRAM buffer must first be
decrypted before being written. Also, the contents of this message are also encrypted
to prevent an attacker from gaining information about the target location of the write
command.
V: For both Flash and EEPROM, the address is any valid address (byte-based); it is
not restricted to page boundaries. If flash is specified, the byte count is assumed to
be 128 bytes as a precaution against someone easily mapping the contents of flash
one byte at a time. For EEPROM, and byte size from 1 to 128 may be used.
v: Same as the “V” command, but the contents of the SRAM buffer must first be
decrypted before being verified. Additionally, the contents of this message block are
also encrypted to prevent an attacker from gaining information about the target
location of the write command.
E: For Flash memory, an entire Flash page will be erased; the address is forced to
the beginning of the specified page. Any EEPROM address and byte count is
allowed, up to 128 bytes.
P: To ‘patch’ a memory area, first the Patch command is issued to copy the original
memory contents to the internal SRAM buffer. The address must be at a page
boundary for Flash memory. Next, the ‘I’ command is used to supply ‘repair’ data that
overwrites only parts of the buffer contents. Finally, a ‘W’ is performed to save the
update.
I: Since this command writes only to the internal SRAM buffer, the Address field is
ignored. The Offset and Block Size values are required, as well as the data block.
Due to SMBus packet size limits, only up to 24 bytes may be transferred on the initial
packet. However, if the Byte Count field specifies more than 24 bytes, then
subsequent ‘chained’ SMBus packets are expected to contain only data, thus
allowing up to 32 bytes to be transferred in each subsequent packet until the Block
Size that was specified in the initial packet has been fulfilled. The most that can ever
be transferred is dictated by the SRAM buffer size (128 bytes) minus the starting
offset. Thus, for a complete fill of the buffer using chained packets, an offset of zero
must be specified. Alternately, individual Insert command packets may be issued with
any amount of data as long as the offset plus the size of any packet does not exceed
128.
Note that the Write and Verify commands, whether for EEPROM or Flash memory as
its target, use only the contents of the on-chip data buffer, not the data block within
the ‘W’ or ‘V’ SMBus message. All data must first be written to the on-chip SRAM
data buffer using the “I” command, and subsequently stored or verified from there.
Note that data held in the buffer is not destroyed after a Write or Verify operation, so if
the same data needs to be repeatedly written to different memory locations, this can
be done by sending new ‘W’ commands without having to reload the SRAM buffer
after each ‘W’ operation; simply supply a different address in the ‘W’ command each
time.
Encrypted data may be used for writing or verifying EEPROM or SRAM memory as
well if desired. Note that use of the Patch command cannot be supported when using
encryption.
29
2599C-AVR-02/06
5.11 Power Modes of Operation
The battery pack can be in one of four power modes: Power-Off, Power-Save, Idle
and Active. These mode names reflect the Sleep Modes for ATmega406. Refer to
Table 5-5. Note that the implementation made is meant as a reference to how the
power management can be implemented; it can be implemented differently if desired.
Table 5-5. Smart battery modes of operation
Mode of Operation Used when:
Power-Off Used when battery fully drained, also referred to as a
Deep Under-voltage condition. Only charging through
pre-charge FET is supported. Host cannot draw power
from battery.
Power-Save Used when Host is turned off, or if the battery is
disconnected from Host/ Charger.
Idle Used when discharge rate is low.
Active Used during charging and ‘normal’ discharging rates
In all modes except Power-Off Mode, the Hardware Battery Protect circuitry is
initialized and operational. See the accompanying state chart in Figure 5-12 for a
graphical view of the interaction of these modes.
Figure 5-12. Operating modes
Power-
Charger Active Save TWI bus
(BATT signal) connected
TWI bus
disconnected
Power applied
Deep Under-voltage /
Power-Off Over-temperature / Active
BP_INT
Deep Under-voltage /
Over-temperature / Low discharge
BP_INT rate
Regular Current
Interrupt
Charging
Idle
30 AVR453
2599C-AVR-02/06
AVR453
the ATmega406 is not executing code, no current measurement nor time
measurement takes place in this mode. The SMBus is also inactive.
This mode is entered automatically by hardware if the battery voltage drops below the
ATmega406 Deep Under-Voltage detection level that result in an automatic power-off
of the on-chip voltage regulator (See datasheet regarding available Deep Under-
Voltage levels). Software can also force entry into this mode when the pack voltage
drops below minimum cell voltage levels in order to prevent permanent cell damage.
The hardware protection can thus be seen as a secondary independent battery
protection circuit.
This mode is exited by a hard Reset is caused by the BATT pin going higher than 6 -
8V, which causes a Power-On-Reset with the PORF bit in MCUSR set to 1.
Therefore, upon initial execution of the main() function after a Reset, when the
PORF flag is set the operating mode will, in this implementation, be forced to be the
Power-Save mode.
31
2599C-AVR-02/06
Despite the somewhat relaxed timing requirements, the 32kHz crystal oscillator is
used as the CCADC clock source in this mode. The SMBus must be fully active and
ready to respond to all requests, but other tasks such as battery voltage and
temperature measurements can operate at a reduced rate in order to save power.
This mode is entered only from Active Mode, as the main difference from that mode is
the accuracy of the method of measuring pack current. Specifically, when battery
current drain falls below a predetermined level, the software changes to this mode in
order to conserve power. Upon entry, the CCADC operating mode is reconfigured to
use the Regular Current mode rather than the Accumulate Mode. Note that the result
of the first four conversions is discarded by software as they do not hold reliable
measurements. The CCADC Regular Discharge Current register is initialized upon
entry. The CCADC Regular Charge Current register is not used in this
implementation.
This mode will be exited if a charge current is detected, in which case Active Mode
will be used. Also, if the battery current drain exceeds a selected level, the Regular
Current Interrupt will fire and the software will switch back to Active Mode.
Since any interrupt will bring the ATmega406 out of Idle Sleep Mode, a mechanism
must be established to identify when it is allowable for the ATmega406 to re-enter Idle
Sleep Mode. In this implementation, if all active tasks in the main loop have been
handled, it is ok to enter Idle Sleep Mode again.
The tasks that need to be handled include periodic VADC scans and calculations of
the cell voltages, SMBus communication, CCADC current measurements and charge
tracking. All of these are initiated or maintained by interrupts, and therefore sleeping
while waiting for interrupts is not problematic in this application. The VADC peripheral
receives clock in Active, Idle and ADC Noise Reduction Sleep Modes, while SMBus
transmissions (including Slave-mode responses) requires either Active or Idle Sleep
Mode. Therefore, Idle Sleep Mode is used instead of ADC Noise Reduction Sleep
Mode.
32 AVR453
2599C-AVR-02/06
AVR453
The software exits Active Mode in response to one of two conditions: either the
SMBus has gone inactive, in which case it switches to Power-Save Mode; or when
the current drain falls below a predetermined level, in which case it switches to Idle
Mode.
6.1 Calibration
Depending on the accuracy of the sense resistor used, it may be necessary to include
gain calibration on the current measurement. In order to avoid frequently dealing with
expensive 'long' multiply operations, it is recommended to add scaling to the routines
that report results and capacities, rather than correcting each and every sample. It is
possible to adjust the calibration of the Current and AverageCurrent readings in
approximately 0.5% steps by modifying the number of samples of the Instantaneous
CCADC interrupt that are used each second. Please see the source code for details.
6.5 EEPROM
Considerably more use can be made of the on-chip EEPROM memory of the
ATmega406, such as maintaining pack charge state information, and historical data
such as the number of charge/discharge cycles or thermal extremes.
33
2599C-AVR-02/06
6.6 Encrypted firmware updates
The bootloader in this implementation is prepared for, but does not implement
encrypted communication. If desired, please also check out the application notes
AVR230: DES Bootloader and AVR231: AES Bootloader.
34 AVR453
2599C-AVR-02/06
AVR453
8 Table of Contents
Features ............................................................................................... 1
1 Introduction ...................................................................................... 1
2 Scope of implementation ................................................................ 2
3 Release Notes for preliminary release of AVR453 ........................ 2
4 Theory of operation ......................................................................... 2
4.1 Li-Ion Battery technology..................................................................................... 3
4.1.1 Charging profile of Li-Ion batteries ............................................................................ 3
4.1.2 Discharging Li-Ion batteries....................................................................................... 4
4.1.3 Cell balancing............................................................................................................ 5
35
2599C-AVR-02/06
5.10 In System Programming (ISP) over SMBus.................................................... 26
5.11 Power Modes of Operation.............................................................................. 30
5.11.1 Power-Off Mode .................................................................................................... 30
5.11.2 Power-Save Mode ................................................................................................. 31
5.11.3 Idle Mode............................................................................................................... 31
5.11.4 Active Mode........................................................................................................... 32
36 AVR453
2599C-AVR-02/06
Disclaimer
Atmel Corporation Atmel Operations
2325 Orchard Parkway
Memory RF/Automotive
2325 Orchard Parkway Theresienstrasse 2
San Jose, CA 95131, USA
San Jose, CA 95131, USA Postfach 3535
Tel: 1(408) 441-0311
Tel: 1(408) 441-0311 74025 Heilbronn, Germany
Fax: 1(408) 487-2600
Fax: 1(408) 436-4314 Tel: (49) 71-31-67-0
Regional Headquarters Fax: (49) 71-31-67-2340
Microcontrollers
2325 Orchard Parkway
Europe 1150 East Cheyenne Mtn. Blvd.
Atmel Sarl San Jose, CA 95131, USA
Colorado Springs, CO 80906, USA
Route des Arsenaux 41 Tel: 1(408) 441-0311
Tel: 1(719) 576-3300
Case Postale 80 Fax: 1(408) 436-4314
Fax: 1(719) 540-1759
CH-1705 Fribourg
Switzerland La Chantrerie Biometrics/Imaging/Hi-Rel MPU/
Tel: (41) 26-426-5555 BP 70602 High Speed Converters/RF Datacom
Fax: (41) 26-426-5500 44306 Nantes Cedex 3, France Avenue de Rochepleine
Tel: (33) 2-40-18-18-18 BP 123
Asia Fax: (33) 2-40-18-19-60 38521 Saint-Egreve Cedex, France
Room 1219 Tel: (33) 4-76-58-30-00
Chinachem Golden Plaza ASIC/ASSP/Smart Cards
Fax: (33) 4-76-58-34-80
Zone Industrielle
77 Mody Road Tsimshatsui
13106 Rousset Cedex, France
East Kowloon
Tel: (33) 4-42-53-60-00
Hong Kong
Fax: (33) 4-42-53-60-01
Tel: (852) 2721-9778
Fax: (852) 2722-1369
1150 East Cheyenne Mtn. Blvd.
Japan Colorado Springs, CO 80906, USA
9F, Tonetsu Shinkawa Bldg. Tel: 1(719) 576-3300
1-24-8 Shinkawa Fax: 1(719) 540-1759
Chuo-ku, Tokyo 104-0033
Japan Scottish Enterprise Technology Park
Tel: (81) 3-3523-3551 Maxwell Building
Fax: (81) 3-3523-7581 East Kilbride G75 0QR, Scotland
Tel: (44) 1355-803-000
Fax: (44) 1355-242-743
Literature Requests
www.atmel.com/literature
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any
intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL’S TERMS AND
CONDITIONS OF SALE LOCATED ON ATMEL’S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED
OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS
INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the
contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any
commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel’s products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
© Atmel Corporation 2006. All rights reserved. Atmel®, logo and combinations thereof, Everywhere You Are®, AVR®, AVR Studio® and
others, are the registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be
trademarks of others.
2599C-AVR-02/06