MPPT algorithm improvements and CAN data logging added

This commit is contained in:
Martin Jäger
2018-03-02 23:59:52 +01:00
parent ba9a600f93
commit e10b5165a2
14 changed files with 932 additions and 384 deletions
+6 -1
View File
@@ -1,4 +1,9 @@
.pioenvs
.clang_complete
.gcc-flags.json
.piolibdeps
.piolibdeps
.vscode/browse.vc.db*
.vscode
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/*.db
@@ -21,6 +21,7 @@ ChargeController::ChargeController(ChargingProfile& profile) :
_profile(profile)
{
_charging_enabled = false;
_time_state_changed = -profile.time_limit_recharge; // start immediately
}
/*****************************************************************************
@@ -56,6 +57,8 @@ ChargeController::ChargeController(ChargingProfile& profile) :
void ChargeController::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) {
_discharging_enabled = false;
+21 -19
View File
@@ -23,39 +23,41 @@
#include "mbed.h"
// default values for 12V lead-acid battery
struct ChargingProfile {
int num_cells;
int num_cells = 6;
// State: Standby
int time_limit_recharge; // sec
float cell_voltage_recharge; // V
int time_limit_recharge = 60; // sec
float cell_voltage_recharge = 2.3; // V
float cell_voltage_absolute_min = 1.8; // V (under this voltage, battery is considered damaged)
// State: CC/bulk
float charge_current_max; // A PCB maximum: 20 A
float charge_current_max = 20; // 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
float cell_voltage_max = 2.4; // max voltage per cell
int time_limit_CV = 120*60; // sec
float current_cutoff_CV = 2.0; // 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
bool trickle_enabled = true;
float cell_voltage_trickle = 2.3; // target voltage for trickle charging of lead-acid batteries
int time_trickle_recharge = 30*60; // 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
bool equalization_enabled = false;
float cell_voltage_equalization = 2.5; // V
int time_limit_equalization = 60*60; // sec
float current_limit_equalization = 1.0; // A
int equalization_trigger_time = 8; // weeks
int equalization_trigger_deep_cycles = 10; // times
float cell_voltage_load_disconnect;
float cell_voltage_load_reconnect;
float cell_voltage_load_disconnect = 1.95;
float cell_voltage_load_reconnect = 2.2;
// TODO
float temperature_compensation;
float temperature_compensation = 1.0;
};
// possible charger states
+31 -17
View File
@@ -8,26 +8,40 @@
# A sign `#` at the beginning of the line indicates a comment
# Comment lines are ignored.
# Simple and base environment
# [env:mybaseenv]
# platform = %INSTALLED_PLATFORM_NAME_HERE%
# framework =
# board =
#
# Automatic targets - enable auto-uploading
# targets = upload
[platformio]
env_default = nucleo
[env:stlink]
[env:nucleo]
platform = ststm32
framework = mbed
board = nucleo_f072rb
upload_protocol = stlink
extra_script = stlink_extra_script.py
# enable float formatting for printf, adding approx. 7 kB of bin file size
build_flags = -Wl,-u_printf_float
#[env:nucleo_f072rb]
#platform = ststm32
#framework = mbed
#board = nucleo_f072rb
#upload_port = G:
# Settings:
# - enable float formatting for printf, adding approx. 7 kB of bin file size
# - C++11 to be able to define default values for struct members
# - Use low speed internal clock (LSI) for RTC (no LSE crystal on PCB)
build_flags =
-Wl,-u_printf_float
-std=c++11
-DMBED_CONF_TARGET_LSE_AVAILABLE=0
# -DPIO_FRAMEWORK_MBED_RTOS_PRESENT
# -DPIO_FRAMEWORK_MBED_EVENTS_PRESENT
# Custom Serial Monitor port
#monitor_port = /dev/ttyUSB1
; Custom Serial Monitor baud rate
monitor_baud = 115200
[env:unit_test]
framework = mbed
board = nucleo_f072rb
platform = ststm32
test_transport = custom
test_port = COM7
upload_protocol = stlink
build_flags = -Wl,-u_printf_float
-std=c++11
-DMBED_CONF_TARGET_LSE_AVAILABLE=0
+15 -64
View File
@@ -17,71 +17,14 @@
#ifndef CONFIG_H
#define CONFIG_H
#include "mbed.h"
#include "ChargeController.h"
#define MPPT_20A
// DC/DC converter settings
const int _pwm_frequency = 70; // kHz
const int _pwm_frequency = 70; // kHz 70 = good compromise between output ripple and efficiency
const float dcdc_current_min = 0.1; // A --> if lower, charger is switched off
const float solar_voltage_max = 55.0; // V
#define CAN_SPEED 250000 // 250 kHz
#define CAN_NODE_ID 10
// State: Standby
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
ChargingProfile profile = {
6, // num_cells;
// State: Standby
60, // time_limit_recharge; // sec
2.3, // cell_voltage_recharge; // V
// State: CC/bulk
10.0, // charge_current_max; // A PCB maximum: 20 A
// State: CV/absorption
2.4, // cell_voltage_max; // max voltage per cell
120*60, // 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;
};
/*
// typcial LiFePO4 battery
const int num_cells = 4;
const int v_cell_max = 3550; // max voltage per cell
const int v_cell_trickle = 3550; // voltage for trickle charging of lead-acid batteries
const int v_cell_load_disconnect = 3000;
const int v_cell_load_reconnect = 3150;
*/
const int thermistorBetaValue = 3435; // typical value for Semitec 103AT-5 thermistor: 3435
//----------------------------------------------------------------------------
// global variables
// 20A board (rev. 0.6)
// 20A board (rev. 0.6-0.8)
#define PIN_UEXT_DIS PC_14 // starting from rev. 0.10
#define PIN_UEXT_TX PA_2
#define PIN_UEXT_RX PA_3
#define PIN_UEXT_SCL PB_6
@@ -89,7 +32,7 @@ const int thermistorBetaValue = 3435; // typical value for Semitec 103AT-5 ther
#define PIN_UEXT_MISO PB_4
#define PIN_UEXT_MOSI PB_5
#define PIN_UEXT_SCK PB_3
#define PIN_UEXT_SSEL PC_13
#define PIN_UEXT_SSEL PC_13 // PCB rev 0.6: PA_0
#define PIN_SWD_TX PA_9
#define PIN_SWD_RX PA_10
@@ -100,15 +43,23 @@ const int thermistorBetaValue = 3435; // typical value for Semitec 103AT-5 ther
#define PIN_LED_GREEN PB_14
#define PIN_LED_RED PB_15
#define PIN_LOAD_DIS PB_2
#define PIN_5V_OUT_EN PB_12
#define PIN_CAN_RX PB_8
#define PIN_CAN_TX PB_9
#define PIN_CAN_STB PA_15
#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_INT PA_1
#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_EEPROM_SCL PB_10
#define PIN_EEPROM_SDA PB_11
#endif
+4 -3
View File
@@ -27,6 +27,7 @@ const int _pwm_frequency = 100; // kHz
const float dcdc_current_min = 0.1; // A --> if lower, charger is switched off
const float solar_voltage_max = 55.0; // V
const int dcdc_restart_interval = 60; // s --> when should we retry to start charging after low solar power cut-off?
// State: Standby
const float solar_voltage_offset_start = 5.0; // V charging switched on if Vsolar > Vbat + offset
@@ -40,12 +41,12 @@ ChargingProfile profile = {
2.3, // cell_voltage_recharge; // V
// State: CC/bulk
10.0, // charge_current_max; // A PCB maximum: 20 A
12.0, // charge_current_max; // A PCB maximum: 20 A
// State: CV/absorption
2.4, // cell_voltage_max; // max voltage per cell
120*60, // time_limit_CV; // sec
2.0, // current_cutoff_CV; // A
1.0, // current_cutoff_CV; // A
// State: float/trickle
true, // trickle_enabled;
@@ -61,7 +62,7 @@ ChargingProfile profile = {
10, // equalization_trigger_deep_cycles; // times
1.95, // cell_voltage_load_disconnect;
2.2, // cell_voltage_load_reconnect;
2.1, // cell_voltage_load_reconnect;
// TODO
1.0 // temperature_compensation;
+138
View File
@@ -0,0 +1,138 @@
/* 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 DATA_OBJECTS_H
#define DATA_OBJECTS_H
#include "stdint.h"
/*
const char* manufacturer = "Libre Solar";
const char* deviceName = "MPPT Solar Charge Controller 20A";
*/
// rename to OutputData
struct DeviceState {
float bus_voltage;
float input_voltage;
float bus_current;
float input_current;
float load_current;
float external_temperature;
float internal_temperature;
bool load_enabled;
float input_Wh_day = 0.0;
float output_Wh_day = 0.0;
float input_Wh_total = 0.0;
float output_Wh_total = 0.0;
};
extern DeviceState device;
struct CalibrationData {
float dcdc_current_min = 0.05; // A --> if lower, charger is switched off
float solar_voltage_max = 55.0; // V
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
};
extern CalibrationData cal;
typedef struct {
const uint16_t id;
const uint8_t access;
const uint8_t category;
const uint8_t type;
const int8_t exponent; // only for int and uint types
void* data;
const char* name;
} DataObject_t;
// ThingSet CAN standard data types
#define TS_T_POS_INT8 0
#define TS_T_POS_INT16 1
#define TS_T_POS_INT32 2
#define TS_T_POS_INT64 3
#define TS_T_NEG_INT8 4
#define TS_T_NEG_INT16 5
#define TS_T_NEG_INT32 6
#define TS_T_NEG_INT64 7
#define TS_T_BYTE_STRING 8
#define TS_T_UTF8_STRING 12
#define TS_T_FLOAT32 30
#define TS_T_FLOAT64 31
#define TS_T_ARRAY 16
#define TS_T_MAP 20
// ThingSet CAN special types and simple values
#define TS_T_TIMESTAMP 33
#define TS_T_DECIMAL_FRAC 35
#define TS_T_FALSE 44
#define TS_T_TRUE 45
#define TS_T_NULL 46
#define TS_T_UNDEFINED 47
// C variable types
#define T_BOOL 0
//#define T_UINT32 1
#define T_INT32 2
#define T_FLOAT32 3
#define T_STRING 4
// ThingSet data object categories
#define TS_C_ALL 0
#define TS_C_DEVICE 1 // read-only device information (e.g. manufacturer, etc.)
#define TS_C_SETTINGS 2 // user-configurable settings (open access, maybe with user password)
#define TS_C_CAL 3 // factory-calibrated settings (access restricted)
#define TS_C_DIAGNOSIS 4 // error memory, etc (at least partly access restricted)
#define TS_C_INPUT 5 // free access
#define TS_C_OUTPUT 6 // free access
// internal access rights to data objects
#define ACCESS_READ (0x1U)
#define ACCESS_WRITE (0x1U << 1)
#define ACCESS_READ_AUTH (0x1U << 2) // read after authentication
#define ACCESS_WRITE_AUTH (0x1U << 3) // write after authentication
static uint16_t oid;
static const DataObject_t dataObjects[] {
// output data
{oid=0, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.bus_voltage), "vBat"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.input_voltage), "vSolar"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.bus_current), "iBat"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.load_current), "iLoad"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.external_temperature), "tempExt"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.internal_temperature), "tempInt"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_BOOL, 0, (void*) &(device.load_enabled), "loaEn"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.input_Wh_day), "eInputDay_Wh"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.output_Wh_day), "eOutputDay_Wh"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.input_Wh_total), "eInputTotal_Wh"},
{++oid, ACCESS_READ, TS_C_OUTPUT, T_FLOAT32, 0, (void*) &(device.output_Wh_total), "eOutputTotal_Wh"},
// calibration data
{oid=100, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_FLOAT32, 0, (void*) &(cal.dcdc_current_min), "iDcdcMin"},
{++oid, ACCESS_READ | ACCESS_WRITE, TS_C_CAL, T_FLOAT32, 0, (void*) &(cal.solar_voltage_max), "vSolarMax"},
{++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"}
};
#endif
+4 -1
View File
@@ -1,4 +1,5 @@
#ifndef DISPLAY_H
#define DISPLAY_H
static unsigned char bmp_load [] = {
0x20, 0x22, 0x04, 0x70, 0x88, 0x8B, 0x88, 0x70, 0x04, 0x22, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00,
@@ -18,3 +19,5 @@ const unsigned char bmp_disconnected [] = {
0x08, 0x08, 0x08, 0x08, 0x00, 0x41, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x41, 0x00, 0x08, 0x08,
0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#endif // DISPLAY_H
+153 -261
View File
@@ -1,124 +1,122 @@
/* LibreSolar MPPT charge controller firmware
* 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.
*/
/* 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 UNIT_TEST
#include "mbed.h"
//#include "config_12a.h" // choose old PCB revision (12A)
#include "config.h" // choose new PCB revision (20A)
#include "config.h"
#include "data_objects.h"
#include "HalfBridge.h"
#include "AnalogValue.h"
#include "ChargeController.h"
#include "Adafruit_SSD1306.h"
//#include "SDFileSystem.h"
//#include "24LCxx_I2C.h"
#include <math.h> // log for thermistor calculation
#include "display.h"
//#define SDCARD_ENABLED
#define OLED_ENABLED
#include "output.h"
#include "output_can.h"
//----------------------------------------------------------------------------
// global variables
#ifdef SDCARD_ENABLED
SDFileSystem sd(PIN_UEXT_MOSI, PIN_UEXT_MISO, PIN_UEXT_SCK, PIN_UEXT_SSEL, "sd");
#endif
#ifdef OLED_ENABLED
I2C i2c(PIN_UEXT_SDA, PIN_UEXT_SCL);
Adafruit_SSD1306_I2c oled(i2c, PB_2, 0x78, 64, 128);
#endif
Serial serial(PIN_SWD_TX, PIN_SWD_RX, "serial");
Serial serial_uext(PIN_UEXT_TX, PIN_UEXT_RX, "serial_uext");
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
int pwm_delta = 1;
int dcdc_off_timestamp = -cal.dcdc_restart_interval; // start immediately
DigitalOut led_green(PIN_LED_GREEN);
DigitalOut led_red(PIN_LED_RED);
DigitalOut load_disable(PIN_LOAD_DIS);
DigitalOut can_disable(PIN_CAN_STB);
DigitalOut out_5v_enable(PIN_5V_OUT_EN);
DigitalOut uext_disable(PIN_UEXT_DIS);
#ifdef MPPT_20A
AnalogOut ref_i_dcdc(PIN_REF_I_DCDC);
#endif
AnalogIn v_ref(PIN_V_REF);
#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 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_voltage(PIN_TEMP_INT, 1.0);
#endif
#ifdef MPPT_12A
AnalogValue solar_voltage(PIN_V_SOLAR, 156.8 / 6.8); // solar voltage divider o-- 100k --o-- 5.6k --o
AnalogValue battery_voltage(PIN_V_BAT, 130 / 10); // battery voltage divider o-- 100k --o-- 10k --o
AnalogValue dcdc_current(PIN_I_DCDC, 1000 / 5 / 50); // op amp gain: 150/2.2 = 68.2, resistor: 2 mOhm
AnalogValue load_current(PIN_I_LOAD, 1000 / 5 / 50);
AnalogValue thermistor_voltage(PIN_TEMP_INT, 1.0);
#endif
AnalogValue thermistor_mosfets(PIN_TEMP_INT, 1.0);
AnalogValue thermistor_battery(PIN_TEMP_BAT, 1.0);
float temp_mosfets; // °C
ChargeController charger(profile);
float temperature; // °C
//C24LCXX_I2C eeprom(PIN_EEPROM_SDA, PIN_EEPROM_SCL, 0x07);
// for daily energy counting
int seconds_zero_solar = 0;
int seconds_day = 0;
int day_counter = 0;
bool nighttime = false;
float input_Wh_day = 0.0;
float output_Wh_day = 0.0;
float input_Wh_total = 0.0;
float output_Wh_total = 0.0;
//----------------------------------------------------------------------------
// function prototypes
void setup();
void update_measurements();
void update_screen();
void energy_counter();
void log_data();
void rtc_write_backup_reg(uint32_t BackupRegister, uint32_t data);
uint32_t rtc_read_backup_reg(uint32_t BackupRegister);
void update_mppt();
//----------------------------------------------------------------------------
int main()
{
Ticker tick1, tick2;
Ticker tick1, tick2, tick3;
setup();
wait(3); // safety feature: be able to re-flash before starting
time_t last_second = time(NULL);
tick1.attach(&update_measurements, 0.01);
tick2.attach(&update_mppt, 0.05);
//tick1.attach(&update_measurements, 0.01); // too often, may cause crash of MCU
tick2.attach(&update_mppt, 0.2);
//dcdc.start(0.5); // for testing only (don't run update_mppt!)
//time_state_changed = time(NULL) - 60*60*24; // start immediately
//tick3.attach(&can_send_data, 1);
int count_10s = 0;
while(1) {
update_measurements();
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);
// updates charger state machine
charger.update(battery_voltage.read(), dcdc_current.read());
@@ -130,12 +128,32 @@ int main()
load_disable = 1;
}
can_send_data();
energy_counter();
update_screen();
log_data();
device.bus_voltage = battery_voltage;
device.input_voltage = solar_voltage;
device.bus_current = dcdc_current;
device.input_current = dcdc_power / solar_voltage;
device.load_current = load_current;
device.external_temperature = temp_mosfets;
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
fflush(stdout);
}
sleep(); // wake-up by ticker interrupts
//sleep(); // wake-up by ticker interrupts
}
}
@@ -144,25 +162,22 @@ void setup()
{
led_green = 1;
load_disable = 1;
#ifdef MPPT_20A
can_disable = 0;
out_5v_enable = 0;
//uext_disable = 0;
ref_i_dcdc = 0.1; // 0 for buck, 1 for boost (TODO)
#endif
// for RTC backup register
__PWR_CLK_ENABLE(); // normally in SystemClock_Config()
HAL_PWR_EnableBkUpAccess();
set_time(rtc_read_backup_reg(0));
input_Wh_day = rtc_read_backup_reg(1);
output_Wh_day = rtc_read_backup_reg(2);
input_Wh_total = rtc_read_backup_reg(3);
output_Wh_total = rtc_read_backup_reg(4);
// adjust default values for 12V LiFePO4 battery
profile.num_cells = 4;
profile.cell_voltage_max = 3.55; // max voltage per cell
profile.cell_voltage_recharge = 3.35;
profile.trickle_enabled = false;
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 / solar_voltage_max, 0.97);
dcdc.duty_cycle_limits((float) profile.cell_voltage_load_disconnect * profile.num_cells / cal.solar_voltage_max, 0.97);
wait(0.2);
update_measurements();
@@ -170,63 +185,73 @@ void setup()
dcdc_current.calibrate_offset(0.0);
load_current.calibrate_offset(0.0);
//serial.baud(9600);
serial.baud(115200);
serial.printf("\nSerial interface started...\n");
#ifdef OLED_ENABLED
i2c.frequency(400000);
#endif
freopen("/serial", "w", stdout); // retarget stdout
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;
}
void update_mppt()
{
//serial.printf("B: %.2fV, %.2fA, S: %.2fV, Charger: %d, DCDC: %d, PWM: %.1f\n",
// battery_voltage.read(), dcdc_current.read(), solar_voltage.read(),
// charger.get_state(), dcdc.enabled(), dcdc.get_duty_cycle() * 100.0);
float dcdc_power_new = battery_voltage * dcdc_current;
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);
}
if (dcdc.enabled() == false && charger.charging_enabled() == true
&& battery_voltage < charger.read_target_voltage()
&& solar_voltage > battery_voltage + solar_voltage_offset_start)
&& 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)
{
dcdc.start(battery_voltage / (solar_voltage - 1.0));
serial.printf("MPPT start!\n");
dcdc.start(battery_voltage / (solar_voltage - 3.0)); // TODO: use factor (1V too low!)
led_red = 1;
}
else if (solar_voltage < battery_voltage + solar_voltage_offset_stop
|| dcdc_current < dcdc_current_min)
else if (dcdc.enabled() == true &&
((solar_voltage < battery_voltage + cal.solar_voltage_offset_stop
&& dcdc_current < cal.dcdc_current_min)
|| charger.charging_enabled() == false))
{
serial.printf("MPPT stop!\n");
dcdc.stop();
led_red = 0;
//serial.printf("DCDC stopped!\n");
}
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;
//serial.printf("DCDC stopped!\n");
}
}
else if (dcdc_current > charger.read_target_current()) {
// increase input voltage to decrease current
dcdc.duty_cycle_step(-1);
dcdc_off_timestamp = time(NULL);
}
else if (dcdc.enabled()) {
//printf("MPPT\n");
// start MPPT
if (dcdc_power > dcdc_power_new) {
pwm_delta = -pwm_delta;
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);
}
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);
}
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);
// 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;
@@ -251,8 +276,8 @@ void energy_counter()
if (nighttime && dcdc_power > 0.1) {
nighttime = false;
input_Wh_day = 0.0;
output_Wh_day = 0.0;
device.input_Wh_day = 0.0;
device.output_Wh_day = 0.0;
seconds_day = 0;
day_counter++;
}
@@ -260,60 +285,12 @@ void energy_counter()
seconds_day++;
}
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));
rtc_write_backup_reg(1, input_Wh_day);
rtc_write_backup_reg(2, output_Wh_day);
rtc_write_backup_reg(3, input_Wh_total);
rtc_write_backup_reg(4, output_Wh_total);
device.input_Wh_day += dcdc_power / 3600.0;
device.output_Wh_day += load_current * battery_voltage / 3600.0;
device.input_Wh_total += dcdc_power / 3600.0;
device.output_Wh_total += load_current * battery_voltage/ 3600.0;
}
void log_data()
{
//FILE *fp = fopen("/sd/solar_log.csv", "a");
FILE *fp = fopen("/serial_uext", "a");
if(fp == NULL) {
serial.printf("Could not open file for write\n");
fclose(fp);
return;
}
fprintf(fp, "%d;", (int)time(NULL));
fprintf(fp, "%d;", day_counter);
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 (charger.get_state()) {
case CHG_IDLE:
fprintf(fp, "Standby;");
break;
case CHG_CC:
fprintf(fp, "CC charge;");
break;
case CHG_CV:
fprintf(fp, "CV charge;");
break;
case CHG_TRICKLE:
fprintf(fp, "Trickle chg;");
break;
default:
fprintf(fp, "Error;");
break;
}
fprintf(fp, "\n");
fclose(fp);
}
//----------------------------------------------------------------------------
void update_measurements()
@@ -327,98 +304,13 @@ void update_measurements()
dcdc_current.update();
load_current.update();
#ifdef MPPT_20A
thermistor_voltage.update();
thermistor_mosfets.update();
// resistance of NTC (Ohm)
unsigned long rts = 10000.0 * thermistor_voltage.read() / (3.3 - thermistor_voltage.read());
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)
temperature = 1.0/(1.0/(273.15+25) + 1.0/thermistorBetaValue*log(rts/10000.0)) - 273.15;
temp_mosfets = 1.0/(1.0/(273.15+25) + 1.0/cal.thermistorBetaValue*log(rts/10000.0)) - 273.15;
}
#endif
}
uint32_t rtc_read_backup_reg(uint32_t BackupRegister) {
RTC_HandleTypeDef RtcHandle;
RtcHandle.Instance = RTC;
return HAL_RTCEx_BKUPRead(&RtcHandle, BackupRegister);
}
void rtc_write_backup_reg(uint32_t BackupRegister, uint32_t data) {
RTC_HandleTypeDef RtcHandle;
RtcHandle.Instance = RTC;
HAL_PWR_EnableBkUpAccess();
HAL_RTCEx_BKUPWrite(&RtcHandle, BackupRegister, data);
HAL_PWR_DisableBkUpAccess();
}
#ifdef OLED_ENABLED
void update_screen(void)
{
oled.clearDisplay();
oled.drawBitmap(6, 0, bmp_pv_panel, 16, 16, 1);
oled.drawBitmap(104, 0, bmp_load, 16, 16, 1);
if (dcdc.enabled() == false) {
oled.drawBitmap(27, 3, bmp_disconnected, 32, 8, 1);
}
else {
oled.drawBitmap(34, 3, bmp_arrow_right, 5, 7, 1);
}
if (load_disable == 1) {
oled.drawBitmap(81, 3, bmp_disconnected, 17, 7, 1);
}
else {
oled.drawBitmap(84, 3, bmp_arrow_right, 5, 7, 1);
}
oled.drawRect(52, 2, 18, 9, 1); // battery shape
oled.drawRect(69, 3, 3, 7, 1); // battery terminal
oled.drawRect(54, 4, 2, 5, 1); // bar 1
oled.drawRect(57, 4, 2, 5, 1); // bar 2
oled.drawRect(60, 4, 2, 5, 1); // bar 3
oled.drawRect(63, 4, 2, 5, 1); // bar 4
oled.drawRect(66, 4, 2, 5, 1); // bar 5
oled.setTextCursor(0, 18);
oled.printf("%4.1fV", solar_voltage.read());
oled.setTextCursor(0, 26);
oled.printf("%4.0fW", fabs(dcdc_power));
oled.setTextCursor(42, 18);
oled.printf("%5.2fV", battery_voltage.read());
oled.setTextCursor(42, 26);
oled.printf("%5.2fA", fabs(dcdc_current));
oled.setTextCursor(90, 18);
oled.printf("%5.2fA\n", fabs(load_current));
oled.setTextCursor(90, 26);
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("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");
break;
case CHG_CV:
oled.printf("CV charge\n");
break;
case CHG_TRICKLE:
oled.printf("Trickle chg\n");
break;
default:
oled.printf("Error\n");
break;
}
oled.display();
}
#endif // OLED
+196
View File
@@ -0,0 +1,196 @@
/* 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 "config.h"
#include "data_objects.h"
#include "HalfBridge.h"
#include "ChargeController.h"
#include "Adafruit_SSD1306.h"
#include "SSD1308.h"
#include "display.h"
Serial serial_uext(PIN_UEXT_TX, PIN_UEXT_RX, "serial_uext");
extern I2C i2c;
Adafruit_SSD1306_I2c oled(i2c, PIN_UEXT_SSEL, 0x78, 64, 128);
//SSD1308 oled = SSD1308(&i2c, SSD1308_SA0);
extern ChargeController charger;
extern HalfBridge dcdc;
//extern DeviceState device;
extern Serial serial;
//SDFileSystem sd(PIN_UEXT_MOSI, PIN_UEXT_MISO, PIN_UEXT_SCK, PIN_UEXT_SSEL, "sd");
void output_serial()
{
#ifdef SDCARD_ENABLED
//sd.mount();
FILE *fp = fopen("/sd/solar_log.csv", "a");
#else
//FILE *fp = fopen("/serial_uext", "a");
FILE *fp = fopen("/serial", "a");
#endif
if(fp == NULL) {
printf("Could not open file for write\n");
}
else {
char buffer[32];
time_t seconds = time(NULL)+60*60*2;
strftime(buffer, 32, "%F %T", localtime(&seconds));
//printf("Time as a custom formatted string = %s", buffer);
fprintf(fp, "%s;", buffer);
// fprintf(fp, "%d;", seconds_day);
// fprintf(fp, "%d;", day_counter);
fprintf(fp, "%.2f;%.1f;", device.input_voltage, device.bus_voltage * device.bus_current);
fprintf(fp, "%.2f;%.1f;", device.bus_voltage, device.bus_current);
fprintf(fp, "%.1f;%.2f;", device.load_current * device.bus_voltage, device.load_current);
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()) {
case CHG_IDLE:
fprintf(fp, "Standby;");
break;
case CHG_CC:
fprintf(fp, "CC;");
break;
case CHG_CV:
fprintf(fp, "CV;");
break;
case CHG_TRICKLE:
fprintf(fp, "Trickle;");
break;
default:
fprintf(fp, "Error;");
break;
}
fprintf(fp, "%.1f;", dcdc.get_duty_cycle() * 100.0);
fprintf(fp, "%d;", dcdc.enabled());
fprintf(fp, "\n");
}
fclose(fp);
#ifdef SDCARD_ENABLED
sd.unmount();
#endif
}
void output_serial_json()
{
serial.printf("{");
bool first = true;
for(unsigned int i = 0; i < sizeof(dataObjects)/sizeof(DataObject_t); ++i) {
if (first == false) {
serial.printf(",");
}
else {
first = false;
}
serial.printf("\"%s\":", dataObjects[i].name);
switch (dataObjects[i].type) {
case T_FLOAT32:
serial.printf("%.3f", *((float*)dataObjects[i].data));
break;
case T_STRING:
serial.printf("\"%s\"", (char*)dataObjects[i].data);
break;
case T_INT32:
serial.printf("%d", *((int*)dataObjects[i].data));
break;
case T_BOOL:
serial.printf("%s", (*((bool*)dataObjects[i].data) == true ? "true" : "false"));
break;
}
}
serial.printf("}\n");
}
void output_oled()
{
i2c.frequency(100000);
oled.clearDisplay();
oled.drawBitmap(6, 0, bmp_pv_panel, 16, 16, 1);
oled.drawBitmap(104, 0, bmp_load, 16, 16, 1);
if (dcdc.enabled() == false) {
oled.drawBitmap(27, 3, bmp_disconnected, 32, 8, 1);
}
else {
oled.drawBitmap(34, 3, bmp_arrow_right, 5, 7, 1);
}
if (device.load_enabled) {
oled.drawBitmap(84, 3, bmp_arrow_right, 5, 7, 1);
}
else {
oled.drawBitmap(81, 3, bmp_disconnected, 17, 7, 1);
}
oled.drawRect(52, 2, 18, 9, 1); // battery shape
oled.drawRect(69, 3, 3, 7, 1); // battery terminal
oled.drawRect(54, 4, 2, 5, 1); // bar 1
oled.drawRect(57, 4, 2, 5, 1); // bar 2
oled.drawRect(60, 4, 2, 5, 1); // bar 3
oled.drawRect(63, 4, 2, 5, 1); // bar 4
oled.drawRect(66, 4, 2, 5, 1); // bar 5
oled.setTextCursor(0, 18);
oled.printf("%4.1fV", device.input_voltage);
oled.setTextCursor(0, 26);
oled.printf("%4.0fW", fabs(device.bus_voltage * device.bus_current));
oled.setTextCursor(42, 18);
oled.printf("%5.2fV", device.bus_voltage);
oled.setTextCursor(42, 26);
oled.printf("%5.2fA", fabs(device.bus_current));
oled.setTextCursor(90, 18);
oled.printf("%5.2fA\n", fabs(device.load_current));
oled.setTextCursor(90, 26);
oled.printf("%5.1fW", fabs(device.load_current) * device.bus_voltage);
oled.setTextCursor(0, 36);
oled.printf("Day +%5.0fWh -%5.0fWh", device.input_Wh_day, fabs(device.output_Wh_day));
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()) {
case CHG_IDLE:
oled.printf("Idle\n");
break;
case CHG_CC:
oled.printf("CC charge\n");
break;
case CHG_CV:
oled.printf("CV charge\n");
break;
case CHG_TRICKLE:
oled.printf("Trickle chg\n");
break;
default:
oled.printf("Error\n");
break;
}
oled.display();
}
+9
View File
@@ -0,0 +1,9 @@
#ifndef OUTPUT_H
#define OUTPUT_H
//void output_wifi();
void output_serial();
void output_serial_json();
void output_oled();
#endif
+305
View File
@@ -0,0 +1,305 @@
/* LibreSolar Battery Management System 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 "output.h"
#include "output_can.h"
#include "data_objects.h"
#include "HalfBridge.h"
#include "ChargeController.h"
extern Serial serial;
extern CAN can;
CANMsgQueue can_tx_queue;
CANMsgQueue can_rx_queue;
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;
}
}
//----------------------------------------------------------------------------
// preliminary simple CAN functions to send data to the bus for logging
// Data format based on CBOR specification (except for first byte, which uses
// only 6 bit to specify type and transport protocol)
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;
// first byte: TinyTP-header or data type for single frame message
// currently: no multi-frame and no timestamp
msg.data[0] = 0x00;
int32_t value;
uint32_t value_abs;
uint8_t exponent_abs;
// CBOR byte order: most significant byte first
switch (data_obj.type) {
case T_FLOAT32:
msg.len = 5;
msg.data[0] |= TS_T_FLOAT32;
f2b.f = *((float*)data_obj.data);
msg.data[1] = f2b.b[3];
msg.data[2] = f2b.b[2];
msg.data[3] = f2b.b[1];
msg.data[4] = f2b.b[0];
break;
case T_INT32:
if (data_obj.exponent == 0) {
msg.len = 5;
value = *((int*)data_obj.data);
value_abs = abs(value);
if (value >= 0) {
msg.data[0] |= TS_T_POS_INT32;
value_abs = abs(value);
}
else {
msg.data[0] |= TS_T_NEG_INT32;
value_abs = abs(value - 1); // 0 is always pos integer
}
msg.data[1] = value_abs >> 24;
msg.data[2] = value_abs >> 16;
msg.data[3] = value_abs >> 8;
msg.data[4] = value_abs;
}
else {
msg.len = 8;
msg.data[0] |= TS_T_DECIMAL_FRAC;
msg.data[1] = 0x82; // array of length 2
// exponent in single byte value, valid: -24 ... 23
exponent_abs = abs(data_obj.exponent);
if (data_obj.exponent >= 0 && data_obj.exponent <= 23) {
msg.data[2] = exponent_abs;
}
else if (data_obj.exponent < 0 && data_obj.exponent > -24) {
msg.data[2] = (exponent_abs - 1) & 0x20; // negative uint8
}
// value as positive or negative uint32
value = *((int*)data_obj.data);
value_abs = abs(value);
if (value >= 0) {
msg.data[3] = 0x1a; // positive int32
value_abs = abs(value);
}
else {
msg.data[3] = 0x3a; // negative int32
value_abs = abs(value - 1); // 0 is always pos integer
}
msg.data[4] = value_abs >> 24;
msg.data[5] = value_abs >> 16;
msg.data[6] = value_abs >> 8;
msg.data[7] = value_abs;
}
break;
case T_BOOL:
msg.len = 1;
if (*((bool*)data_obj.data) == true) {
msg.data[0] = 0xf5; // simple type: true
}
else {
msg.data[0] = 0xf4; // simple type: false
}
break;
case T_STRING:
break;
}
can_tx_queue.enqueue(msg);
}
void can_send_data()
{
for (unsigned int i = 0; i < sizeof(dataObjects)/sizeof(DataObject_t); ++i) {
can_pub_msg(dataObjects[i]);
}
}
void can_process_outbox()
{
int max_attempts = 15;
while (!can_tx_queue.empty() && max_attempts > 0) {
CANMessage msg;
can_tx_queue.first(msg);
if(can.write(msg)) {
can_tx_queue.dequeue();
}
else {
//serial.printf("Sending CAN message failed, err: %u, MCR: %u, MSR: %u, TSR: %u, id: %u\n", can.tderror(), (uint32_t)CAN1->MCR, (uint32_t)CAN1->MSR, (uint32_t)CAN1->TSR, msg.id);
}
max_attempts--;
}
}
void can_list_object_ids(int category) {
}
void can_send_object_name(int data_obj_id) {
uint8_t msg_priority = 7; // low priority service message
uint8_t function_id = 0x84;
CANMessage msg;
msg.format = CANExtended;
msg.type = CANData;
msg.id = msg_priority << 26 | function_id << 16 | can_node_id; // TODO: add destination node ID
int arr_id = -1;
for (arr_id = 0; arr_id < sizeof(dataObjects)/sizeof(DataObject_t); arr_id++) {
if (dataObjects[arr_id].id == data_obj_id) {
break; // correct array entry found
}
}
if (arr_id >= 0) {
if (dataObjects[arr_id].access & ACCESS_READ) {
msg.data[2] = T_STRING;
int len = strlen(dataObjects[arr_id].name);
for (int i = 0; i < len && i < (8-3); i++) {
msg.data[i+3] = *(dataObjects[arr_id].name + i);
}
msg.len = ((len < 5) ? 3 + len : 8);
serial.printf("TS Send Object Name: %s (id = %d)\n", dataObjects[arr_id].name, data_obj_id);
}
}
else {
// send error message
// data[0] : ISO-TP header
msg.data[1] = 1; // TODO: Define error code numbers
msg.len = 2;
}
can_tx_queue.enqueue(msg);
}
void can_process_inbox() {
int max_attempts = 15;
while (!can_rx_queue.empty() && max_attempts >0) {
CANMessage msg;
can_rx_queue.dequeue(msg);
if (!(msg.id & (0x1U<<25))) {
serial.printf("CAN ID bit 25 = 1 --> ignored\n");
continue; // might be SAE J1939 or NMEA 2000 message --> ignore
}
if (msg.id & (0x1U<<24)) {
serial.printf("Data object publication frame\n");
// data object publication frame
} else {
serial.printf("Service frame\n");
// service frame
int function_id = (msg.id >> 16) & (int)0xFF;
int data_obj_id;
int value;
switch (function_id) {
case TS_WRITE:
data_obj_id = msg.data[1] + (msg.data[2] << 8);
value = msg.data[6] + (msg.data[7] << 8);
for (unsigned int i = 0; i < sizeof(dataObjects)/sizeof(DataObject_t); ++i) {
if (dataObjects[i].id == data_obj_id) {
if (dataObjects[i].access & ACCESS_WRITE) {
// TODO: write data
serial.printf("ThingSet Write: %d to %s (id = %d)\n", value, dataObjects[i].name, data_obj_id);
} else {
serial.printf("No write allowed to data object %s (id = %d)\n", dataObjects[i].name, data_obj_id);
}
break;
}
}
break;
case TS_OBJ_NAME:
data_obj_id = msg.data[1] + (msg.data[2] << 8);
can_send_object_name(data_obj_id);
serial.printf("Get Data Object Name: %d\n", data_obj_id);
break;
case TS_LIST:
can_list_object_ids(msg.data[1]);
serial.printf("List Data Object IDs: %d\n", msg.data[1]);
break;
}
}
max_attempts--;
}
}
void can_receive() {
CANMessage msg;
while (can.read(msg)) {
if (!can_rx_queue.full()) {
can_rx_queue.enqueue(msg);
serial.printf("Message received. id: %d, data: %d\n", msg.id, msg.data[0]);
} else {
serial.printf("CAN rx queue full\n");
}
}
}
+47
View File
@@ -0,0 +1,47 @@
#ifndef OUTPUT_CAN_H
#define OUTPUT_CAN_H
#include "mbed.h"
#include "config.h"
#include "data_objects.h"
#define PUB_MULTIFRAME_EN (0x1U << 7)
#define PUB_TIMESTAMP_EN (0x1U << 6)
// Protocol functions
#define TS_READ 0x00
#define TS_WRITE 0x01
#define TS_PUB_REQ 0x02
#define TS_SUB_REQ 0x03
#define TS_OBJ_NAME 0x04
#define TS_LIST 0x05
#define CAN_QUEUE_SIZE 30
static uint8_t can_node_id = CAN_NODE_ID;
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;
};
void can_send_data();
void can_receive();
void can_process_outbox();
void can_process_inbox();
void can_list_object_ids(int category = TS_C_ALL);
void can_send_object_name(int obj_id);
#endif
-18
View File
@@ -1,18 +0,0 @@
from SCons.Script import DefaultEnvironment
from os.path import join
env = DefaultEnvironment()
env.Replace(
# UPLOADER=join("$PIOPACKAGES_DIR", "tool-stlink", "st-flash"),
MYUPLOADERFLAGS=[
"--reset", # reset board before and after flashing
"write", # write in flash
"$SOURCES", # firmware path to flash
"0x08000000" # flash start adress
],
UPLOADCMD='$UPLOADER $MYUPLOADERFLAGS',
)
#print env.Dump()
#print ARGUMENTS