blob: 64f1557d7bc5af0ef9129a79606934efb9c407a8 [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
Philipp Schrader790cb542023-07-05 21:06:52 -07009#define ADC_SC2_BASE \
10 (ADC_SC2_REFSEL(0) /* Use the external reference pins. \
11 */)
Brian Silverman8d3816a2017-07-03 18:52:15 -070012
13#define ADC_FINISH_CALIBRATION(n, PM) \
14 do { \
15 uint16_t variable = 0; \
16 variable += ADC##n##_CL##PM##0; \
17 variable += ADC##n##_CL##PM##1; \
18 variable += ADC##n##_CL##PM##2; \
19 variable += ADC##n##_CL##PM##3; \
20 variable += ADC##n##_CL##PM##4; \
21 variable += ADC##n##_CL##PM##S; \
22 variable /= 2; \
23 variable |= 0x8000; \
24 ADC##n##_##PM##G = variable; \
25 } while (0);
26
Brian Silverman45564a82018-09-02 16:35:22 -070027#define ADC_INIT_SINGLE(n, maybe_muxsel) \
Brian Silverman8d3816a2017-07-03 18:52:15 -070028 do { \
Brian Silverman45564a82018-09-02 16:35:22 -070029 ADC##n##_CFG1 = \
30 ADC_CFG1_ADIV(2) /* Divide clock by 4 to get 15MHz. */ | \
31 0 /* !ADLSMP to sample faster */ | \
32 ADC_CFG1_MODE(1) /* 12 bit single-ended or 13-bit differential. */ | \
33 ADC_CFG1_ADICLK(0) /* Use the bus clock (60MHz). */; \
34 ADC##n##_CFG2 = (maybe_muxsel) | \
Brian Silverman8d3816a2017-07-03 18:52:15 -070035 ADC_CFG2_ADHSC /* Support higher ADC clock speeds. */; \
36 ADC##n##_SC1A = 0; /* Clear SC1A's COCO flag. */ \
37 ADC##n##_SC2 = ADC_SC2_BASE; \
38 do { \
39 ADC##n##_SC3 = ADC_SC3_CAL | ADC_SC3_AVGE | \
40 ADC_SC3_AVGS(3) /* Average 32 samples (max). */; \
41 /* Wait for calibration to complete. */ \
42 while (!(ADC##n##_SC1A & ADC_SC1_COCO)) { \
43 } \
44 } while (ADC##n##_SC3 & ADC_SC3_CALF); \
45 ADC_FINISH_CALIBRATION(n, P); \
46 ADC_FINISH_CALIBRATION(n, M); \
47 \
48 ADC##n##_SC3 = 0 /* Disable hardware averaging. */; \
49 } while (0)
50
Brian Silverman9ed2cf12018-05-12 13:06:38 -070051} // namespace
52
Brian Silverman45564a82018-09-02 16:35:22 -070053void AdcInitCommon(AdcChannels adc0_channels, AdcChannels adc1_channels) {
Brian Silverman8d3816a2017-07-03 18:52:15 -070054 SIM_SCGC3 |= SIM_SCGC3_ADC1;
55 SIM_SCGC6 |= SIM_SCGC6_ADC0;
56 // TODO(Brian): Mess with SIM_SOPT7 to reconfigure ADC trigger input source?
Brian Silverman45564a82018-09-02 16:35:22 -070057 ADC_INIT_SINGLE(0, (adc0_channels == AdcChannels::kB) ? ADC_CFG2_MUXSEL : 0);
58 ADC_INIT_SINGLE(1, (adc1_channels == AdcChannels::kB) ? ADC_CFG2_MUXSEL : 0);
Brian Silverman19ea60f2018-01-03 21:43:15 -080059}
Brian Silverman8d3816a2017-07-03 18:52:15 -070060
Brian Silvermana96c1a42018-05-12 12:11:31 -070061} // namespace motors
Brian Silverman8d3816a2017-07-03 18:52:15 -070062} // namespace frc971