Major updates of software structure

- new classes ChargeController and AnalogValue introduced
- BuckConverter renamed back to HalfBridge
- charging profile settings via struct
This commit is contained in:
Martin Jäger
2017-04-14 18:04:13 +02:00
parent 0908ef3aba
commit ead80a86ad
10 changed files with 771 additions and 573 deletions
+150 -139
View File
@@ -1,165 +1,176 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
0. Additional Definitions.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
1. Exception to Section 3 of the GNU GPL.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Conveying Modified Versions.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
3. Object Code Incorporating Material from Library Header Files.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
4. Combined Works.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
END OF TERMS AND CONDITIONS
+3 -3
View File
@@ -1,7 +1,7 @@
# MPPT Charger Software
Software based on ARM mbed library for the LibreSolar 20 A MPPT solar charge controller
## State machine
## State machine in class ChargeController
The charge management is implemented using a state machine with the following states:
@@ -22,6 +22,6 @@ This mode is only used for lead-acid batteries after several deep-discharge cycl
![Text](img/MPPT_flow_chart.png)
## DC/DC control class
## DC/DC controller using class HalfBridge
The PWM signal generation for the DC/DC controller inside the charge controller is done by a separate class BuckConverter. Most of the dangerous functions which could blow up your MOSFETs are implemented here.
The PWM signal generation for the DC/DC controller inside the charge controller is done by a separate class HalfBridge. Most of the dangerous functions which could blow up your MOSFETs are implemented here.
+53
View File
@@ -0,0 +1,53 @@
/* mbed library for ADC readings
* Copyright (c) 2017 Martin Jäger (www.libre.solar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "AnalogValue.h"
float AnalogValue::_vcc = 3.3;
AnalogValue::AnalogValue(PinName pin, float multiplier, const int num_readings, float filter_constant) :
_adc(pin), _num_readings(num_readings)
{
_multiplier = multiplier;
update(); // initialize value without filter
_filter_constant = filter_constant;
}
void AnalogValue::update()
{
float tmp = adc_read_avg(_adc, _num_readings) * _vcc * _multiplier;
_value = (1.0 - _filter_constant) * tmp + _filter_constant * _value;
}
float AnalogValue::adc_read_avg(AnalogIn& input, int num_readings)
{
// averaging: use read_u16 for faster calculation
unsigned int sum_adc_readings = 0;
for (int i = 0; i < num_readings; i++) {
sum_adc_readings += input.read_u16(); // normalized to 0xFFFF
}
return (float) (sum_adc_readings / num_readings) / (float)0xFFFF;
}
float AnalogValue::read()
{
return _value;
}
void AnalogValue::update_reference_voltage(AnalogIn& adc_ref, float ref_voltage, int num_readings)
{
_vcc = ref_voltage / adc_read_avg(adc_ref, num_readings);
}
+88
View File
@@ -0,0 +1,88 @@
/* mbed library for ADC readings
* Copyright (c) 2017 Martin Jäger (www.libre.solar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed.h"
class AnalogValue
{
public:
/** Create an AnalogValue object
*
* @param pin ADC input pin
* @param multiplier Factor to calculate desired output (e.g. for voltage dividers, gain, etc.)
* @param num_readings Number of ADC readings to be averaged
* @param filter_constant Low pass filter constant (0.0 to 1.0, 0.0 for no filtering)
*/
AnalogValue(PinName pin, float multiplier, const int num_readings = 8, float filter_constant = 0.0);
/** Updates ADC reading and applies low-pass filter. Should be called with a regular time interval
*/
void update();
/** Charger state machine update, should be called exactly once per second
*
* @param adc_ref AnalogIn for the pin with the reference voltage attached
* @param ref_voltage Rated reference voltage
* @param num_readings Number of ADC readings to be averaged
*/
static void update_reference_voltage(AnalogIn& adc_ref, float ref_voltage, int num_readings = 8);
/** Read the last updated (and filtered) ADC result (incl. multiplier)
*
* @returns
* Saved ADC result with multiplier applied
*/
float read();
/** An operator shorthand for read()
*
* The float() operator can be used as a shorthand for read() to simplify common code sequences
*
* Example:
* @code
* float x = volume.read();
* float x = volume;
*
* if(volume.read() > 0.25) { ... }
* if(volume > 0.25) { ... }
* @endcode
*/
operator float() {
return read();
}
private:
/** Read out ADC results and apply averaging and/or low pass filter
*
* @param input AnalogIn for the pin to be read
* @param num_readings Number of ADC readings to be averaged
*
* @returns
* Averaged and filtered ADC result
*/
static float adc_read_avg(AnalogIn& input, int num_readings);
static float _vcc; // actual VCC of ADC
AnalogIn _adc;
float _multiplier;
float _value;
const int _num_readings;
float _filter_constant;
};
+167
View File
@@ -0,0 +1,167 @@
/* mbed library for a battery charge controller
* Copyright (c) 2017 Martin Jäger (www.libre.solar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ChargeController.h"
ChargeController::ChargeController(ChargingProfile& profile) :
_profile(profile)
{
_charging_enabled = false;
}
/*****************************************************************************
* Charger state machine
## Idle
Initial state of the charge controller. If the solar voltage is high enough
and the battery is not full, charging in CC mode is started.
### CC / bulk charging
The battery is charged with maximum possible current (MPPT algorithm is
active) until the CV voltage limit is reached.
### CV / absorption charging
Lead-acid batteries are charged for some time using a slightly higher charge
voltage. After a current cutoff limit or a time limit is reached, the charger
goes into trickle or equalization mode for lead-acid batteries or back into
Standby for Li-ion batteries.
### Trickle charging
This mode is kept forever for a lead-acid battery and keeps the battery at
full state of charge. If too much power is drawn from the battery, the
charger switches back into CC / bulk charging mode.
### Equalization charging
This mode is only used for lead-acid batteries after several deep-discharge
cycles or a very long period of time with no equalization. Voltage is
increased to 15V or above, so care must be taken for the other system
components attached to the battery. (currently, no equalization charging is
enabled in the software)
*/
void ChargeController::update(float battery_voltage, float battery_current) {
// Load management
if (battery_voltage < _profile.cell_voltage_load_disconnect * _profile.num_cells) {
_discharging_enabled = false;
}
if (battery_voltage >= _profile.cell_voltage_load_reconnect * _profile.num_cells) {
_discharging_enabled = true;
}
// state machine
switch (_state) {
case CHG_IDLE: {
if (battery_voltage < _profile.num_cells * _profile.cell_voltage_recharge
&& (time(NULL) - _time_state_changed) > _profile.time_limit_recharge)
{
_target_current = _profile.charge_current_max;
_target_voltage = _profile.num_cells * _profile.cell_voltage_max;
_charging_enabled = true;
enter_state(CHG_CC);
}
break;
}
case CHG_CC: {
if (battery_voltage > _target_voltage) {
_target_voltage = _profile.num_cells * _profile.cell_voltage_max;
enter_state(CHG_CV);
}
break;
}
case CHG_CV: {
if (battery_voltage >= _target_voltage) {
_time_voltage_limit_reached = time(NULL);
}
// cut-off limit reached because battery full (i.e. CV mode still
// reached by available solar power within last 2s) or CV period long enough?
if ((battery_current < _profile.current_cutoff_CV && (time(NULL) - _time_voltage_limit_reached) < 2)
|| (time(NULL) - _time_state_changed) > _profile.time_limit_CV)
{
if (_profile.equalization_enabled) {
// TODO: additional conditions!
_target_voltage = _profile.num_cells * _profile.cell_voltage_equalization;
_target_current = _profile.current_limit_equalization;
enter_state(CHG_EQUALIZATION);
}
else if (_profile.trickle_enabled) {
_target_voltage = _profile.num_cells * _profile.cell_voltage_trickle;
enter_state(CHG_TRICKLE);
}
else {
_target_current = 0;
_charging_enabled = false;
enter_state(CHG_IDLE);
}
}
break;
}
case CHG_TRICKLE: {
if (battery_voltage >= _target_voltage) {
_time_voltage_limit_reached = time(NULL);
}
if (time(NULL) - _time_voltage_limit_reached > _profile.time_trickle_recharge)
{
_target_current = _profile.charge_current_max;
_target_voltage = _profile.num_cells * _profile.cell_voltage_max;
enter_state(CHG_CC);
}
// assumtion: trickle does not harm the battery --> never go back to idle
// (for Li-ion battery: disable trickle!)
break;
}
}
}
void ChargeController::enter_state(int next_state)
{
printf("Enter State: %d\n", next_state);
_time_state_changed = time(NULL);
_state = next_state;
}
bool ChargeController::discharging_enabled()
{
return _discharging_enabled;
}
bool ChargeController::charging_enabled()
{
return _charging_enabled;
}
int ChargeController::get_state()
{
return _state;
}
float ChargeController::read_target_current()
{
return _target_current;
}
float ChargeController::read_target_voltage()
{
return _target_voltage;
}
+134
View File
@@ -0,0 +1,134 @@
/* mbed library for a battery charge controller
* Copyright (c) 2017 Martin Jäger (www.libre.solar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// settings: battery_capacity, charge_profile
// input: actual charge current, actual battery voltage
// output: SOC, target_voltage, target_current (=max current)
#ifndef CHARGECONTROLLER_H
#define CHARGECONTROLLER_H
#include "mbed.h"
struct ChargingProfile {
int num_cells;
// State: Standby
int time_limit_recharge; // sec
float cell_voltage_recharge; // V
// State: CC/bulk
float charge_current_max; // A PCB maximum: 20 A
// State: CV/absorption
float cell_voltage_max; // max voltage per cell
int time_limit_CV; // sec
float current_cutoff_CV; // A
// State: float/trickle
bool trickle_enabled;
float cell_voltage_trickle; // target voltage for trickle charging of lead-acid batteries
int time_trickle_recharge; // sec
// State: equalization
bool equalization_enabled;
float cell_voltage_equalization; // V
int time_limit_equalization; // sec
float current_limit_equalization; // A
int equalization_trigger_time; // weeks
int equalization_trigger_deep_cycles; // times
float cell_voltage_load_disconnect;
float cell_voltage_load_reconnect;
// TODO
float temperature_compensation;
};
// possible charger states
enum charger_states {CHG_IDLE, CHG_CC, CHG_CV, CHG_TRICKLE, CHG_EQUALIZATION};
class ChargeController
{
public:
/** Create Charge Controller object
*
* @param profile ChargingProfile struct including voltage limits, etc.
*/
ChargeController(ChargingProfile& profile);
/** Get target battery current for current charger state
*
* @returns
* Target current (A)
*/
float read_target_current();
/** Get target battery voltage for current charger state
*
* @returns
* Target voltage (V)
*/
float read_target_voltage();
/** Determine if charging of the battery is allowed
*
* @returns
* True if charging is allowed
*/
bool charging_enabled();
/** Determine if discharging the battery is allowed
*
* @returns
* True if discharging is allowed
*/
bool discharging_enabled();
/** Charger state machine update, should be called exactly once per second
*
* @param battery_voltage Actual measured battery voltage (V)
* @param battery_current Actual measured battery current (A)
*/
void update(float battery_voltage, float battery_current);
/** Get current charge controller state
*
* @returns
* CHG_IDLE, CHG_CC, CHG_CV, CHG_TRICKLE or CHG_EQUALIZATION
*/
int get_state();
private:
/** Enter a different charger state
*
* @param next_state Next state (e.g. CHG_CC)
*/
void enter_state(int next_state);
ChargingProfile& _profile; // all charging profile variables
int _state; // valid states: enum charger_states
int _time_state_changed; // timestamp of last state change
float _target_voltage; // target voltage for current state
float _target_current; // target current for current state
int _time_voltage_limit_reached; // last time the CV limit was reached
bool _charging_enabled;
bool _discharging_enabled;
};
#endif // CHARGECONTROLLER_H
@@ -1,5 +1,5 @@
/* mbed library for MPPT buck converter
* Copyright (c) 2016 Martin Jäger (www.libre.solar)
/* mbed library for half bridge driver PWM generation
* Copyright (c) 2016-2017 Martin Jäger (www.libre.solar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,59 +14,18 @@
* limitations under the License.
*/
#include "BuckConverter.h"
#include "HalfBridge.h"
BuckConverter::BuckConverter(int freq_kHz)
HalfBridge::HalfBridge(int freq_kHz)
{
init_registers();
frequency_kHz(freq_kHz);
last_time_CV_reset();
_pwm_delta = 1;
_enabled = false;
}
void BuckConverter::update(int input_voltage_mV, int output_voltage_mV, int output_current_mA) {
int output_power_mW = output_voltage_mV * output_current_mA / 1000;
//printf("P=%d P_prev=%d Vi=%d Vo=%d Io=%d\n", output_power_mW, _output_power_prev_mW, input_voltage_mV, output_voltage_mV, output_current_mA);
if (output_voltage_mV > _max_voltage_mV) {
// increase input voltage to lower output voltage
if (output_current_mA > _min_current_mA) {
duty_cycle_step(-1);
_time_voltage_limit_reached = time(NULL);
}
else {
// switch off and wait for voltage to go down
// (otherwise current could get negative, i.e. into solar panel)
TIM1->BDTR &= ~(TIM_BDTR_MOE);
}
//printf("output_voltage_mV = %d, _max_voltage_mV = %d\n", output_voltage_mV, _max_voltage_mV);
//fflush(stdout);
}
else if (~(TIM1->BDTR & TIM_BDTR_MOE) && _enabled == true) {
// switched off because of too high output voltage?
// now: output_voltage_mV <= _max_voltage_mV --> start again
start((float) output_voltage_mV / (input_voltage_mV - 1000.0));
}
else if (output_current_mA > _max_current_mA) {
// increase input voltage to decrease current
duty_cycle_step(-1);
}
else {
// start MPPT
if (_output_power_prev_mW > output_power_mW) {
_pwm_delta = -_pwm_delta;
}
duty_cycle_step(_pwm_delta);
}
_output_power_prev_mW = output_power_mW;
}
void BuckConverter::init_registers() {
void HalfBridge::init_registers() {
// Enable peripheral clock of GPIOA and GPIOB
RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;
@@ -112,27 +71,7 @@ void BuckConverter::init_registers() {
TIM1->EGR |= TIM_EGR_UG;
}
void BuckConverter::set_max_voltage(int voltage_mV) {
_max_voltage_mV = voltage_mV;
}
void BuckConverter::set_max_current(int current_mA) {
_max_current_mA = current_mA;
}
void BuckConverter::set_min_current(int current_mA) {
_min_current_mA = current_mA;
}
time_t BuckConverter::last_time_CV() {
return _time_voltage_limit_reached;
}
void BuckConverter::last_time_CV_reset() {
_time_voltage_limit_reached = 0x7FFFFFFF; // maximum value
}
void BuckConverter::frequency_kHz(int freq) {
void HalfBridge::frequency_kHz(int freq) {
_pwm_resolution = SystemCoreClock / (freq * 1000);
@@ -141,8 +80,7 @@ void BuckConverter::frequency_kHz(int freq) {
TIM1->ARR = _pwm_resolution / 2;
}
void BuckConverter::set_duty_cycle(float duty) {
void HalfBridge::set_duty_cycle(float duty) {
float duty_target;
// protection against wrong settings which could destroy the hardware
@@ -159,7 +97,7 @@ void BuckConverter::set_duty_cycle(float duty) {
TIM1->CCR1 = _pwm_resolution / 2 * duty_target;
}
void BuckConverter::duty_cycle_step(int delta)
void HalfBridge::duty_cycle_step(int delta)
{
float duty_target;
duty_target = (float)(TIM1->CCR1 + delta) / (_pwm_resolution / 2);
@@ -177,12 +115,12 @@ void BuckConverter::duty_cycle_step(int delta)
}
float BuckConverter::get_duty_cycle() {
float HalfBridge::get_duty_cycle() {
return (float)(TIM1->CCR1) / (_pwm_resolution / 2);;
}
void BuckConverter::deadtime_ns(int deadtime) {
void HalfBridge::deadtime_ns(int deadtime) {
uint8_t deadtime_clocks = (SystemCoreClock / 1000 / 1000) * deadtime / 1000;
@@ -194,7 +132,7 @@ void BuckConverter::deadtime_ns(int deadtime) {
}
void BuckConverter::start(float pwm_duty) {
void HalfBridge::start(float pwm_duty) {
set_duty_cycle(pwm_duty);
// Break and Dead-Time Register
@@ -205,7 +143,7 @@ void BuckConverter::start(float pwm_duty) {
}
void BuckConverter::stop() {
void HalfBridge::stop() {
// Break and Dead-Time Register
// MOE = 1: Main output enable
@@ -214,8 +152,13 @@ void BuckConverter::stop() {
_enabled = false;
}
bool HalfBridge::enabled() {
void BuckConverter::lock_settings() {
return _enabled;
}
void HalfBridge::lock_settings() {
// TODO: does not work properly... maybe HW bug?
@@ -223,7 +166,7 @@ void BuckConverter::lock_settings() {
TIM1->BDTR |= TIM_BDTR_LOCK_1 | TIM_BDTR_LOCK_0;
}
void BuckConverter::duty_cycle_limits(float min_duty, float max_duty) {
void HalfBridge::duty_cycle_limits(float min_duty, float max_duty) {
_min_duty = min_duty;
_max_duty = max_duty;
@@ -1,5 +1,5 @@
/* mbed library for MPPT buck converter
* Copyright (c) 2016 Martin Jäger (www.libre.solar)
/* mbed library for half bridge driver PWM generation
* Copyright (c) 2016-2017 Martin Jäger (www.libre.solar)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,21 +14,19 @@
* limitations under the License.
*/
#ifndef HALFBRIDGE_H
#define HALFBRIDGE_H
#include "mbed.h"
class BuckConverter
class HalfBridge
{
public:
/** Create a half bridge object
*/
BuckConverter(int freq_kHz);
void set_max_voltage(int voltage_mV);
void set_max_current(int current_mA);
void set_min_current(int current_mA);
time_t last_time_CV ();
void last_time_CV_reset();
HalfBridge(int freq_kHz);
/** Set the PWM frequency in kHz
*
@@ -57,13 +55,12 @@ public:
*/
void stop();
/** Updates duty cycle to match voltage levels based on measured values
/** Get status of the PWM output
*
* @param input_voltage_mV Measured input voltage (mV)
* @param output_voltage_mV Measured output voltage (mA)
* @param output_current_mA Measured output current (mA)
* @returns
* True if PWM output enabled
*/
void update(int input_voltage_mV, int output_voltage_mV, int output_current_mA);
bool enabled();
/** Set the duty cycle of the PWM signal between 0.0 and 1.0
*
@@ -103,10 +100,6 @@ private:
int _pwm_delta;
bool _enabled;
int _max_voltage_mV;
int _max_current_mA;
int _min_current_mA;
int _output_power_prev_mW;
time_t _time_voltage_limit_reached;
};
#endif // HALFBRIDGE_H
+37 -27
View File
@@ -18,46 +18,56 @@
#define CONFIG_H
#include "mbed.h"
#include "ChargeController.h"
#define MPPT_20A
// DC/DC converter settings
const int _pwm_frequency = 70; // kHz
const int charge_current_cutoff = 20; // mA --> if lower, charger is switched off
const int max_solar_voltage = 55000; // mV
const int num_cells = 6;
const float dcdc_current_min = 0.1; // A --> if lower, charger is switched off
const float solar_voltage_max = 55.0; // V
// State: Standby
const int solar_voltage_offset_start = 5000; // mV charging switched on if Vsolar > Vbat + offset
const int solar_voltage_offset_stop = 1000; // mV charging switched off if Vsolar < Vbat + offset
const int time_limit_recharge = 60;//5*60; // sec
const int cell_voltage_recharge = 2300; // mV
const float solar_voltage_offset_start = 5.0; // V charging switched on if Vsolar > Vbat + offset
const float solar_voltage_offset_stop = 1.0; // V charging switched off if Vsolar < Vbat + offset
// State: CC/bulk
const int charge_current_max = 10000; // mA PCB maximum: 20 A
ChargingProfile profile = {
6, // num_cells;
// State: CV/absorption
const int cell_voltage_max = 2400; // max voltage per cell
const int time_limit_CV = 120; // min
const int current_cutoff_CV = 2000; // mA
// State: Standby
60, // time_limit_recharge; // sec
2.3, // cell_voltage_recharge; // V
// State: float/trickle
const bool trickle_enabled = true;
const int cell_voltage_trickle = 2300; // voltage for trickle charging of lead-acid batteries
const int time_trickle_recharge = 30; // min
// State: CC/bulk
10.0, // charge_current_max; // A PCB maximum: 20 A
// State: equalization
const bool equalization_enabled = false;
const int cell_voltage_equalization = 2500; // mV
const int time_limit_equalization = 60; // min
const int current_limit_equalization = 1000; // mA
const int equalization_trigger_time = 8; // weeks
const int equalization_trigger_deep_cycles = 10; // times
// State: CV/absorption
2.4, // cell_voltage_max; // max voltage per cell
120, // time_limit_CV; // sec
2.0, // current_cutoff_CV; // A
// State: float/trickle
true, // trickle_enabled;
2.3, // cell_voltage_trickle; // target voltage for trickle charging of lead-acid batteries
30*60, // time_trickle_recharge; // sec
// State: equalization
false, // equalization_enabled;
2.5, // cell_voltage_equalization; // V
60, // time_limit_equalization; // sec
1.0, // current_limit_equalization; // A
8, // equalization_trigger_time; // weeks
10, // equalization_trigger_deep_cycles; // times
1.95, // cell_voltage_load_disconnect;
2.2, // cell_voltage_load_reconnect;
// TODO
1.0 // temperature_compensation;
};
const int cell_voltage_load_disconnect = 1950;
const int cell_voltage_load_reconnect = 2200;
/*
// typcial LiFePO4 battery
+106 -307
View File
@@ -17,7 +17,9 @@
#include "mbed.h"
//#include "config_12a.h" // choose old PCB revision (12A)
#include "config.h" // choose new PCB revision (20A)
#include "BuckConverter.h"
#include "HalfBridge.h"
#include "AnalogValue.h"
#include "ChargeController.h"
#include "Adafruit_SSD1306.h"
//#include "SDFileSystem.h"
#include <math.h> // log for thermistor calculation
@@ -26,8 +28,6 @@
//#define SDCARD_ENABLED
#define OLED_ENABLED
#define ADC_AVG_SAMPLES 8 // number of ADC values to read for averaging
//----------------------------------------------------------------------------
// global variables
@@ -44,7 +44,9 @@ Serial serial(PIN_SWD_TX, PIN_SWD_RX, "serial");
Serial serial_uext(PIN_UEXT_TX, PIN_UEXT_RX, "serial_uext");
// PWM will be generated on pins PA8 (TIM1_CH1) and PB13 (TIM1_CH1N)
BuckConverter mppt(_pwm_frequency);
HalfBridge dcdc(_pwm_frequency);
float dcdc_power; // saves previous output power
int pwm_delta = 1;
DigitalOut led_green(PIN_LED_GREEN);
DigitalOut led_red(PIN_LED_RED);
@@ -53,24 +55,22 @@ DigitalOut load_disable(PIN_LOAD_DIS);
//AnalogOut ref_i_dcdc(PIN_REF_I_DCDC);
AnalogIn v_ref(PIN_V_REF);
AnalogIn v_bat(PIN_V_BAT);
AnalogIn v_solar(PIN_V_SOLAR);
AnalogIn v_temp(PIN_TEMP_INT);
AnalogIn i_load(PIN_I_LOAD);
AnalogIn i_dcdc(PIN_I_DCDC);
int solar_voltage; // mV
int battery_voltage; // mV
int dcdc_current = 0; // mA
int load_current = 0; // mA
float temperature; // °C
int solar_power = 0; // unit: mW
#ifdef MPPT_20A
AnalogValue solar_voltage(PIN_V_SOLAR, 1056.0 / 56.0); // solar voltage divider o-- 100k --o-- 5.6k --o
AnalogValue battery_voltage(PIN_V_BAT, 110 / 10); // battery voltage divider o-- 100k --o-- 10k --o
AnalogValue dcdc_current(PIN_I_DCDC, 1000 / 2 / (1500.0 / 22.0)); // op amp gain: 150/2.2 = 68.2, resistor: 2 mOhm
AnalogValue load_current(PIN_I_LOAD, 1000 / 2 / (1500.0 / 22.0));
AnalogValue thermistor_voltage(PIN_TEMP_INT, 1.0);
#endif
ChargeController charger(profile);
float temperature; // °C
int dcdc_current_offset = 0;
int load_current_offset = 0;
int time_state_changed = 0;
// for daily energy counting
int seconds_zero_solar = 0;
int seconds_day = 0;
@@ -81,25 +81,18 @@ float output_Wh_day = 0.0;
float input_Wh_total = 0.0;
float output_Wh_total = 0.0;
int pwm_delta = 1;
enum charger_states {STANDBY, CHG_CC, CHG_CV, CHG_TRICKLE, CHG_EQUALIZATION, BAT_ERROR, CHG_BIKE, TEST}; // states for charger state machine
int state = BAT_ERROR;
//----------------------------------------------------------------------------
// function prototypes
void setup();
void update_measurements();
void enter_state(int next_state);
void state_machine();
void update_screen();
void energy_counter();
void load_management();
void log_data();
void rtc_write_backup_reg(uint32_t BackupRegister, uint32_t data);
uint32_t rtc_read_backup_reg(uint32_t BackupRegister);
float adc_read_avg(AnalogIn& input);
void update_mppt();
//----------------------------------------------------------------------------
int main()
@@ -112,11 +105,9 @@ int main()
time_t last_second = time(NULL);
tick1.attach(&update_measurements, 0.01);
tick2.attach(&state_machine, 0.1);
tick2.attach(&update_mppt, 0.1);
enter_state(STANDBY);
time_state_changed = time(NULL) - 60*60*24; // start immediately
//enter_state(TEST);
//time_state_changed = time(NULL) - 60*60*24; // start immediately
while(1) {
// called once per second
@@ -148,20 +139,15 @@ void setup()
input_Wh_total = (float)rtc_read_backup_reg(3); // Wh
output_Wh_total = (float)rtc_read_backup_reg(4); // Wh
mppt.frequency_kHz(_pwm_frequency);
mppt.deadtime_ns(300);
mppt.set_duty_cycle(0.90);
mppt.lock_settings();
mppt.set_max_current(charge_current_max);
mppt.set_min_current(charge_current_cutoff);
mppt.set_max_voltage(num_cells * cell_voltage_max);
mppt.duty_cycle_limits((float) cell_voltage_load_disconnect * num_cells / max_solar_voltage, 0.97);
dcdc.deadtime_ns(300);
dcdc.lock_settings();
dcdc.duty_cycle_limits((float) profile.cell_voltage_load_disconnect * profile.num_cells / solar_voltage_max, 0.97);
update_measurements();
// calibration of current sensors in no load condition
load_current_offset = -load_current;
dcdc_current_offset = -dcdc_current;
//load_current_offset = -load_current;
//dcdc_current_offset = -dcdc_current;
serial.baud(115200);
serial.printf("\nSerial interface started...\n");
@@ -173,186 +159,62 @@ void setup()
freopen("/serial", "w", stdout); // retarget stdout
}
void load_management() {
if (battery_voltage < cell_voltage_load_disconnect * num_cells) {
void load_management()
{
if (charger.discharging_enabled()) {
load_disable = 0;
} else {
load_disable = 1;
}
if (battery_voltage >= cell_voltage_load_reconnect * num_cells) {
load_disable = 0;
}
}
// actions to be performed upon entering a state
void enter_state(int next_state)
void update_mppt()
{
switch (next_state)
{
case STANDBY:
serial.printf("Enter State: STANDBY\n");
mppt.stop();
led_red = 0;
break;
case CHG_CC:
serial.printf("Enter State: CHG_CC\n");
//serial.printf("P=%d Vsol=%d Vbat=%d Ibat=%d delta_time_CV=%d\n", solar_power, solar_voltage, battery_voltage, dcdc_current, time(NULL) - mppt.last_time_CV());
mppt.set_max_current(charge_current_max);
mppt.set_max_voltage(num_cells * cell_voltage_max);
mppt.last_time_CV_reset();
mppt.start((float) battery_voltage / (solar_voltage - 1000.0));
led_red = 1;
break;
case CHG_CV:
serial.printf("Enter State: CHG_CV\n");
//serial.printf("P=%d Vsol=%d Vbat=%d Ibat=%d delta_time_CV=%d\n", solar_power, solar_voltage, battery_voltage, dcdc_current, time(NULL) - mppt.last_time_CV());
mppt.set_max_voltage(num_cells * cell_voltage_max);
break;
case CHG_TRICKLE:
serial.printf("Enter State: CHG_TRICKLE\n");
//serial.printf("P=%d Vsol=%d Vbat=%d Ibat=%d delta_time_CV=%d\n", solar_power, solar_voltage, battery_voltage, dcdc_current, time(NULL) - mppt.last_time_CV());
mppt.set_max_voltage(num_cells * cell_voltage_trickle);
mppt.last_time_CV_reset();
break;
case CHG_EQUALIZATION:
serial.printf("Enter State: CHG_EQUALIZATION\n");
mppt.set_max_voltage(num_cells * cell_voltage_equalization);
mppt.last_time_CV_reset();
mppt.set_max_current(current_limit_equalization);
break;
case TEST:
serial.printf("Enter State: TEST\n");
//mppt.set_current_limit(charge_current_max);
//mppt.set_voltage_limit(num_cells * cell_voltage_max);
mppt.start(0.50);
led_red = 1;
break;
case BAT_ERROR:
serial.printf("Enter State: BAT_ERROR\n");
mppt.stop();
led_red = 0;
break;
default:
mppt.stop();
led_red = 0;
break;
}
time_state_changed = time(NULL);
state = next_state;
}
/*****************************************************************************
* Charger state machine
## Standby
Initial state of the charge controller. If the solar voltage is high enough
and the battery is not full, charging in CC mode is started.
### CC / bulk charging
The battery is charged with maximum possible current (MPPT algorithm is
active) until the CV voltage limit is reached.
### CV / absorption charging
Lead-acid batteries are charged for some time using a slightly higher charge
voltage. After a current cutoff limit or a time limit is reached, the charger
goes into trickle or equalization mode for lead-acid batteries or back into
Standby for Li-ion batteries.
### Trickle charging
This mode is kept forever for a lead-acid battery and keeps the battery at
full state of charge. If too much power is drawn from the battery, the
charger switches back into CC / bulk charging mode.
### Equalization charging
This mode is only used for lead-acid batteries after several deep-discharge
cycles or a very long period of time with no equalization. Voltage is
increased to 15V or above, so care must be taken for the other system
components attached to the battery. (currently, no equalization charging is
enabled in the software)
*/
void state_machine()
{
mppt.update(solar_voltage, battery_voltage, dcdc_current);
charger.update(battery_voltage.read(), dcdc_current.read());
load_management();
switch (state) {
float dcdc_power_new = battery_voltage * dcdc_current;
case STANDBY: {
if (solar_voltage > battery_voltage + solar_voltage_offset_start
&& battery_voltage < num_cells * cell_voltage_recharge
&& (time(NULL) - time_state_changed) > time_limit_recharge)
{
enter_state(CHG_CC);
}
break;
}
case CHG_CC: {
if (mppt.last_time_CV() <= time(NULL)) {
serial.printf("Last_time_cv = %d, time(NULL) = %d\n", mppt.last_time_CV(), time(NULL));
enter_state(CHG_CV);
}
else if (dcdc_current < charge_current_cutoff
|| solar_voltage < battery_voltage + solar_voltage_offset_stop) {
enter_state(STANDBY);
}
break;
}
case CHG_CV: {
// cut-off limit reached because battery full (i.e. CV mode still
// reached by available solar power within last 2s) or CV period long enough?
if ((dcdc_current < current_cutoff_CV && (time(NULL) - mppt.last_time_CV()) < 2)
|| (time(NULL) - time_state_changed) > time_limit_CV * 60)
{
if (equalization_enabled) {
// TODO: additional conditions!
enter_state(CHG_EQUALIZATION);
}
else if (trickle_enabled) {
enter_state(CHG_TRICKLE);
}
else {
enter_state(STANDBY);
}
}
else if (dcdc_current < charge_current_cutoff
|| solar_voltage < battery_voltage + solar_voltage_offset_stop)
{
enter_state(STANDBY);
}
break;
}
case CHG_TRICKLE: {
if (time(NULL) - mppt.last_time_CV() > time_trickle_recharge * 60)
{
enter_state(CHG_CC);
}
else if ((dcdc_current < charge_current_cutoff
&& battery_voltage < num_cells * cell_voltage_trickle)
|| solar_voltage < battery_voltage + solar_voltage_offset_stop)
{
enter_state(STANDBY);
}
break;
}
case TEST: {
break;
}
default:
mppt.stop();
break;
if (dcdc.enabled() == false && charger.charging_enabled() == true
&& battery_voltage < charger.read_target_voltage()
&& solar_voltage > battery_voltage + solar_voltage_offset_start)
{
dcdc.start(battery_voltage / (solar_voltage - 1.0));
led_red = 1;
}
else if (solar_voltage < battery_voltage + solar_voltage_offset_stop
|| dcdc_current < dcdc_current_min)
{
dcdc.stop();
led_red = 0;
}
if (battery_voltage > charger.read_target_voltage()) {
// increase input voltage to lower output voltage
if (dcdc_current > dcdc_current_min) {
dcdc.duty_cycle_step(-1);
}
else {
// switch off and wait for voltage to go down
// (otherwise current could get negative, i.e. into solar panel)
dcdc.stop();
led_red = 0;
}
}
else if (dcdc_current > charger.read_target_current()) {
// increase input voltage to decrease current
dcdc.duty_cycle_step(-1);
}
else {
//printf("MPPT\n");
// start MPPT
if (dcdc_power > dcdc_power_new) {
pwm_delta = -pwm_delta;
}
dcdc.duty_cycle_step(pwm_delta);
}
dcdc_power = dcdc_power_new;
}
@@ -360,7 +222,7 @@ void state_machine()
// must be called once per second
void energy_counter()
{
if (solar_power < 100) {
if (dcdc_power < 0.1) {
seconds_zero_solar++;
}
else {
@@ -372,7 +234,7 @@ void energy_counter()
nighttime = true;
}
if (nighttime && solar_power > 100) {
if (nighttime && dcdc_power > 0.1) {
nighttime = false;
input_Wh_day = 0.0;
output_Wh_day = 0.0;
@@ -383,10 +245,10 @@ void energy_counter()
seconds_day++;
}
input_Wh_day += solar_power / 1000.0 / 3600.0;
output_Wh_day += load_current / 1000.0 * battery_voltage / 1000.0 / 3600.0;
input_Wh_total += solar_power / 1000.0 / 3600.0;
output_Wh_total += load_current / 1000.0 * battery_voltage / 1000.0 / 3600.0;
input_Wh_day += dcdc_power / 3600.0;
output_Wh_day += load_current * battery_voltage / 3600.0;
input_Wh_total += dcdc_power / 3600.0;
output_Wh_total += load_current * battery_voltage/ 3600.0;
// save values to RTC backup register
rtc_write_backup_reg(0, time(NULL));
@@ -409,15 +271,15 @@ void log_data()
fprintf(fp, "%d;", (int)time(NULL));
fprintf(fp, "%d;", day_counter);
fprintf(fp, "%.2f;%.1f;", solar_voltage / 1000.0, solar_power / 1000.0);
fprintf(fp, "%.2f;%.1f;", battery_voltage / 1000.0, dcdc_current / 1000.0);
fprintf(fp, "%.1f;%.2f;", (load_current < 0 ? 0 : load_current) / 1000.0 * battery_voltage / 1000.0,
(load_current < 0 ? 0 : load_current) / 1000.0);
fprintf(fp, "%.2f;%.1f;", solar_voltage.read(), dcdc_power);
fprintf(fp, "%.2f;%.1f;", battery_voltage.read(), dcdc_current.read());
fprintf(fp, "%.1f;%.2f;", (load_current < 0 ? 0 : load_current.read()) * battery_voltage.read(),
(load_current < 0 ? 0 : load_current.read()));
fprintf(fp, "%d;", !load_disable);
fprintf(fp, "%.0f;%.0f;", input_Wh_day, fabs(output_Wh_day));
fprintf(fp, "%.1f;%.1f;", input_Wh_total / 1000.0, fabs(output_Wh_total / 1000.0));
switch (state) {
case STANDBY:
switch (charger.get_state()) {
case CHG_IDLE:
fprintf(fp, "Standby;");
break;
case CHG_CC:
@@ -429,9 +291,6 @@ void log_data()
case CHG_TRICKLE:
fprintf(fp, "Trickle chg;");
break;
case CHG_BIKE:
fprintf(fp, "Bike gen;");
break;
default:
fprintf(fp, "Error;");
break;
@@ -441,80 +300,27 @@ void log_data()
fclose(fp);
}
float adc_read_avg (AnalogIn& input) {
// use read_u16 for faster calculation
unsigned int sum_adc_readings = 0;
for (int i = 0; i < ADC_AVG_SAMPLES; i++) {
sum_adc_readings += input.read_u16(); // normalized to 0xFFFF
}
return (float) (sum_adc_readings / ADC_AVG_SAMPLES) / (float)0xFFFF;
}
//----------------------------------------------------------------------------
void update_measurements()
{
int vcc = 3300;
float tmp = 0.0;
// low pass filter of measurement values:
// y(n) = (1-c)*x(n) + c*y(n-1) with c=exp(-Ta/RC)
// https://en.wikipedia.org/wiki/Low-pass_filter#Simple_infinite_impulse_response_filter
float c = 0.3; // filter constant
// first call of function
if (battery_voltage == 0) {
c = 0.0;
}
#ifdef MPPT_12A
// solar voltage divider o-- 150k --o-- 6.8k --o
tmp = adc_read_avg(v_solar) * vcc * 1568 / 68;
solar_voltage = (1.0 - c) * tmp + c * solar_voltage;
// battery voltage divider o-- 120k --o-- 10k --o
tmp = adc_read_avg(v_bat) * vcc * 130 / 10;
battery_voltage = (1.0 - c) * tmp + c * battery_voltage;
tmp = adc_read_avg(i_dcdc) * vcc * 1000 / 5 / 50;
dcdc_current = (1.0 - c) * (tmp + dcdc_current_offset) + c * dcdc_current;
tmp = adc_read_avg(i_load) * vcc * 1000 / 5 / 50;
load_current = (1.0 - c) * (tmp + load_current_offset) + c * load_current;
solar_power = battery_voltage * dcdc_current / 1000;
#ifdef MPPT_20A
//AnalogValue::update_reference_voltage(v_ref, 2.5);
#endif
solar_voltage.update();
battery_voltage.update();
dcdc_current.update();
load_current.update();
#ifdef MPPT_20A
// reference voltage (should be 2.5V)
vcc = 2500 / adc_read_avg(v_ref);
thermistor_voltage.update();
// solar voltage divider o-- 100k --o-- 5.6k --o
tmp = adc_read_avg(v_solar) * vcc * 1056 / 56;
solar_voltage = (1.0 - c) * tmp + c * solar_voltage;
// battery voltage divider o-- 100k --o-- 10k --o
tmp = adc_read_avg(v_bat) * vcc * 110 / 10;
battery_voltage = (1.0 - c) * tmp + c * battery_voltage;
// dcdc current (op amp gain: 150/2.2 = 68.2, resistor: 2 mOhm)
tmp = adc_read_avg(i_dcdc) * vcc * 1000 / 2 / (1500 / 22);
dcdc_current = (1.0 - c) * (tmp + dcdc_current_offset) + c * dcdc_current;
// load current (op amp gain: 150/2.2 = 68.2, resistor: 2 mOhm)
tmp = adc_read_avg(i_load) * vcc * 1000 / 2 / (1500 / 22);
load_current = (1.0 - c) * (tmp + load_current_offset) + c * load_current;
solar_power = battery_voltage * dcdc_current / 1000;
// temperature sensed by NTC
tmp = adc_read_avg(v_temp) * vcc; // voltage read by ADC
unsigned long rts = 10000.0 * tmp / (3300.0 - tmp); // Ohm
// resistance of NTC (Ohm)
unsigned long rts = 10000.0 * thermistor_voltage.read() / (3.3 - thermistor_voltage.read());
// Temperature calculation using Beta equation for 10k thermistor
// (25°C reference temperature for Beta equation assumed)
float temp_K = 1.0/(1.0/(273.15+25) + 1.0/thermistorBetaValue*log(rts/10000.0)); // K
temperature = (1.0 - c) * (temp_K - 273.15) + c * temperature;
temperature = 1.0/(1.0/(273.15+25) + 1.0/thermistorBetaValue*log(rts/10000.0)) - 273.15;
#endif
}
uint32_t rtc_read_backup_reg(uint32_t BackupRegister) {
@@ -531,7 +337,6 @@ void rtc_write_backup_reg(uint32_t BackupRegister, uint32_t data) {
HAL_PWR_DisableBkUpAccess();
}
#ifdef OLED_ENABLED
void update_screen(void)
{
@@ -539,7 +344,7 @@ void update_screen(void)
oled.drawBitmap(6, 0, bmp_pv_panel, 16, 16, 1);
oled.drawBitmap(104, 0, bmp_load, 16, 16, 1);
if (state == STANDBY) {
if (dcdc.enabled() == false) {
oled.drawBitmap(27, 3, bmp_disconnected, 32, 8, 1);
}
else {
@@ -562,29 +367,29 @@ void update_screen(void)
oled.drawRect(66, 4, 2, 5, 1); // bar 5
oled.setTextCursor(0, 18);
oled.printf("%4.1fV", solar_voltage / 1000.0);
oled.printf("%4.1fV", solar_voltage.read());
oled.setTextCursor(0, 26);
oled.printf("%4.0fW", abs(solar_power) / 1000.0);
oled.printf("%4.0fW", fabs(dcdc_power));
oled.setTextCursor(42, 18);
oled.printf("%5.2fV", battery_voltage / 1000.0);
oled.printf("%5.2fV", battery_voltage.read());
oled.setTextCursor(42, 26);
oled.printf("%5.2fA", abs(dcdc_current) / 1000.0);
oled.printf("%5.2fA", fabs(dcdc_current));
oled.setTextCursor(90, 18);
oled.printf("%5.2fA\n", abs(load_current) / 1000.0);
oled.printf("%5.2fA\n", fabs(load_current));
oled.setTextCursor(90, 26);
oled.printf("%5.1fW", abs(load_current) / 1000.0 * battery_voltage / 1000.0);
oled.printf("%5.1fW", fabs(load_current) * battery_voltage);
oled.setTextCursor(0, 36);
oled.printf("Day +%5.0fWh -%5.0fWh", input_Wh_day, fabs(output_Wh_day));
oled.printf("Tot +%4.1fkWh -%4.1fkWh", input_Wh_total / 1000.0, fabs(output_Wh_total) / 1000.0);
oled.setTextCursor(0, 56);
oled.printf("Temp %.1f PWM %.1f%% ", temperature, mppt.get_duty_cycle() * 100.0);
switch (state) {
case STANDBY:
oled.printf("Standby\n");
oled.printf("T %.1f PWM %.1f%% ", temperature, dcdc.get_duty_cycle() * 100.0);
switch (charger.get_state()) {
case CHG_IDLE:
oled.printf("Idle\n");
break;
case CHG_CC:
oled.printf("CC charge\n");
@@ -595,12 +400,6 @@ void update_screen(void)
case CHG_TRICKLE:
oled.printf("Trickle chg\n");
break;
case CHG_BIKE:
oled.printf("Bike gen\n");
break;
case TEST:
oled.printf("Test\n");
break;
default:
oled.printf("Error\n");
break;