blob: 6325f9fa8a5a293721eb03088b7b646082331b0d [file] [log] [blame]
Brian Silverman8d3816a2017-07-03 18:52:15 -07001#include "motors/peripheral/adc.h"
2
3#include "motors/core/kinetis.h"
4
5namespace frc971 {
Brian Silvermana96c1a42018-05-12 12:11:31 -07006namespace motors {
Brian Silverman19ea60f2018-01-03 21:43:15 -08007namespace {
Brian Silverman8d3816a2017-07-03 18:52:15 -07008
9#define ADC_SC2_BASE (ADC_SC2_REFSEL(0) /* Use the external reference pins. */)
10
11#define ADC_FINISH_CALIBRATION(n, PM) \
12 do { \
13 uint16_t variable = 0; \
14 variable += ADC##n##_CL##PM##0; \
15 variable += ADC##n##_CL##PM##1; \
16 variable += ADC##n##_CL##PM##2; \
17 variable += ADC##n##_CL##PM##3; \
18 variable += ADC##n##_CL##PM##4; \
19 variable += ADC##n##_CL##PM##S; \
20 variable /= 2; \
21 variable |= 0x8000; \
22 ADC##n##_##PM##G = variable; \
23 } while (0);
24
Brian Silverman45564a82018-09-02 16:35:22 -070025#define ADC_INIT_SINGLE(n, maybe_muxsel) \
Brian Silverman8d3816a2017-07-03 18:52:15 -070026 do { \
Brian Silverman45564a82018-09-02 16:35:22 -070027 ADC##n##_CFG1 = \
28 ADC_CFG1_ADIV(2) /* Divide clock by 4 to get 15MHz. */ | \
29 0 /* !ADLSMP to sample faster */ | \
30 ADC_CFG1_MODE(1) /* 12 bit single-ended or 13-bit differential. */ | \
31 ADC_CFG1_ADICLK(0) /* Use the bus clock (60MHz). */; \
32 ADC##n##_CFG2 = (maybe_muxsel) | \
Brian Silverman8d3816a2017-07-03 18:52:15 -070033 ADC_CFG2_ADHSC /* Support higher ADC clock speeds. */; \
34 ADC##n##_SC1A = 0; /* Clear SC1A's COCO flag. */ \
35 ADC##n##_SC2 = ADC_SC2_BASE; \
36 do { \
37 ADC##n##_SC3 = ADC_SC3_CAL | ADC_SC3_AVGE | \
38 ADC_SC3_AVGS(3) /* Average 32 samples (max). */; \
39 /* Wait for calibration to complete. */ \
40 while (!(ADC##n##_SC1A & ADC_SC1_COCO)) { \
41 } \
42 } while (ADC##n##_SC3 & ADC_SC3_CALF); \
43 ADC_FINISH_CALIBRATION(n, P); \
44 ADC_FINISH_CALIBRATION(n, M); \
45 \
46 ADC##n##_SC3 = 0 /* Disable hardware averaging. */; \
47 } while (0)
48
Brian Silverman9ed2cf12018-05-12 13:06:38 -070049} // namespace
50
Brian Silverman45564a82018-09-02 16:35:22 -070051void AdcInitCommon(AdcChannels adc0_channels, AdcChannels adc1_channels) {
Brian Silverman8d3816a2017-07-03 18:52:15 -070052 SIM_SCGC3 |= SIM_SCGC3_ADC1;
53 SIM_SCGC6 |= SIM_SCGC6_ADC0;
54 // TODO(Brian): Mess with SIM_SOPT7 to reconfigure ADC trigger input source?
Brian Silverman45564a82018-09-02 16:35:22 -070055 ADC_INIT_SINGLE(0, (adc0_channels == AdcChannels::kB) ? ADC_CFG2_MUXSEL : 0);
56 ADC_INIT_SINGLE(1, (adc1_channels == AdcChannels::kB) ? ADC_CFG2_MUXSEL : 0);
Brian Silverman19ea60f2018-01-03 21:43:15 -080057}
Brian Silverman8d3816a2017-07-03 18:52:15 -070058
Brian Silvermana96c1a42018-05-12 12:11:31 -070059} // namespace motors
Brian Silverman8d3816a2017-07-03 18:52:15 -070060} // namespace frc971