Skip to content

Instantly share code, notes, and snippets.

@AlanBell
Last active November 30, 2021 20:50
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 AlanBell/85799bbd4934b9abad4a8ff89a4563e1 to your computer and use it in GitHub Desktop.
Save AlanBell/85799bbd4934b9abad4a8ff89a4563e1 to your computer and use it in GitHub Desktop.
A hello world for the 28BYJ-48 Stepper motor
#!/usr/bin/python3
import time
import machine
#the stepper motor can be driven by energising the 4 coils in different sequences
#considering them as binary values converted to decimal (so coil activation 0110 would be 6)
#we can express the sequences like this
wave=[1,2,4,8]#wave low torque, low power consumption?
fullstep=[3,6,12,9]#full step (more torque?)
halfstep=[1,3,2,6,4,12,8,9]#half steps, longer sequence but can be stepped through faster
#use these values to see the lights pulse and check you wired it up in the order you think you wired it up
#steptime=1
#steps=3
#use these values to go as fast as possible for one revolution in each mode
#slow it down if it just vibrates and doesn't turn
steptime=0.002
steps=512
#you will have to change this according to the GPIO pins wired up
#pin numbers and GPIO numbers don't match up on most devices
#for example on nodeMCU devices D0,D1,D2,D3 would be GPIO 16,5,4,0
pins = [
machine.Pin(2, machine.Pin.OUT), # 1
machine.Pin(3, machine.Pin.OUT), # 2
machine.Pin(4, machine.Pin.OUT), # 4
machine.Pin(5, machine.Pin.OUT), # 8
]
def turnoff():
#turn off the pins or things get warm
pins[0](0)
pins[1](0)
pins[2](0)
pins[3](0)
time.sleep(.2)#just so you can see a pause between phases
for n in range(steps):
for phase in fullstep:
for n, p in enumerate(pins):
pins[n](phase & 1<<n)
time.sleep(steptime)
turnoff()
for n in range(steps):
for phase in reversed(halfstep):#reverse the phases to go backwards
for n, p in enumerate(pins):
pins[n](phase & 1<<n)
time.sleep(steptime/2)#halfstep can be driven twice as fast
turnoff()
for n in range(steps):
for phase in wave:
for n, p in enumerate(pins):
pins[n](phase & 1<<n)
time.sleep(steptime)
turnoff()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment