Skip to content

Commit

Permalink
added state machine
Browse files Browse the repository at this point in the history
  • Loading branch information
cKrijgsman committed May 6, 2024
1 parent e61e79d commit 36e0c74
Showing 1 changed file with 93 additions and 0 deletions.
93 changes: 93 additions & 0 deletions tutorials/coding-challenge/step-4-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ parent: "Coding Challenge"
nav_exclude: true
---

## Without Statemachine
````python
import time
import board
Expand Down Expand Up @@ -67,4 +68,96 @@ while True:
leds.fill(color_off)
leds.show()

````

## With statemachine
````python
import time
import board
import analogio
import digitalio
import neopixel

# States
state_on_loud = 0
state_on_quiete = 1
state_off = 2
state_memory = 3
current_state = 0


# Register sensors
button = digitalio.DigitalInOut(board.D4)
button.direction = digitalio.Direction.INPUT

sound_sensor = analogio.AnalogIn(board.A0)

# Register LED
leds = neopixel.NeoPixel(board.D13, 1, auto_write=False, pixel_order=neopixel.GRBW)

# colors
color_off = (0,0,0,0)
color_on = (0,0,0,10)

leds.fill(color_off)
leds.show()


timer_mark = 0
timer_duration = 1

color = None
triggered = False

color_memory = []

while True:

if current_state == state_off:
# make sure the LED is off
leds.fill(color_off)
leds.show()
# check if we should turn on
if sound_sensor.value > 30000:
# Start the timer!
color = (random.randint(0,70),random.randint(0,70),random.randint(0,70),0)
color_memory.append(color)
timer_mark = time.monotinic()
current_state = state_on_loud
elif button.value is True:
current_state = state_memory

elif current_state == state_on_loud:
leds.fill(color)
leds.show()
if time.monotinic() - timer_mark >= timer_duration:
current_state = state_off
elif button.value is True:
current_state = state_memory
elif sound_sensor.value < 25000:
current_state = state_on_quiete


elif current_state == state_on_quiete:
leds.fill(color)
leds.show()
if time.monotinic() - timer_mark >= timer_duration:
current_state = state_off
elif button.value is True:
current_state = state_memory
elif sound_sensor.value > 30000:
# Her start the timer!
color = (random.randint(0,70),random.randint(0,70),random.randint(0,70),0)
color_memory.append(color)
timer_mark = time.monotinic()
current_state = state_on_loud
elif current_state == state_memory:
for color in color_memory:
leds.fill(color)
leds.show()
time.sleep(1)
leds.fill(color_off)
leds.show()
color_memory = []
current_state = state_off
````

0 comments on commit 36e0c74

Please sign in to comment.