blob: 756e16679cc55fc366bfd6b94c8f954f3a531155 [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
25#define ADC_INIT_SINGLE(n) \
26 do { \
27 ADC##n##_CFG1 = ADC_CFG1_ADIV(2) /* Divide clock by 4 to get 15MHz. */ | \
28 ADC_CFG1_MODE(1) /* 12 bit mode. */ | \
29 ADC_CFG1_ADICLK(0) /* Use the bus clock (60MHz). */; \
30 ADC##n##_CFG2 = ADC_CFG2_MUXSEL /* Use the b channels. */ | \
31 ADC_CFG2_ADHSC /* Support higher ADC clock speeds. */; \
32 ADC##n##_SC1A = 0; /* Clear SC1A's COCO flag. */ \
33 ADC##n##_SC2 = ADC_SC2_BASE; \
34 do { \
35 ADC##n##_SC3 = ADC_SC3_CAL | ADC_SC3_AVGE | \
36 ADC_SC3_AVGS(3) /* Average 32 samples (max). */; \
37 /* Wait for calibration to complete. */ \
38 while (!(ADC##n##_SC1A & ADC_SC1_COCO)) { \
39 } \
40 } while (ADC##n##_SC3 & ADC_SC3_CALF); \
41 ADC_FINISH_CALIBRATION(n, P); \
42 ADC_FINISH_CALIBRATION(n, M); \
43 \
44 ADC##n##_SC3 = 0 /* Disable hardware averaging. */; \
45 } while (0)
46
Brian Silverman9ed2cf12018-05-12 13:06:38 -070047} // namespace
48
Brian Silverman19ea60f2018-01-03 21:43:15 -080049void AdcInitCommon() {
Brian Silverman8d3816a2017-07-03 18:52:15 -070050 SIM_SCGC3 |= SIM_SCGC3_ADC1;
51 SIM_SCGC6 |= SIM_SCGC6_ADC0;
52 // TODO(Brian): Mess with SIM_SOPT7 to reconfigure ADC trigger input source?
53 ADC_INIT_SINGLE(0);
54 ADC_INIT_SINGLE(1);
Brian Silverman19ea60f2018-01-03 21:43:15 -080055}
Brian Silverman8d3816a2017-07-03 18:52:15 -070056
Brian Silvermana96c1a42018-05-12 12:11:31 -070057} // namespace motors
Brian Silverman8d3816a2017-07-03 18:52:15 -070058} // namespace frc971