// so this should be close to a test run
// currently burning down a real EGO
// but using a juice pack for 5 volts
// too: added some printing for OpenLogger
// TO DO
// _x_ add "engage" and "abort" buttons, latch and wait
// caibration
// floatItAlpha - crude full but using 1/2 voltages
// floatIt - version N, here we are moving to floating point for
// talking about all voltages
# include "U8glib.h"
# include "jbutton.h"
long int gTimer; // just seconds crudley for now
unsigned int processTimer; // for display of up or down counting time
// empirical a/d constant. version X: calibrate feature
// in a perfect world it is the band gap voltage
// combines all linear factors
int rawBatteryCount; // battery input voltage
int calibrationCount; // calibration pot
const float batteryNominalVoltage = 58.8;
const byte nCells = 14; // 58.8 volt battery or 51.8 @ 3.7 volts/cell
const float targetCellVoltage = 3.75; // get the best number for this
float cellVoltage;
float batteryVoltage;
bool halfVoltageMode;
//... 15 minutes, prolly enough
const unsigned long recoverTime = 15L * 60 * 1000; // in millis ATM
U8GLIB_SSD1306_128X32 u8g(U8G_I2C_OPT_NONE);
// relays
const byte vbPlus = 2; // red iso relay
const byte vbMinus = 3; // black iso relay
const byte loadA = 4; // loadA
const byte loadX = 5; // extra load wired now as dependent on load
// analog
const byte vBATT = A0;
const byte vCALIB = A1;
// pilot lamps
const byte heartBeat = 13;
const byte powered = 8; // FSM running/not
const byte recovering = 12; // yellow
const byte discharging = A3; // red
// this is not the entire story, careful
# define ON HIGH
# define OFF LOW
// jButtons
const byte engageButton = 9;
const byte abortButton = 11; // and we have 10 for its lamp
const byte increaseCC = A1;
const byte decreaseCC = A2;
enum {ENGAGE, ABORT, INCCC, DECCC}; // start the discharge FSM; HCF (halt and (don't) catch fire)
jButton buttonX[] = {engageButton, abortButton, increaseCC, decreaseCC };
const byte nJButtons = sizeof buttonX / sizeof *buttonX;
// the FSM
enum { IDLE = 0, DISCHARGE, RECOVER, RECALC, FINI, DIE, DEAD};
const char *tags[] = {"Idle", "Work", "Rest", "Repeat", "Done.", "Dying", "Dead"};
unsigned char state;
const int TRY = 7; // max recover/retry cycles: way enough, stop early if
int tries; // number of recovery/discharge cycles
unsigned long now; // always the millis();
bool logRequest; // extra logging request flag
int pLevel = -1; // valid 0, 1 or 2 -
// right now: leave references INTERNAL
// use an empirical value for the constant
void readAnalogInputs()
{
// analogReference(DEFAULT);
// analogRead(vCALIB);
delay(10); // leaving for now as it is part of the timing
// calibrationCount = analogRead(vCALIB);
// calibrationCount = 255; // empirical
//... wokwi does not use INTERNAL -->
analogReference(INTERNAL);
analogRead(vBATT);
delay(10);
rawBatteryCount = analogRead(vBATT);
// xprintf("%d %d\n", rawBatteryCount, calibrationCount);
}
void setup()
{
// assumes HIGH = energized
pinMode(vbPlus, OUTPUT);
pinMode(vbMinus, OUTPUT);
pinMode(loadA, OUTPUT);
pinMode(loadX, OUTPUT);
pinMode(powered, OUTPUT);
pinMode(discharging, OUTPUT);
pinMode(recovering, OUTPUT);
pinMode(heartBeat, OUTPUT);
// jButtons
for (int ii = 0; ii < nJButtons; ii++)
buttonX[ii].begin();
analogReference(INTERNAL);
// engage the isolation relays and latch this thing ON
digitalWrite(vbPlus, ON);
digitalWrite(vbMinus, ON);
// battery unloaded ATM - should be
loadOFF();
// lamp is engaged bool indicator
digitalWrite(powered, LOW);
mySetup(9600); // I know. for OpenLogger
xprintf("\nhello world.\n");
setupOLED();
// setupAnalog();
// prime the LPF before any validity
calibrationCount = 255; // empirical. now tweakable.
for (int ii = 0; ii < 10; ii++) {
readAnalogInputs();
calculateVoltages();
}
halfVoltageMode = batteryVoltage < 35.0; // add an indicator to the display when true
loopz(); // draw the OLED. panes?
}
void setupOLED() {
u8g.setFont(u8g_font_unifont);
u8g.setColorIndex(1);
}
bool engaged; // manual global control of do/don't default not automatic
bool burning;
// a little test boost
void loop()
{
static unsigned long lastHeartBeat;
static unsigned long lastPass;
now = millis();
gTimer = millis() / 1000; // 10,000? Argh!
static long lastGTime;
if (lastGTime != gTimer) {
// Serial.print(gTimer);
handleTimer();
lastGTime = gTimer;
}
if (now - lastHeartBeat > 389) {
digitalWrite(heartBeat, digitalRead(heartBeat) == LOW ? HIGH : LOW);
lastHeartBeat = now;
}
if (now - lastPass < 50) return; // throttle to 20 Hz
lastPass = now;
checkCalibration();
readAnalogInputs(); // set rawBatteryCount and calibrationCount eats the time slice for now
calculateVoltages();
// log section. every N seconds or on request
static long lastVoltageReport;
if (gTimer - lastVoltageReport >= 15 || logRequest) {
char buffer[10];
dtostrf(batteryVoltage, 6, 2, buffer);
xprintf("%ld %d %s %s %d\n", gTimer, rawBatteryCount, buffer, tags[state], pLevel);
lastVoltageReport = gTimer;
logRequest = false;
}
checkButtons();
if (engaged) batteryFSM();
else loadOFF();
loopz();
}
// just check if we want to + or - the constant.
void checkCalibration()
{
buttonX[INCCC].loop();
buttonX[DECCC].loop();
if (buttonX[INCCC].isPress())
calibrationCount++;
if (buttonX[DECCC].isPress())
calibrationCount++;
}
void calculateVoltages()
{
float calibratedAdjustment =
1.0 + 0.2 * calibrationCount / 1024.0; // 1 to 1.2, not quite enough
float voltageScale = halfVoltageMode ? 2.0 : 1.0;
float newBatteryVoltage = rawBatteryCount / 1024.0
* calibratedAdjustment
* batteryNominalVoltage
* voltageScale;
// leaky integrator LPF
batteryVoltage = 0.75 * batteryVoltage + 0.25 * newBatteryVoltage;
cellVoltage = batteryVoltage / nCells;
}
void checkButtons()
{
buttonX[ENGAGE].loop();
buttonX[ABORT].loop();
// toggle FSM on/off crudely
if (buttonX[ENGAGE].isPress()) {
engaged = !engaged;
if /* engaging */ (engaged) {
}
else /* disnegaging */ {
state = IDLE; // machinery stalled until manually re-engaged
}
//xprintf("well I never %ld %lu\n", xL, xUL);
xprintf("* %ld Now%s engaged %.\n", gTimer, engaged ? "" : " not");
digitalWrite(powered, engaged ? HIGH : LOW);
}
// abort. do not pass Go, do not collect $200.
if (buttonX[ABORT].isPress()) {
engaged = false; // if the code even runs (power is cut soon-ish)
state = FINI; // but literally we are shutting off the power at the isolation relays
digitalWrite(loadA, OFF);
digitalWrite(loadX,OFF);
digitalWrite(vbPlus, LOW);
digitalWrite(vbMinus, LOW);
}
}
void batteryFSM()
{
static unsigned long timer;
if (cellVoltage < 2.5) {
loadOFF(); // should already be
xprintf("UNDER VOLTAGE %s", tags[state]);
state = DIE;
}
if (cellVoltage - targetCellVoltage < 0.05)
static int lastState = -1;
if (lastState != state) {
xprintf("* %ld %s\n", gTimer, tags[state]);
lastState = state;
}
// it starts power on and latched dust settled
switch (state) {
case IDLE :
tries = 0;
state = DISCHARGE;
processTimer = 0; // we'll count up as the battery is discharging
break;
case DISCHARGE :
if (tries == 0) loadFULL();
else loadHALF();
if (cellVoltage <= targetCellVoltage) {
timer = now;
loadOFF();
state = RECOVER;
processTimer = recoverTime / 1000; // and down as the battery is in recovery
}
break;
case RECOVER :
if (now - timer >= recoverTime) {
state = RECALC;
}
break;
case RECALC :
tries++;
if (tries >= TRY) state = FINI;
else state = DISCHARGE;
break;
case FINI :
loadOFF();
digitalWrite(vbPlus, OFF);
digitalWrite(vbMinus, OFF);
xprintf("* %ld the system is without power, dead.\n", gTimer);
Serial.flush();
state = DIE;
break;
// and catch that DIE phase somewhere because...
case DIE :
state = DEAD;
break;
case DEAD : // this code should never execute. should it run the UI in some meaningful way?
// I think all paths here are impossible because the FSM is not engaged
break;
}
digitalWrite(recovering, state == RECOVER ? HIGH : LOW); // yellow
digitalWrite(discharging, state == DISCHARGE ? HIGH : LOW); // red
}
// state dictates counting up or counting down the process time
// there may be a timing issue or race here when state is neither
// process we want time displayed for
void handleTimer()
{
if (state == DISCHARGE) processTimer++;
else if (state == RECOVER) processTimer--;
}
// connect 0, 1 or both 100 ohm resistors. set pLevel
void loadOFF() {
// always write the relays
digitalWrite(loadA, OFF);
digitalWrite(loadX,OFF);
// but report changes only
if (pLevel != 0) {
xprintf("+ %ld NO LOAD\n", gTimer);
pLevel = 0;
}
}
void loadHALF() {
digitalWrite(loadA, ON);
digitalWrite(loadX,OFF);
if (pLevel != 1) {
xprintf("+ %ld HALF LOAD\n", gTimer);
pLevel = 1;
}
}
void loadFULL() {
digitalWrite(loadA, ON);
digitalWrite(loadX,ON);
if (pLevel != 2) {
xprintf("+ %ld FULL LOAD\n", gTimer);
pLevel = 2;
}
}
// u8g by pages
void loopz(void) {
u8g.firstPage();
do {
draw();
} while (u8g.nextPage());
}
// redraw the entire OLED display
/*
01234567890123456
01234567890123456
*/
void draw(void) {
char buffer[10];
float displayVoltage = round(batteryVoltage * 10.0 + 0.5) / 10.0;
u8g.setPrintPos(0, 10);
u8g.print(displayVoltage, 1);
int minutes = processTimer / 60;
int seconds = processTimer - 60 * minutes;
sprintf(buffer, "%3d:%02d", minutes, seconds);
u8g.drawStr(62, 10, buffer);
dtostrf(cellVoltage, 6, 2, buffer);
if (halfVoltageMode) buffer[0] = 'X';
u8g.drawStr(0, 30, buffer);
u8g.drawStr(62, 30, tags[state]);
}
// test of some kind
// redraw the entire OLED display
void drawX(void) {
u8g.drawStr( 0, 10, "Seriously");
u8g.drawStr( 0, 32, "LINE COUNTER");
}
void drawY(void) {
char buffer[10];
u8g.setPrintPos(0, 10);
u8g.print(batteryVoltage);
// TIMER
u8g.setPrintPos(64, 10);
// MMM:SS maintained by the basic loop going up or down by state/transition
// u8g.print("MMM:SS");
u8g.print(processTimer); // seconds for now up or down and init
dtostrf(cellVoltage, 6, 2, buffer);
if (halfVoltageMode) buffer[0] = 'X';
u8g.drawStr(0, 30, buffer);
u8g.drawStr(62, 30, tags[state]);
}
// programmer misses printf...
void xprintf(const char *format, ...)
{
char buffer[256];
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
Serial.print(buffer);
}
// programmer forgets day of week, version
void mySetup(unsigned long bandRate)
{
Serial.begin(bandRate);
char s[] = __FILE__;
byte b = sizeof(s);
while ( (b > 0) && (s[b] != 47)) b--;
char *u = s + b + 1;
xprintf("\nHEllo WOrld!\n");
xprintf("%s %s\n\n", __DATE__, u);
xprintf("!\n");
}B ...... R
Loading
ssd1306
ssd1306
X+ ...... X
ABORT ...... ENGAGE