Key to understanding this whole State Machine thing, is realising that we look for changes in pins, not just their current setting.
It’s often not enough to know that (say) a switch is closed; it may be key to know that it just became closed. That’s why in code for these things you’ll see variables like lastSwitchReading for example. Each time through loop(), read the switch into say currentSwitchReading and compare the two. If they differ, it means they switch changed since you last looked. If it changed and it’s now open, do something (or nothing); if it changed and is now closed, do something else (or nothing). If it didn’t change, do nothing. Then update lastSwitchReading with currentSwitchReading, so next time round it’s comparing the new previous state.
Once you have that clear, it’s plain sailing…
So my code looks to see if the coin switch became pressed: that means a new coin was dropped. It’s no point looking to see if the coin switch is pressed: the milli seconds it’s held closed is a lifetime to Arduino so it would reflect multiple coins. Similarly it looks to see if the boom became closed (ie it had been open, now it’s closed), not just that it is closed.
Then my code you’ll see that I look for four scenarioes:
- If it’s locked and a coin dropped, unlock it
- If it’s not locked and a coin dropped, we scored a coin so say thanks
- If it’s locked and someone passes, well that’s a forced entry so shout an alarm
- If it’s unlocked and someone passes, that’s cool so say Hi and lock behind them