Programmatically check for loss of VIN power

I power most of my Electron-based devices with 5VDC through VIN. I also normally attach a LiPo battery. Is there a way to programmatically check for loss of power to VIN? I seem to often have GFCI’s trip and the Electron eventually goes offline and I’d like to know in advance if there’s been a loss of incoming power. I guess I could check to see the LiPo state and whether or not it’s being drained, but a direct detection of loss of VIN would be more desirable.

Somewhere on this forum is a solution proposed by @rickkas7 to do what you are looking for. I just haven't got time to search for it now.
Since Vin is not that different from USB you may search for either of the two.

But since most GPIOs on the Electron are 5V tolerant you could just use an input pin to read the voltage on Vin as this won't be showing any voltage when the device is running off LiPo only.


I found Rick's post

On the Electron, E Series and Boron (devices with a bq24195), the PMIC isPowerGood() method returns true when powered by USB or VIN. It’s false when running off battery.

2 Likes

@rickkas7, can you please offer me a code snippet on how to call that method?

// How often to check power in milliseconds. Since this requires accessing the PMIC, it's
// best to not check on every loop.
const unsigned long POWER_CHECK_INTERVAL_MS = 5000;
unsigned long lastPowerCheck = 0;

// This code can only be used on the Electron, E Series, or Boron that have the bq24195 PMIC.
// If you get a compile error on the next line, make sure you're targeting a compatible device.
PMIC pmic;


void setup() {
}

void loop() {

	if (millis() - lastPowerCheck >= POWER_CHECK_INTERVAL_MS) {
		lastPowerCheck = millis();

		if (pmic.isPowerGood()) {
			// Running off USB or VIN
		}
		else {
			// Running off battery
		}
	}
}
3 Likes

Thanks!

Do all Electron, E Series, or Boron have the bq24195 PMIC? If not, how do I tell? I have an Electron in the field that, I believe, has lost incoming power, but pmic.isPowerGood() is returning 1 as evidenced by:

declared at the top of the program

PMIC pmic; //used to test for presence of 5VDC power

The following is effectively in a loop that’s called once per minute

snprintf(gDI,sizeof(gDI),"%u%u%u%u%u%u%u%u%u%u%u%u%u",gDi1,gDi2,gDi3,gDi4,gDi5,gDi6,gDi7,gDi8,gDi9,gDi10,gDi11,gDi12,pmic.isPowerGood());