Skip to content

Instantly share code, notes, and snippets.

@pingswept
Last active November 3, 2025 21:56
Show Gist options
  • Select an option

  • Save pingswept/570fa21f9f2a9f4775749013ef14b0de to your computer and use it in GitHub Desktop.

Select an option

Save pingswept/570fa21f9f2a9f4775749013ef14b0de to your computer and use it in GitHub Desktop.
state machine example
import board
import digitalio as dio
import time
motor_cw = dio.DigitalInOut(board.D3)
motor_cw.direction = dio.Direction.OUTPUT
motor_ccw = dio.DigitalInOut(board.D4)
motor_ccw.direction = dio.Direction.OUTPUT
led = dio.DigitalInOut(board.D5)
led.direction = dio.Direction.OUTPUT
button = dio.DigitalInOut(board.D6)
button.direction = dio.Direction.INPUT
STATE_CLOCKWISE = 1 # these are just arbitrary constants used to number the states
STATE_COUNTERCLOCKWISE = 2 # the values 1 and 2 are not significant
STATE_VICTORY = 3
STATE_END = 4
state = STATE_CLOCKWISE
next_reversal = time.monotonic() + 2.0 # this is like setting a timer 2 seconds in the future
led.value = False
while True:
print(time.monotonic())
print(state)
time.sleep(0.1)
if state is STATE_CLOCKWISE:
motor_ccw.value = False
motor_cw.value = True
if button.value is True:
motor_cw.value = False # stop the motor
state = STATE_VICTORY
elif time.monotonic() > next_reversal: # this is like checking the timer we set above
next_reversal = time.monotonic() + 2.0 # reset the timer again
state = STATE_COUNTERCLOCKWISE
elif state is STATE_COUNTERCLOCKWISE:
motor_cw.value = False
motor_ccw.value = True
if button.value is True:
motor_ccw.value = False # stop the motor
state = STATE_VICTORY
elif time.monotonic() > next_reversal: # this is like checking the timer we set above
next_reversal = time.monotonic() + 2.0 # reset the timer again
state = STATE_CLOCKWISE
elif state is STATE_VICTORY:
for i in range(10):
led.value = True
time.sleep(0.4)
led.value = False
time.sleep(0.2)
state = STATE_END
elif state is STATE_END:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment