blob: 660ab3fedaea026c986439622328b437d6ecc6bd [file] [log] [blame]
Luigi Santivetti2e35a2e2019-11-17 22:26:14 +00001/*
2 adc.c - Low level functions for enabling ADC (Analog Digital Converter)
3 functionalities
4 Part of Grbl
5
6 Copyright (c) 2019 Luigi Santivetti
7
8 Grbl is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 Grbl is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with Grbl. If not, see <http://www.gnu.org/licenses/>.
20
21 Conventions:
22 - DEFAULT_ADC_ prefix is reserved for defines from defaults.h
23 - _ prefix for defines function-like
24 - __ prefix for defines variable-like
25 - Switch cases tend to have inline break clause
26 - Fill column size is 80, tab width is 2, always untabified
27 - Single line comment doesn't have trailing full stop
28 - Badly enough, defines are indented, for consistency reasons
29*/
30
31#include "grbl.h"
32
33// First available channel, this is always valid
34#define ADC_DEFAULT_CHANNEL 0
35
36// Max and min number of readings allowed per channel
37#define ADC_MIN_READINGS 1
38#define ADC_MAX_READINGS 16
39#define ADC_MSK_READINGS (DEFAULT_ADC_READINGS - 1)
40
41// Track the ADC status. These are mutually exclusive states
42#define ADC_STATUS_INIT bit(14)
43#define ADC_STATUS_STOP bit(15)
44#define _adc_get_status_module(XX) bit_istrue(adc->s, XX)
45
46// Mutually exclusive states, always clear them first
47#define _adc_set_status_module(XX) \
48 do { \
49 adc->s &= ~(ADC_STATUS_INIT | ADC_STATUS_STOP); \
50 bit_true(adc->s, XX); \
51 } while (0)
52
53// Flag data as reliable
54#define _adc_set_status_channel() \
55 do { \
56 bit_true(adc->s, bit(adc->i_c)); \
57 } while (0)
58
59// Alias current channel being stored in the ADC buffer
60#define __adc_current_channel_avr adc->b[adc->i_c].avr
61
62#ifdef ADC_CONFIG_SYSTEM_ALARM
63 #define __adc_current_channel_min adc->b[adc->i_c].min
64 #define __adc_current_channel_max adc->b[adc->i_c].max
65#endif
66
67#if DEFAULT_ADC_READINGS > 1
68 // isr_next_callback_id is always either 1 or 0, updated dynamically avoids
69 // the need for if-else runtime decision making in the ISR.
70 #define __isr_next_callback_id (adc->i_r & bit(0))
71
72 // Alias for consistency with adc_current_channel_avr
73 #define __adc_current_channel_sum adc->sum
74
75 // Right shift the current reading index, is reset to when reaches bit(0) and
76 // is initialized at DEFAULT_ADC_READINGS.
77 #define _adc_update_index_reading() \
78 do { adc->i_r = adc->i_r >> 1; } while (0)
79
80 // Reset current reading index when beginning reading a new channel
81 #define _adc_reset_index_reading() \
82 do { adc->i_r = DEFAULT_ADC_READINGS; } while (0)
83#endif
84
85// Validate DEFAULT_ADC_READINGS range
86#if (DEFAULT_ADC_READINGS > ADC_MAX_READINGS) || \
87 (DEFAULT_ADC_READINGS < ADC_MIN_READINGS)
88 #error "Invalid DEFAULT_ADC_READINGS"
89
90// Reading once per channel isn't ideal
91#elif DEFAULT_ADC_READINGS == 1
92 #warning "One shot reading is unreliable"
93
94// For accumulation 10 bit (max resolution) times DEFAULT_ADC_READINGS must fit
95// in uint16_t.
96#elif (0x3FF * DEFAULT_ADC_READINGS) >> 16
97 #error "Invalid DEFAULT_ADC_READINGS"
98
99// DEFAULT_ADC_READINGS must be a power of 2
100#elif DEFAULT_ADC_READINGS & ADC_MSK_READINGS
101 #error "Invalid DEFAULT_ADC_READINGS"
102#endif
103
104// DEFAULT_ADC_RESOLUTION allowed value is an interger number of bits
105#if DEFAULT_ADC_RESOLUTION == 8
106#elif DEFAULT_ADC_RESOLUTION == 10
107#else
108 #error "Invalid DEFAULT_ADC_RESOLUTION"
109#endif
110
111// DEFAULT_ADC_CHANNELS_MASK, 11-bit, bitmask.
112// The ADC has 11 channels, i-th bit for enabling i-th channel.
113// i.e.
114// 00000001001, enable first and fourth channel,
115// 00000100010, enable second and sixth channel.
116#if !defined(DEFAULT_ADC_CHANNELS_MASK) || (DEFAULT_ADC_CHANNELS_MASK == 0) || \
117 (DEFAULT_ADC_CHANNELS_MASK >> ADC_CONFIG_CHANNELS_COUNT)
118 #error "Invalid DEFAULT_ADC_CHANNELS_MASK"
119#endif
120
121// Available and supported modes. Extend this for supporting new modes
122#define MODE0 ADC_CONFIG_MODE_SW_TRIGGER
123#define MODE1 ADC_CONFIG_MODE_HW_TRIGGER
124#if DEFAULT_ADC_MODE == MODE0
125#elif DEFAULT_ADC_MODE == MODE1
126 // In this mode, although possible, isn't reliable to dinamically switch
127 // channel, only allow one channel.
128 #if ADC_CHANNELS_ENABLED_COUNT > 1
129 #error "Invalid ADC_CHANNELS_ENABLED_COUNT"
130 #endif
131#else
132 // None of the above is invalid
133 #error "Invalid DEFAULT_ADC_MODE"
134#endif
135
136// Available ADC clocks. These are the only allowed and implemented
137#if DEFAULT_ADC_CLOCK == 125
138#elif DEFAULT_ADC_CLOCK == 250
139#elif DEFAULT_ADC_CLOCK == 500
140#elif DEFAULT_ADC_CLOCK == 1000
141#elif DEFAULT_ADC_CLOCK == 2000
142#elif DEFAULT_ADC_CLOCK == 4000
143#elif DEFAULT_ADC_CLOCK == 8000
144#else
145 // None of the above is invalid
146 #error "Invalid DEFAULT_ADC_CLOCK"
147#endif
148
149// If the ADC uses 10 bit, only clocks >50Hz and <200Khz are allowed
150#if (DEFAULT_ADC_RESOLUTION != 8) && (DEFAULT_ADC_CLOCK != CLK_125KHZ)
151 #error "Invalid DEFAULT_ADC_CLOCK"
152#endif
153
154// Available ADC inputs for reference voltage. Edit this for supporting new vref
155#if DEFAULT_ADC_REFERENCE == ADC_CONFIG_REFERENCE_INTERNAL_1VREF
156#elif DEFAULT_ADC_REFERENCE == ADC_CONFIG_REFERENCE_INTERNAL_5VREF
157#elif DEFAULT_ADC_REFERENCE == ADC_CONFIG_REFERENCE_EXTERNAL_AVCC
158#else
159 #error "Invalid DEFAULT_ADC_MODE"
160#endif
161
162// Track power reduction status at the moment the ADC module is started
163static uint8_t prr_need_restart;
164adc_data *adc_global;
165
166#ifdef ADC_CONFIG_SYSTEM_ALARM
167// FIXME: move range initialization to settings.c
168//
169// This should really be done in settings.c, as in, min and max should be
170// defined in settings_t. However, for the time being, do NOT write this
171// data to EEPROM, which means rebuild if needed.
172
173#define _set_channel_range(channel, number, MIN, MAX, FLAG) \
174 do { \
175 adc->b[channel].min = (adc_value) (FLAG ? DEFAULT_ADC_RANGE_CHANNEL_ ## number ## _MIN : MIN); \
176 adc->b[channel].max = (adc_value) (FLAG ? DEFAULT_ADC_RANGE_CHANNEL_ ## number ## _MAX : MAX); \
177 } while (0)
178
179static inline void adc_init_range_channel(adc_data *adc)
180{
181 #if ADC_CHANNEL_00_ENABLED
182 _set_channel_range(ADC0, 0, 0, 0, 0);
183 #endif
184 #if ADC_CHANNEL_01_ENABLED
185 _set_channel_range(ADC1, 1, 0, 0, 0);
186 #endif
187 #if ADC_CHANNEL_02_ENABLED
188 _set_channel_range(ADC2, 2, 0, 0, 0);
189 #endif
190 #if ADC_CHANNEL_03_ENABLED
191 _set_channel_range(ADC3, 3, 0, 0, 0);
192 #endif
193 #if ADC_CHANNEL_04_ENABLED
194 _set_channel_range(ADC4, 4, 0, 0, 0);
195 #endif
196 #if ADC_CHANNEL_05_ENABLED
197 _set_channel_range(ADC5, 5, 0, 0, 0);
198 #endif
199 #if ADC_CHANNEL_06_ENABLED
200 _set_channel_range(ADC6, 6, 0, 0, 0);
201 #endif
202 #if ADC_CHANNEL_07_ENABLED
203 _set_channel_range(ADC7, 7, 0, 0, 0);
204 #endif
205 #if ADC_CHANNEL_08_ENABLED
206 _set_channel_range(ADC8, 8, 0, 0, 0);
207 #endif
208 #if ADC_CHANNEL_09_ENABLED
209 _set_channel_range(ADC9, 9, 0, 0, 0);
210 #endif
211 #if ADC_CHANNEL_10_ENABLED
212 _set_channel_range(ADC10, 10, 0, 0, 0);
213 #endif
214}
215#endif
216
217// Switching mode can start a conversion. Check ATMega328p, 7810D–AVR–01/15,
218// page 220. Auto triggering is enabled by setting the ADC auto trigger enable
219// bit, ADATE in ADCSRA. The trigger source is selected by setting the ADC
220// trigger, select bits, ADTS in ADCSRB.
221static inline void adc_init_mode(const int mode)
222{
223 // Trigger bit must be set for any mode but when the next conversion is started
224 // in software.
225 bit_true(ADC_ST1_REG, bit(ADC_ST1_TRIGGER_BIT));
226
227 switch (mode) {
228 case MODE0:
229 bit_false(ADC_ST1_REG, bit(ADC_ST1_TRIGGER_BIT)); break;
230 case MODE1:
231 bit_false(ADC_ST2_REG, ADC_ST2_MODEFR_MASK); break;
232 }
233}
234
235// If the user has a fixed voltage source connected to the AREF pin, the user
236// may not use the other reference voltage options in the application, as they
237// will be shorted to the external voltage.
238static inline void adc_init_reference(const int ref)
239{
240 // Clear all reference bits
241 bit_false(ADC_MUX_REG, ADC_MUX_REFALL_MASK);
242
243 // ATMega328p, 7810D–AVR–01/15, Table 23-3:
244 switch (ref) {
245 case ADC_CONFIG_REFERENCE_INTERNAL_1VREF:
246 bit_true(ADC_MUX_REG, ADC_MUX_REFALL_MASK); break;
247 case ADC_CONFIG_REFERENCE_INTERNAL_5VREF:
248 bit_true(ADC_MUX_REG, ADC_MUX_REFAVC_MASK); break;
249 case ADC_CONFIG_REFERENCE_EXTERNAL_AVCC:
250 bit_true(ADC_MUX_REG, ADC_MUX_REFEXT_MASK); break;
251 }
252}
253
254// ATMega328p, 7810D–AVR–01/15, page 208 says:
255// the successive approximation circuitry requires an input clock frequency
256// between 50kHz and 200kHz to get maximum resolution.
257static inline void adc_init_clock(const int clock)
258{
259 // Clear all clock bits
260 bit_false(ADC_ST1_REG, ADC_ST1_CLKALL_MASK);
261
262 // ATMega328p, 7810D–AVR–01/15, Table 23-5:
263 switch (clock) {
264 case 125: bit_true(ADC_ST1_REG, ADC_ST1_125KHZ_MASK); break;
265 case 250: bit_true(ADC_ST1_REG, ADC_ST1_250KHZ_MASK); break;
266 case 500: bit_true(ADC_ST1_REG, ADC_ST1_500KHZ_MASK); break;
267 case 1000: bit_true(ADC_ST1_REG, ADC_ST1_001MHZ_MASK); break;
268 case 2000: bit_true(ADC_ST1_REG, ADC_ST1_002MHZ_MASK); break;
269 case 4000: bit_true(ADC_ST1_REG, ADC_ST1_004MHZ_MASK); break;
270 case 8000: bit_true(ADC_ST1_REG, ADC_ST1_008MHZ_MASK); break;
271 }
272}
273
274// Check ATMega328p, 7810D–AVR–01/15, page 210, 23.5 and 23.5.1
275static inline void adc_set_channel(const int channel)
276{
277 // Clear all channel bits
278 bit_false(ADC_MUX_REG, ADC_MUX_CHALL_MASK);
279
280 // ATMega328p, 7810D–AVR–01/15, Table 23-4:
281 switch (channel) {
282 #if ADC_CHANNEL_00_ENABLED
283 case ADC0: bit_true(ADC_MUX_REG, ADC_MUX_CH0_MASK); break;
284 #endif
285 #if ADC_CHANNEL_01_ENABLED
286 case ADC1: bit_true(ADC_MUX_REG, ADC_MUX_CH1_MASK); break;
287 #endif
288 #if ADC_CHANNEL_02_ENABLED
289 case ADC2: bit_true(ADC_MUX_REG, ADC_MUX_CH2_MASK); break;
290 #endif
291 #if ADC_CHANNEL_03_ENABLED
292 case ADC3: bit_true(ADC_MUX_REG, ADC_MUX_CH3_MASK); break;
293 #endif
294 #if ADC_CHANNEL_04_ENABLED
295 case ADC4: bit_true(ADC_MUX_REG, ADC_MUX_CH4_MASK); break;
296 #endif
297 #if ADC_CHANNEL_05_ENABLED
298 case ADC5: bit_true(ADC_MUX_REG, ADC_MUX_CH5_MASK); break;
299 #endif
300 #if ADC_CHANNEL_06_ENABLED
301 case ADC6: bit_true(ADC_MUX_REG, ADC_MUX_CH6_MASK); break;
302 #endif
303 #if ADC_CHANNEL_07_ENABLED
304 case ADC7: bit_true(ADC_MUX_REG, ADC_MUX_CH7_MASK); break;
305 #endif
306 #if ADC_CHANNEL_08_ENABLED
307 case ADC8: bit_true(ADC_MUX_REG, ADC_MUX_CHTMP_MASK); break;
308 #endif
309 #if ADC_CHANNEL_09_ENABLED
310 case ADC9: bit_true(ADC_MUX_REG, ADC_MUX_CHGND_MASK); break;
311 #endif
312 #if ADC_CHANNEL_10_ENABLED
313 case ADC10: bit_true(ADC_MUX_REG, ADC_MUX_CHVBG_MASK); break;
314 #endif
315 }
316}
317
318// ATMega328p, 7810D–AVR–01/15, page 208 says:
319// When ADCL is read, the ADC data register is not updated until ADCH is read.
320// Consequently, if the result is left adjusted and no more than 8-bit
321// precision is required, it is sufficient to read ADCH. Otherwise, ADCL must
322// be read first, then ADCH.
323#if DEFAULT_ADC_RESOLUTION == 8
324 static inline uint8_t adc_merge_registers()
325 {
326 return ADC_HGH_REG;
327 }
328#else
329 static inline uint16_t adc_merge_registers()
330 {
331 uint8_t low = ADC_LOW_REG;
332 uint16_t hgh = ((uint16_t) ADC_HGH_REG) << 8;
333 return hgh | low;
334 }
335#endif
336
337#if DEFAULT_ADC_READINGS > 1
338 static inline adc_value adc_get_average(const adc_data *adc)
339 {
340 return (adc_value) (__adc_current_channel_sum / DEFAULT_ADC_READINGS);
341 }
342#else
343 static inline adc_value adc_get_average(const adc_data *adc)
344 {
345 (void)adc;
346
347 return (adc_value) adc_merge_registers();
348 }
349#endif
350
351#if DEFAULT_ADC_MODE == MODE0
352 static inline void adc_set_next_channel(adc_data *adc)
353 {
354 #if ADC_CHANNELS_ENABLED_COUNT & (ADC_CHANNELS_ENABLED_COUNT - 1)
355 adc->i_c = adc->i_c + 1;
356 adc->i_c = adc->i_c % ADC_CHANNELS_ENABLED_COUNT;
357 #else
358 adc->i_c = (adc->i_c + 1) & (ADC_CHANNELS_ENABLED_COUNT - 1);
359 #endif
360 adc_set_channel(adc->i_c);
361 }
362#endif
363
364static inline void adc_kick_conversion()
365{
366 prr_need_restart = ADC_PRR_REG_cpu;
367
368 // Disable power reduction. Note: this register is outside the ADC block
369 bit_false(ADC_PRR_REG_cpu, bit(ADC_PRR_cpu_PRADC_BIT));
370
371 // How long this takes depends on the mode. In single conversion 13.5 cycles
372 bit_true(ADC_ST1_REG, bit(ADC_ST1_START_BIT));
373}
374
375#ifdef ADC_CONFIG_SYSTEM_ALARM
376static inline int adc_need_alarm(const adc_data *adc)
377{
378 const adc_value channel_avr = __adc_current_channel_avr;
379
380 if (channel_avr >= __adc_current_channel_max ||
381 channel_avr <= __adc_current_channel_min)
382 return 1;
383
384 return 0;
385}
386
387static inline void adc_flag_system_alarm(const adc_data *adc)
388{
389 if (sys.state != STATE_ALARM)
390 if (!sys_rt_exec_alarm && adc_need_alarm(adc)) {
391 mc_reset();
392 system_set_exec_alarm(EXEC_ALARM_ADC);
393 }
394}
395#endif
396
397static inline void adc_isr_update_channel_avr(adc_data *adc)
398{
399 // Work out reliable data, not quite so when one-shot reading. Note, change this in
400 // order to use a different method (i.e. filtering).
401 __adc_current_channel_avr = adc_get_average(adc);
402
403 #ifdef ADC_CONFIG_SYSTEM_ALARM
404 // This is called only once every DEFAULT_ADC_READINGS times, data is reliable,
405 // it's a good time to raise an alarm, if any.
406 adc_flag_system_alarm(adc);
407 #endif
408
409 #if DEFAULT_ADC_READINGS > 1
410 // Reset previous sum, prepare for the next channel
411 __adc_current_channel_sum = 0;
412
413 // Wrap reading index for the next channel
414 _adc_reset_index_reading();
415 #endif
416
417 // FIXME: maybe needed for dummy values
418 // Flag data for this channel as reliable
419 _adc_set_status_channel();
420
421 #if DEFAULT_ADC_MODE == MODE0
422 adc_set_next_channel(adc);
423 #endif
424}
425
426static inline void adc_isr_call_read_op(adc_data *adc)
427{
428 #if DEFAULT_ADC_READINGS > 1
429 // Select and call back from the adc struct, do not bother in checking. In
430 // case of abnormal and trusted data this will flag directly the main system
431 // alarm flag, otherwise keep reading until the current channel is drained.
432 adc->isr[__isr_next_callback_id](adc);
433 #else
434 adc_isr_update_channel_avr(adc);
435 #endif
436}
437
438static inline void adc_isr_call_reset_op(adc_data *adc)
439{
440 #if (DEFAULT_ADC_READINGS > 1) && (DEFAULT_ADC_MODE == MODE0)
441 // Start next conversion
442 adc->isr[ADC_ISR_PFN_RST_ID](adc);
443 #elif DEFAULT_ADC_MODE == MODE0
444 (void)adc;
445 // Start next conversion
446 adc_kick_conversion();
447 #endif
448 // No need reset if HW triggering
449}
450
451#if DEFAULT_ADC_READINGS > 1
452 // Callback for ADC_ISR_PFN_SUM_ID
453 static void adc_isr_callback_sum(adc_data *adc)
454 {
455 // Acquire new data
456 __adc_current_channel_sum += adc_merge_registers();
457 _adc_update_index_reading();
458 }
459
460 // Callback for ADC_ISR_PFN_AVR_ID
461 static void adc_isr_callback_avr(adc_data *adc)
462 {
463 adc_isr_update_channel_avr(adc);
464 }
465
466 // Callbacks for ADC_ISR_PFN_RST_ID, only available if SW triggering
467 #if DEFAULT_ADC_MODE == MODE0
468 static void adc_isr_callback_rst(adc_data *adc)
469 {
470 adc_kick_conversion();
471 }
472
473 static void adc_isr_callback_noop() { return; }
474 #endif
475#endif
476
477adc_value adc_read_unsigned(const adc_data *adc, const adc_channel c)
478{
479 return adc->b[c].avr;
480}
481
482void adc_deinit(adc_data *adc)
483{
484 #if (DEFAULT_ADC_MODE == MODE0) && (DEFAULT_ADC_READINGS > 1)
485 // Prevent starting a new conversion in case an IRQ kicks in
486 adc->isr[ADC_ISR_PFN_RST_ID] = adc_isr_callback_noop;
487 #endif
488
489 // Do not turn it back on if it wasn't originally
490 if (bit_istrue(prr_need_restart, bit(ADC_PRR_cpu_PRADC_BIT)))
491 bit_true(ADC_PRR_REG_cpu, bit(ADC_PRR_cpu_PRADC_BIT));
492
493 // Disable the ADC interrupt
494 bit_false(ADC_ST1_REG, bit(ADC_ST1_IRQ_BIT));
495
496 // Disable ADC module
497 bit_false(ADC_ST1_REG, bit(ADC_ST1_ENABLE_BIT));
498}
499
500void adc_init(adc_data *adc)
501{
502 uint8_t i;
503
504 // Init global reference to adc
505 adc_global = adc;
506
507 adc_init_reference(DEFAULT_ADC_REFERENCE);
508 adc_init_clock(DEFAULT_ADC_CLOCK);
509 adc_init_mode(DEFAULT_ADC_MODE);
510
511 #ifdef ADC_CONFIG_SYSTEM_ALARM
512 adc_init_range_channel(adc);
513 #endif
514
515 adc_set_channel(ADC_DEFAULT_CHANNEL);
516
517 #if DEFAULT_ADC_RESOLUTION == 8
518 // Left adjust so to fit in one register only
519 bit_true(ADC_ST1_REG, bit(ADC_ST1_LEFTSHIFT_BIT));
520 #else
521 bit_false(ADC_ST1_REG, bit(ADC_ST1_LEFTSHIFT_BIT));
522 #endif
523
524 #if DEFAULT_ADC_READINGS > 1
525 // i_r is a bit-mask and 1 is left-shifted for DEFAULT_ADC_READINGS
526 // number of times.
527 adc->i_r = DEFAULT_ADC_READINGS;
528 adc->isr[ADC_ISR_PFN_SUM_ID] = adc_isr_callback_sum;
529 adc->isr[ADC_ISR_PFN_AVR_ID] = adc_isr_callback_avr;
530 adc->sum = 0;
531
532 #if (DEFAULT_ADC_MODE == MODE0)
533 adc->isr[ADC_ISR_PFN_RST_ID] = adc_isr_callback_rst;
534 #endif
535 #endif
536
537 adc->i_c = ADC_DEFAULT_CHANNEL;
538 adc->s = ADC_STATUS_INIT;
539
540 // Enable the ADC interrupt
541 bit_true(ADC_ST1_REG, bit(ADC_ST1_IRQ_BIT));
542
543 // This instruction takes 12 ADC clocks to execute
544 bit_true(ADC_ST1_REG, bit(ADC_ST1_ENABLE_BIT));
545
546 // reset buffer's avr, in case of a sys reset and adc_init is called again
547 for (i = 0; i < ADC_CHANNELS_ENABLED_COUNT; i++)
548 adc->b[i].avr = 0;
549
550 // Start the first conversion
551 adc_kick_conversion();
552}
553
554ISR(ADC_vect)
555{
556 adc_isr_call_read_op(adc_global);
557
558 adc_isr_call_reset_op(adc_global);
559}