const int analogPin = A0; const int ledPin = 4; const float R1 = 47000.0; // ohms const float R2 = 33000.0; // ohms const float dividerRatio = R2 / (R1 + R2); // 0.4125 const float VREF = 5.00; const int ADC_MAX = 1023; const float thresholdv = 7.20; // V, turn LED ON when below this const float hysteresis = 0.10; // V of hysteresis (prevents chattering) float measuredVbat = 0.0; bool lowState = false; // true when battery is "low" and LED should be ON void setup() { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); Serial.begin(9600); delay(50); } float readBatteryVoltage(int samples = 10) { long sum = 0; for (int i = 0; i < samples; ++i) { sum += analogRead(analogPin); delay(5); } float avg = float(sum) / samples; float vAtPin = (avg / ADC_MAX) * VREF; float vBat = vAtPin / dividerRatio; return vBat; } void loop() { measuredVbat = readBatteryVoltage(12); // average 12 samples // hysteresis: switch ON when below (threshold - h/2), switch OFF when above (threshold + h/2) float lower = thresholdv - (hysteresis / 2.0); float upper = thresholdv + (hysteresis / 2.0); if (!lowState && measuredVbat < lower) { lowState = true; digitalWrite(ledPin, HIGH); // battery low -> LED ON } else if (lowState && measuredVbat > upper) { lowState = false; digitalWrite(ledPin, LOW); // battery recovered -> LED OFF } // debug print Serial.print("VBAT = "); Serial.print(measuredVbat, 3); Serial.print(" V state="); Serial.println(lowState ? "LOW" : "OK"); delay(1000); }