You can also just check to see if the Electron is USB powered. This will be inexact - you likely won’t see momentary drops in main power because most USB power supplies will smooth over these, but you will certainly see anything longer than a few seconds. And it doesn’t even require any additional hardware - you can do it entirely in software on the Electron!
#include "Particle.h"
bool isUsbPowered(); // forward declaration
PMIC pmic;
bool lastPowerState = false;
void setup() {
pmic.begin();
}
void loop() {
bool powerState = isUsbPowered();
if (powerState != lastPowerState) {
Particle.publish("usbPowered", (powerState ? "true" : "false"), 60, PRIVATE);
lastPowerState = powerState;
}
delay(2000);
}
bool isUsbPowered() {
byte systemStatus = pmic.getSystemStatus();
return ((systemStatus & 0xc0) == 0x40);
}
/*
//System Status Register
//NOTE: This is a read-only register
REG08
BIT
--- VBUS status
7: VBUS_STAT[1] | 00: Unknown (no input, or DPDM detection incomplete), 01: USB host
6: VBUS_STAT[0] | 10: Adapter port, 11: OTG
--- Charging status
5: CHRG_STAT[1] | 00: Not Charging, 01: Pre-charge (<VBATLOWV)
4: CHRG_STAT[0] | 10: Fast Charging, 11: Charge termination done
3: DPM_STAT 0: Not DPM
1: VINDPM or IINDPM
2: PG_STAT 0: Power NO Good :(
1: Power Good :)
1: THERM_STAT 0: Normal
1: In Thermal Regulation (HOT)
0: VSYS_STAT 0: Not in VSYSMIN regulation (BAT > VSYSMIN)
1: In VSYSMIN regulation (BAT < VSYSMIN)ault is 3.5V (101)
0: Reserved
*/