OK, that was easier than I thought:
#include "Particle.h"
bool hasVUSB();
bool hadVUSB = false;
void setup() {
}
void loop() {
bool curVUSB = hasVUSB();
if (curVUSB != hadVUSB) {
char buf[128];
snprintf(buf, sizeof(buf), "VUSB=%d", curVUSB);
Particle.publish("power", buf, PRIVATE);
hadVUSB = curVUSB;
}
}
bool hasVUSB() {
uint32_t *pReg = (uint32_t *)0x40000438; // USBREGSTATUS
return (*pReg & 1) != 0;
}
Just copy and paste the hasVUSB() function. It returns true if USB or VUSB is powered and false if not (you’re running off battery). This works on all Gen3 devices (Argon, Boron, Xenon, B Series SoM). It does not work on Gen2 (Photon, P1, Electron, E Series).