Skip to content

Commit e248462

Browse files
committed
Fixed battery measurement.
1 parent cc3641c commit e248462

File tree

1 file changed

+15
-22
lines changed

1 file changed

+15
-22
lines changed

src/include/System.cpp

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -103,10 +103,14 @@ uint8_t System::readTouchpad(uint8_t _pad)
103103
*/
104104
double System::readBattery()
105105
{
106+
// Read the pin on the battery MOSFET. If is high, that means is older version of the board
107+
// that uses PMOS only. If it's low, newer board with both PMOS and NMOS.
106108
pinModeInternal(IO_INT_ADDR, ioRegsInt, 9, INPUT);
107109
int state = digitalReadIO(9, IO_INT_ADDR);
108110
pinModeInternal(IO_INT_ADDR, ioRegsInt, 9, OUTPUT);
109111

112+
// If the input is pulled high, it's PMOS only.
113+
// If it's pulled low, it's PMOS and NMOS.
110114
if (state)
111115
{
112116
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, LOW);
@@ -115,15 +119,15 @@ double System::readBattery()
115119
{
116120
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, HIGH);
117121
}
118-
/*
119-
#ifdef ARDUINO_ESP32_DEV
120-
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, LOW);
121-
#else
122-
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, HIGH);
123-
#endif
124-
*/
125-
delay(1);
126-
int adc = analogRead(35);
122+
123+
// Wait a little bit after a MOSFET enable.
124+
delay(5);
125+
126+
// Set to the highest resolution and read the voltage.
127+
analogReadResolution(12);
128+
int adc = analogReadMilliVolts(35);
129+
130+
// Turn off the MOSFET (and voltage divider).
127131
if (state)
128132
{
129133
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, HIGH);
@@ -133,19 +137,8 @@ double System::readBattery()
133137
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, LOW);
134138
}
135139

136-
137-
/*
138-
139-
#ifdef ARDUINO_ESP32_DEV
140-
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, HIGH);
141-
#else
142-
digitalWriteInternal(IO_INT_ADDR, ioRegsInt, 9, LOW);
143-
#endif
144-
*/
145-
// Calculate the voltage using the following formula
146-
// 1.1V is internal ADC reference of ESP32, 3.548133892 is 11dB in linear
147-
// scale (Analog signal is attenuated by 11dB before ESP32 ADC input)
148-
return (double(adc) / 4095 * 1.1 * 3.548133892 * 2);
140+
// Calculate the voltage at the battery terminal (voltage is divided in half by voltage divider).
141+
return (double(adc) * 2.0 / 1000);
149142
}
150143

151144
#ifndef ARDUINO_INKPLATE2

0 commit comments

Comments
 (0)