Skip to content

State Machine

To load the ball when it is the trough, after settling:

bool ball_in_through = troughSensor2.get();
in Trough_Ready
    // No ball in the through
    do { trough.setActive(LOW); }
    on ball_in_through goto Trough_Filled
in Trough_Filled
    // There is a ball in the though
    on !ball_in_through goto Ready
    after 100ms on ball_in_through goto Trough_Loading
in Trough_Loading
    // The ball has settled, load it for the auto-plunger
    do { trough.setActive(HIGH); }
    after 100ms goto Trough_Ready
Becomes:
unsigned long troughStateSwitchTime;
bool ball_in_through = troughSensor2.get();
if (troughState == Trough_Ready) {
    // No ball in the through
    trough.setActive(LOW);
    if (ball_in_through) {
        troughState = Trough_Filled;
        troughStateSwitchTime = currentTime;
    }
} else if (troughState == Trough_Filled) {
    // There is a ball in the though
    if (!ball_in_through) {
        troughState = Trough_Ready;
        troughStateSwitchTime = currentTime;
    }
    if (currentTime - troughStateSwitchTime > 100 && ball_in_through) {
        troughState = Trough_Loading;
        troughStateSwitchTime = currentTime;
    }
} else if (troughState == Trough_Loading) {
    trough.setActive(HIGH);
    if (currentTime - troughStateSwitchTime > 100) {
        troughState = Trough_Ready;
        troughStateSwitchTime = currentTime;
    }
}
Or, with some helper functions after and goto:
unsigned long troughStateSwitchTime;
bool ball_in_through = troughSensor2.get();
if (troughState == Trough_Ready) {
    // No ball in the through
    trough.setActive(LOW);
    if (ball_in_through)
        goto(Trough_Filled, troughStateSwitchTime);
} else if (troughState == Trough_Filled) {
    // There is a ball in the though
    if (!ball_in_through)
        goto(Trough_Ready, troughStateSwitchTime);
    if (after(troughStateSwitchTime, 100) && ball_in_through)
        goto(Trough_Loading, troughStateSwitchTime);
} else if (troughState == Trough_Loading) {
    trough.setActive(HIGH);
    if (after(troughStateSwitchTime, 100))
        goto(Trough_Ready, troughStateSwitchTime);
}