From 1f2ff6d4cf59adb0be76eb5a5f3a51f17eea631e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomislav=20Kopi=C4=87?= Date: Sat, 30 Nov 2024 17:14:34 +0100 Subject: [PATCH] Fixup battery calc --- src/SmartCube/cubeBattery.h | 18 ++++++++++++++++++ src/main.cpp | 29 +++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/SmartCube/cubeBattery.h diff --git a/src/SmartCube/cubeBattery.h b/src/SmartCube/cubeBattery.h new file mode 100644 index 0000000..c9ea52b --- /dev/null +++ b/src/SmartCube/cubeBattery.h @@ -0,0 +1,18 @@ +#define ADC_PIN 10 // GPIO10 on WEMOS S2 Mini + +const float R1 = 100000.0; // 100k ohms +const float R2 = 47000.0; // 47k ohms +const float ADC_MAX = 4095.0; // 12-bit ADC resolution +const float V_REF = 3.3; // Reference voltage for ESP32-S2 ADC + +float readBatteryVoltage() { + int rawADC = analogRead(ADC_PIN); + float voltage = (rawADC / ADC_MAX) * V_REF; + return voltage * (R1 + R2) / R2; // Scale to actual battery voltage +} + +int batteryPercentage(float voltage) { + if (voltage >= 4.2) return 100; + if (voltage <= 3.0) return 0; + return (voltage - 3.0) * 100 / (4.2 - 3.0); // Linear mapping +} \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 7f78ed1..22123d0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,6 +4,7 @@ #include "SmartCube/cubeSound.h" // Include custom header for sound functions #include "SmartCube/cubeButtons.h" // Include custom header for button handling functions #include "SmartCube/cubeWifiManager.h" // Include custom header for managing WiFi connections +#include "SmartCube/cubeBattery.h" // Include custom header for reading battery level // Initialize the OLED display with specified width, height, and reset pin Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); @@ -11,7 +12,35 @@ Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); // Initialize the WiFi manager, passing the display object for any display output cubeWifiManager cubeWifiManager(display); +void initSystems() { + pinMode(PIN_BTN_L, INPUT); + pinMode(PIN_BTN_M, INPUT); + pinMode(PIN_BTN_R, INPUT); + pinMode(PIN_BUZZER, OUTPUT); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, HIGH); + Wire.begin(); // Initialize I2C + Wire.setClock(400000L); // Set I2C to Fast Mode (400 kHz) + display.ssd1306_command(SSD1306_SETCONTRAST); + display.ssd1306_command(200); // Value between 0 and 255 + // Initialize the SSD1306 display + if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Adjust I2C address if needed + for(;;); // Don't proceed, loop forever + } + + // Rotate the display 180 degrees + display.setRotation(2); + + // Clear the display buffer + display.clearDisplay(); + display.setTextSize(1); + display.setTextColor(WHITE); + display.setCursor(0, 0); + display.display(); +} + void setup() { + initSystems(); cubeWifiManager.start(); // Start the WiFi manager }