DMA for ADC implemented, mbed Ticker removed, files restructured

- DMA partly uses ST HAL API (to be improved in further versions)
- When using mbed ticker to trigger ADC, the program might stall --> use own timer instead
- C++ libraries changed to more simple C-style functions and files (better compatibility with plain C environments)
This commit is contained in:
Martin Jäger
2018-03-10 14:21:49 +01:00
parent efa5ac2bbd
commit 4aa51fbe25
25 changed files with 808 additions and 1107 deletions
+294
View File
@@ -0,0 +1,294 @@
/* LibreSolar MPPT charge controller firmware
* Copyright (c) 2016-2018 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"
#include "config.h"
#include "data_objects.h"
// for DMA and ADC configuration using ST HAL (see below)
#include "pinmap.h"
extern const PinMap PinMap_ADC[];
extern const PinMap PinMap_ADC_Internal[];
// for ADC and DMA
#define NUM_ADC_CH 7
volatile uint16_t adc_readings[NUM_ADC_CH] = {0,0,0,0,0,0,0};
volatile uint32_t adc_filtered[NUM_ADC_CH] = {0,0,0,0,0,0,0};
#define ADC_FILTER_CONST 5 // filter multiplier = 1/(2^ADC_FILTER_CONST)
volatile int num_adc_conversions;
extern float solar_voltage;
extern float battery_voltage;
extern float dcdc_current;
extern float dcdc_current_offset;
extern float load_current;
extern float load_current_offset;
extern float temp_mosfets;
extern float temp_battery;
extern Serial serial;
extern CalibrationData cal;
//----------------------------------------------------------------------------
void update_measurements()
{
int v_temp, rts;
// reference voltage of 2.5 V at PIN_V_REF
int vcc = 2500 * 4096 / (adc_filtered[2] >> (4 + ADC_FILTER_CONST)); // mV
battery_voltage =
(float)(((adc_filtered[3] >> (4 + ADC_FILTER_CONST)) * vcc) / 4096) *
adc_channels[3].multiplier / 1000.0;
solar_voltage =
(float)(((adc_filtered[4] >> (4 + ADC_FILTER_CONST)) * vcc) / 4096) *
adc_channels[4].multiplier / 1000.0;
load_current =
(float)(((adc_filtered[5] >> (4 + ADC_FILTER_CONST)) * vcc) / 4096) *
adc_channels[5].multiplier / 1000.0 + load_current_offset;
dcdc_current =
(float)(((adc_filtered[6] >> (4 + ADC_FILTER_CONST)) * vcc) / 4096) *
adc_channels[6].multiplier / 1000.0 + dcdc_current_offset;
// battery temperature calculation
v_temp = ((adc_filtered[0] >> (4 + ADC_FILTER_CONST)) * vcc) / 4096; // voltage read by ADC (mV)
rts = 10000 * v_temp / (vcc - v_temp); // resistance of NTC (Ohm)
// Temperature calculation using Beta equation for 10k thermistor
// (25°C reference temperature for Beta equation assumed)
temp_battery = 1.0/(1.0/(273.15+25) + 1.0/cal.thermistor_beta_value*log(rts/10000.0)) - 273.15; // °C
// MOSFET temperature calculation
v_temp = ((adc_filtered[1] >> (4 + ADC_FILTER_CONST)) * vcc) / 4096; // voltage read by ADC (mV)
rts = 10000 * v_temp / (vcc - v_temp); // resistance of NTC (Ohm)
temp_mosfets = 1.0/(1.0/(273.15+25) + 1.0/cal.thermistor_beta_value*log(rts/10000.0)) - 273.15; // °C
}
void start_dma()
{
/* Enable the peripheral clock on DMA */
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
/* Enable DMA transfer on ADC and circular mode */
ADC1->CFGR1 |= ADC_CFGR1_DMAEN | ADC_CFGR1_DMACFG;
/* Configure the peripheral data register address */
DMA1_Channel1->CPAR = (uint32_t)(&(ADC1->DR));
/* Configure the memory address */
DMA1_Channel1->CMAR = (uint32_t)(&(adc_readings[0]));
/* Configure the number of DMA tranfer to be performed on DMA channel 1 */
DMA1_Channel1->CNDTR = NUM_ADC_CH;
/* Configure increment, size, interrupts and circular mode */
DMA1_Channel1->CCR =
DMA_CCR_MINC | /* memory increment mode enabled */
DMA_CCR_MSIZE_0 | /* memory size 16-bit */
DMA_CCR_PSIZE_0 | /* peripheral size 16-bit */
DMA_CCR_TEIE | /* transfer error interrupt enable */
DMA_CCR_TCIE | /* transfer complete interrupt enable */
DMA_CCR_CIRC; /* circular mode enable */
/* DIR = 0: read from peripheral */
/* Enable DMA Channel 1 */
DMA1_Channel1->CCR |= DMA_CCR_EN;
/* Configure NVIC for DMA (priority 16: default value according to startup code) */
NVIC_SetPriority(DMA1_Channel1_IRQn, 16);
NVIC_EnableIRQ(DMA1_Channel1_IRQn);
// Trigger ADC conversions
ADC1->CR |= ADC_CR_ADSTART;
}
extern "C" void DMA1_Channel1_IRQHandler(void)
{
if ((DMA1->ISR & DMA_ISR_TCIF1) != 0) // Test if transfer completed on DMA channel 1
{
// low pass filter with filter constant c = 1/16
// y(n) = c * x(n) + (c - 1) * y(n-1)
for (int i = 0; i < NUM_ADC_CH; i++) {
// adc_readings: 12-bit ADC values left-aligned in uint16_t
adc_filtered[i] += (uint32_t)adc_readings[i] - (adc_filtered[i] >> ADC_FILTER_CONST);
}
num_adc_conversions++;
//DMA1->IFCR |= DMA_IFCR_CTCIF1;
}
DMA1->IFCR |= 0x0FFFFFFF; // clear all interrupt registers
/*
if (num_adc_conversions % 100 == 0) {
serial.printf("Filtered: %d %d %d %d %d %d %d (num_conv: %d)\n",
adc_filtered[0] >> (4+ADC_FILTER_CONST), adc_filtered[1] >> (4+ADC_FILTER_CONST), adc_filtered[2] >> (4+ADC_FILTER_CONST), adc_filtered[3] >> (4+ADC_FILTER_CONST),
adc_filtered[4] >> (4+ADC_FILTER_CONST), adc_filtered[5] >> (4+ADC_FILTER_CONST), adc_filtered[6] >> (4+ADC_FILTER_CONST), num_adc_conversions);
}
*/
}
// ToDo: Change to more clean function with direct register access without using ST HAL
void setup_adc()
{
uint32_t function = (uint32_t)NC;
analogin_t _adc;
analogin_t* obj = &_adc;
for (unsigned int i = 0; i < sizeof(adc_channels)/sizeof(AnalogValue_t); i++) {
obj->pin = adc_channels[i].pin;
// Get the peripheral name from the pin and assign it to the object
obj->handle.Instance = (ADC_TypeDef *)pinmap_peripheral(obj->pin, PinMap_ADC);
// Get the functions (adc channel) from the pin and assign it to the object
function = pinmap_function(obj->pin, PinMap_ADC);
// Configure GPIO
pinmap_pinout(obj->pin, PinMap_ADC);
MBED_ASSERT(obj->handle.Instance != (ADC_TypeDef *)NC);
MBED_ASSERT(function != (uint32_t)NC);
obj->channel = STM_PIN_CHANNEL(function);
// Configure ADC object structures
obj->handle.State = HAL_ADC_STATE_RESET;
obj->handle.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
obj->handle.Init.Resolution = ADC_RESOLUTION_12B;
obj->handle.Init.DataAlign = ADC_DATAALIGN_RIGHT;
obj->handle.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;
obj->handle.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
obj->handle.Init.LowPowerAutoWait = DISABLE;
obj->handle.Init.LowPowerAutoPowerOff = DISABLE;
obj->handle.Init.ContinuousConvMode = DISABLE;
obj->handle.Init.DiscontinuousConvMode = DISABLE;
obj->handle.Init.ExternalTrigConv = ADC_SOFTWARE_START;
obj->handle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
obj->handle.Init.DMAContinuousRequests = DISABLE;
obj->handle.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
__HAL_RCC_ADC1_CLK_ENABLE();
if (HAL_ADC_Init(&obj->handle) != HAL_OK) {
error("Cannot initialize ADC");
}
ADC_ChannelConfTypeDef sConfig = {0};
// Configure ADC channel
sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5;
// Clear all channels as it is not done in HAL_ADC_ConfigChannel()
obj->handle.Instance->CHSELR = 0;
HAL_ADC_ConfigChannel(&obj->handle, &sConfig);
HAL_ADC_Start(&obj->handle); // Start conversion
// Read out value at one time to finish ADC configuration
if (HAL_ADC_PollForConversion(&obj->handle, 10) == HAL_OK) {
HAL_ADC_GetValue(&obj->handle);
}
}
// Configure ADC object structures
obj->handle.State = HAL_ADC_STATE_RESET;
obj->handle.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
obj->handle.Init.Resolution = ADC_RESOLUTION_12B;
obj->handle.Init.DataAlign = ADC_DATAALIGN_LEFT; // for exeponential moving average filter
obj->handle.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;
obj->handle.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
obj->handle.Init.LowPowerAutoWait = DISABLE;
obj->handle.Init.LowPowerAutoPowerOff = DISABLE;
obj->handle.Init.ContinuousConvMode = DISABLE;
obj->handle.Init.DiscontinuousConvMode = DISABLE;
obj->handle.Init.ExternalTrigConv = ADC_SOFTWARE_START;
//obj->handle.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T15_TRGO; //ADC_SOFTWARE_START;
obj->handle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
//obj->handle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING; //ADC_EXTERNALTRIGCONVEDGE_NONE;
obj->handle.Init.DMAContinuousRequests = ENABLE; //DISABLE;
obj->handle.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
if (HAL_ADC_Init(&obj->handle) != HAL_OK) {
error("Cannot initialize ADC");
}
// calibrate ADC (doesn't matte that it's after first reading of ADC value)
HAL_ADCEx_Calibration_Start(&obj->handle);
// ADC sampling time register
// 000: 1.5 ADC clock cycles
// 001: 7.5 ADC clock cycles
// 010: 13.5 ADC clock cycles
// 011: 28.5 ADC clock cycles
// 100: 41.5 ADC clock cycles
// 101: 55.5 ADC clock cycles
// 110: 71.5 ADC clock cycles
// 111: 239.5 ADC clock cycles
ADC1->SMPR = ADC_SMPR_SMP_1;
// Select ADC channels
ADC1->CHSELR =
ADC_CHSELR_CHSEL0 | /* PIN_TEMP_BAT PA_0 */
ADC_CHSELR_CHSEL1 | /* PIN_TEMP_INT PA_1 */
ADC_CHSELR_CHSEL5 | /* PIN_V_REF PA_5 */
ADC_CHSELR_CHSEL6 | /* PIN_V_BAT PA_6 */
ADC_CHSELR_CHSEL7 | /* PIN_V_SOLAR PA_7 */
ADC_CHSELR_CHSEL8 | /* PIN_I_LOAD PB_0 */
ADC_CHSELR_CHSEL9; /* PIN_I_DCDC PB_1 */
//ADC1->CFGR1 &= ~(ADC_CFGR1_EXTEN_0 | ADC_CFGR1_EXTEN_1);
//ADC1->CFGR1 |= ADC_CFGR1_EXTEN_0; // enable external trigger (e.g. timer)
//ADC1->CFGR1 |= ADC_CFGR1_EXTSEL_2; // set TIM15 as trigger source
}
void setup_adc_timer()
{
// Enable peripheral clock of GPIOA and GPIOB
RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;
// Enable TIM1 clock
RCC->APB2ENR |= RCC_APB2ENR_TIM15EN;
// timer clock: 48 MHz / 4800 = 10 kHz
TIM15->PSC = 4799;
// interrupt on timer update
TIM15->DIER |= TIM_DIER_UIE;
// Auto Reload Register
TIM15->ARR = 10; // 1 kHz sample frequency at 10 kHz clock
//NVIC_SetPriority(DMA1_Channel1_IRQn, 16);
NVIC_EnableIRQ(TIM15_IRQn);
// Control Register 1
// TIM_CR1_CEN = 1: Counter enable
TIM15->CR1 |= TIM_CR1_CEN;
}
extern "C" void TIM15_IRQHandler(void)
{
TIM15->SR &= ~(1 << 0);
ADC1->CR |= ADC_CR_ADSTART;
}
+27
View File
@@ -0,0 +1,27 @@
/* LibreSolar MPPT charge controller firmware
* Copyright (c) 2016-2018 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.
*/
#ifndef ADC_DMA_H
#define ADC_DMA_H
void update_measurements();
void setup_adc_timer();
void setup_adc();
void start_dma();
#endif // ADC_DMA
+48
View File
@@ -0,0 +1,48 @@
#include "can_msg_queue.h"
bool CANMsgQueue::full() {
return _length == CAN_QUEUE_SIZE;
}
bool CANMsgQueue::empty() {
return _length == 0;
}
void CANMsgQueue::enqueue(CANMessage msg) {
if (!full()) {
_queue[(_first + _length) % CAN_QUEUE_SIZE] = msg;
_length++;
}
}
int CANMsgQueue::dequeue() {
if (!empty()) {
_first = (_first + 1) % CAN_QUEUE_SIZE;
_length--;
return 1;
} else {
return 0;
}
}
int CANMsgQueue::dequeue(CANMessage& msg) {
if (!empty()) {
msg = _queue[_first];
_first = (_first + 1) % CAN_QUEUE_SIZE;
_length--;
return 1;
} else {
return 0;
}
}
int CANMsgQueue::first(CANMessage& msg) {
if (!empty()) {
msg = _queue[_first];
return 1;
} else {
return 0;
}
}
+24
View File
@@ -0,0 +1,24 @@
#ifndef CAN_MSG_QUEUE_H
#define CAN_MSG_QUEUE_H
#include "mbed.h"
#define CAN_QUEUE_SIZE 30
class CANMsgQueue {
public:
bool full();
bool empty();
void enqueue(CANMessage msg);
int dequeue(CANMessage& msg);
int dequeue();
int first(CANMessage& msg);
private:
CANMessage _queue[CAN_QUEUE_SIZE];
int _first;
int _length;
};
#endif
+53 -34
View File
@@ -14,14 +14,33 @@
* limitations under the License.
*/
#include "ChargeController.h"
#include "charger.h"
ChargeController::ChargeController(ChargingProfile& profile) :
_profile(profile)
static ChargingProfile *_profile; // all charging profile variables
static int _state; // valid states: enum charger_states
static int _time_state_changed; // timestamp of last state change
static float _target_voltage; // target voltage for current state
static float _target_current; // target current for current state
static int _time_voltage_limit_reached; // last time the CV limit was reached
static bool _charging_enabled;
static bool _discharging_enabled;
// private function
/** Enter a different charger state
*
* @param next_state Next state (e.g. CHG_CC)
*/
void charger_enter_state(int next_state);
void charger_init(ChargingProfile *profile)
{
_profile = profile;
_charging_enabled = false;
_time_state_changed = -profile.time_limit_recharge; // start immediately
_time_state_changed = -profile->time_limit_recharge; // start immediately
}
/*****************************************************************************
@@ -55,15 +74,15 @@ ChargeController::ChargeController(ChargingProfile& profile) :
*/
void ChargeController::update(float battery_voltage, float battery_current) {
void charger_update(float battery_voltage, float battery_current) {
//printf("_time_state_change = %d, time = %d, v_bat = %f, i_bat = %f\n", _time_state_changed, time(NULL), battery_voltage, battery_current);
// Load management
if (battery_voltage < _profile.cell_voltage_load_disconnect * _profile.num_cells) {
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) {
if (battery_voltage >= _profile->cell_voltage_load_reconnect * _profile->num_cells) {
_discharging_enabled = true;
}
@@ -71,21 +90,21 @@ void ChargeController::update(float battery_voltage, float battery_current) {
switch (_state) {
case CHG_IDLE: {
if (battery_voltage < _profile.num_cells * _profile.cell_voltage_recharge
&& (time(NULL) - _time_state_changed) > _profile.time_limit_recharge)
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;
_target_current = _profile->charge_current_max;
_target_voltage = _profile->num_cells * _profile->cell_voltage_max;
_charging_enabled = true;
enter_state(CHG_CC);
charger_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);
_target_voltage = _profile->num_cells * _profile->cell_voltage_max;
charger_enter_state(CHG_CV);
}
break;
}
@@ -97,23 +116,23 @@ void ChargeController::update(float battery_voltage, float battery_current) {
// 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 ((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) {
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);
_target_voltage = _profile->num_cells * _profile->cell_voltage_equalization;
_target_current = _profile->current_limit_equalization;
charger_enter_state(CHG_EQUALIZATION);
}
else if (_profile.trickle_enabled) {
_target_voltage = _profile.num_cells * _profile.cell_voltage_trickle;
enter_state(CHG_TRICKLE);
else if (_profile->trickle_enabled) {
_target_voltage = _profile->num_cells * _profile->cell_voltage_trickle;
charger_enter_state(CHG_TRICKLE);
}
else {
_target_current = 0;
_charging_enabled = false;
enter_state(CHG_IDLE);
charger_enter_state(CHG_IDLE);
}
}
break;
@@ -124,11 +143,11 @@ void ChargeController::update(float battery_voltage, float battery_current) {
_time_voltage_limit_reached = time(NULL);
}
if (time(NULL) - _time_voltage_limit_reached > _profile.time_trickle_recharge)
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);
_target_current = _profile->charge_current_max;
_target_voltage = _profile->num_cells * _profile->cell_voltage_max;
charger_enter_state(CHG_CC);
}
// assumtion: trickle does not harm the battery --> never go back to idle
// (for Li-ion battery: disable trickle!)
@@ -137,34 +156,34 @@ void ChargeController::update(float battery_voltage, float battery_current) {
}
}
void ChargeController::enter_state(int next_state)
void charger_enter_state(int next_state)
{
printf("Enter State: %d\n", next_state);
_time_state_changed = time(NULL);
_state = next_state;
}
bool ChargeController::discharging_enabled()
bool charger_discharging_enabled()
{
return _discharging_enabled;
}
bool ChargeController::charging_enabled()
bool charger_charging_enabled()
{
return _charging_enabled;
}
int ChargeController::get_state()
int charger_get_state()
{
return _state;
}
float ChargeController::read_target_current()
float charger_read_target_current()
{
return _target_current;
}
float ChargeController::read_target_voltage()
float charger_read_target_voltage()
{
return _target_voltage;
}
+42 -62
View File
@@ -63,74 +63,54 @@ struct ChargingProfile {
// 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);
/** Create Charge Controller object
*
* @param profile ChargingProfile struct including voltage limits, etc.
*/
void charger_init(ChargingProfile *profile);
/** Get target battery current for current charger state
*
* @returns
* Target current (A)
*/
float read_target_current();
/** Get target battery current for current charger state
*
* @returns
* Target current (A)
*/
float charger_read_target_current();
/** Get target battery voltage for current charger state
*
* @returns
* Target voltage (V)
*/
float read_target_voltage();
/** Get target battery voltage for current charger state
*
* @returns
* Target voltage (V)
*/
float charger_read_target_voltage();
/** Determine if charging of the battery is allowed
*
* @returns
* True if charging is allowed
*/
bool charging_enabled();
/** Determine if charging of the battery is allowed
*
* @returns
* True if charging is allowed
*/
bool charger_charging_enabled();
/** Determine if discharging the battery is allowed
*
* @returns
* True if discharging is allowed
*/
bool discharging_enabled();
/** Determine if discharging the battery is allowed
*
* @returns
* True if discharging is allowed
*/
bool charger_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);
/** 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 charger_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;
};
/** Get current charge controller state
*
* @returns
* CHG_IDLE, CHG_CC, CHG_CV, CHG_TRICKLE or CHG_EQUALIZATION
*/
int charger_get_state();
#endif // CHARGECONTROLLER_H
#endif // CHARGER_H
+36 -8
View File
@@ -17,8 +17,10 @@
#ifndef CONFIG_H
#define CONFIG_H
#include "mbed.h"
// DC/DC converter settings
const int _pwm_frequency = 70; // kHz 70 = good compromise between output ripple and efficiency
#define PWM_FREQUENCY 70 // kHz 70 = good compromise between output ripple and efficiency
#define CAN_SPEED 250000 // 250 kHz
#define CAN_NODE_ID 10
@@ -51,15 +53,41 @@ const int _pwm_frequency = 70; // kHz 70 = good compromise between output rippl
#define PIN_REF_I_DCDC PA_4
#define PIN_V_REF PA_5
#define PIN_V_BAT PA_6
#define PIN_V_SOLAR PA_7
#define PIN_TEMP_BAT PA_0
#define PIN_TEMP_INT PA_1
#define PIN_I_LOAD PB_0
#define PIN_I_DCDC PB_1
#define PIN_TEMP_BAT PA_0 // ADC_IN0
#define PIN_TEMP_INT PA_1 // ADC_IN1
#define PIN_V_REF PA_5 // ADC_IN5
#define PIN_V_BAT PA_6 // ADC_IN6
#define PIN_V_SOLAR PA_7 // ADC_IN7
#define PIN_I_LOAD PB_0 // ADC_IN8
#define PIN_I_DCDC PB_1 // ADC_IN9
#define PIN_EEPROM_SCL PB_10
#define PIN_EEPROM_SDA PB_11
extern float solar_voltage;
extern float battery_voltage;
extern float dcdc_current;
extern float load_current;
extern float temp_mosfets; // °C
extern float temp_battery; // °C
static float ref_voltage;
typedef struct {
uint8_t channel_number;
PinName pin;
float* value;
float multiplier;
} AnalogValue_t;
static const AnalogValue_t adc_channels[] = {
{ 0, PIN_TEMP_BAT, &temp_battery, 0.0 },
{ 1, PIN_TEMP_INT, &temp_mosfets, 0.0 },
{ 5, PIN_V_REF, &ref_voltage, 0.0 },
{ 6, PIN_V_BAT, &battery_voltage, 110.0 / 10 }, // battery voltage divider 100k + 10k
{ 7, PIN_V_SOLAR, &solar_voltage, 1056.0 / 56.0 }, // solar voltage divider: 100k + 5.6k
{ 8, PIN_I_LOAD, &load_current, 1000 / 2 / (1500.0 / 22.0) }, // op amp gain: 150/2.2 = 68.2, resistor: 2 mOhm
{ 9, PIN_I_DCDC, &dcdc_current, 1000 / 2 / (1500.0 / 22.0) }
};
#endif
+1 -1
View File
@@ -18,7 +18,7 @@
#define CONFIG_12A_H
#include "mbed.h"
#include "ChargeController.h"
#include "charger.h"
#define MPPT_12A
+2 -2
View File
@@ -47,7 +47,7 @@ struct CalibrationData {
int32_t dcdc_restart_interval = 60; // s --> when should we retry to start charging after low solar power cut-off?
float solar_voltage_offset_start = 5.0; // V charging switched on if Vsolar > Vbat + offset
float solar_voltage_offset_stop = 1.0; // V charging switched off if Vsolar < Vbat + offset
int32_t thermistorBetaValue = 3435; // typical value for Semitec 103AT-5 thermistor: 3435
int32_t thermistor_beta_value = 3435; // typical value for Semitec 103AT-5 thermistor: 3435
};
extern CalibrationData cal;
@@ -132,7 +132,7 @@ static const DataObject_t dataObjects[] {
{++oid, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_INT32, 0, (void*) &(cal.dcdc_restart_interval), "tDcdcRestart"},
{++oid, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_FLOAT32, 0, (void*) &(cal.solar_voltage_offset_start), "vSolarOffsetStart"},
{++oid, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_FLOAT32, 0, (void*) &(cal.solar_voltage_offset_stop), "vSolarOffsetStop"},
{++oid, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_INT32, 0, (void*) &(cal.thermistorBetaValue), "thermistorBetaValue"}
{++oid, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_INT32, 0, (void*) &(cal.thermistor_beta_value), "thermistorBetaValue"}
};
#endif
+30 -30
View File
@@ -14,18 +14,17 @@
* limitations under the License.
*/
#include "HalfBridge.h"
#include "dcdc.h"
HalfBridge::HalfBridge(int freq_kHz)
{
init_registers();
frequency_kHz(freq_kHz);
_pwm_delta = 1;
_enabled = false;
}
static int _pwm_resolution;
static float _min_duty;
static float _max_duty;
static int _pwm_delta;
void HalfBridge::init_registers() {
static bool _enabled;
void dcdc_init(int freq_kHz) {
// Enable peripheral clock of GPIOA and GPIOB
RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;
@@ -69,18 +68,19 @@ void HalfBridge::init_registers() {
// Force update generation (UG = 1)
TIM1->EGR |= TIM_EGR_UG;
}
void HalfBridge::frequency_kHz(int freq) {
_pwm_resolution = SystemCoreClock / (freq * 1000);
// set PWM frequency and resolution
_pwm_resolution = SystemCoreClock / (freq_kHz * 1000);
// Auto Reload Register
// center-aligned mode --> divide resolution by 2
TIM1->ARR = _pwm_resolution / 2;
_pwm_delta = 1;
_enabled = false;
}
void HalfBridge::set_duty_cycle(float duty) {
void dcdc_set_duty_cycle(float duty) {
float duty_target;
// protection against wrong settings which could destroy the hardware
@@ -97,17 +97,17 @@ void HalfBridge::set_duty_cycle(float duty) {
TIM1->CCR1 = _pwm_resolution / 2 * duty_target;
}
void HalfBridge::duty_cycle_step(int delta)
void dcdc_duty_cycle_step(int delta)
{
float duty_target;
duty_target = (float)(TIM1->CCR1 + delta) / (_pwm_resolution / 2);
// protection against wrong settings which could destroy the hardware
if (duty_target < _min_duty) {
set_duty_cycle(_min_duty);
dcdc_set_duty_cycle(_min_duty);
}
else if (duty_target > _max_duty) {
set_duty_cycle(_max_duty);
dcdc_set_duty_cycle(_max_duty);
}
else {
TIM1->CCR1 = TIM1->CCR1 + delta;
@@ -115,12 +115,12 @@ void HalfBridge::duty_cycle_step(int delta)
}
float HalfBridge::get_duty_cycle() {
float dcdc_get_duty_cycle() {
return (float)(TIM1->CCR1) / (_pwm_resolution / 2);;
}
void HalfBridge::deadtime_ns(int deadtime) {
void dcdc_deadtime_ns(int deadtime) {
uint8_t deadtime_clocks = (SystemCoreClock / 1000 / 1000) * deadtime / 1000;
@@ -132,18 +132,18 @@ void HalfBridge::deadtime_ns(int deadtime) {
}
void HalfBridge::start(float pwm_duty) {
set_duty_cycle(pwm_duty);
void dcdc_start(float pwm_duty) {
dcdc_set_duty_cycle(pwm_duty);
// Break and Dead-Time Register
// MOE = 1: Main output enable
TIM1->BDTR |= TIM_BDTR_MOE;
//TIM1->BDTR |= TIM_BDTR_MOE;
_enabled = true;
}
void HalfBridge::stop() {
void dcdc_stop() {
// Break and Dead-Time Register
// MOE = 1: Main output enable
@@ -152,13 +152,13 @@ void HalfBridge::stop() {
_enabled = false;
}
bool HalfBridge::enabled() {
bool dcdc_enabled() {
return _enabled;
}
void HalfBridge::lock_settings() {
void dcdc_lock_settings() {
// TODO: does not work properly... maybe HW bug?
@@ -166,16 +166,16 @@ void HalfBridge::lock_settings() {
TIM1->BDTR |= TIM_BDTR_LOCK_1 | TIM_BDTR_LOCK_0;
}
void HalfBridge::duty_cycle_limits(float min_duty, float max_duty) {
void dcdc_duty_cycle_limits(float min_duty, float max_duty) {
_min_duty = min_duty;
_max_duty = max_duty;
// adjust set value to new limits
if (get_duty_cycle() < _min_duty) {
set_duty_cycle(_min_duty);
if (dcdc_get_duty_cycle() < _min_duty) {
dcdc_set_duty_cycle(_min_duty);
}
else if (get_duty_cycle() > _max_duty) {
set_duty_cycle(_max_duty);
else if (dcdc_get_duty_cycle() > _max_duty) {
dcdc_set_duty_cycle(_max_duty);
}
}
+83
View File
@@ -0,0 +1,83 @@
/* 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.
* 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.
*/
#ifndef DCDC_H
#define DCDC_H
#include "mbed.h"
/** Initiatializes the registers to generate the PWM signal
*
* @param freq Frequency in kHz
*/
void dcdc_init(int freq_kHz);
/** Set the deadtime between switching the two FETs on/off
*
* @param deadtime Deadtime in ns
*/
void dcdc_deadtime_ns(int deadtime);
/** Lock the settings of PWM generation to prevent accidental changes
* (does not work properly, yet! --> TODO)
*/
void dcdc_lock_settings(void);
/** Start the PWM generation
*
* @param pwm_duty Duty cycle between 0.0 and 1.0
*/
void dcdc_start(float pwm_duty);
/** Stop the PWM generation
*/
void dcdc_stop();
/** Get status of the PWM output
*
* @returns
* True if PWM output enabled
*/
bool dcdc_enabled();
/** Set the duty cycle of the PWM signal between 0.0 and 1.0
*
* @param duty Duty cycle between 0.0 and 1.0
*/
void dcdc_set_duty_cycle(float duty);
/** Adjust the duty cycle with minimum step size
*
* @param delta Number of steps (positive or negative)
*/
void dcdc_duty_cycle_step(int delta);
/** Read the currently set duty cycle
*
* @returns
* Duty cycle between 0.0 and 1.0
*/
float dcdc_get_duty_cycle();
/** Set limits for the duty cycle to prevent hardware damages
*
* @param min_duty Minimum duty cycle (e.g. 0.5 for limiting input voltage)
* @param max_duty Maximum duty cycle (e.g. 0.97 for charge pump)
*/
void dcdc_duty_cycle_limits(float min_duty, float max_duty);
#endif // HALFBRIDGE_H
+1 -1
View File
@@ -1,7 +1,7 @@
#ifndef DISPLAY_H
#define DISPLAY_H
static unsigned char bmp_load [] = {
const unsigned char bmp_load [] = {
0x20, 0x22, 0x04, 0x70, 0x88, 0x8B, 0x88, 0x70, 0x04, 0x22, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x00, 0x00, 0x07, 0x04, 0x07, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
-105
View File
@@ -1,105 +0,0 @@
/* 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.
* 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.
*/
#ifndef HALFBRIDGE_H
#define HALFBRIDGE_H
#include "mbed.h"
class HalfBridge
{
public:
/** Create a half bridge object
*/
HalfBridge(int freq_kHz);
/** Set the PWM frequency in kHz
*
* @param freq Frequency in kHz
*/
void frequency_kHz(int freq);
/** Set the deadtime between switching the two FETs on/off
*
* @param deadtime Deadtime in ns
*/
void deadtime_ns(int deadtime);
/** Lock the settings of PWM generation to prevent accidental changes
* (does not work properly, yet! --> TODO)
*/
void lock_settings(void);
/** Start the PWM generation
*
* @param pwm_duty Duty cycle between 0.0 and 1.0
*/
void start(float pwm_duty);
/** Stop the PWM generation
*/
void stop();
/** Get status of the PWM output
*
* @returns
* True if PWM output enabled
*/
bool enabled();
/** Set the duty cycle of the PWM signal between 0.0 and 1.0
*
* @param duty Duty cycle between 0.0 and 1.0
*/
void set_duty_cycle(float duty);
/** Adjust the duty cycle with minimum step size
*
* @param delta Number of steps (positive or negative)
*/
void duty_cycle_step(int delta);
/** Read the currently set duty cycle
*
* @returns
* Duty cycle between 0.0 and 1.0
*/
float get_duty_cycle();
/** Set limits for the duty cycle to prevent hardware damages
*
* @param min_duty Minimum duty cycle (e.g. 0.5 for limiting input voltage)
* @param max_duty Maximum duty cycle (e.g. 0.97 for charge pump)
*/
void duty_cycle_limits(float min_duty, float max_duty);
private:
/** Initiatializes the registers to generate the PWM signal
*/
void init_registers();
int _pwm_resolution;
float _min_duty;
float _max_duty;
int _pwm_delta;
bool _enabled;
};
#endif // HALFBRIDGE_H
+142 -100
View File
@@ -19,34 +19,28 @@
#include "mbed.h"
#include "config.h"
#include "data_objects.h"
#include "HalfBridge.h"
#include "AnalogValue.h"
#include "ChargeController.h"
#include "dcdc.h"
#include "charger.h"
#include "adc_dma.h"
//#include "24LCxx_I2C.h"
#include <math.h> // log for thermistor calculation
#include "output.h"
//#include "output_can.h"
#include "output_can.h"
//----------------------------------------------------------------------------
// global variables
Serial serial(PIN_SWD_TX, PIN_SWD_RX, "serial");
CAN can(PIN_CAN_RX, PIN_CAN_TX, CAN_SPEED);
DigitalOut uext_sda(PIN_UEXT_SDA);
DigitalOut uext_scl(PIN_UEXT_SCL);
I2C i2c(PIN_UEXT_SDA, PIN_UEXT_SCL);
DeviceState device;
CalibrationData cal;
ChargingProfile profile;
ChargeController charger(profile);
// PWM will be generated on pins PA8 (TIM1_CH1) and PB13 (TIM1_CH1N)
HalfBridge dcdc(_pwm_frequency);
float dcdc_power; // saves previous output power
float dcdc_power; // stores previous output power
int pwm_delta = 1;
int dcdc_off_timestamp = -cal.dcdc_restart_interval; // start immediately
@@ -58,17 +52,15 @@ DigitalOut out_5v_enable(PIN_5V_OUT_EN);
DigitalOut uext_disable(PIN_UEXT_DIS);
AnalogOut ref_i_dcdc(PIN_REF_I_DCDC);
AnalogIn v_ref(PIN_V_REF);
AnalogValue solar_voltage(PIN_V_SOLAR, 1056.0 / 56.0, 4, 0.2); // solar voltage divider o-- 100k --o-- 5.6k --o
AnalogValue battery_voltage(PIN_V_BAT, 110 / 10, 4, 0.2); // battery voltage divider o-- 100k --o-- 10k --o
AnalogValue dcdc_current(PIN_I_DCDC, 1000 / 2 / (1500.0 / 22.0), 4, 0.3); // 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_mosfets(PIN_TEMP_INT, 1.0);
AnalogValue thermistor_battery(PIN_TEMP_BAT, 1.0);
float temp_mosfets; // °C
//C24LCXX_I2C eeprom(PIN_EEPROM_SDA, PIN_EEPROM_SCL, 0x07);
float solar_voltage;
float battery_voltage;
float dcdc_current;
float dcdc_current_offset = 0.0;
float load_current;
float load_current_offset = 0.0;
float temp_mosfets; // °C
float temp_battery; // °C
// for daily energy counting
int seconds_zero_solar = 0;
@@ -80,54 +72,49 @@ bool nighttime = false;
// function prototypes
void setup();
void update_measurements();
void energy_counter();
void update_mppt();
void init_watchdog(float timeout); // timeout in seconds
void feed_the_dog();
//----------------------------------------------------------------------------
int main()
{
Ticker tick1, tick2, tick3;
Ticker tick1, tick2;
setup();
wait(3); // safety feature: be able to re-flash before starting
init_watchdog(1.0);
time_t last_second = time(NULL);
//tick1.attach(&update_measurements, 0.01); // too often, may cause crash of MCU
//tick2.attach(&update_mppt, 0.2);
dcdc.start(0.9); // for testing only (don't run update_mppt!)
//tick3.attach(&can_send_data, 1);
int count_10s = 0;
while(1) {
update_measurements();
update_mppt();
//can_process_outbox();
//can_process_inbox();
can_process_outbox();
can_process_inbox();
// called once per second
if (time(NULL) - last_second >= 1) {
last_second = time(NULL);
count_10s++;
serial.printf("Still alive... time: %d\n", time(NULL));
//serial.printf("Clock speed: %d\n", SystemCoreClock);
//serial.printf("Still alive... time: %d\n", time(NULL));
// updates charger state machine
charger.update(battery_voltage.read(), dcdc_current.read());
charger_update(battery_voltage, dcdc_current);
// load management
if (charger.discharging_enabled()) {
if (charger_discharging_enabled()) {
load_disable = 0;
} else {
load_disable = 1;
}
//can_send_data();
can_send_data();
energy_counter();
@@ -140,18 +127,11 @@ int main()
device.internal_temperature = temp_mosfets;
device.load_enabled = !load_disable;
#ifdef WIFI_ENABLED
if (count_10s >= 10) {
count_10s = 0;
//output_wifi(device, charger, dcdc);
}
#else
//output_serial_json();
output_oled();
#endif
output_oled();
fflush(stdout);
}
feed_the_dog();
//sleep(); // wake-up by ticker interrupts
}
}
@@ -163,7 +143,7 @@ void setup()
load_disable = 1;
can_disable = 0;
out_5v_enable = 0;
//uext_disable = 0;
uext_disable = 0;
ref_i_dcdc = 0.1; // 0 for buck, 1 for boost (TODO)
// adjust default values for 12V LiFePO4 battery
@@ -174,92 +154,98 @@ void setup()
profile.cell_voltage_load_disconnect = 3.0;
profile.cell_voltage_load_reconnect = 3.15;
dcdc.deadtime_ns(300);
dcdc.lock_settings();
dcdc.duty_cycle_limits((float) profile.cell_voltage_load_disconnect * profile.num_cells / cal.solar_voltage_max, 0.97);
wait(0.2);
update_measurements();
dcdc_current.calibrate_offset(0.0);
load_current.calibrate_offset(0.0);
//serial.baud(9600);
serial.baud(115200);
serial.printf("\nSerial interface started...\n");
printf("\nSerial interface started...\n");
freopen("/serial", "w", stdout); // retarget stdout
i2c.frequency(400000);
dcdc_init(PWM_FREQUENCY);
dcdc_deadtime_ns(300);
dcdc_lock_settings();
dcdc_duty_cycle_limits((float) profile.cell_voltage_load_disconnect * profile.num_cells / cal.solar_voltage_max, 0.97);
//can.mode(CAN::Normal);
//can.attach(&can_receive);
charger_init(&profile);
setup_adc_timer();
setup_adc();
start_dma();
wait(0.2); // wait for ADC to collect some measurement values
update_measurements();
dcdc_current_offset = -dcdc_current;
load_current_offset = -load_current;
can.mode(CAN::Normal);
can.attach(&can_receive);
// TXFP: Transmit FIFO priority driven by request order (chronologically)
// NART: No automatic retransmission
//CAN1->MCR |= CAN_MCR_TXFP | CAN_MCR_NART;
CAN1->MCR |= CAN_MCR_TXFP | CAN_MCR_NART;
}
void update_mppt()
{
float dcdc_power_new = battery_voltage * dcdc_current;
if (dcdc.enabled()) {
/*
if (dcdc_enabled()) {
serial.printf("B: %.2fV, %.2fA, S: %.2fV, Pwr: %.2fW, Charger: %d, DCDC: %d, PWM: %.1f\n",
battery_voltage.read(), dcdc_current.read(), solar_voltage.read(), dcdc_power_new,
charger.get_state(), dcdc.enabled(), dcdc.get_duty_cycle() * 100.0);
battery_voltage, dcdc_current, solar_voltage, dcdc_power_new,
charger_get_state(), dcdc_enabled(), dcdc_get_duty_cycle() * 100.0);
}
if (dcdc.enabled() == false && charger.charging_enabled() == true
&& battery_voltage < charger.read_target_voltage()
*/
if (dcdc_enabled() == false && charger_charging_enabled() == true
&& battery_voltage < charger_read_target_voltage()
&& battery_voltage > (profile.cell_voltage_absolute_min * profile.num_cells)
&& solar_voltage > battery_voltage + cal.solar_voltage_offset_start
&& time(NULL) > dcdc_off_timestamp + cal.dcdc_restart_interval)
{
serial.printf("MPPT start!\n");
dcdc.start(battery_voltage / (solar_voltage - 3.0)); // TODO: use factor (1V too low!)
dcdc_start(battery_voltage / (solar_voltage - 3.0)); // TODO: use factor (1V too low!)
led_red = 1;
}
else if (dcdc.enabled() == true &&
else if (dcdc_enabled() == true &&
((solar_voltage < battery_voltage + cal.solar_voltage_offset_stop
&& dcdc_current < cal.dcdc_current_min)
|| charger.charging_enabled() == false))
|| charger_charging_enabled() == false))
{
serial.printf("MPPT stop!\n");
dcdc.stop();
dcdc_stop();
led_red = 0;
dcdc_off_timestamp = time(NULL);
}
else if (dcdc.enabled()) {
else if (dcdc_enabled()) {
if (battery_voltage > charger.read_target_voltage()
|| dcdc_current > charger.read_target_current()
if (battery_voltage > charger_read_target_voltage()
|| dcdc_current > charger_read_target_current()
|| temp_mosfets > 80)
{
// increase input voltage --> lower output voltage and decreased current
dcdc.duty_cycle_step(-1);
dcdc_duty_cycle_step(-1);
}
else if (dcdc_current < cal.dcdc_current_min) {
// very low current --> decrease input voltage to increase current
pwm_delta = 1;
dcdc.duty_cycle_step(1);
dcdc_duty_cycle_step(1);
}
else {
//serial.printf("P: %.2f, P_prev: %.2f, v_bat: %.2f, i_bat: %.2f, v_target: %.2f, i_target: %.2f, PWM: %.1f\n",
// dcdc_power_new, dcdc_power, battery_voltage.read(), dcdc_current.read(), charger.read_target_voltage(), charger.read_target_current(), dcdc.get_duty_cycle() * 100.0);
/*
serial.printf("P: %.2f, P_prev: %.2f, v_bat: %.2f, i_bat: %.2f, v_target: %.2f, i_target: %.2f, PWM: %.1f\n",
dcdc_power_new, dcdc_power, battery_voltage, dcdc_current, charger_read_target_voltage(), charger_read_target_current(), dcdc_get_duty_cycle() * 100.0);
*/
// start MPPT
if (dcdc_power > dcdc_power_new) {
pwm_delta = -pwm_delta;
}
dcdc.duty_cycle_step(pwm_delta);
dcdc_duty_cycle_step(pwm_delta);
}
}
dcdc_power = dcdc_power_new;
}
//----------------------------------------------------------------------------
// must be called once per second
void energy_counter()
@@ -294,25 +280,81 @@ void energy_counter()
}
//----------------------------------------------------------------------------
void update_measurements()
// configures IWDG (timeout in seconds)
void init_watchdog(float timeout) {
#define LSI_FREQ 40000 // approx. 40 kHz according to RM0091
uint16_t prescaler;
float calculated_timeout;
IWDG->KR = 0x5555; // Disable write protection of IWDG registers
// set prescaler
if ((timeout * (LSI_FREQ/4)) < 0x7FF) {
IWDG->PR = IWDG_PRESCALER_4;
prescaler = 4;
}
else if ((timeout * (LSI_FREQ/8)) < 0xFF0) {
IWDG->PR = IWDG_PRESCALER_8;
prescaler = 8;
}
else if ((timeout * (LSI_FREQ/16)) < 0xFF0) {
IWDG->PR = IWDG_PRESCALER_16;
prescaler = 16;
}
else if ((timeout * (LSI_FREQ/32)) < 0xFF0) {
IWDG->PR = IWDG_PRESCALER_32;
prescaler = 32;
}
else if ((timeout * (LSI_FREQ/64)) < 0xFF0) {
IWDG->PR = IWDG_PRESCALER_64;
prescaler = 64;
}
else if ((timeout * (LSI_FREQ/128)) < 0xFF0) {
IWDG->PR = IWDG_PRESCALER_128;
prescaler = 128;
}
else {
IWDG->PR = IWDG_PRESCALER_256;
prescaler = 256;
}
// set reload value (between 0 and 0x0FFF)
IWDG->RLR = (uint32_t)(timeout * (LSI_FREQ/prescaler));
calculated_timeout = ((float)(prescaler * IWDG->RLR)) / LSI_FREQ;
printf("WATCHDOG set with prescaler:%d reload value: 0x%X - timeout:%f\n",prescaler, IWDG->RLR, calculated_timeout);
IWDG->KR = 0xAAAA; // reload
IWDG->KR = 0xCCCC; // start
feed_the_dog();
}
// Reset the watchdog timer
void feed_the_dog()
{
#ifdef MPPT_20A
//AnalogValue::update_reference_voltage(v_ref, 2.5);
#endif
IWDG->KR = 0xAAAA;
}
solar_voltage.update();
battery_voltage.update();
dcdc_current.update();
load_current.update();
// this function is called by mbed if a serious error occured: error() function called
void mbed_die(void)
{
dcdc_stop();
load_disable = 1;
thermistor_mosfets.update();
while (1) {
led_red = 1;
led_green = 0;
wait_ms(100);
led_red = 0;
led_green = 1;
wait_ms(100);
// resistance of NTC (Ohm)
unsigned long rts = 10000.0 * thermistor_mosfets.read() / (3.3 - thermistor_mosfets.read());
// Temperature calculation using Beta equation for 10k thermistor
// (25°C reference temperature for Beta equation assumed)
temp_mosfets = 1.0/(1.0/(273.15+25) + 1.0/cal.thermistorBetaValue*log(rts/10000.0)) - 273.15;
// stay here to indicate something was wrong
feed_the_dog();
}
}
#endif
+8 -10
View File
@@ -16,8 +16,8 @@
#include "config.h"
#include "data_objects.h"
#include "HalfBridge.h"
#include "ChargeController.h"
#include "dcdc.h"
#include "charger.h"
#include "Adafruit_SSD1306.h"
#include "display.h"
@@ -28,8 +28,6 @@ extern I2C i2c;
Adafruit_SSD1306_I2c oled(i2c, PIN_UEXT_SSEL, 0x78, 64, 128);
extern ChargeController charger;
extern HalfBridge dcdc;
//extern DeviceState device;
extern Serial serial;
@@ -63,7 +61,7 @@ void output_serial()
fprintf(fp, "%d;", device.load_enabled);
fprintf(fp, "%.0f;%.0f;", device.input_Wh_day, fabs(device.output_Wh_day));
fprintf(fp, "%.1f;%.1f;", device.input_Wh_total / 1000.0, fabs(device.output_Wh_total / 1000.0));
switch (charger.get_state()) {
switch (charger_get_state()) {
case CHG_IDLE:
fprintf(fp, "Standby;");
break;
@@ -80,8 +78,8 @@ void output_serial()
fprintf(fp, "Error;");
break;
}
fprintf(fp, "%.1f;", dcdc.get_duty_cycle() * 100.0);
fprintf(fp, "%d;", dcdc.enabled());
fprintf(fp, "%.1f;", dcdc_get_duty_cycle() * 100.0);
fprintf(fp, "%d;", dcdc_enabled());
fprintf(fp, "\n");
}
@@ -129,7 +127,7 @@ void output_oled()
oled.drawBitmap(6, 0, bmp_pv_panel, 16, 16, 1);
oled.drawBitmap(104, 0, bmp_load, 16, 16, 1);
if (dcdc.enabled() == false) {
if (dcdc_enabled() == false) {
oled.drawBitmap(27, 3, bmp_disconnected, 32, 8, 1);
}
else {
@@ -171,8 +169,8 @@ void output_oled()
oled.printf("Tot +%4.1fkWh -%4.1fkWh", device.input_Wh_total / 1000.0, fabs(device.output_Wh_total) / 1000.0);
oled.setTextCursor(0, 56);
oled.printf("T %.1f PWM %.1f%% ", device.internal_temperature, dcdc.get_duty_cycle() * 100.0);
switch (charger.get_state()) {
oled.printf("T %.1f PWM %.1f%% ", device.internal_temperature, dcdc_get_duty_cycle() * 100.0);
switch (charger_get_state()) {
case CHG_IDLE:
oled.printf("Idle\n");
break;
+8 -6
View File
@@ -22,8 +22,8 @@
//#include "can_iso_tp.h"
#include "data_objects.h"
#include "HalfBridge.h"
#include "ChargeController.h"
#include "dcdc.h"
#include "charger.h"
extern Serial serial;
extern CAN can;
@@ -40,13 +40,15 @@ void can_pub_msg(DataObject_t data_obj)
union float2bytes { float f; char b[4]; } f2b; // for conversion of float to single bytes
int msg_priority = 6;
int msg_id_template = msg_priority << 26 | can_node_id;
CANMessage msg;
msg.format = CANExtended;
msg.type = CANData;
msg.id = msg_id_template | data_obj.id << 8;
msg.id = msg_priority << 26
| (1U << 24) | (1U << 24) // identify as publication message
| data_obj.id << 8
| can_node_id;
// first byte: TinyTP-header or data type for single frame message
// currently: no multi-frame and no timestamp
@@ -119,10 +121,10 @@ void can_pub_msg(DataObject_t data_obj)
case T_BOOL:
msg.len = 1;
if (*((bool*)data_obj.data) == true) {
msg.data[0] = 0xf5; // simple type: true
msg.data[0] = TS_T_TRUE; // simple type: true
}
else {
msg.data[0] = 0xf4; // simple type: false
msg.data[0] = TS_T_FALSE; // simple type: false
}
break;
case T_STRING: