Python Code 16.1.1 SteppingMotor
First observe the project result, and then analyze the code.
1. Use cd command to enter 16.1.1_SteppingMotor directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/16.1.1_ SteppingMotor
2. Use python command to execute code "SteppingMotor.py".
python SteppingMotor.py
After the program is executed, the stepping motor will rotate 360° clockwise and then 360° anticlockwise,
circularly.
The following is the program code:
im port RPi. GPIO as GPIO
im port time
motorPins = ( 12, 16, 18, 22) #define pins connected to four phase ABCD of stepper
motor
CCWStep = (0x01,0x02,0x04,0x08) #define power supply order for coil for rotating
anticlockwise
CWStep = ( 0x08,0x04,0x02,0x01) #define power supply order for coil for rotating
clockwise
def setup():
p rint 'Program is starting...'
GPIO. setmode(GPIO.BOARD) # Numbers GPIOs by physical location
for pin in motorPins:
GPIO.setup(pin,GPIO.OUT)
#as for four phase stepping motor, four steps are a cycle. the function is used to drive
the stepping motor clockwise or anticlockwise to take four steps
def moveOnePeriod(direction,ms):
for j in range(0,4,1): #cycle for power supply order
for i in range(0,4,1): #assign to each pin, a total of 4 pins
if ( direction == 1):#power supply order clockwise
GPIO. output(motorPins[i],((CCWStep[j] == 1<<i) and GPIO.HIGH orGPIO.LOW))
else : #power supply order anticlockwise
GPIO. output(motorPins[i],((CWStep[j] == 1<<i) a nd GPIO. HIGH or GPIO.LOW))
if(ms<3): #the delay can not be less than 3ms, otherwise it will exceed
speed limit of the motor
ms = 3
time.sleep(ms*0.001)
#continuous rotation function, the parameter steps specify the rotation cycles, every
four steps is a cycle
def moveSteps(direction, ms, steps):
for i in range(steps):
moveOnePeriod(direction, ms)
#function used to stop rotating
def motorStop():