#define OUTPUT_5V 4 // HIGH on this pin will switch the "5V*" output ON
#define BATTERYSENSE A7 // Sense VBAT_COND signal (when powered externally should read ~3.25v/3.3v (1000-1023), when external power is cutoff it should start reading around 2.85v/3.3v * 1023 ~= 880 (ratio given by 10k+4.7K divider from VBAT_COND = 1.47 multiplier)
// hence the actual input voltage = analogRead(A7) * 0.00322 (3.3v/1024) * 1.47 (10k+4.7k voltage divider ratio)
// when plugged in this should be 4.80v, nothing to worry about
// when on battery power this should decrease from 4.15v (fully charged Lipoly) to 3.3v (discharged Lipoly)
// trigger a shutdown to the target device once voltage is around 3.4v to allow 30sec safe shutdown
#define LOWBATTERYTHRESHOLD 3.7 // a shutdown will be triggered to the target device when battery voltage drops below this (Volts)
#define ButtonHoldTime 1800 // Button must be hold this many mseconds before a shutdown sequence is started (should be much less than PIForceShutdownDelay)
#define PIShutdownDelay_Min 6000 // will start checking the SIG_OKTOCUTOFF line after this long
#define PIShutdownDelay_Max 38000 // window of time in which SIG_OKTOCUTOFF is expected to go HIGH
// should be at least 3000 more than Min
// if nothing happens after this window, if button is
// still pressed, force cutoff power, otherwise switch back to normal ON state
#define PIForceShutdownDelay 6500 // when SIG_OKTOCUTOFF==0 (PI in unknown state): if button is held
// for this long, force shutdown (this should be less than PIShutdownDelay_Max)
#define ShutdownFINALDELAY 4000 // after shutdown signal is received, delay for this long
// to allow all PI LEDs to stop activity (pulse LED faster)
#define PRINTPERIOD 1000
intlastValidReading=1;
unsignedlonglastValidReadingTime=0;
unsignedlongnow=0;
intPowerState=0;
longlastPeriod=-1;
floatsystemVoltage=5;
voidsetup(){
Serial.begin(115200);
pinMode(BUTTON,INPUT_PULLUP);
pinMode(SIG_OKTOCUTOFF,INPUT);
pinMode(SIG_REQUESTHALT,OUTPUT);
pinMode(LED,OUTPUT);
pinMode(OUTPUT_5V,OUTPUT);
pinMode(A7,INPUT);
digitalWrite(SIG_REQUESTHALT,LOW);//added after sudden shutdown quirks, DO NOT REMOVE!
digitalWrite(OUTPUT_5V,LOW);//added after sudden shutdown quirks, DO NOT REMOVE!
}
voidloop(){
intreading=digitalRead(BUTTON);
now=millis();
digitalWrite(SIG_REQUESTHALT,LOW);//added after sudden shutdown quirks, DO NOT REMOVE!
//make sure the button is held down for at least 'ButtonHoldTime' before taking action (this is to avoid accidental button presses and consequently Pi shutdowns)