Battery voltage monitor and AD conversion for XIAO_ESP32C

So, I was expecting this latest revision to work perfectly but alas no joy :frowning:

The sketch i’m using is:

#include <WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Wi-Fi credentials
const char* ssid = "network";
const char* password = "pwd";

// MQTT broker details
const char* mqtt_server = "192.168.1.19";
const char* mqtt_user = "fridge1";
const char* mqtt_password = "fridge1";

// Device hostname
const char* hostname = "C3-Fridge-1";

// Pin definitions
#define DS18B20_PIN 6  // GPIO6 for DS18B20
#define BATTERY_PIN 4  // GPIO4 (D4) for ADC battery monitoring

// Voltage divider resistors
#define R1 220000 // 220kΩ
#define R2 220000 // 220kΩ

// Battery voltage limits
#define BATTERY_MAX 4.2
#define BATTERY_MIN 3.0

// Deep sleep time in microseconds (15 minutes)
#define SLEEP_TIME 900000000

// DS18B20 setup
OneWire oneWire(DS18B20_PIN);
DallasTemperature sensors(&oneWire);

// Wi-Fi and MQTT clients
WiFiClient espClient;
PubSubClient client(espClient);

// Function to read battery voltage
float readBatteryVoltage() {
    analogSetPinAttenuation(BATTERY_PIN, ADC_11db); // Configure ADC for 0-2.5V range
    int raw = analogRead(BATTERY_PIN); // Read raw ADC value
    float vOut = (raw / 4095.0) * 2.5; // Convert ADC value to voltage
    float vBattery = vOut / 0.5; // Scale to battery voltage
    return vBattery;
}

// Function to calculate battery percentage
int calculateBatteryPercentage(float voltage) {
    float percentage = ((voltage - BATTERY_MIN) / (BATTERY_MAX - BATTERY_MIN)) * 100.0;
    if (percentage > 100) percentage = 100;
    if (percentage < 0) percentage = 0;
    return (int)percentage;
}

// Function to connect to Wi-Fi
void connectToWiFi() {
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    WiFi.setHostname(hostname);

    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
    }
}

// Function to connect to MQTT broker
void connectToMQTT() {
    while (!client.connected()) {
        if (client.connect(hostname, mqtt_user, mqtt_password)) {
            // Connected
        } else {
            delay(5000);
        }
    }
}

void setup() {
    sensors.begin(); // Start DS18B20
    connectToWiFi();
    client.setServer(mqtt_server, 1883);
    connectToMQTT();

    // Read temperature
    sensors.requestTemperatures();
    float temperature = sensors.getTempCByIndex(0);
    if (temperature == DEVICE_DISCONNECTED_C) {
        temperature = -127; // Error value
    }

    // Read battery voltage
    float batteryVoltage = readBatteryVoltage();

    // Calculate battery percentage
    int batteryPercentage = calculateBatteryPercentage(batteryVoltage);

    // Publish data
    char payload[100];
    snprintf(payload, sizeof(payload), "{\"hostname\":\"%s\",\"temperature\":%.2f,\"battery_percentage\":%d}", hostname, temperature, batteryPercentage);
    client.publish("fridge/temperature", payload);

    // Deep sleep
    esp_sleep_enable_timer_wakeup(SLEEP_TIME);
    delay(1000); // Ensure MQTT message is sent
    esp_deep_sleep_start();
}

void loop() {
    // Not used
}

I’ve included a picture which probably doesn’t help very much (I have not included the picture as “You cannot embed media items in a post”) but what it shows is the battery connected to battery pads with 2 x 220k Ohm resistors 1 going from each battery connection to GPIO 4. The temperature sensor is in GPIO 6 with power from 3v3 and GND. Everything works but I’m getting 0 from battery percentage on the MQTT broker. While posting this I am also noticing the label on my resistor bag says 220Ohm and not actually 220KOhm so i’m going to go and ask the wife to tell me what colours are on these as being colour blind makes this much more of an effort… I promise this isn’t a satirical post. Posting just now in case the resistors are correct but will update.