# mPy - stepper motor control 28BYJ-48
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2026-04-10  initial release

import	time
from	machine		import	Pin

class Stepper:
    step_table = [[True,  False, False, False],		# half steps
                  [True,  True,  False, False],
                  [False, True,  False, False],
                  [False, True,  True,  False],
                  [False, False, True,  False],
                  [False, False, True,  True ],
                  [False, False, False, True ],
                  [True,  False, False, True ]]


    # hardware setup
    def __init__(self, pins = (14, 27, 26, 25)):
        self.coils = [Pin(pin, Pin.OUT, value=0) for pin in pins]
        self.idx   = 0				# position 0
        self.setCoils()				# all coils off
        
        
    # activate coils according to parameters
    def setCoils(self, levels = (False, False, False, False)):
        for coil, level in zip(self.coils, levels):
            coil(level)
            
            
    # all coils off
    def off(self):
        self.setCoils()
        
        
    # go n steps, on 28BYJ-48 is 4096 steps equal to 1 revolution
    def go(self, n):
        for _ in range(abs(n)):
            self.setCoils(self.step_table[self.idx])
            if n > 0: self.idx += 1
            else    : self.idx -= 1
            self.idx %= 8
            time.sleep_us(1000)
            
# ============================= test ===============================

def test():
    stepper = Stepper()
    stepper.go( 4096)		# 1 rev forwards
    stepper.go(-4096)		# 1 rev reverse
    stepper.off()


test()
    
# ================================ end =================================
