AP_BattMonitor_Analog.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <AP_HAL/AP_HAL.h>
  2. #include <AP_Common/AP_Common.h>
  3. #include <AP_Math/AP_Math.h>
  4. #include "AP_BattMonitor.h"
  5. #include "AP_BattMonitor_Analog.h"
  6. extern const AP_HAL::HAL& hal;
  7. /// Constructor
  8. AP_BattMonitor_Analog::AP_BattMonitor_Analog(AP_BattMonitor &mon,
  9. AP_BattMonitor::BattMonitor_State &mon_state,
  10. AP_BattMonitor_Params &params) :
  11. AP_BattMonitor_Backend(mon, mon_state, params)
  12. {
  13. _volt_pin_analog_source = hal.analogin->channel(_params._volt_pin);
  14. _curr_pin_analog_source = hal.analogin->channel(_params._curr_pin);
  15. // always healthy
  16. _state.healthy = true;
  17. }
  18. // read - read the voltage and current
  19. void
  20. AP_BattMonitor_Analog::read()
  21. {
  22. // this copes with changing the pin at runtime
  23. _volt_pin_analog_source->set_pin(_params._volt_pin);
  24. // get voltage
  25. _state.voltage = _volt_pin_analog_source->voltage_average() * _params._volt_multiplier;
  26. // read current
  27. if (has_current()) {
  28. // calculate time since last current read
  29. uint32_t tnow = AP_HAL::micros();
  30. float dt = tnow - _state.last_time_micros;
  31. // this copes with changing the pin at runtime
  32. _curr_pin_analog_source->set_pin(_params._curr_pin);
  33. // read current
  34. _state.current_amps = (_curr_pin_analog_source->voltage_average()-_params._curr_amp_offset)*_params._curr_amp_per_volt;
  35. // update total current drawn since startup
  36. if (_state.last_time_micros != 0 && dt < 2000000.0f) {
  37. // .0002778 is 1/3600 (conversion to hours)
  38. float mah = _state.current_amps * dt * 0.0000002778f;
  39. _state.consumed_mah += mah;
  40. _state.consumed_wh += 0.001f * mah * _state.voltage;
  41. }
  42. // record time
  43. _state.last_time_micros = tnow;
  44. }
  45. }
  46. /// return true if battery provides current info
  47. bool AP_BattMonitor_Analog::has_current() const
  48. {
  49. return (_params.type() == AP_BattMonitor_Params::BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT);
  50. }