enum
{
STATE_IDLE_INIT,
STATE_IDLE,
STATE_CURRENT_DETECTED,
STATE_ON_WAIT_12_SECONDS,
STATE_HIGH,
} state;
const int sensorPin = 2;
int currentReading = HIGH; // pin 2 is HIGH when button is not pressed
unsigned long previousMillis;
void setup()
{
Serial.begin( 9600);
Serial.println( "The sketch has started.");
pinMode( sensorPin, INPUT_PULLUP);
}
void loop()
{
unsigned long currentMillis = millis();
// ---------------------------------------------------
// BUTTON
// ---------------------------------------------------
// Detect if the button changes, and pass
// that information on, to the finite state machine.
// Only the event of the change is passed on, because
// this sketch did not need to know the state
// of the button, only a change.
// ---------------------------------------------------
bool currenHigh = false;
bool currentLow = false;
bool readSensor(){
//code to read from ADC pin and calculate RMS voltage and current
//return high or low
}
int boilerState = readSensor();
if( boilerState == LOW) // low is button pressed
{
currenHigh = true;
}
else
{
currentLow = true;
}
// ---------------------------------------------------
// STATE MACHINE
// ---------------------------------------------------
switch( state)
{
case STATE_IDLE_INIT:
// Before going to the actual "idle" state, a message is printed.
Serial.println( "Send State Low to DB");
state = STATE_IDLE;
break;
case STATE_IDLE:
// This "idle" state is when there is nothing to do.
// This state is executed until a button is pressed.
// It "waits" until a button is pressed, but it does
// not really wait, since it is run over and over again.
Serial.println("State: IDLE");
if( currenHigh)
{
state = STATE_CURRENT_DETECTED;
Serial.println( "Waiting 12s");
}
break;
case STATE_CURRENT_DETECTED:
Serial.println("State: STATE_CURRENT_DETECTED");
previousMillis = currentMillis;
state = STATE_ON_WAIT_12_SECONDS;
break;
case STATE_ON_WAIT_12_SECONDS:
Serial.println("State: STATE_ON_WAIT_12_SECONDS");
if( currentLow && currentMillis - previousMillisButton <= 12000)
{
state = STATE_IDLE;
}
else
{
if( currenHigh && currentMillis - previousMillisButton >= 12000)
{
state = STATE_HIGH;
Serial.println(String(currentMillis - previousMillis));
Serial.println("send HIGH state to DB");
}
}
break;
case STATE_HIGH:
Serial.println("State: HIGH");
if( currentLow){
Serial.println(String(currentMillis - previousMillis -12000));
Serial.println("send LOW state and time to DB");
state = STATE_IDLE;
}
break;
}
// ---------------------------------------------------
// BLINK WITHOUT DELAY
// ---------------------------------------------------
// Blinking the led is outside the final state machine.
// The final state machine can turn the blinking on and off.
// ---------------------------------------------------
}