2015-08-11 03:28:42 -03:00
|
|
|
#include <AP_HAL/AP_HAL.h>
|
|
|
|
#include <AP_Common/AP_Common.h>
|
|
|
|
#include <AP_Math/AP_Math.h>
|
2014-12-04 01:35:31 -04:00
|
|
|
#include "AP_BattMonitor.h"
|
|
|
|
#include "AP_BattMonitor_Analog.h"
|
|
|
|
|
|
|
|
extern const AP_HAL::HAL& hal;
|
|
|
|
|
|
|
|
/// Constructor
|
2017-10-27 02:36:49 -03:00
|
|
|
AP_BattMonitor_Analog::AP_BattMonitor_Analog(AP_BattMonitor &mon,
|
|
|
|
AP_BattMonitor::BattMonitor_State &mon_state,
|
|
|
|
AP_BattMonitor_Params ¶ms) :
|
|
|
|
AP_BattMonitor_Backend(mon, mon_state, params)
|
2014-12-04 01:35:31 -04:00
|
|
|
{
|
2017-10-27 02:36:49 -03:00
|
|
|
_volt_pin_analog_source = hal.analogin->channel(_params._volt_pin);
|
|
|
|
_curr_pin_analog_source = hal.analogin->channel(_params._curr_pin);
|
2015-03-18 08:06:25 -03:00
|
|
|
|
|
|
|
// always healthy
|
|
|
|
_state.healthy = true;
|
2014-12-04 01:35:31 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// read - read the voltage and current
|
|
|
|
void
|
|
|
|
AP_BattMonitor_Analog::read()
|
|
|
|
{
|
|
|
|
// this copes with changing the pin at runtime
|
2017-10-27 02:36:49 -03:00
|
|
|
_volt_pin_analog_source->set_pin(_params._volt_pin);
|
2014-12-04 01:35:31 -04:00
|
|
|
|
|
|
|
// get voltage
|
2017-10-27 02:36:49 -03:00
|
|
|
_state.voltage = _volt_pin_analog_source->voltage_average() * _params._volt_multiplier;
|
2014-12-04 01:35:31 -04:00
|
|
|
|
|
|
|
// read current
|
2017-05-24 04:43:10 -03:00
|
|
|
if (has_current()) {
|
2014-12-04 01:35:31 -04:00
|
|
|
// calculate time since last current read
|
2015-11-19 23:08:43 -04:00
|
|
|
uint32_t tnow = AP_HAL::micros();
|
2014-12-04 01:35:31 -04:00
|
|
|
float dt = tnow - _state.last_time_micros;
|
|
|
|
|
|
|
|
// this copes with changing the pin at runtime
|
2017-10-27 02:36:49 -03:00
|
|
|
_curr_pin_analog_source->set_pin(_params._curr_pin);
|
2014-12-04 01:35:31 -04:00
|
|
|
|
|
|
|
// read current
|
2017-10-27 02:36:49 -03:00
|
|
|
_state.current_amps = (_curr_pin_analog_source->voltage_average()-_params._curr_amp_offset)*_params._curr_amp_per_volt;
|
2014-12-04 01:35:31 -04:00
|
|
|
|
|
|
|
// update total current drawn since startup
|
|
|
|
if (_state.last_time_micros != 0 && dt < 2000000.0f) {
|
|
|
|
// .0002778 is 1/3600 (conversion to hours)
|
2016-08-25 09:53:33 -03:00
|
|
|
float mah = _state.current_amps * dt * 0.0000002778f;
|
2018-02-15 12:10:36 -04:00
|
|
|
_state.consumed_mah += mah;
|
2016-08-25 09:53:33 -03:00
|
|
|
_state.consumed_wh += 0.001f * mah * _state.voltage;
|
2014-12-04 01:35:31 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// record time
|
|
|
|
_state.last_time_micros = tnow;
|
|
|
|
}
|
|
|
|
}
|
2017-05-24 04:43:10 -03:00
|
|
|
|
|
|
|
/// return true if battery provides current info
|
|
|
|
bool AP_BattMonitor_Analog::has_current() const
|
|
|
|
{
|
2017-10-27 02:36:49 -03:00
|
|
|
return (_params.type() == AP_BattMonitor_Params::BattMonitor_TYPE_ANALOG_VOLTAGE_AND_CURRENT);
|
2017-05-24 04:43:10 -03:00
|
|
|
}
|