4008-04-07 Release
[avr_bc100.git] / BaseTinyFirmware / IAR / 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 <ioavr.h>\r
35 #include <inavr.h>\r
36 #include <stdlib.h>\r
37 \r
38 #include "structs.h"\r
39 #include "enums.h"\r
40 \r
41 #include "ADC.h"\r
42 #include "statefunc.h"\r
43 #include "battery.h"\r
44 #include "charge.h"\r
45 #include "main.h"\r
46 #include "menu.h"\r
47 #include "OWI.h"\r
48 #include "PWM.h"\r
49 #include "time.h"\r
50 #include "USI.h"\r
51 \r
52 \r
53 //******************************************************************************\r
54 // Variables\r
55 //******************************************************************************\r
56 unsigned char ErrorFlags;  //!< \brief Holds error flags.\r
57                            //!< \note See statefunc.h for definitions of flags.\r
58 \r
59 //! \brief Holds the state in which latest error flag was set.\r
60 //! \note See menu.h for definitions of states.\r
61 unsigned char ErrorState;\r
62 \r
63 //! \brief Set to 1 by the watchdog-timeout-ISR\r
64 //! \note added by Martin Thomas\r
65 volatile unsigned char WatchdogFlag;\r
66 \r
67 //******************************************************************************\r
68 // Functions\r
69 //******************************************************************************\r
70 /*! \brief Initialization\r
71  *\r
72  * - Sets the system clock prescaler to 1 (run at 8 MHz)\r
73  * - Initializes the one-wire interface\r
74  * - Clears on-chip EEPROM\r
75  * - Sets battery enable pins as outputs, then disables batteries\r
76  * - Initializes SPI according to \ref SPIMODE\r
77  * - Initializes ADC\r
78  * - Initializes timers\r
79  * - Reads battery data from both battery inputs (via ADC)\r
80  * - Disables batteries again\r
81  * - Sets battery A as the current one (\ref BattActive = 0)\r
82  * - Clears ErrorFlags\r
83  *\r
84  * \param inp Not used.\r
85  *\r
86  * \retval ST_BATCON Next state in the sequence.\r
87  */\r
88 unsigned char Initialize(unsigned char inp)\r
89 {\r
90         unsigned char i, page;\r
91 \r
92         // Disable interrupts while setting prescaler.\r
93         __disable_interrupt();\r
94 \r
95         CLKPR = (1<<CLKPCE);          // Enable CLKPS bit modification.\r
96         CLKPR = 0;                    // Set prescaler 1 => 8 MHz clock frequency.\r
97 \r
98         // Init 1-Wire(R) interface.\r
99         OWI_Init(OWIBUS);\r
100 \r
101         // Clear on-chip EEPROM.\r
102         for (page = 0; page < 4; page++) {\r
103                 for (i = 0; i < 32; i++) {\r
104                         // From mthomas GCC addition\r
105                         if (BattEEPROM[page][i] != 0) {\r
106                                 BattEEPROM[page][i] = 0;\r
107                         }\r
108                 }\r
109         }\r
110 \r
111         DDRB = (1<<PB4) | (1<<PB5);   // Set battery enable pins as outputs.\r
112         DisableBatteries();\r
113         SPI_Init(SPIMODE);\r
114         ADC_Init();\r
115         Time_Init();\r
116 \r
117         // Attempt to get ADC-readings (also gets RID-data) from both batteries.\r
118         for (i = 0; i < 2; i++) {\r
119                 EnableBattery(i);\r
120                 ADC_Wait();\r
121                 BatteryStatusRefresh();\r
122         }\r
123 \r
124         DisableBatteries();\r
125 \r
126         BattActive = 0;               // We have to start somewhere..\r
127         ErrorFlags = 0;\r
128 \r
129         // Init complete! Go to ST_BATCON next.\r
130         return(ST_BATCON);\r
131 }\r
132 \r
133 \r
134 /*! \brief Tests jumper settings and batteries, starts charging if necessary.\r
135  *\r
136  * First, JumperCheck() is called. If successful, the function checks if any\r
137  * valid batteries are connected and attempts to charge these, if necessary.\n\r
138  * If no charging is necessary, the charger goes to ST_SLEEP next.\n\r
139  * ST_ERROR is next if either JumperCheck() fails or there are no valid\r
140  * batteries. In this last case, the error is also flagged.\r
141  *\r
142  * \param inp Not used.\r
143  *\r
144  * \retval ST_ERROR Next state if either the jumper check failed, or there are\r
145  * no valid batteries.\r
146  * \retval ST_PREQUAL Next state if a battery is found to enabled and not fully\r
147  * charged.\r
148  * \retval ST_SLEEP Next state if battery/batteries are enabled and fully\r
149  * charged.\r
150  */\r
151 unsigned char BatteryControl(unsigned char inp)\r
152 {\r
153         unsigned char i;\r
154 \r
155         // Make sure ADC inputs are configured properly! (Will disables batteries.)\r
156         if (!JumperCheck()) {\r
157                 return(ST_ERROR);           // Error. Exit before damage is done!\r
158         }\r
159 \r
160         // If neither battery is valid, flag error and go to error state\r
161         if ((!BattControl[0].Enabled) && (!BattControl[1].Enabled)) {\r
162                 SetErrorFlag(ERR_NO_BATTERIES_ENABLED);\r
163 \r
164                 return(ST_ERROR);\r
165         }\r
166 \r
167         // Get ADC-readings, try to read EPROM, and start prequalification\r
168         // of any uncharged battery.\r
169         for (i = 0; i < 2; i++) {\r
170                 if (BattControl[i].Enabled) {\r
171                         EnableBattery(i);\r
172                         ADC_Wait();\r
173 \r
174                         if (BatteryStatusRefresh()) {\r
175                                 if (!BattData.Charged) {\r
176                                         BatteryDataRefresh();\r
177 \r
178                                         return(ST_PREQUAL);\r
179                                 }\r
180                         }\r
181                 }\r
182         }\r
183 \r
184         // If we end up here, one or two batteries are found and fully charged.\r
185         // Disconnect, so we don't drain them, and go to sleep.\r
186         DisableBatteries();\r
187 \r
188         return(ST_SLEEP);\r
189 }\r
190 \r
191 \r
192 /*! \brief Start running on batteries\r
193  *\r
194  * \todo Run on batteries, if battery voltage high enough.\r
195  * \todo Jump here when mains voltage drops below threshold\r
196  *\r
197  */\r
198 unsigned char Discharge(unsigned char inp)\r
199 {\r
200         return(ST_BATCON);  // Supply voltage restored, start charging\r
201 }\r
202 \r
203 \r
204 /*! \brief Sleeps until either battery needs charging\r
205  *\r
206  * Calls Doze(), then refreshes the status for both batteries on wakeup. If\r
207  * connected batteries are both charged, the function will loop. If not, it's\r
208  * back to ST_BATCON.\r
209  *\r
210  * \param inp Not used.\r
211  *\r
212  * \retval ST_BATCON Next state if a connected battery isn't fully charged.\r
213  */\r
214 unsigned char Sleep(unsigned char inp)\r
215 {\r
216         unsigned char i;\r
217 \r
218         do {\r
219                 Doze();               // Take a nap (~8 seconds).\r
220 \r
221                 // If any batteries need charging, go to ST_BATCON.\r
222                 // Otherwise, keep sleeping.\r
223                 for (i = 0; i < 2; i++) {\r
224                         EnableBattery(i);\r
225                         ADC_Wait();\r
226                         if ((BatteryStatusRefresh()) && (!BattData.Charged)) {\r
227                                 return(ST_BATCON);\r
228                         }\r
229                 }\r
230 \r
231                 DisableBatteries();  // Disable both batteries before Doze()!\r
232         } while (TRUE);\r
233 }\r
234 \r
235 /*! \brief Watchdog interrupt-service-routine\r
236  *\r
237  * Called on watchdog timeout, added by Martin Thomas\r
238  */\r
239 #pragma vector = WDT_vect\r
240 __interrupt void WDT_ISR(void)\r
241 {\r
242         WatchdogFlag = 1;\r
243 }\r
244 \r
245 \r
246 /*! \brief Doze off for approx. 8 seconds (Vcc = 5 V)\r
247  *\r
248  * Waits for ADC-cycles to complete, disables the ADC, then sleeps for\r
249  * approx. 8 seconds (Vcc = 5 V) using the watchdog timer.\r
250  * On wakeup, ADC is re-enabled.\r
251  * Modification by Martin Thomas:\r
252  *  Do not enter standby mode if PB6 is low (MASTER_INT on BC100)\r
253  *  so SPI communication with the master-controller is still possible\r
254  *  during "doze".\r
255  */\r
256 void Doze(void)\r
257 {\r
258         uint8_t sreg_saved;\r
259         // Wait for this ADC cycle to complete, then halt after the next one.\r
260         ADC_Wait();\r
261         ADCS.Halt = TRUE;\r
262         ADCS.Flag = FALSE;\r
263 \r
264         do {\r
265         } while (ADCS.Flag == FALSE);\r
266 \r
267         WDTCR = (1<<WDP3)|(1<<WDP0);            // 8.0 seconds at 5 volts VCC.\r
268         WDTCR |= (1<<WDIF)|(1<<WDIE)|(1<<WDE);  // Clear flag and enable watchdog.\r
269 \r
270         DDRB  &= ~(1<<PB6);   // MASTER_INT as input\r
271         PORTB |= (1<<PB6);    // enabled internal pullup\r
272         WatchdogFlag = 0;\r
273         if ( PINB & (1<<PB6) ) {\r
274                 MCUCR |= (1<<SE) | (1<<SM1) | (1<<SM0); // Sleep enable, mode = standby.\r
275                 __sleep();                              // Go to sleep, wake up by WDT.\r
276         }\r
277         else {\r
278                 do {\r
279                 } while ( !(WatchdogFlag) );\r
280         }\r
281 \r
282         __watchdog_reset();                     // Clear watchdog reset flag.\r
283         PORTB &= ~(1<<PB6);    // disabled internal pullup\r
284         MCUSR &= ~(1<<WDRF);\r
285 \r
286         sreg_saved = SREG;\r
287         cli();\r
288         WDTCR |= (1<<WDCE)|(1<<WDE);            // Watchdog change enable.\r
289         WDTCR = 0;                              // Turn off watchdog.\r
290         SREG = sreg_saved;\r
291 \r
292         ADCS.Halt = FALSE;                      // Enable consecutive runs of ADC.\r
293         ADCSRA |= (1<<ADEN)|(1<<ADSC);          // Enable ADC & start conversion.\r
294 \r
295         // Wait for this cycle to complete.\r
296         ADC_Wait();\r
297 }\r
298 \r
299 \r
300 /*! \brief Handles errors\r
301  *\r
302  * Stops PWM output and disables batteries. The function then goes into a loop\r
303  * that starts with a call to Doze(), then attempts to handle each error. The\r
304  * loop will reiterate until all flags are cleared.\n\r
305  * The charger will reinitialize after this.\r
306  *\r
307  * Jumper errors are handled by clearing the flag, then calling JumperCheck().\r
308  * If unsuccessful, the error flag will now have been set again.\n\r
309  *\r
310  * If there are no valid batteries, the loop will simply reiterate until a\r
311  * valid battery is found. The error flag will then be cleared.\n\r
312  *\r
313  * In the case of PWM controller or battery temperature errors, the error\r
314  * flag is simply cleared. This is because the problem may have gone away during\r
315  * Doze(), or after reinitializing.\n\r
316  *\r
317  * If a battery is exhausted, we clear its exhausted-flag in \ref BattData,\r
318  * and change batteries before clearing the error flag.\r
319  *\r
320  * \param inp Not used.\r
321  */\r
322 unsigned char Error(unsigned char inp)\r
323         {\r
324         unsigned char i;\r
325 \r
326         PWM_Stop();           // Stop charging.\r
327         DisableBatteries();   // Disable all loads.\r
328 \r
329         do {\r
330                 Doze();           // Take a nap.\r
331 \r
332                 // For each bit in ErrorFlags, starting with LSB, handle\r
333                 // associated error, if the flag is set.\r
334                 for (i = 0x01; i!=0; i<<=1) {\r
335                         if(i & ErrorFlags) {\r
336                                 switch (i) {\r
337 \r
338                                 case  ERR_JUMPER_MISMATCH:\r
339                                         // Clear flag & recheck.\r
340                                         ErrorFlags &= ~i;\r
341                                         JumperCheck();\r
342                                 break;\r
343 \r
344 \r
345                                 case  ERR_NO_BATTERIES_ENABLED:\r
346                                         // Clear if any battery gets enabled.\r
347                                         if ((BattControl[0].Enabled) || (BattControl[1].Enabled)) {\r
348                                                         ErrorFlags &= ~i;\r
349                                         }\r
350                                 break;\r
351 \r
352 \r
353                                 case  ERR_PWM_CONTROL:\r
354                                         // Clear flag.\r
355                                         ErrorFlags &= ~i;\r
356                                 break;\r
357 \r
358 \r
359                                 case  ERR_BATTERY_TEMPERATURE:\r
360                                         // Clear flag.\r
361                                         ErrorFlags &= ~i;\r
362                                 break;\r
363 \r
364 \r
365                                 case  ERR_BATTERY_EXHAUSTED:\r
366                                         // Try the other battery.\r
367                                         BattData.Exhausted = FALSE;\r
368                                         BattActive = (BattActive + 1) % 2;\r
369                                         ErrorFlags &= ~i;\r
370                                 break;\r
371 \r
372 \r
373                                 default:\r
374                                 break;\r
375                                 }\r
376                         }\r
377                 }\r
378         } while (ErrorFlags);\r
379 \r
380         return(ST_INIT);\r
381 }\r
382 \r
383 \r
384 /*! \brief Sets the specified error-flag and saves the current state\r
385  *\r
386  * Updates \ref ErrorFlags and \ref ErrorState.\r
387  *\r
388  * \note Error flags are specified in statefunc.h.\r
389  *\r
390  * \param Flag Specifies what error to flag.\r
391  */\r
392 void SetErrorFlag(unsigned char Flag)\r
393 {\r
394         ErrorFlags |= Flag;\r
395         ErrorState = CurrentState;\r
396 }\r
397 \r
398 \r
399 /*! \brief Checks on-board jumpers.\r
400  *\r
401  * Checks on-board jumpers by disconnecting all loads, engaging the PWM and\r
402  * increasing the duty cycle until conditioned output voltage equals conditioned\r
403  * input voltage. At low PWM duty and no load buck output should be zero and,\r
404  * when increasing PWM duty, should quickly jump to steady state output roughly\r
405  * equal to input voltage. Will disable and leave disabled all batteries.\r
406  *\r
407  * \retval FALSE If jumper or load mismatch.\r
408  * \retval TRUE If everything OK.\r
409  */\r
410 unsigned char JumperCheck(void)\r
411 {\r
412          DisableBatteries();       // Disconnect, or loads may be destroyed!\r
413 \r
414          PWM_Start();              // Start PWM (controls the buck charger).\r
415 \r
416          // Use general timer: shouldn't take longer than (6 x 255) / 2500 ~= 0.62s.\r
417          Time_Set(TIMER_GEN,0,1,0);\r
418 \r
419         do {\r
420                 // If the PWM output voltage saturates the ADC, stop PWM output and\r
421                 // report a failure.\r
422                 if (ADCS.rawVBAT == 1023) {\r
423                         PWM_Stop();\r
424                         return(FALSE);\r
425                 }\r
426 \r
427                 // If the absolute difference between measured (VIN - VBAT) and the\r
428                 // typical value are below our set maximum, everything is OK.\r
429                 if (abs((signed int)(ADCS.VIN - VIN_VBAT_DIFF_TYP - ADCS.VBAT)) <\r
430                                      VIN_VBAT_DIFF_MAX ) {\r
431 \r
432                         PWM_Stop();\r
433                         return(TRUE);\r
434                 }\r
435 \r
436                 // Charge current is too high -> check load and jumper J405 and J406.\r
437                 if (abs(ADCS.IBAT) > 100) {\r
438                         PWM_Stop();\r
439                         return(FALSE);\r
440                 }\r
441 \r
442                 // If the PWM output can't be increased high enough -> check jumpers\r
443                 // J400-J404, J407 and J408.\r
444                 if (!PWM_IncrementDutyCycle()) {\r
445                         PWM_Stop();\r
446                         return(FALSE);\r
447                 }\r
448 \r
449       // Wait for ADC conversions to complete\r
450                 ADC_Wait();\r
451         } while (Time_Left(TIMER_GEN));\r
452 \r
453 \r
454         // If we end up here, the measurements took too long.\r
455         PWM_Stop();\r
456         return(FALSE);\r
457 }\r