Solenoid Engine Single – Microbit – Micro Python – Speed Controls

# Solenoid Engine Simple Script - govener
from microbit import *

# asking for a power stroke
ison = 0
# saved state of is on
last_ison = 0
# ready for next pulse
ready = 1
# time of last pulse
pulsetime = 0

# define speed limits
MAXSPEED = 100
MINSPEED = 1500

# speed in mS between pulses (smaller is faster)
Speed = 500

while True:
# if pin2.read_analog() < 400: if V1 Engine
    if pin2.read_analog() > 600:
        ison = 1
    else:
        ison = 0

# start of stroke check speed
# had a pulse if time ready next pulse
    if ison == 1 and last_ison == 0:
        if (running_time()-pulsetime) > Speed:
            ready = 1
            display.show(Image.DIAMOND)
# if pulse needed turn on solenoid
    if ready == 1:
        pin1.write_digital(1)
        pulsetime = running_time()
        if ison == 0:
            ready = 0
            display.show(Image.HAPPY)
    else:
        pin1.write_digital(0)

# set last condition
    last_ison = ison

    if button_a.is_pressed():
        if Speed < MINSPEED:
            Speed = Speed + 1
            display.show(Image.ARROW_S)

    if button_b.is_pressed():
        if Speed > MAXSPEED:
            Speed = Speed - 1
            display.show(Image.ARROW_N)