Initial import
[avr_bc100.git] / BaseTinyFirmware / GCC / statefunc.c
1 /* This file has been prepared for Doxygen automatic documentation generation.*/\r
2 /*! \file *********************************************************************\r
3  *\r
4  * \brief\r
5  *      State functions\r
6  *\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
10  *\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
13  *\r
14  * \par Application note:\r
15  *      AVR458: Charging Li-Ion Batteries with BC100 \n\r
16  *      AVR463: Charging NiMH Batteries with BC100\r
17  *\r
18  * \par Documentation\r
19  *      For comprehensive code documentation, supported compilers, compiler \r
20  *      settings and supported devices see readme.html\r
21  *\r
22  * \author\r
23  *      Atmel Corporation: http://www.atmel.com \n\r
24  *      Support email: avr@atmel.com\r
25  *\r
26  * \r
27  * $Name$\r
28  * $Revision: 2299 $\r
29  * $RCSfile$\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
33 \r
34 #include <avr/io.h>\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
40 \r
41 #include <stdlib.h>\r
42 \r
43 #include "structs.h"\r
44 #include "enums.h"\r
45 \r
46 #include "ADC.h"\r
47 #include "statefunc.h"\r
48 #include "battery.h"\r
49 #include "charge.h"\r
50 #include "main.h"\r
51 #include "menu.h"\r
52 #include "OWI.h"\r
53 #include "PWM.h"\r
54 #include "time.h"\r
55 #include "USI.h"\r
56 \r
57 \r
58 //******************************************************************************\r
59 // Variables\r
60 //******************************************************************************\r
61 unsigned char ErrorFlags;  //!< \brief Holds error flags.\r
62                            //!< \note See statefunc.h for definitions of flags.\r
63 \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
67 \r
68 \r
69 //******************************************************************************\r
70 // Functions\r
71 //******************************************************************************\r
72 /*! \brief Initialization\r
73  *\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
79  * - Initializes ADC\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
85  *\r
86  * \param inp Not used.\r
87  *\r
88  * \retval ST_BATCON Next state in the sequence.\r
89  */\r
90 unsigned char Initialize(unsigned char inp)\r
91 {\r
92         unsigned char i, page;\r
93 \r
94         // Disable interrupts while setting prescaler.\r
95         cli();\r
96         \r
97         CLKPR = (1<<CLKPCE);          // Enable CLKPS bit modification.\r
98         CLKPR = 0;                    // Set prescaler 1 => 8 MHz clock frequency.\r
99         \r
100         // Init 1-Wire(R) interface.\r
101         OWI_Init(OWIBUS);\r
102         \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
107                 }\r
108         }\r
109 \r
110         DDRB = (1<<PB4) | (1<<PB5);   // Set battery enable pins as outputs.\r
111         DisableBatteries();\r
112         SPI_Init(SPIMODE);\r
113         ADC_Init();\r
114         Time_Init();\r
115 \r
116         // Attempt to get ADC-readings (also gets RID-data) from both batteries.\r
117         for (i = 0; i < 2; i++) {\r
118                 EnableBattery(i);\r
119                 ADC_Wait();\r
120                 BatteryStatusRefresh();\r
121         }\r
122     \r
123         DisableBatteries();\r
124         \r
125         BattActive = 0;               // We have to start somewhere..\r
126         ErrorFlags = 0;\r
127         \r
128         // Init complete! Go to ST_BATCON next.\r
129         return(ST_BATCON);\r
130 }\r
131 \r
132 \r
133 /*! \brief Tests jumper settings and batteries, starts charging if necessary.\r
134  *\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
140  *\r
141  * \param inp Not used.\r
142  *\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
146  * charged.\r
147  * \retval ST_SLEEP Next state if battery/batteries are enabled and fully\r
148  * charged.\r
149  */\r
150 unsigned char BatteryControl(unsigned char inp)\r
151 {\r
152         unsigned char i;\r
153         \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
157         }\r
158         \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
162                 \r
163                 return(ST_ERROR);\r
164         }\r
165 \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
170                         EnableBattery(i);\r
171                         ADC_Wait();\r
172 \r
173                         if (BatteryStatusRefresh()) {\r
174                                 if (!BattData.Charged) {\r
175                                         BatteryDataRefresh();\r
176 \r
177                                         return(ST_PREQUAL);       \r
178                                 }\r
179                         }\r
180                 }\r
181         }\r
182 \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
186 \r
187         return(ST_SLEEP);\r
188 }\r
189 \r
190 \r
191 /*! \brief Start running on batteries\r
192  *\r
193  * \todo Run on batteries, if battery voltage high enough.\r
194  * \todo Jump here when mains voltage drops below threshold\r
195  *\r
196  */\r
197 unsigned char Discharge(unsigned char inp)\r
198 {\r
199         return(ST_BATCON);  // Supply voltage restored, start charging\r
200 }\r
201 \r
202 \r
203 /*! \brief Sleeps until either battery needs charging\r
204  *\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
208  *\r
209  * \param inp Not used.\r
210  *\r
211  * \retval ST_BATCON Next state if a connected battery isn't fully charged.\r
212  */\r
213 unsigned char Sleep(unsigned char inp)\r
214 {\r
215         unsigned char i;\r
216 \r
217         do {\r
218                 Doze();               // Take a nap (~8 seconds).\r
219 \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
223                         EnableBattery(i);\r
224                         ADC_Wait();\r
225                         if ((BatteryStatusRefresh()) && (!BattData.Charged)) {\r
226                                 return(ST_BATCON);\r
227                         }\r
228                 }\r
229                 \r
230                 DisableBatteries();  // Disable both batteries before Doze()!\r
231         } while (TRUE);\r
232 }\r
233 \r
234 \r
235 /*! \brief Doze off for approx. 8 seconds (Vcc = 5 V)\r
236  *\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
240  */\r
241 void Doze(void)\r
242 {\r
243         // Wait for this ADC cycle to complete, then halt after the next one.\r
244         ADC_Wait();\r
245         ADCS.Halt = TRUE;\r
246         ADCS.Flag = FALSE;\r
247         \r
248         do {\r
249         } while (ADCS.Flag == FALSE);    \r
250         \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
255         \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
260         \r
261         ADCS.Halt = FALSE;                      // Enable consecutive runs of ADC.\r
262         ADCSRA |= (1<<ADEN)|(1<<ADSC);          // Enable ADC & start conversion.\r
263         \r
264         // Wait for this cycle to complete.\r
265         ADC_Wait();                             \r
266 }\r
267 \r
268 \r
269 /*! \brief Handles errors\r
270  *\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
275  *\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
278  *\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
281  *\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
285  *\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
288  *\r
289  * \param inp Not used.\r
290  */\r
291 unsigned char Error(unsigned char inp)\r
292         {\r
293         unsigned char i;\r
294         \r
295         PWM_Stop();           // Stop charging.\r
296         DisableBatteries();   // Disable all loads.\r
297         \r
298         do {\r
299                 Doze();           // Take a nap.\r
300 \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
305                                 switch (i) {\r
306                                 \r
307                                 case  ERR_JUMPER_MISMATCH:\r
308                                         // Clear flag & recheck.\r
309                                         ErrorFlags &= ~i;\r
310                                         JumperCheck();\r
311                                 break;\r
312 \r
313 \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
317                                                         ErrorFlags &= ~i;\r
318                                         }\r
319                                 break;\r
320 \r
321 \r
322                                 case  ERR_PWM_CONTROL:\r
323                                         // Clear flag.\r
324                                         ErrorFlags &= ~i;\r
325                                 break;\r
326 \r
327 \r
328                                 case  ERR_BATTERY_TEMPERATURE:\r
329                                         // Clear flag.\r
330                                         ErrorFlags &= ~i;\r
331                                 break;\r
332 \r
333 \r
334                                 case  ERR_BATTERY_EXHAUSTED:\r
335                                         // Try the other battery.\r
336                                         BattData.Exhausted = FALSE;\r
337                                         BattActive = (BattActive + 1) % 2;\r
338                                         ErrorFlags &= ~i;\r
339                                 break;\r
340 \r
341                                         \r
342                                 default:\r
343                                 break;\r
344                                 }\r
345                         }\r
346                 }\r
347         } while (ErrorFlags);\r
348 \r
349         return(ST_INIT);\r
350 }\r
351 \r
352 \r
353 /*! \brief Sets the specified error-flag and saves the current state\r
354  *\r
355  * Updates \ref ErrorFlags and \ref ErrorState.\r
356  *\r
357  * \note Error flags are specified in statefunc.h.\r
358  *\r
359  * \param Flag Specifies what error to flag.\r
360  */\r
361 void SetErrorFlag(unsigned char Flag)\r
362 {\r
363         ErrorFlags |= Flag;\r
364         ErrorState = CurrentState;\r
365 }\r
366 \r
367 \r
368 /*! \brief Checks on-board jumpers.\r
369  *\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
375  *\r
376  * \retval FALSE If jumper or load mismatch.\r
377  * \retval TRUE If everything OK.\r
378  */\r
379 unsigned char JumperCheck(void)\r
380 {\r
381          DisableBatteries();       // Disconnect, or loads may be destroyed!\r
382          \r
383          PWM_Start();              // Start PWM (controls the buck charger).\r
384         \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
387         \r
388         do {\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
392                         PWM_Stop();\r
393                         return(FALSE);\r
394                 }\r
395 \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
400                                  \r
401                         PWM_Stop();\r
402                         return(TRUE);\r
403                 }\r
404 \r
405                 // Charge current is too high -> check load and jumper J405 and J406.\r
406                 if (abs(ADCS.IBAT) > 100) {\r
407                         PWM_Stop();\r
408                         return(FALSE);\r
409                 }\r
410 \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
414                         PWM_Stop();\r
415                         return(FALSE);\r
416                 }\r
417                 \r
418       // Wait for ADC conversions to complete\r
419                 ADC_Wait();\r
420         } while (Time_Left(TIMER_GEN));\r
421         \r
422 \r
423         // If we end up here, the measurements took too long.\r
424         PWM_Stop();\r
425         return(FALSE);\r
426 }\r