Skip to content

Instantly share code, notes, and snippets.

@morehavoc
Last active February 10, 2023 04:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morehavoc/d185d6693abb7dfbdba9ce168fa07a63 to your computer and use it in GitHub Desktop.
Save morehavoc/d185d6693abb7dfbdba9ce168fa07a63 to your computer and use it in GitHub Desktop.
Example class for running a stepper motor in micopython
import machine
import time
DELAY = 0.01
STEPS = 27
class Motor:
def __init__(self, CA1, CA2, CB1, CB2, halfSteps=False):
self._coils = (CA1, CA2, CB1, CB2)
self._pattern = 0
if not halfSteps:
self._patterns = ((0,1,0,1), (0,1,1,0), (1,0,1,0), (1,0,0,1))
else:
self._patterns = ((0,1,0,1), (0,1,0,0), (0,1,1,0), (0,0,1,0),
(1,0,1,0), (1,0,0,0), (1,0,0,1), (0,0,0,1))
def _setStep(self, w1, w2, w3, w4):
self._coils[0].value(w1)
self._coils[1].value(w2)
self._coils[2].value(w3)
self._coils[3].value(w4)
def stepone(self, forward=True):
if forward:
self._pattern += 1
self._pattern = self._pattern if self._pattern < len(self._patterns) else 0
else:
self._pattern -= 1
self._pattern = self._pattern if self._pattern > -1 else len(self._patterns) - 1
# move the motor
p = self._patterns[self._pattern]
self._setStep(*p)
coils = (
machine.Pin(26, machine.Pin.OUT),
machine.Pin(27, machine.Pin.OUT),
machine.Pin(14, machine.Pin.OUT),
machine.Pin(12, machine.Pin.OUT)
)
motor = Motor(*coils, halfSteps=False)
# then call motor.stepone() in a loop to step the motor.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment