// BatteryReader.h #ifndef BATTERY_READER_H #define BATTERY_READER_H #include #include "Config.h" class BatteryReader { private: uint8_t batteryPin; float filteredVoltage = 0.0; bool firstReading = true; const float alpha = 0.3; // پارامترهای مخصوص باتری لیتیومی const float BATTERY_RATIO = (10000.0 + 10000.0) / 10000.0; // اگر مقسم ولتاژ مشابه است const float BATTERY_FULL_VOLTAGE = 4.2; // ولتاژ کامل باتری لیتیومی const float BATTERY_EMPTY_VOLTAGE = 3.0; // ولتاژ خالی public: BatteryReader(uint8_t pin) : batteryPin(pin) { init(); } void init() { pinMode(batteryPin, INPUT_ANALOG); analogReadResolution(12); delay(50); for (int i = 0; i < 5; i++) { analogRead(batteryPin); delay(1); } } float readRawVoltage() { int samples = 32; long sum = 0; for (int i = 0; i < samples; i++) { sum += analogRead(batteryPin); delayMicroseconds(20); } int rawValue = sum / samples; float voltageAtPin = (rawValue * ADC_REF_VOLTAGE) / ADC_RESOLUTION; float batteryVoltage = voltageAtPin * BATTERY_RATIO; return batteryVoltage; } float readVoltage() { float currentVoltage = readRawVoltage(); if (firstReading) { filteredVoltage = currentVoltage; firstReading = false; } else { filteredVoltage = (alpha * currentVoltage) + ((1 - alpha) * filteredVoltage); } return currentVoltage; } // محاسبه درصد شارژ باتری float getBatteryPercentage() { float voltage = readVoltage(); // محدود کردن ولتاژ به محدوده تعریف شده voltage = constrain(voltage, BATTERY_EMPTY_VOLTAGE, BATTERY_FULL_VOLTAGE); // محاسبه درصد float percentage = ((voltage - BATTERY_EMPTY_VOLTAGE) / (BATTERY_FULL_VOLTAGE - BATTERY_EMPTY_VOLTAGE)) * 100.0; return constrain(percentage, 0, 100); } void debugInfo() { float rawVoltage = readRawVoltage(); int rawADC = analogRead(batteryPin); float pinVoltage = rawVoltage / BATTERY_RATIO; Serial1.println("\n🔋 Battery Debug Info:"); Serial1.print("Raw ADC value: "); Serial1.println(rawADC); Serial1.print("Voltage at pin: "); Serial1.print(pinVoltage, 3); Serial1.println("V"); Serial1.print("Battery voltage: "); Serial1.print(rawVoltage, 3); Serial1.println("V"); Serial1.print("Battery percentage: "); Serial1.print(getBatteryPercentage(), 1); Serial1.println("%"); } }; #endif