import board  # core module in circuit python on ESP32
import digitalio  # core module in circuit python on ESP32
# import time  # core module in circuit python on ESP32

# identfy the pinouts on the ESP32 for stepper control
pulse = digitalio.DigitalInOut(board.D10)
whichway = digitalio.DigitalInOut(board.D11)
pulse.direction = digitalio.Direction.OUTPUT
whichway.direction = digitalio.Direction.OUTPUT
home = digitalio.DigitalInOut(board.D12)
home.direction = digitalio.Direction.INPUT
home.pull = digitalio.Pull.DOWN

# Ready LED
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

hold = 0.001  # One millisecond
count = 300  # alternative to hold using a count cycle


def StepOnce(hold):  # send one pulse to stepper motor
    led.value = True
    pulse.value = True
    # time.sleep(hold) - this doesn't work well  # the -1 slows the cycle more
    # make the pulse shorter than the pause
    counter = count - 1 * 0.5
    while counter >= 0 :  # wait the count
        counter = counter - 1
        pass
    led.value = False
    pulse.value = False
    # time.sleep(hold) - this doesn't work well
    counter = count
    while counter - 1 >= 0 :  # wait the count  # the -1 slows the cycle more
        counter = counter - 1
        pass

def motor_move(deg):

    # set move direction
    if deg >= 0:
        whichway.value = 0
    else:
        whichway.value = 1

    # calculate steps to move
    step = int(abs(45 * deg))
    # 360 deg/ 81:1 = 4.4444deg/stepper revolution
    # 200 step/stepper rev / 4.4444 deg/harmonic rev = 45step/deg

    # while steps remain, pulse stepper
    print("In stepper.py line 42: Deg=", deg, "Steps moved:", step)
    while step >= 0:
        StepOnce(hold)
        step = step - 1
    print("In stepper.py line 42: Leaving Stepper.py")




