ADC  8.0
VREF.h
1 #ifndef VREF_H
2 #define VREF_H
3 
4 #include <Arduino.h>
5 
6 #include <atomic.h>
7 
9 namespace VREF
10 {
11 
13 
23  inline void start(uint8_t mode = VREF_SC_MODE_LV_HIGHPOWERBUF, uint8_t trim = 0x20) {
24  VREF_TRM = VREF_TRM_CHOPEN | (trim&0x3F); // enable module and set the trimmer to medium (max=0x3F=63)
25  // enable 1.2 volt ref with all compensations in high power mode
26  VREF_SC = VREF_SC_VREFEN | VREF_SC_REGEN | VREF_SC_ICOMPEN | VREF_SC_MODE_LV(mode);
27 
28  // "PMC_REGSC[BGEN] bit must be set if the VREF regulator is
29  // required to remain operating in VLPx modes."
30  // Also "If the chop oscillator is to be used in very low power modes,
31  // the system (bandgap) voltage reference must also be enabled."
32  // enable bandgap, can be read directly with ADC_INTERNAL_SOURCE::BANDGAP
33  atomic::setBitFlag(PMC_REGSC, PMC_REGSC_BGBE);
34  }
35 
37 
40  inline void trim(uint8_t trim) {
41  bool chopen = atomic::getBitFlag(VREF_TRM, VREF_TRM_CHOPEN);
42  VREF_TRM = (chopen ? VREF_TRM_CHOPEN : 0) | (trim&0x3F);
43  }
44 
46 
48  __attribute__((always_inline)) inline void stop(){
49  VREF_SC = 0;
50  atomic::clearBitFlag(PMC_REGSC, PMC_REGSC_BGBE);
51  }
52 
54 
63  __attribute__((always_inline)) inline volatile bool isStable() {
64  return atomic::getBitFlag(VREF_SC, VREF_SC_VREFST);
65  }
66 
68 
71  __attribute__((always_inline)) inline volatile bool isOn() {
72  return atomic::getBitFlag(VREF_SC, VREF_SC_VREFEN);
73  }
74 
76 
80  inline void waitUntilStable() {
81  delay(35); // see note in isStable()
82  while(isOn() && !isStable()) {
83  yield();
84  }
85  }
86 
87 }
88 
89 #endif // VREF_H
void waitUntilStable()
Wait for the internal reference to stabilize.
Definition: VREF.h:80
volatile bool isOn()
Check if the internal reference is on.
Definition: VREF.h:71
void stop()
Stops the internal reference.
Definition: VREF.h:48
void trim(uint8_t trim)
Set the trim.
Definition: VREF.h:40
Controls the Teensy internal voltage reference module (VREFV1)
Definition: VREF.h:9
void start(uint8_t mode=VREF_SC_MODE_LV_HIGHPOWERBUF, uint8_t trim=0x20)
Start the 1.2V internal reference (if present)
Definition: VREF.h:23
volatile bool isStable()
Check if the internal reference has stabilized.
Definition: VREF.h:63