2 * Copyright © 2019 Keith Packard <keithp@keithp.com>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
16 #include <ao_adc-samd21.h>
21 while (samd21_adc.status & (1 << SAMD21_ADC_STATUS_SYNCBUSY))
26 ao_adc_do_conversion(void)
29 samd21_adc.swtrig = (1 << SAMD21_ADC_SWTRIG_START);
31 while ((samd21_adc.intflag & (1 << SAMD21_ADC_INTFLAG_RESRDY)) == 0)
34 return samd21_adc.result;
38 ao_adc_read(uint8_t channel)
41 samd21_adc.inputctrl = ((channel << SAMD21_ADC_INPUTCTRL_MUXPOS) |
42 (SAMD21_ADC_INPUTCTRL_MUXNEG_GND << SAMD21_ADC_INPUTCTRL_MUXNEG) |
43 (0 << SAMD21_ADC_INPUTCTRL_INPUTSCAN) |
44 (0 << SAMD21_ADC_INPUTCTRL_INPUTOFFSET) |
45 (SAMD21_ADC_INPUTCTRL_GAIN_DIV2 << SAMD21_ADC_INPUTCTRL_GAIN));
47 /* Read twice and discard the first value as recommended by app note
48 * http://www.atmel.com/images/Atmel-42645-ADC-Configurations-with-Examples_ApplicationNote_AT11481.pdf
50 (void) ao_adc_do_conversion();
51 return ao_adc_do_conversion();
58 samd21_gclk_clkctrl(0, SAMD21_GCLK_CLKCTRL_ID_ADC);
60 /* enable the device */
61 samd21_pm.apbcmask |= (1 << SAMD21_PM_APBCMASK_ADC);
64 samd21_adc.ctrla = (1 << SAMD21_ADC_CTRLA_SWRST);
68 while ((samd21_adc.ctrla & (1 << SAMD21_ADC_CTRLA_SWRST)) != 0 ||
69 (samd21_adc.status & (1 << SAMD21_ADC_STATUS_SYNCBUSY)) != 0)
72 /* Load ADC calibration values */
73 uint32_t b = (samd21_aux1.calibration >> SAMD21_AUX1_CALIBRATION_ADC_BIASCAL) & SAMD21_AUX1_CALIBRATION_ADC_BIASCAL_MASK;
74 uint32_t l = (samd21_aux1.calibration >> SAMD21_AUX1_CALIBRATION_ADC_LINEARITY) & SAMD21_AUX1_CALIBRATION_ADC_LINEARITY_MASK;
76 samd21_adc.calib = ((b << SAMD21_ADC_CALIB_BIAS_CAL) |
77 (l << SAMD21_ADC_CALIB_LINEARITY_CAL));
82 samd21_adc.ctrlb = ((0 << SAMD21_ADC_CTRLB_DIFFMODE) |
83 (0 << SAMD21_ADC_CTRLB_LEFTADJ) |
84 (0 << SAMD21_ADC_CTRLB_FREERUN) |
85 (0 << SAMD21_ADC_CTRLB_CORREN) |
86 (SAMD21_ADC_CTRLB_RESSEL_12BIT << SAMD21_ADC_CTRLB_RESSEL) |
87 (SAMD21_ADC_CTRLB_PRESCALER_DIV512 << SAMD21_ADC_CTRLB_PRESCALER));
91 samd21_adc.sampctrl = 0x1f;
95 samd21_adc.refctrl = (SAMD21_ADC_REFCTRL_REFSEL_INTVCC1 << SAMD21_ADC_REFCTRL_REFSEL);
99 samd21_adc.ctrla = (1 << SAMD21_ADC_CTRLA_ENABLE);