If condition A is true I would like a block of code to execute and loop indefinitely. If condition A is false I would like the same block of code to run ten times and then do nothing but wait for conditions to change.
I know it could be done with if, for or while loops. I know this sounds easy but I also know there is a right and wrong way to do it.
const int pinTest = 9;
const int pinLED = 13;
#define STATE_TEST_CONDITION 0
#define STATE_FALSE 1
#define STATE_WAIT_CONDITION_CHANGE 2
void setup()
{
pinMode( pinTest, INPUT_PULLUP );
pinMode( pinLED, OUTPUT );
digitalWrite( pinLED, LOW );
Serial.begin(9600);
while(!Serial); //wait for serial console to open
}
void loop()
{
static unsigned long
timeLoop = 0;
if( (millis() - timeLoop) < 250 )
return;
timeLoop = millis();
//run the block of code statemachine
BlockOfCodeSM( TestCondition() );
}//loop
bool TestCondition( void )
{
//do whatever you need to do and end it with
//a 'true' or 'false'
//simulated here with a button on pin 9
return( digitalRead(pinTest)?true:false );
}//TestCondition
void BlockOfCodeSM( bool Condition_A )
{
static int
numRuns;
static byte
bocState = STATE_TEST_CONDITION;
switch( bocState )
{
case STATE_TEST_CONDITION:
//if condition A is true, run
//block of code every pass
if( Condition_A == true )
{
Serial.println("Pass" );
RunBlockOfCode();
}
else
{
//Condition_A is false; set up to
//run only 10 times
numRuns = 10;
bocState = STATE_FALSE;
}//else
break;
case STATE_FALSE:
//run the block of code 10 times
//at numRuns == 0 we've done ten passes
//so move on to the state where we wait
//for "conditions to change"
Serial.print("Fail passes left: " ); Serial.println(numRuns);
RunBlockOfCode();
numRuns--;
if( numRuns == 0 )
bocState = STATE_WAIT_CONDITION_CHANGE;
break;
case STATE_WAIT_CONDITION_CHANGE:
//we're here waiting for "conditions to change"
//we came in with Condition_A having been false
//so wait for the condition to become true.
//when it does, restart the state machine
if( Condition_A == true )
bocState = STATE_TEST_CONDITION;
break;
}//switch
}//BlockOfCodeSM
void RunBlockOfCode( void )
{
static bool
bFlag = 0;
//do stuff here
//just blinking the built-in LED to show activity
bFlag ^= 0x01;
digitalWrite( pinLED, bFlag?HIGH:LOW ); //toggle LED each pass
}//RunBlockOfCode