3 Battery Monitoring
Baran Schöneberg edited this page 2024-10-13 16:33:28 +02:00

To monitor the battery voltage and determine when it is running low, you can use the analog-to-digital converter (ADC) of the ESP-8266 Controller.

  • Components Needed:

Voltage Divider Circuit: Two resistors to create a voltage divider that scales down the battery voltage to a level that the ADC can read.

ESP-8266 Controller: Use the ADC pin (A0) to read the scaled-down voltage.

Steps to Set Up the Voltage Monitoring:

  • Design the Voltage Divider:

The ADC on the ESP-8266 can read voltages from 0V to 1V. You need to scale down the battery voltage (up to 8.4V) to this range.

Use two resistors, R1 and R2, to create a voltage divider.

The output voltage ( V_{out} ) is given by: [ V_{out} = V_{in} \times \frac{R2}{R1 + R2} ]

For example, if ( V_{in} ) is 8.4V, and you want ( V_{out} ) to be 1V: [ \frac{R2}{R1 + R2} = \frac{1}{8.4} ]

Choose R1 = 7.4kΩ and R2 = 1kΩ (or any other ratio that satisfies the equation).

  • Connect the Voltage Divider:

Connect the positive terminal of the battery pack to one end of R1. Connect the other end of R1 to one end of R2 and to the ADC pin (A0) of the ESP-8266. Connect the other end of R2 to the ground (GND). Example Connection Diagram: [ Battery + ] ----> [ R1 ] ----> [ R2 ] ----> GND | | A0 (ESP-8266) Code to Read the Battery Voltage:

const int analogPin = A0; // ADC pin
const float R1 = 7400.0; // Resistor R1 value in ohms
const float R2 = 1000.0; // Resistor R2 value in ohms
const float maxADCValue = 1023.0; // Maximum ADC value (10-bit ADC)
const float referenceVoltage = 1.0; // Reference voltage for ADC (1V)

void setup() {
  Serial.begin(115200);
}

void loop() {
  int adcValue = analogRead(analogPin);
  float voltage = (adcValue / maxADCValue) * referenceVoltage;
  float batteryVoltage = voltage * (R1 + R2) / R2;
  
  Serial.print("Battery Voltage: ");
  Serial.println(batteryVoltage);
  
  // Check if battery voltage is below a threshold
  if (batteryVoltage < 6.0) { // Example threshold
    Serial.println("Battery is running low!");
  }
  
  delay(1000); // Read every second
}

Explanation:

  • Analog Read: The analogRead(analogPin) function reads the voltage at the ADC pin and returns a value between 0 and 1023.

  • Voltage Calculation: The actual voltage at the ADC pin is calculated by scaling the ADC value to the reference voltage (1V).

  • Battery Voltage Calculation: The battery voltage is then calculated using the voltage divider ratio.

  • Threshold Check: The code checks if the battery voltage is below a certain threshold (e.g., 6.0V) and prints a warning message if it is.

By using this setup, you can continuously monitor the battery voltage and take appropriate actions (e.g., sending alerts, shutting down the system) when the battery is running low.