Skip to content

Instantly share code, notes, and snippets.

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

  • Save pingswept/7b6efb9f5e1c7378e57c54e67d67fcfd to your computer and use it in GitHub Desktop.

Select an option

Save pingswept/7b6efb9f5e1c7378e57c54e67d67fcfd to your computer and use it in GitHub Desktop.
another state machine example
import board
import analogio as aio
import digitalio as dio
import pwmio
import time
cw = pwmio.PWMOut(board.D6, frequency=500, duty_cycle=0)
ccw = pwmio.PWMOut(board.D8, frequency=500, duty_cycle=0)
motor = cw
sensor = aio.AnalogIn(board.A0)
button = dio.DigitalInOut(board.D4)
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 = STATE_CLOCKWISE
def scaleSensorReadingToMotorRange(reading):
return reading # in real code, you would adjust your sensor reading with some constants here
while True:
print(time.monotonic())
print(state)
time.sleep(0.1)
if state is STATE_CLOCKWISE:
motor = cw
motor.duty_cycle = scaleSensorReadingToMotorRange(sensor.value)
if button.value is True:
motor.duty_cycle = 0
state = STATE_COUNTERCLOCKWISE
time.sleep(0.2)
elif state is STATE_COUNTERCLOCKWISE:
motor = ccw
motor.duty_cycle = scaleSensorReadingToMotorRange(sensor.value)
if button.value is True:
motor.duty_cycle = 0
state = STATE_CLOCKWISE
time.sleep(0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment