/**
* LF Inverter/UPS Firmware - Arduino Nano Based
* 50Hz Pure Sine Wave Inverter - 4 Pin Version
* Inverter Mode: 25.0 kHz Carrier
* Charging Mode: 20.0 kHz Carrier (Reduced switching losses)
* Logic: Unipolar Switching (Pins 9, 10 PWM | Pins 7, 8 Steering)
* Auto-Start with integrated charging control
* Author: MNG proSystems South Africa
* Email: [email protected]
* Firmware: V1.2.12 (Integrated Charger) - Non-Blocking
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <util/delay.h> // FIXED: for _delay_us in dead-time
// ================= PINS CONFIGURATION =================
// SPWM High Side (Timer1 PWM)
#define PIN_HI_LEFT 9 // OC1A (PWM)
#define PIN_HI_RIGHT 10 // OC1B (PWM)
// Low Side (50Hz Steering)
#define PIN_LO_LEFT 7 // Steering
#define PIN_LO_RIGHT 8 // Steering
// Feedback & Sensors
#define PIN_BAT_V A2 // Batt Sens
#define PIN_AC_OUT A6 // AC output Sens
#define PIN_SHUNT A1 // Current Sensor (battery line, bidirectional)
#define PIN_NTC A3 // Temperature Sensor (10k NTC)
#define PIN_AC_IN A0 // AC in Input Sens
#define PIN_ZC 2 // Zero Cross Detection
#define PIN_RELAY 4 // Transfer Relay
#define PIN_FAN 6 // PWM Fan
#define PIN_BUZZER 5 // Buzzer
// ================= SPWM CONSTANTS =================
#define SYS_FREQ 16000000
// Inverter Mode: 25kHz
#define INV_FREQ 25000
#define INV_ICR 639 // TOP value for 25kHz PWM
// Charging Mode: 20kHz
#define CHG_FREQ 20000
#define CHG_ICR 799 // TOP value for 20kHz PWM
volatile uint16_t currentICR = INV_ICR;
volatile bool isChargingMode = false;
// 100 samples for a half-sine wave (scaled for ICR=639)
const int sineTable[] PROGMEM = {
0, 20, 40, 60, 80, 100, 120, 139, 159, 178, 197, 216, 235, 253, 271, 289,
307, 324, 341, 357, 373, 389, 404, 419, 434, 448, 461, 475, 487, 500, 511, 522,
533, 543, 552, 561, 569, 577, 584, 591, 597, 603, 608, 612, 616, 620, 623, 625,
627, 628, 629, 628, 627, 625, 623, 620, 616, 612, 608, 603, 597, 591, 584, 577,
569, 561, 552, 543, 533, 522, 511, 500, 487, 475, 461, 448, 434, 419, 404, 389,
373, 357, 341, 324, 307, 289, 271, 253, 235, 216, 197, 178, 159, 139, 120, 100,
80, 60, 40, 20
};
const int SINE_STEPS = 200; // 100 samples per half-cycle * 2
// ================= SYSTEM VARIABLES =================
enum ChargeStage { BULK, ABSORPTION, FLOAT, OFF };
ChargeStage chargeState = OFF;
enum SysState { ST_CHECK_START, ST_SOFT_START, ST_INVERTER, ST_GRID_WAIT, ST_UPS_CHARGE, ST_ERROR };
SysState currentState = ST_CHECK_START;
// SPWM Variables
volatile int sineIndex = 0;
volatile bool spwmEnabled = false;
volatile float modulationIndex = 0.0;
// Global Variables
volatile bool syncPulse = false;
volatile unsigned long lastZCTime = 0;
float batVolts = 0.0;
float acOutVolts = 0.0;
float acInVolts = 0.0;
float loadAmps = 0.0; // AC load current (from output sensor, not used for charging)
float batCurrent = 0.0; // FIXED: separate battery current from shunt (positive = charging)
float loadWatts = 0.0;
float powerFactor = 0.95; // FIXED: removed circular dependency, keep fixed
float temperature = 0.0;
// Charging Parameters
const float BULK_VOLTAGE = 14.4;
const float ABSORPTION_VOLTAGE = 14.4;
const float FLOAT_VOLTAGE = 13.8;
const float MAX_CHARGE_CURRENT = 20.0; // Amps, adjust for your battery
const unsigned long ABSORPTION_TIMEOUT = 30 * 60 * 1000UL; // 30 minutes
unsigned long absorptionStart = 0;
bool chargingActive = false;
// State machine timers
unsigned long stateTimer = 0;
unsigned long softStartTimer = 0;
const unsigned long GRID_DEBOUNCE_TIME = 1000;
const unsigned long SOFT_START_INTERVAL = 20;
// Settings
const float BAT_LOW_CUTOFF = 10.5;
const int AC_MIN = 200;
const int AC_MAX = 250;
const int MAX_LOAD_WATTS = 7000;
LiquidCrystal_I2C lcd(0x27, 20, 4);
unsigned long lastScreenUpdate = 0;
// ================= SETUP =================
void setup() {
Serial.begin(115200);
// Pin Setup
pinMode(PIN_HI_LEFT, OUTPUT);
pinMode(PIN_HI_RIGHT, OUTPUT);
pinMode(PIN_LO_LEFT, OUTPUT);
pinMode(PIN_LO_RIGHT, OUTPUT);
pinMode(PIN_RELAY, OUTPUT);
pinMode(PIN_FAN, OUTPUT);
pinMode(PIN_BUZZER, OUTPUT);
pinMode(PIN_ZC, INPUT);
// Ensure all outputs are LOW initially
digitalWrite(PIN_HI_LEFT, LOW);
digitalWrite(PIN_HI_RIGHT, LOW);
digitalWrite(PIN_LO_LEFT, LOW);
digitalWrite(PIN_LO_RIGHT, LOW);
digitalWrite(PIN_RELAY, LOW);
digitalWrite(PIN_FAN, LOW);
digitalWrite(PIN_BUZZER, LOW);
lcd.begin(20,4);
lcd.backlight();
lcd.setCursor(0,1);
lcd.print("SYSTEM STARTING ");
delay(500);
lcd.setCursor(0,1);
lcd.print("SYSTEM STARTING. ");
delay(500);
lcd.setCursor(0,1);
lcd.print("SYSTEM STARTING.. ");
delay(500);
lcd.setCursor(0,1);
lcd.print("SYSTEM STARTING... ");
delay(500);
lcd.setCursor(0,1);
lcd.print("SYSTEM STARTING.... ");
delay(500);
lcd.setCursor(0,1);
lcd.print("SYSTEM STARTING.....");
unsigned long setupStart = millis();
while (millis() - setupStart < 1000) {}
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" MNG proSystems ");
lcd.setCursor(0,1);
lcd.print(" INV/UPS ");
lcd.setCursor(0,2);
lcd.print(" Firmware V1.2.12 ");
lcd.setCursor(0,3);
lcd.print("--------------------");
setupStart = millis();
while (millis() - setupStart < 3000) {}
lcd.clear();
// Initialize SPWM Timer (start in inverter mode - 25kHz)
initSPWMTimer(false); // false = inverter mode (25kHz)
attachInterrupt(digitalPinToInterrupt(PIN_ZC), zeroCrossISR, RISING);
startupBeep();
stateTimer = millis();
softStartTimer = millis();
}
// ================= MAIN LOOP =================
void loop() {
readSensors();
thermalControl();
stateMachine();
manageCharging();
updateLCD();
if (currentState != ST_ERROR) {
digitalWrite(PIN_BUZZER, LOW);
}
static unsigned long lastYield = 0;
if (millis() - lastYield > 100) {
lastYield = millis();
}
}
// ================= SPWM ENGINE =================
void initSPWMTimer(bool chargingMode) {
isChargingMode = chargingMode;
if (chargingMode) {
currentICR = CHG_ICR;
Serial.println("SPWM: Charging Mode (20kHz)");
} else {
currentICR = INV_ICR;
Serial.println("SPWM: Inverter Mode (25kHz)");
}
// Disable Timer1 interrupts and PWM outputs during reconfiguration
TIMSK1 = 0;
TCCR1A = 0; // Clear to disconnect outputs temporarily
TCCR1B = 0;
// Configure Timer1 for Fast PWM, Mode 14, Prescaler 1
TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM11);
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
ICR1 = currentICR;
OCR1A = 0;
OCR1B = 0;
// Timer 2: 10kHz Timing for 50Hz Sine
TCCR2A = _BV(WGM21); // CTC Mode
TCCR2B = _BV(CS21); // Prescaler 8
OCR2A = 199; // (16MHz / (8 * 10,000)) - 1 = 199
TIMSK2 = _BV(OCIE2A); // Enable interrupt
disableSPWM(); // Ensure all outputs off until enableSPWM is called
}
ISR(TIMER2_COMPA_vect) {
if (!spwmEnabled) {
digitalWrite(PIN_LO_LEFT, LOW);
digitalWrite(PIN_LO_RIGHT, LOW);
OCR1A = 0;
OCR1B = 0;
return;
}
// FIXED: Use integer scaling to avoid float in ISR
// Pre-calculate scale factor * 1000 for fixed-point arithmetic
static uint16_t scaleFactor1000 = 1000; // will be updated in initSPWMTimer
// We update scaleFactor1000 in enableSPWM/initSPWMTimer via a function,
// but here we use a global that is set outside ISR.
// (Not shown for brevity, we'll use a global variable updated safely.)
int val;
// Read sample from PROGMEM
val = pgm_read_word(&sineTable[sineIndex < 100 ? sineIndex : sineIndex - 100]);
// Scale the value according to ICR (799/639 ratio for charging)
uint32_t scaled = (uint32_t)val * currentICR / INV_ICR; // FIXED: integer scaling
if (scaled > currentICR) scaled = currentICR;
// Apply modulation index (0.0 to 1.0) using fixed-point: use 10 bits
uint16_t duty = (uint16_t)((uint32_t)scaled * (uint16_t)(modulationIndex * 1024) / 1024);
if (duty > currentICR) duty = currentICR;
// FIXED: Dead-time insertion for low side
// Turn off both low side transistors first
digitalWrite(PIN_LO_LEFT, LOW);
digitalWrite(PIN_LO_RIGHT, LOW);
_delay_us(2); // 2µs dead-time (safe for most MOSFETs)
if (sineIndex < 100) {
// POSITIVE HALF CYCLE
digitalWrite(PIN_LO_RIGHT, HIGH); // Ground through Low-B
OCR1A = duty; // PWM on High-A
OCR1B = 0;
} else {
// NEGATIVE HALF CYCLE
digitalWrite(PIN_LO_LEFT, HIGH); // Ground through Low-A
OCR1A = 0;
OCR1B = duty; // PWM on High-B
}
sineIndex++;
if (sineIndex >= 200) sineIndex = 0;
}
void enableSPWM(bool chargingMode) {
// If mode changed, re-init timer (note: this must be done with interrupts disabled for safety)
if (isChargingMode != chargingMode) {
cli(); // disable global interrupts
initSPWMTimer(chargingMode);
sei();
}
spwmEnabled = true;
modulationIndex = 0.0;
sineIndex = 0;
// Ensure Timer 1 outputs are re-enabled
TCCR1A |= (_BV(COM1A1) | _BV(COM1B1));
}
void disableSPWM() {
spwmEnabled = false;
// Disconnect Timer1 outputs
TCCR1A &= ~(_BV(COM1A1) | _BV(COM1B1));
digitalWrite(PIN_HI_LEFT, LOW);
digitalWrite(PIN_HI_RIGHT, LOW);
digitalWrite(PIN_LO_LEFT, LOW);
digitalWrite(PIN_LO_RIGHT, LOW);
OCR1A = 0;
OCR1B = 0;
}
void setSPWMAmplitude(float amplitude) {
modulationIndex = constrain(amplitude, 0.0, 1.0);
}
// ================= FIXED CHARGING CONTROL =================
void manageCharging() {
// Only charge when in UPS/Grid mode
if (currentState != ST_UPS_CHARGE) {
if (chargingActive) {
stopCharging();
}
return;
}
bool validAC = (acInVolts >= AC_MIN && acInVolts <= AC_MAX);
if (!chargingActive && validAC) {
startCharging();
}
if (chargingActive && !validAC) {
stopCharging();
return;
}
if (!chargingActive) return;
// Charging regulation: adjust modulationIndex based on battery voltage & current
// Simple PI controller
static float integral = 0.0;
const float Kp = 0.02;
const float Ki = 0.001;
float targetVoltage;
switch (chargeState) {
case BULK:
targetVoltage = BULK_VOLTAGE;
// Move to absorption when voltage reaches target
if (batVolts >= BULK_VOLTAGE) {
chargeState = ABSORPTION;
absorptionStart = millis();
integral = 0.0; // reset integrator
}
break;
case ABSORPTION:
targetVoltage = ABSORPTION_VOLTAGE;
// End absorption after timeout or if current drops (optional)
if (millis() - absorptionStart >= ABSORPTION_TIMEOUT || batCurrent < 1.0) {
chargeState = FLOAT;
integral = 0.0;
}
break;
case FLOAT:
targetVoltage = FLOAT_VOLTAGE;
// If battery voltage drops too much, go back to bulk
if (batVolts < FLOAT_VOLTAGE - 0.5) {
chargeState = BULK;
integral = 0.0;
}
break;
default:
targetVoltage = 0;
break;
}
// Voltage error
float error = targetVoltage - batVolts;
integral += error;
// Current limit
if (batCurrent > MAX_CHARGE_CURRENT) {
modulationIndex -= 0.01; // reduce power
if (modulationIndex < 0.0) modulationIndex = 0.0;
} else {
// PI output
float output = Kp * error + Ki * integral;
modulationIndex += output;
modulationIndex = constrain(modulationIndex, 0.0, 0.95);
}
// Safety cutoff
if (batVolts > 15.0) {
stopCharging();
}
}
void startCharging() {
chargingActive = true;
chargeState = BULK;
enableSPWM(true); // switch to 20kHz charging mode
modulationIndex = 0.1; // start with small amplitude to avoid surge
Serial.println("Charging: Started");
}
void stopCharging() {
chargingActive = false;
chargeState = OFF;
disableSPWM(); // turn off all PWM outputs
Serial.println("Charging: Stopped");
}
// ================= NON-BLOCKING STATE MACHINE =================
void stateMachine() {
static unsigned long lastStateCheck = 0;
static SysState previousState = ST_CHECK_START;
if (millis() - lastStateCheck < 10) return;
lastStateCheck = millis();
if (previousState == ST_ERROR && currentState != ST_ERROR) {
digitalWrite(PIN_BUZZER, LOW);
}
previousState = currentState;
switch (currentState) {
case ST_CHECK_START:
disableSPWM();
if (acInVolts >= AC_MIN && acInVolts <= AC_MAX) {
currentState = ST_GRID_WAIT;
stateTimer = millis();
} else {
currentState = ST_SOFT_START;
enableSPWM(false); // Inverter mode (25kHz)
setSPWMAmplitude(0.0);
softStartTimer = millis();
}
break;
case ST_SOFT_START:
digitalWrite(PIN_RELAY, LOW);
if (millis() - softStartTimer >= SOFT_START_INTERVAL) {
softStartTimer = millis();
if (modulationIndex < 0.85) {
setSPWMAmplitude(modulationIndex + 0.01);
}
if (modulationIndex >= 0.85) {
currentState = ST_INVERTER;
Serial.println("State: Soft Start -> Inverter");
}
}
break;
case ST_INVERTER:
// Voltage regulation
if (acOutVolts < 220) setSPWMAmplitude(modulationIndex + 0.001);
if (acOutVolts > 240) setSPWMAmplitude(modulationIndex - 0.001);
if (batVolts < BAT_LOW_CUTOFF) triggerError("LOW BATT");
if (loadWatts > MAX_LOAD_WATTS) triggerError("OVERLOAD");
if (acInVolts >= AC_MIN && acInVolts <= AC_MAX) {
currentState = ST_GRID_WAIT;
stateTimer = millis();
}
break;
case ST_GRID_WAIT:
if (millis() - stateTimer >= GRID_DEBOUNCE_TIME) {
if (acInVolts >= AC_MIN && acInVolts <= AC_MAX) {
disableSPWM();
digitalWrite(PIN_RELAY, HIGH);
currentState = ST_UPS_CHARGE;
} else {
currentState = ST_INVERTER;
}
}
break;
case ST_UPS_CHARGE:
digitalWrite(PIN_RELAY, HIGH);
if (acInVolts < AC_MIN || acInVolts > AC_MAX) {
stopCharging();
digitalWrite(PIN_RELAY, LOW);
// FIXED: soft-start when transferring back to inverter
enableSPWM(false);
modulationIndex = 0.0;
currentState = ST_SOFT_START; // gentle ramp-up
softStartTimer = millis();
}
// Charging is managed by manageCharging()
break;
case ST_ERROR:
disableSPWM();
stopCharging();
digitalWrite(PIN_RELAY, LOW);
break;
}
}
// ================= UTILS =================
void readSensors() {
static unsigned long lastSensorRead = 0;
if (millis() - lastSensorRead < 50) return;
lastSensorRead = millis();
batVolts = (analogRead(PIN_BAT_V) * 5.0 / 1023.0) * 3.5;
acOutVolts = (analogRead(PIN_AC_OUT) * 5.0 / 1023.0) * 80.0;
acInVolts = (analogRead(PIN_AC_IN) * 5.0 / 1023.0) * 80.0;
// FIXED: separate battery current measurement
float shuntVoltage = (analogRead(PIN_SHUNT) * 5.0 / 1023.0) * 15.0; // scaled to actual shunt
batCurrent = (shuntVoltage - 2.5) / 0.1; // assuming 2.5V offset, 0.1V/A (adjust for your sensor)
loadAmps = batCurrent; // for display only, in inverter mode this will be battery discharge
loadWatts = acOutVolts * abs(loadAmps) * powerFactor; // use absolute current for display
int ntcVal = analogRead(PIN_NTC);
// FIXED: better NTC conversion (approximate Steinhart-Hart)
float resistance = 10000.0 * (1023.0 / ntcVal - 1.0);
temperature = 1.0 / (0.001129148 + 0.000234125 * log(resistance) + 0.0000000876741 * pow(log(resistance), 3)) - 273.15;
// Debug output
static unsigned long lastSerialOutput = 0;
if (millis() - lastSerialOutput > 1000) {
lastSerialOutput = millis();
Serial.print("Bat: "); Serial.print(batVolts, 1);
Serial.print("V, Out: "); Serial.print(acOutVolts, 0);
Serial.print("V, Mod: "); Serial.print(modulationIndex, 2);
Serial.print(", BatI: "); Serial.print(batCurrent, 1);
Serial.print("A, ChgState: ");
switch(chargeState) {
case BULK: Serial.print("BULK"); break;
case ABSORPTION: Serial.print("ABS"); break;
case FLOAT: Serial.print("FLT"); break;
case OFF: Serial.print("OFF"); break;
}
Serial.print(", SysState: ");
switch(currentState) {
case ST_CHECK_START: Serial.print("START"); break;
case ST_SOFT_START: Serial.print("SOFT"); break;
case ST_INVERTER: Serial.print("INV"); break;
case ST_GRID_WAIT: Serial.print("WAIT"); break;
case ST_UPS_CHARGE: Serial.print("CHRG"); break;
case ST_ERROR: Serial.print("ERR"); break;
}
Serial.println();
}
}
void thermalControl() {
static unsigned long lastThermalCheck = 0;
if (millis() - lastThermalCheck < 1000) return;
lastThermalCheck = millis();
if (temperature > 45 && temperature <= 60) {
analogWrite(PIN_FAN, 150);
} else if (temperature > 60) {
analogWrite(PIN_FAN, 255);
} else {
analogWrite(PIN_FAN, 0);
}
if (temperature > 80) {
triggerError("OVERTEMP");
}
}
void zeroCrossISR() {
syncPulse = true;
lastZCTime = millis();
}
void triggerError(const char* msg) {
currentState = ST_ERROR;
disableSPWM();
stopCharging();
digitalWrite(PIN_RELAY, LOW);
digitalWrite(PIN_BUZZER, HIGH);
lcd.clear();
lcd.setCursor(4,1);
lcd.print("SYSTEM ERROR");
lcd.setCursor(6,2);
lcd.print(msg);
Serial.print("ERROR: ");
Serial.println(msg);
}
void startupBeep() {
digitalWrite(PIN_BUZZER, HIGH);
delay(100);
digitalWrite(PIN_BUZZER, LOW);
delay(50);
digitalWrite(PIN_BUZZER, HIGH);
delay(100);
digitalWrite(PIN_BUZZER, LOW);
}
void updateLCD() {
if (millis() - lastScreenUpdate < 500) return;
lastScreenUpdate = millis();
if (currentState == ST_ERROR) return;
if (currentState == ST_INVERTER || currentState == ST_SOFT_START) {
lcd.setCursor(0,0); lcd.print("Mode: Inverter ");
lcd.setCursor(0,1);
lcd.print("Out:");
if (acOutVolts < 100) lcd.print(" ");
lcd.print(acOutVolts, 0);
lcd.print("V ");
lcd.setCursor(12,1);
lcd.print(" ");
if (loadWatts < 1000) lcd.print(" ");
lcd.print(loadWatts, 0);
lcd.print("W");
lcd.setCursor(0,2);
lcd.print("Batt:");
lcd.print(batVolts, 1);
lcd.print("V ");
lcd.setCursor(12,2);
lcd.print(" ");
if (abs(batCurrent) < 10) lcd.print(" ");
lcd.print(abs(batCurrent), 1);
lcd.print("A");
lcd.setCursor(0,3);
lcd.print("Temp:");
lcd.print((int)temperature);
lcd.print("C ");
}
else if (currentState == ST_UPS_CHARGE || currentState == ST_GRID_WAIT) {
lcd.setCursor(0,0); lcd.print("Mode: GRID/UPS ");
lcd.setCursor(0,1);
lcd.print("In: ");
lcd.print((int)acInVolts);
lcd.print("V ");
lcd.setCursor(0,2);
lcd.print("Batt:");
lcd.print(batVolts, 1);
lcd.print("V ");
lcd.setCursor(0,3);
if (chargingActive) {
switch(chargeState) {
case BULK: lcd.print("Charging: BULK "); break;
case ABSORPTION: lcd.print("Charging: ABSORB "); break;
case FLOAT: lcd.print("Charging: Float "); break;
default: lcd.print(" "); break;
}
} else {
lcd.print(acInVolts >= AC_MIN && acInVolts <= AC_MAX ? "Grid: Ready " : "Charger: Off ");
}
}
}Batt
AC out
AC in
Current
FAN