50814ca6413782eef7d73523cbbf2e590c972910
[avr_bc100.git] / BaseTinyFirmware / GCC / ADC.c
1 /* This file has been prepared for Doxygen automatic documentation generation.*/\r
2 /*! \file *********************************************************************\r
3  *\r
4  * \brief\r
5  *      Functions for use of ADC\r
6  *\r
7  *      Contains high level functions for initializing the ADC, interrupt\r
8  *      handling, and treatment of samples.\n\r
9  *      The ADC is set to free running mode and uses an external reference\r
10  *      voltage.\n\r
11  *      To make all sampling take at least 25 clock cycles the ADC is stopped\r
12  *      and restarted by the ISR.\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 \n\r
25  *      Original author: \n\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/ADC.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 \r
37 #include "structs.h"\r
38 \r
39 #include "main.h"\r
40 #include "ADC.h"\r
41 \r
42 \r
43 //******************************************************************************\r
44 // Variables\r
45 //******************************************************************************\r
46 // ADC status struct.\r
47 //! \brief Holds sampled data and ADC-status\r
48 volatile ADC_Status_t ADCS;\r
49 \r
50 \r
51 /*! \brief Indicates maximum battery voltage.\r
52  *\r
53  * This variable is stored in EEPROM and indicates how much the battery voltage\r
54  * is downscaled by HW before it is sampled. The amount of downscaling depends\r
55  * on the maximum battery voltage, and is necessary to avoid saturation of the\r
56  * ADC (reference voltage is 2.5 V).\r
57  *\r
58  * \note Used by the ADC ISR when calling ScaleU() and ScaleI().\r
59  *\r
60  * \note Defaults to 1, which means 10 V max battery voltage.\r
61  *\r
62  * \note Table of settings:\r
63  * <pre>\r
64  * VBAT_RANGE | Max battery voltage | Jumper setting\r
65  *         0  |             5V      |        1/2\r
66  *         1  |            10V      |        1/4\r
67  *         2  |            20V      |        1/8\r
68  *         3  |            30V      |       1/12\r
69  *         4  |            40V      |       1/16\r
70  * </pre>\r
71  */\r
72 // Maximum battery voltage (affects scaling of samples).\r
73 unsigned char EEMEM VBAT_RANGE = 1;\r
74 \r
75 \r
76 //******************************************************************************\r
77 // Functions\r
78 //******************************************************************************\r
79 /*! \brief Interrupt Service routine for ADC.\r
80  *\r
81  * This ISR stores the sampled values in the ADC status-struct, then\r
82  * updates the ADC MUX to the next channel in the scanning-sequence.\n\r
83  * Once the sequence is completed, ADCS.Flag is set and unless\r
84  * ADCS.Halt has been set, the sequence starts over. Otherwise, the ADC\r
85  * is disabled.\n\r
86  * If the mains voltage is below minimum, ADCS.Mains gets set to FALSE.\r
87  *\r
88  * \note Table of scanning sequence:\r
89  * <pre>\r
90  * Seq |    MUX |  pos I/P |  neg I/P | gain | measure | signed\r
91  * ----+--------+----------+----------+------+---------+-------\r
92  *  01 | 000001 | ADC1/PA1 |      n/a |   1x |     NTC |     no\r
93  *  02 | 000010 | ADC2/PA2 |      n/a |   1x |     RID |     no\r
94  *  03 | 000011 | ADC3/PA4 |      n/a |   1x |    VIN- |     no\r
95  *  04 | 000100 | ADC4/PA5 |      n/a |   1x |    VIN+ |     no\r
96  *  05 | 000101 | ADC5/PA6 |      n/a |   1x |   VBAT- |     no\r
97  *  06 | 000110 | ADC6/PA7 |      n/a |   1x |   VBAT+ |     no\r
98  *  07 | 010010 | ADC4/PA5 | ADC3/PA4 |  20x |     IIN |     no\r
99  *  08 | 010111 | ADC6/PA7 | ADC5/PA6 |  20x |    IBAT |    yes\r
100  * </pre>\r
101  *\r
102  * \todo IIN (#7 in sequence) is never used.\r
103  *\r
104  * \todo Signed is never set. Signed measurements of IBAT will halve the\r
105  * measuring sensitivity, and is therefore not favourable. At the moment,\r
106  * great currents (f.ex. if something happens with the battery) will be\r
107  * interpreted as negative, which might cause unfavourable behaviour during\r
108  * charging (depending on what PWM behaviour is defined), f.ex.\r
109  * ConstantCurrent() will keep increasing the PWM output. This results in an\r
110  * PWM controller error being flagged and the program going into\r
111  * error-state and eventually reinitializing.\r
112  */\r
113 ISR(ADC_vect)\r
114 {\r
115         static unsigned char avgIndex = 0;\r
116         unsigned char i, Next, Signed;\r
117         signed int  temp = 0;\r
118 \r
119         Signed = FALSE;  // Presume next conversion is unipolar.\r
120         ADCSRA &= ~(1<<ADEN);  // Stop conversion before handling. This makes all\r
121           // conversions take at least 25 ADCCLK. (It is restarted later)\r
122 \r
123         // Handle the conversion, depending on what channel it is from, then\r
124         // switch to the next channel in the sequence.\r
125         switch (ADCS.MUX){\r
126                 // MUX = 0b000001 => ADC1 (PA1) = NTC\r
127                 case 0x01:\r
128                         ADCS.rawNTC = ADC;\r
129                         Next=0x02;\r
130                 break;\r
131 \r
132 \r
133                 // MUX = 0b000010 => ADC2 (PA2) = RID\r
134                 case 0x02:\r
135                         ADCS.rawRID = ADC;\r
136                         Next=0x03;\r
137                 break;\r
138 \r
139 \r
140                 // MUX = 0b000011 => ADC3 (PA4) = VIN-\r
141                 case 0x03:\r
142                         // Supply voltage is always divided by 16.\r
143                         ADCS.VIN = ScaleU(4, (unsigned int)ADC);  // Cast because ADC is short.\r
144 \r
145                         // Is mains failing?\r
146                         if (ADCS.VIN < VIN_MIN) {\r
147                                 ADCS.Mains = FALSE;\r
148                         } else {\r
149                                 ADCS.Mains = TRUE;\r
150                         }\r
151 \r
152                         Next=0x05;\r
153                 break;\r
154 \r
155 \r
156                 // MUX = 0b000101 => ADC5 (PA6) = VBAT-\r
157                 case 0x05:\r
158                         ADCS.rawVBAT = ADC;\r
159 \r
160                         // Scale voltage according to jumper setting.\r
161                         ADCS.VBAT = ScaleU(eeprom_read_byte(&VBAT_RANGE), (unsigned int)ADC); // ADC is a short.\r
162                         Next=0x17;\r
163 //                      Signed = TRUE;  // Next conversion is bipolar. Halves sensitivity!\r
164                 break;\r
165 \r
166 \r
167                 case 0x17:  // MUX = 0b010111 => 20 x [ADC6(PA7) - ADC5(PA6)] = IBAT\r
168                         // If bipolar, from -512 to 0, to 511:\r
169                         // 0x200 ... 0x3ff, 0x000, 0x001 ... 0x1FF\r
170 \r
171                         // Scale sample according to jumper setting, handle negative numbers.\r
172                         if (ADC > 511) {\r
173                                 ADCS.IBAT = -(signed int)ScaleI(eeprom_read_byte(&VBAT_RANGE),\r
174                                                                 (1024 - (ADC-ADCS.ADC5_G20_OS)));\r
175                         } else if (ADC > 0) {\r
176                                 ADCS.IBAT = ScaleI(eeprom_read_byte(&VBAT_RANGE), (ADC-ADCS.ADC5_G20_OS));\r
177                         } else {\r
178                                 ADCS.IBAT = 0;\r
179                         }\r
180 \r
181                         // Insert sample of battery current into the averaging-array\r
182                         // (overwriting the oldest sample), then recalculate and store the\r
183                         // average. This is the last conversion in the sequence, so\r
184                         // flag a complete ADC-cycle and restart sequence.\r
185                         ADCS.discIBAT[(avgIndex++ & 0x03)] = ADCS.IBAT;\r
186                         for (i = 0; i < 4 ; i++) {\r
187                                 temp += ADCS.discIBAT[i];\r
188                         }\r
189 \r
190                         ADCS.avgIBAT = (temp / 4);\r
191 \r
192                         ADCS.Flag = TRUE;\r
193                         Next=0x01;\r
194                         Signed = FALSE;  // This is the only bipolar conversion.\r
195                 break;\r
196 \r
197 \r
198                 default:  // Should not happen. (Invalid MUX-channel)\r
199                         Next=0x01;  // Start at the beginning of sequence.\r
200                 break;\r
201         }\r
202 \r
203         // Update MUX to next channel in sequence, set a bipolar conversion if\r
204         // this has been flagged.\r
205         ADCS.MUX = Next;\r
206         ADMUX = (1<<REFS0) + ADCS.MUX;\r
207 \r
208         if (Signed)     {\r
209                 ADCSRB |= (1<<BIN);\r
210         } else {\r
211                 ADCSRB &= ~(1<<BIN);\r
212         }\r
213 \r
214         // Re-enable the ADC unless a halt has been flagged and a conversion\r
215         // cycle has completed.\r
216         if (!((ADCS.Halt) && (ADCS.Flag))) {\r
217                 ADCSRA |= (1<<ADEN)|(1<<ADSC);\r
218         }\r
219 }\r
220 \r
221 \r
222 /*! \brief Scales sample to represent "actual voltage" in mV.\r
223  *\r
224  * This function returns the actual sampled voltage, scaled according\r
225  * to the jumper settings.\r
226  *\r
227  * \param setting Indicates what downscaling was used.\r
228  * \param data The sampled value.\r
229  *\r
230  * \note Table for setting-parameter:\n\r
231  * <pre>\r
232  * Presume VREF = 2.5V and Gain = 1x.\r
233  * => Resolution @ 1/1 = 2.5V / 1024 = 2.4414 mV/LSB\r
234  * setting | source |   R1 | R2/(R1+R2) | UADC(LSB) | U(MAX)\r
235  * --------+--------+------+------------+-----------+-------\r
236  *     N/A |        |    - |       -    |   2.441mV |  2.50V\r
237  *       0 |   VBAT |  10k |     1/2    |   4.883mV |  5.00V\r
238  *       1 |   VBAT |  30k |     1/4    |   9.766mV |  9.99V\r
239  *       2 |   VBAT |  70k |     1/8    |   19.53mV | 19.98V\r
240  *       3 |   VBAT | 110k |    1/12    |   29.30mV | 29.97V\r
241  *       4 |   VBAT | 150k |    1/16    |   39.06mV | 39.96V\r
242  *       4 |    VIN | 150k |    1/16    |   39.06mV | 39.96V\r
243  * </pre>\r
244  */\r
245 unsigned int ScaleU(unsigned char setting, unsigned int data)\r
246 {\r
247         // Temporary variable needed.\r
248         unsigned int scaled = 0;\r
249 \r
250         // Jumper setting 3: mV/LSB = 29.30 ~= 29 + 1/4 + 1/16\r
251         if (setting == 3)       {\r
252                 scaled = 29 * data;\r
253                 scaled += (data >> 2);\r
254                 scaled += (data >> 4);\r
255         } else {\r
256                 // Jumper setting 4: mV/LSB = 39.06 ~= 39 + 1/16\r
257                 scaled = 39 * data;\r
258                 scaled += (data >> 4);\r
259 \r
260                 if (setting <3) {\r
261                         // Jumper setting 0: mV/LSB = 4.883 = 39.06 / 8\r
262                         //                1: mV/LSB = 9.766 = 39.06 / 4\r
263                         //                2: mV/LSB = 19.53 = 39.06 / 2\r
264                         scaled = (scaled >> (3-setting));\r
265                 }\r
266         }\r
267 \r
268         return(scaled);\r
269 }\r
270 \r
271 \r
272 /*! \brief Scales sample to represent "actual current" in mA.\r
273  *\r
274  * This function returns the actual sampled current, scaled according\r
275  * to the jumper settings.\r
276  *\r
277  * \param setting Indicates what downscaling was used.\r
278  * \param data The sampled value.\r
279  *\r
280  * \note Table for setting-parameter:\n\r
281  * <pre>\r
282  * Presume VREF = 2.5V and Gain = 1x or 20x.\r
283  * => Resolution(U) @ (1/1 and 20x) = 2.5V / (GAIN x 1024) = 0.1221 mV/LSB\r
284  * => Resolution(I) = Resolution(U) / Rshunt = Resolution(U) / 0.07\r
285  * Setting |   R1 | R2/(R1+R2) |   U(LSB) |   I(LSB) | I(MAX) | Gain\r
286  * --------+------+------------+----------+----------+--------+-----\r
287  *     N/A |    - |       -    | 0.1221mV |  1.744mA |  1.78A |  20x\r
288  *       0 |  10k |     1/2    | 0.2442mV |  3.489mA |  3.57A |  20x\r
289  *       1 |  30k |     1/4    | 0.4884mV |  6.978mA |  7.14A |  20x\r
290  *       2 |  70k |     1/8    | 0.9768mV | 13.955mA |  14.3A |  20x\r
291  *       3 | 110k |    1/12    | 1.4652mV | 20.931mA |  21.4A |  20x\r
292  *       4 | 150k |    1/16    | 1.9536mV | 27.909mA |  28.5A |  20x\r
293  *       5 |  10k |     1/2    | 2.4414mV | 34.877mA |  35.7A |   1x\r
294  * </pre>\r
295  */\r
296 unsigned int ScaleI(unsigned char setting, unsigned int data)\r
297 {\r
298         // Temporary variable needed.\r
299         unsigned int  scaled = 0;\r
300 \r
301         // Jumper setting 3: mA/LSB = 20.931mA ~= 21 - 1/16 + 1/128\r
302         if (setting == 3) {\r
303                 scaled = 21 * data;\r
304                 scaled -= (data >> 4);\r
305                 scaled += (data >> 7);\r
306         }       else    { // Jumper setting 4: mA/LSB = 27.909mA ~= 28 - 1/8 + 1/32\r
307                 scaled = 28 * data;\r
308                 scaled -= (data >> 3);\r
309                 scaled += (data >> 5);\r
310 \r
311                 if (setting <3) {\r
312                         // Jumper setting 0: mA/LSB = 3.489mA = 27.909 / 8\r
313                         //                1: mA/LSB = 6.978mA = 27.909 / 4\r
314                         //                2: mA/LSB = 13.955mA = 27.909 / 2\r
315                         scaled = (scaled >> (3-setting));\r
316                 }\r
317         }\r
318 \r
319         return(scaled);\r
320 }\r
321 \r
322 \r
323 /*! \brief Waits for two full cycles of ADC-conversions to occur.\r
324  *\r
325  * This function clears the cycle complete-flag, then waits for it to be set\r
326  * again. This is then repeated once before the function exits.\r
327  *\r
328  */\r
329 void ADC_Wait(void)\r
330 {\r
331         // Clear ADC flag and wait for cycle to complete.\r
332         ADCS.Flag = FALSE;\r
333         do {\r
334         } while (ADCS.Flag == FALSE);\r
335 \r
336         // Repeat, so we are sure the data belongs to the same cycle.\r
337         ADCS.Flag = FALSE;\r
338         do {\r
339         } while (ADCS.Flag == FALSE);\r
340 }\r
341 \r
342 \r
343 /*! \brief Initializes ADC and input pins.\r
344  *\r
345  * This function initializes the ADC to free running mode, sampling from\r
346  * PA1/2/4/5/6/7, and using an external reference voltage (PA3).\n\r
347  * It also measures and stores calibration data for offset.\r
348  *\r
349  * \todo Odd offset measurement for ADC3_G20_OS? It is never used anyway.\r
350  *\r
351  * \note Table of MUX settings for offset measurement:\r
352  * <pre>\r
353  *    Ch | Pin |    Gain |    MUX\r
354  * ------+-----+---------+-------\r
355  *  ADC1 | PA1 |     20x | 001101\r
356  *  ADC3 | PA4 |     20x | 010001\r
357  *  ADC5 | PA6 |     20x | 010110\r
358  *  ADC9 | PB6 |     20x | 011011\r
359  *  ADC0 | PA0 | 20x/32x | 111000\r
360  *  ADC0 | PA0 |   1x/8x | 111001\r
361  *  ADC1 | PA1 | 20x/32x | 111010\r
362  *  ADC2 | PA2 | 20x/32x | 111011\r
363  *  ADC4 | PA5 | 20x/32x | 111100\r
364  *  ADC5 | PA6 | 20x/32x | 111101\r
365  *  ADC6 | PA7 | 20x/32x | 111110\r
366  * </pre>\r
367  */\r
368 void ADC_Init(void)\r
369 {\r
370         unsigned char i;\r
371         unsigned char sreg_saved;\r
372 \r
373         sreg_saved = SREG;\r
374         cli();\r
375 \r
376         ADCS.Halt = FALSE; // Enable consecutive runs of ADC.\r
377 \r
378         // Configure ADC pins (inputs and disabled pull-ups).\r
379         DDRA &= ~((1<<PA1)|(1<<PA2)|(1<<PA4)|(1<<PA5)|(1<<PA6)|(1<<PA7));\r
380         PORTA &= ~((1<<PA1)|(1<<PA2)|(1<<PA4)|(1<<PA5)|(1<<PA6)|(1<<PA7));\r
381 \r
382         // Set ADC3 as reference, and MUX to measure the same pin.\r
383         ADMUX = (1<<REFS0) | (1<<MUX0) | (1<<MUX1);\r
384 \r
385         ADCSRB = 0;\r
386 \r
387         // Start conversion, no interrupt (disable ADC-ISR).\r
388         ADCSRA = (1<<ADEN) | (1<<ADSC) | ADC_PRESCALER;\r
389 \r
390         do { // Wait for conversion to finish.\r
391         } while (!(ADCSRA & (1<<ADIF)));\r
392 \r
393         ADCSRA |= (1<<ADIF);  // Clear ADC interrupt flag manually.\r
394 \r
395         ADCS.ADC3_G20_OS = ADC;  // Save the sampled offset.\r
396 \r
397         ADMUX = (1<<REFS0) | 0x16;  // ADC5/ADC5 (external ref.), 20x\r
398 \r
399         // Start conversion, no interrupt. ADC_PRESCALER is defined in ADC.h.\r
400         ADCSRA = (1<<ADEN) | (1<<ADSC) | ADC_PRESCALER;\r
401 \r
402         do { // Wait for conversion to finish.\r
403         } while (!(ADCSRA & (1<<ADIF)));\r
404 \r
405         ADCSRA |= (1<<ADIF);  // Clear ADC interrupt flag.\r
406 \r
407         ADCS.ADC5_G20_OS = ADC;  // Save the sampled offset.\r
408 \r
409         // Reset the ADC-cycle.\r
410         ADCS.Flag = FALSE;\r
411         ADCS.MUX = 0x01;\r
412         ADMUX = (1<<REFS0) | ADCS.MUX;\r
413 \r
414         // Clear averaged battery current and the discrete readings.\r
415         ADCS.avgIBAT = 0;\r
416 \r
417         for (i = 0; i < 4; i++) {\r
418                 ADCS.discIBAT[i] = 0;\r
419         }\r
420 \r
421         // Re-enable the ADC and ISR.\r
422         ADCSRA=(1<<ADEN)|(1<<ADSC)|(1<<ADIE)|ADC_PRESCALER;\r
423 \r
424         sei();\r
425 \r
426         // Get a complete cycle of data before returning.\r
427         ADC_Wait();\r
428 \r
429         SREG = sreg_saved;\r
430 }\r