//#include #include "BatteryMonitor.h" #include "BoardCfg.h" #include "timer.h" #include "ina219.h" #include "WiFiCtrl.h" #include "I2C.h" float mBatteryVoltage; int mBatteryCurrent; int mBatterySOC; float mVoltageMeanSum; int mVoltageMeanCount; bool mCurrentModuleOK; void InitBatteryMonitor() { mBatteryVoltage = 0; mBatteryCurrent = 0; mBatterySOC = 0; mCurrentModuleOK = true; TimerStart(BATTERY_MONITOR_TIMER,100); //experimental stuff! mVoltageMeanSum = 0.0; mVoltageMeanCount = 0; if(ina219Init() == RET_ERROR) { mCurrentModuleOK = false; } //ina219SetCalibration_16V_500mA(); // ina219SetCalibration_16V_200mA(); } void BatteryMonitorTick() { static int NetworkSendCounter; //Every second (10 counts) we want to send the battery data. if(IsTimerExpired(BATTERY_MONITOR_TIMER)) { int adc; float conv, raw; AD1CON1bits.SAMP = 0; while(AD1CON1bits.DONE == 0); adc = ADC1BUF0; AD1CON1bits.SAMP = 1; // adc &= 0xFFFE; conv = (float)adc / 1023; conv *= 3.36; raw = conv; conv *= 11; //avoid rollovers in case the LORA network gets disconnected. //This could go for a long time but 5000 samples is too much anyways. if(mVoltageMeanCount >= 5000) { mVoltageMeanCount = 0; mVoltageMeanSum = conv; } else { mVoltageMeanCount++; mVoltageMeanSum += conv; } mBatteryVoltage = conv; TimerStart(BATTERY_MONITOR_TIMER,100); if(mCurrentModuleOK == true) { mBatteryCurrent = ina219GetCurrent_mA(); if(I2CWasLastTransactionOK() == 0 ) { mCurrentModuleOK = false; } } // if(NetworkSendCounter++ == 10) // { // NetworkSendCounter = 0; // SendNetworkBatteryData(); // } } } float GetBatteryVoltage() { mBatteryVoltage = (mVoltageMeanSum/mVoltageMeanCount); mVoltageMeanSum = 0.0; mVoltageMeanCount = 0; return mBatteryVoltage; } int GetSolarPanelCurrent() { return mBatteryCurrent; } int GetBatterySOC() { return mBatterySOC; } int SendNetworkBatteryData() { // int VoltageMilliVolts = (int)(mBatteryVoltage * 1000); // int BattCurrent = mBatteryCurrent; // // char BatData[10]; // BatData[0] = (char)(VoltageMilliVolts & 0x000000FF); //Battery Voltage 1 // VoltageMilliVolts >>= 8; // BatData[1] = (char)(VoltageMilliVolts & 0x000000FF); //Battery Voltage 2 // BatData[2] = (char)(BattCurrent & 0x000000FF); //Solar panel Current 1 // BattCurrent >>= 8; // BatData[3] = (char)(BattCurrent & 0x000000FF); //Solar panel Current 2 // // SendNetworkData(BatData,4); printf("Battery voltage: %f\n",mBatteryVoltage); } bool GetCurrentModuleOK() { return mCurrentModuleOK; }