TechoBoard.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <Arduino.h>
  2. #include <Wire.h>
  3. #include "TechoBoard.h"
  4. #ifdef LILYGO_TECHO
  5. void TechoBoard::begin() {
  6. NRF52Board::begin();
  7. // Configure battery measurement control BEFORE Wire.begin()
  8. // to ensure P0.02 is not claimed by another peripheral
  9. pinMode(PIN_VBAT_MEAS_EN, OUTPUT);
  10. digitalWrite(PIN_VBAT_MEAS_EN, LOW);
  11. pinMode(PIN_VBAT_READ, INPUT);
  12. Wire.begin();
  13. pinMode(SX126X_POWER_EN, OUTPUT);
  14. digitalWrite(SX126X_POWER_EN, HIGH);
  15. delay(10);
  16. }
  17. uint16_t TechoBoard::getBattMilliVolts() {
  18. // Use LilyGo's exact ADC configuration
  19. analogReference(AR_INTERNAL_3_0);
  20. analogReadResolution(12);
  21. // Enable battery voltage divider (MOSFET gate on P0.31)
  22. pinMode(PIN_VBAT_MEAS_EN, OUTPUT);
  23. digitalWrite(PIN_VBAT_MEAS_EN, HIGH);
  24. // Reclaim P0.02 for analog input (in case another peripheral touched it)
  25. pinMode(PIN_VBAT_READ, INPUT);
  26. delay(10); // let divider + ADC settle
  27. // Read and average (matching LilyGo's approach)
  28. uint32_t sum = 0;
  29. for (int i = 0; i < 8; i++) {
  30. sum += analogRead(PIN_VBAT_READ);
  31. delayMicroseconds(100);
  32. }
  33. uint16_t adc = sum / 8;
  34. // Disable divider to save power
  35. digitalWrite(PIN_VBAT_MEAS_EN, LOW);
  36. // LilyGo's exact formula: adc * (3000.0 / 4096.0) * 2.0
  37. // = adc * 0.73242188 * 2.0 = adc * 1.46484375
  38. uint16_t millivolts = (uint16_t)((float)adc * (3000.0f / 4096.0f) * 2.0f);
  39. return millivolts;
  40. }
  41. #endif