// see state diagram on https://arduino.stackexchange.com/questions/95023/i-need-help-for-applying-a-logic-to-this-code
// scroll through the answers.
int softStart = A0;
int enable = A1;
int powerBTN = A2;
enum State { OFF = 0, ON = 1, WAIT_ON = 2 , WAIT_OFF = 3, IN_SOFT_START = 4, SOFT_START_CONFIRM = 5 } ;
State state ;
State oldState ;
bool stateChange = true ;
uint32_t inCurrentStateAtMs = 0 ;
void setState ( State newState ) {
// forces change to new state
inCurrentStateAtMs = millis() ;
oldState = state ;
state = newState ;
stateChange = true ;
}
void setup() {
Serial.begin(115200);
pinMode(softStart, OUTPUT);
pinMode(enable, OUTPUT);
pinMode(powerBTN, INPUT_PULLUP) ;
digitalWrite(enable, LOW);
digitalWrite(softStart, LOW);
setState( State::OFF ) ;
}
void loop() {
if ( stateChange ) {
//debug
stateChange = false ;
Serial.print("state changes to: ");
Serial.println( state ) ;
}
switch ( state ) {
case State::OFF : {
if ( ! digitalRead( powerBTN ) && millis() - inCurrentStateAtMs > 100 ) {
setState( State::WAIT_ON ) ;
}
break ;
}
case State::WAIT_ON : {
if ( digitalRead( powerBTN ) && millis() - inCurrentStateAtMs < 500 ) {
digitalWrite( enable, HIGH ) ;
setState( State::ON );
}
else if ( digitalRead( powerBTN ) && millis() - inCurrentStateAtMs >= 500 ) {
digitalWrite( enable, LOW ) ;
digitalWrite( softStart, HIGH ) ;
setState( State::IN_SOFT_START );
}
break ;
}
case State::ON : {
if ( ! digitalRead( powerBTN ) && millis() - inCurrentStateAtMs > 100 ) {
setState( State::WAIT_OFF );
}
break ;
}
case State::WAIT_OFF : {
if ( digitalRead( powerBTN ) && millis() - inCurrentStateAtMs > 100 ) {
digitalWrite( enable, LOW ) ;
setState( State::OFF ) ;
}
break;
}
case State::IN_SOFT_START : {
if ( ! digitalRead( powerBTN ) ) {
digitalWrite( enable, HIGH ) ;
state = State::SOFT_START_CONFIRM ;
}
else if ( millis() - inCurrentStateAtMs > 3000 ) {
// timeout
digitalWrite( softStart, LOW ) ;
setState( State::OFF );
}
break ;
}
case State::SOFT_START_CONFIRM : {
if ( digitalRead( powerBTN ) && millis() - inCurrentStateAtMs > 2000 ) {
digitalWrite( softStart, LOW ) ;
setState( State::ON ) ;
}
break ;
}
} // switch
} // loop
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
led1:A
led1:C
led2:A
led2:C
gnd1:GND
gnd2:GND
gnd3:GND
softStart
enable
state diagram on:
https://arduino.stackexchange.com/questions/95023/i-need-help-for-applying-a-logic-to-this-code
Scroll through the answers