Skip to content

Commit

Permalink
ESP32: Fix ADC/battery sense logic (SlimeVR#310)
Browse files Browse the repository at this point in the history
* ESP32: Fix ADC voltage readings

* Forgot endif oops

* Refactor a little bit

* Fix spelling of 'resolution'
  • Loading branch information
kounocom authored Jan 19, 2024
1 parent c26ec17 commit 35da44b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
9 changes: 6 additions & 3 deletions src/batterymonitor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,11 @@ void BatteryMonitor::Loop()
}
}
#endif
#if BATTERY_MONITOR == BAT_EXTERNAL
voltage = ((float)analogRead(PIN_BATTERY_LEVEL)) * batteryADCMultiplier;
#if ESP8266 && BATTERY_MONITOR == BAT_EXTERNAL
voltage = ((float)analogRead(PIN_BATTERY_LEVEL)) * ADCVoltageMax / ADCResolution * ADCMultiplier;
#endif
#if ESP32 && BATTERY_MONITOR == BAT_EXTERNAL
voltage = ((float)analogReadMilliVolts(PIN_BATTERY_LEVEL)) / 1000 * ADCMultiplier;
#endif
#if BATTERY_MONITOR == BAT_MCP3021 || BATTERY_MONITOR == BAT_INTERNAL_MCP3021
if (address > 0)
Expand All @@ -91,7 +94,7 @@ void BatteryMonitor::Loop()
if (status == 0)
{
float v = (((uint16_t)(MSB & 0x0F) << 6) | (uint16_t)(LSB >> 2));
v *= batteryADCMultiplier;
v *= ADCMultiplier;
voltage = (voltage > 0) ? min(voltage, v) : v;
}
}
Expand Down
14 changes: 5 additions & 9 deletions src/batterymonitor.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,11 @@
#include "logging/Logger.h"

#if ESP8266
#define ADCResulution 1023.0 // ESP8266 has 12bit ADC
#define ADCResolution 1023.0 // ESP8266 has 10bit ADC
#define ADCVoltageMax 1.0 // ESP8266 input is 1.0 V = 1023.0
#endif
#if ESP32
#define ADCResulution 4095.0 // ESP32 has 12bit ADC
#define ADCVoltageMax 3.3 // ESP32 input is 3.3 V = 4095.0
#endif
#ifndef ADCResulution
#define ADCResulution 1023.0
#ifndef ADCResolution
#define ADCResolution 1023.0
#endif
#ifndef ADCVoltageMax
#define ADCVoltageMax 1.0
Expand All @@ -64,10 +60,10 @@
// Diagramm:
// (Battery)--- [BATTERY_SHIELD_RESISTANCE] ---(INPUT_BOARD)--- [BATTERY_SHIELD_R2] ---(ESP_INPUT)--- [BATTERY_SHIELD_R1] --- (GND)
// SlimeVR Board can handle max 5V > so analogRead of 5.0V input will result in 1023.0
#define batteryADCMultiplier ADCVoltageMax / ADCResulution * (BATTERY_SHIELD_R1 + BATTERY_SHIELD_R2 + BATTERY_SHIELD_RESISTANCE) / BATTERY_SHIELD_R1
#define ADCMultiplier (BATTERY_SHIELD_R1 + BATTERY_SHIELD_R2 + BATTERY_SHIELD_RESISTANCE) / BATTERY_SHIELD_R1
#elif BATTERY_MONITOR == BAT_MCP3021 || BATTERY_MONITOR == BAT_INTERNAL_MCP3021
// Default recommended resistors are 9.1k and 5.1k
#define batteryADCMultiplier 3.3 / 1023.0 * 14.2 / 9.1
#define ADCMultiplier 3.3 / 1023.0 * 14.2 / 9.1
#endif

class BatteryMonitor
Expand Down

0 comments on commit 35da44b

Please sign in to comment.