1 /* This file has been prepared for Doxygen automatic documentation generation.*/
\r
2 /*! \file *********************************************************************
\r
7 * Contains the functions related to the states defined in menu.h.\n
\r
8 * Also contains related functions, i.e. for checking jumpers, setting
\r
9 * error flags and "dozing".
\r
11 * \note The state function Charge() is in a separate file since it
\r
12 * should easily be changed with regard to battery type.
\r
14 * \par Application note:
\r
15 * AVR458: Charging Li-Ion Batteries with BC100 \n
\r
16 * AVR463: Charging NiMH Batteries with BC100
\r
18 * \par Documentation
\r
19 * For comprehensive code documentation, supported compilers, compiler
\r
20 * settings and supported devices see readme.html
\r
23 * Atmel Corporation: http://www.atmel.com \n
\r
24 * Support email: avr@atmel.com
\r
30 * $URL: http://svn.norway.atmel.com/AppsAVR8/avr458_Charging_Li-Ion_Batteries_with_BC100/tag/20070904_release_1.0/code/IAR/statefunc.c $
\r
31 * $Date: 2007-08-23 12:55:51 +0200 (to, 23 aug 2007) $\n
\r
32 ******************************************************************************/
\r
35 #include <avr/interrupt.h>
\r
36 #include <avr/wdt.h>
\r
37 #include <avr/wdt.h>
\r
38 #include <avr/sleep.h>
\r
39 #include <avr/eeprom.h>
\r
43 #include "structs.h"
\r
47 #include "statefunc.h"
\r
48 #include "battery.h"
\r
58 //******************************************************************************
\r
60 //******************************************************************************
\r
61 unsigned char ErrorFlags; //!< \brief Holds error flags.
\r
62 //!< \note See statefunc.h for definitions of flags.
\r
64 //! \brief Holds the state in which latest error flag was set.
\r
65 //! \note See menu.h for definitions of states.
\r
66 unsigned char ErrorState;
\r
69 //******************************************************************************
\r
71 //******************************************************************************
\r
72 /*! \brief Initialization
\r
74 * - Sets the system clock prescaler to 1 (run at 8 MHz)
\r
75 * - Initializes the one-wire interface
\r
76 * - Clears on-chip EEPROM
\r
77 * - Sets battery enable pins as outputs, then disables batteries
\r
78 * - Initializes SPI according to \ref SPIMODE
\r
80 * - Initializes timers
\r
81 * - Reads battery data from both battery inputs (via ADC)
\r
82 * - Disables batteries again
\r
83 * - Sets battery A as the current one (\ref BattActive = 0)
\r
84 * - Clears ErrorFlags
\r
86 * \param inp Not used.
\r
88 * \retval ST_BATCON Next state in the sequence.
\r
90 unsigned char Initialize(unsigned char inp)
\r
92 unsigned char i, page;
\r
94 // Disable interrupts while setting prescaler.
\r
97 CLKPR = (1<<CLKPCE); // Enable CLKPS bit modification.
\r
98 CLKPR = 0; // Set prescaler 1 => 8 MHz clock frequency.
\r
100 // Init 1-Wire(R) interface.
\r
103 // Clear on-chip EEPROM.
\r
104 for (page = 0; page < 4; page++) {
\r
105 for (i = 0; i < 32; i++) {
\r
106 eeprom_write_byte(&BattEEPROM[page][i], 0);
\r
110 DDRB = (1<<PB4) | (1<<PB5); // Set battery enable pins as outputs.
\r
111 DisableBatteries();
\r
116 // Attempt to get ADC-readings (also gets RID-data) from both batteries.
\r
117 for (i = 0; i < 2; i++) {
\r
120 BatteryStatusRefresh();
\r
123 DisableBatteries();
\r
125 BattActive = 0; // We have to start somewhere..
\r
128 // Init complete! Go to ST_BATCON next.
\r
133 /*! \brief Tests jumper settings and batteries, starts charging if necessary.
\r
135 * First, JumperCheck() is called. If successful, the function checks if any
\r
136 * valid batteries are connected and attempts to charge these, if necessary.\n
\r
137 * If no charging is necessary, the charger goes to ST_SLEEP next.\n
\r
138 * ST_ERROR is next if either JumperCheck() fails or there are no valid
\r
139 * batteries. In this last case, the error is also flagged.
\r
141 * \param inp Not used.
\r
143 * \retval ST_ERROR Next state if either the jumper check failed, or there are
\r
144 * no valid batteries.
\r
145 * \retval ST_PREQUAL Next state if a battery is found to enabled and not fully
\r
147 * \retval ST_SLEEP Next state if battery/batteries are enabled and fully
\r
150 unsigned char BatteryControl(unsigned char inp)
\r
154 // Make sure ADC inputs are configured properly! (Will disables batteries.)
\r
155 if (!JumperCheck()) {
\r
156 return(ST_ERROR); // Error. Exit before damage is done!
\r
159 // If neither battery is valid, flag error and go to error state
\r
160 if (!(eeprom_read_byte(&BattControl[0]) & BIT_BATTERY_ENABLED) && (!eeprom_read_byte(&BattControl[1]) & BIT_BATTERY_ENABLED)) {
\r
161 SetErrorFlag(ERR_NO_BATTERIES_ENABLED);
\r
166 // Get ADC-readings, try to read EPROM, and start prequalification
\r
167 // of any uncharged battery.
\r
168 for (i = 0; i < 2; i++) {
\r
169 if (eeprom_read_byte(&BattControl[i]) & BIT_BATTERY_ENABLED) {
\r
173 if (BatteryStatusRefresh()) {
\r
174 if (!BattData.Charged) {
\r
175 BatteryDataRefresh();
\r
177 return(ST_PREQUAL);
\r
183 // If we end up here, one or two batteries are found and fully charged.
\r
184 // Disconnect, so we don't drain them, and go to sleep.
\r
185 DisableBatteries();
\r
191 /*! \brief Start running on batteries
\r
193 * \todo Run on batteries, if battery voltage high enough.
\r
194 * \todo Jump here when mains voltage drops below threshold
\r
197 unsigned char Discharge(unsigned char inp)
\r
199 return(ST_BATCON); // Supply voltage restored, start charging
\r
203 /*! \brief Sleeps until either battery needs charging
\r
205 * Calls Doze(), then refreshes the status for both batteries on wakeup. If
\r
206 * connected batteries are both charged, the function will loop. If not, it's
\r
207 * back to ST_BATCON.
\r
209 * \param inp Not used.
\r
211 * \retval ST_BATCON Next state if a connected battery isn't fully charged.
\r
213 unsigned char Sleep(unsigned char inp)
\r
218 Doze(); // Take a nap (~8 seconds).
\r
220 // If any batteries need charging, go to ST_BATCON.
\r
221 // Otherwise, keep sleeping.
\r
222 for (i = 0; i < 2; i++) {
\r
225 if ((BatteryStatusRefresh()) && (!BattData.Charged)) {
\r
230 DisableBatteries(); // Disable both batteries before Doze()!
\r
235 /*! \brief Doze off for approx. 8 seconds (Vcc = 5 V)
\r
237 * Waits for ADC-cycles to complete, disables the ADC, then sleeps for
\r
238 * approx. 8 seconds (Vcc = 5 V) using the watchdog timer.
\r
239 * On wakeup, ADC is re-enabled.
\r
243 // Wait for this ADC cycle to complete, then halt after the next one.
\r
249 } while (ADCS.Flag == FALSE);
\r
251 WDTCR = (1<<WDP3)|(1<<WDP0); // 8.0 seconds at 5 volts VCC.
\r
252 WDTCR |= (1<<WDIF)|(1<<WDIE)|(1<<WDE); // Clear flag and enable watchdog.
\r
253 MCUCR |= (1<<SE) | (1<<SM1)|(1<<SM0); // Sleep enable, mode = standby.
\r
254 sleep_cpu(); // Go to sleep, wake up by WDT.
\r
256 wdt_reset(); // Clear watchdog reset flag.
\r
257 MCUSR &= ~(1<<WDRF);
\r
258 WDTCR |= (1<<WDCE)|(1<<WDE); // Watchdog change enable.
\r
259 WDTCR = 0; // Turn off watchdog.
\r
261 ADCS.Halt = FALSE; // Enable consecutive runs of ADC.
\r
262 ADCSRA |= (1<<ADEN)|(1<<ADSC); // Enable ADC & start conversion.
\r
264 // Wait for this cycle to complete.
\r
269 /*! \brief Handles errors
\r
271 * Stops PWM output and disables batteries. The function then goes into a loop
\r
272 * that starts with a call to Doze(), then attempts to handle each error. The
\r
273 * loop will reiterate until all flags are cleared.\n
\r
274 * The charger will reinitialize after this.
\r
276 * Jumper errors are handled by clearing the flag, then calling JumperCheck().
\r
277 * If unsuccessful, the error flag will now have been set again.\n
\r
279 * If there are no valid batteries, the loop will simply reiterate until a
\r
280 * valid battery is found. The error flag will then be cleared.\n
\r
282 * In the case of PWM controller or battery temperature errors, the error
\r
283 * flag is simply cleared. This is because the problem may have gone away during
\r
284 * Doze(), or after reinitializing.\n
\r
286 * If a battery is exhausted, we clear its exhausted-flag in \ref BattData,
\r
287 * and change batteries before clearing the error flag.
\r
289 * \param inp Not used.
\r
291 unsigned char Error(unsigned char inp)
\r
295 PWM_Stop(); // Stop charging.
\r
296 DisableBatteries(); // Disable all loads.
\r
299 Doze(); // Take a nap.
\r
301 // For each bit in ErrorFlags, starting with LSB, handle
\r
302 // associated error, if the flag is set.
\r
303 for (i = 0x01; i!=0; i<<=1) {
\r
304 if(i & ErrorFlags) {
\r
307 case ERR_JUMPER_MISMATCH:
\r
308 // Clear flag & recheck.
\r
314 case ERR_NO_BATTERIES_ENABLED:
\r
315 // Clear if any battery gets enabled.
\r
316 if ((eeprom_read_byte(&BattControl[0]) & BIT_BATTERY_ENABLED) || (eeprom_read_byte(&BattControl[1]) & BIT_BATTERY_ENABLED)) {
\r
322 case ERR_PWM_CONTROL:
\r
328 case ERR_BATTERY_TEMPERATURE:
\r
334 case ERR_BATTERY_EXHAUSTED:
\r
335 // Try the other battery.
\r
336 BattData.Exhausted = FALSE;
\r
337 BattActive = (BattActive + 1) % 2;
\r
347 } while (ErrorFlags);
\r
353 /*! \brief Sets the specified error-flag and saves the current state
\r
355 * Updates \ref ErrorFlags and \ref ErrorState.
\r
357 * \note Error flags are specified in statefunc.h.
\r
359 * \param Flag Specifies what error to flag.
\r
361 void SetErrorFlag(unsigned char Flag)
\r
363 ErrorFlags |= Flag;
\r
364 ErrorState = CurrentState;
\r
368 /*! \brief Checks on-board jumpers.
\r
370 * Checks on-board jumpers by disconnecting all loads, engaging the PWM and
\r
371 * increasing the duty cycle until conditioned output voltage equals conditioned
\r
372 * input voltage. At low PWM duty and no load buck output should be zero and,
\r
373 * when increasing PWM duty, should quickly jump to steady state output roughly
\r
374 * equal to input voltage. Will disable and leave disabled all batteries.
\r
376 * \retval FALSE If jumper or load mismatch.
\r
377 * \retval TRUE If everything OK.
\r
379 unsigned char JumperCheck(void)
\r
381 DisableBatteries(); // Disconnect, or loads may be destroyed!
\r
383 PWM_Start(); // Start PWM (controls the buck charger).
\r
385 // Use general timer: shouldn't take longer than (6 x 255) / 2500 ~= 0.62s.
\r
386 Time_Set(TIMER_GEN,0,1,0);
\r
389 // If the PWM output voltage saturates the ADC, stop PWM output and
\r
390 // report a failure.
\r
391 if (ADCS.rawVBAT == 1023) {
\r
396 // If the absolute difference between measured (VIN - VBAT) and the
\r
397 // typical value are below our set maximum, everything is OK.
\r
398 if (abs((signed int)(ADCS.VIN - VIN_VBAT_DIFF_TYP - ADCS.VBAT)) <
\r
399 VIN_VBAT_DIFF_MAX ) {
\r
405 // Charge current is too high -> check load and jumper J405 and J406.
\r
406 if (abs(ADCS.IBAT) > 100) {
\r
411 // If the PWM output can't be increased high enough -> check jumpers
\r
412 // J400-J404, J407 and J408.
\r
413 if (!PWM_IncrementDutyCycle()) {
\r
418 // Wait for ADC conversions to complete
\r
420 } while (Time_Left(TIMER_GEN));
\r
423 // If we end up here, the measurements took too long.
\r