Skip to main content

Section 3.6 State machines

State machines are a powerful way to organize and implement complex behaviors in software.

from machine import TouchPad, Pin

TOUCH_THRESH = 350

# Define the states
STATE_ZERO = 0
STATE_ONE = 1
STATE_TWO = 2

# Set up the system
current_state = STATE_ZERO
t = TouchPad(Pin(13))
lastTouch = t.read()
pressed = False

# Do this forever
while True:
    # First, processing that we want to do regardless of state

    # Check if we've received a press    
    nowTouch = t.read()
    if lastTouch > TOUCH_THRESH and nowTouch < TOUCH_THRESH:
        pressed = True
    else:
        pressed = False
    lastTouch = nowTouch
    
    # Now figure out which state we're in and process appropriately
    if current_state == STATE_ZERO:
        # Handle transitions out of state zero
        if pressed:
            current_state = STATE_ONE

        # Do anything specific to state zero
        led.off()
        
    elif current_state == STATE_ONE:
        # Handle transitions out of state one
        if pressed:
            current_state = STATE_TWO

        # Do anything specific to state one
        led.on()
        
    elif current_state == STATE_TWO:
        # Handle transitions out of state two
        if pressed:
            current_state = STATE_ZERO
            
        # Do anything specific to state two
        led.off()

    else:
        # We shouldn't ever end up here, but in case something goes wrong,
        # just reset to state zero
        state = STATE_ZERO;