Page 1 of 1

Python code for Phidget Stepper

Posted: Wed Sep 08, 2021 7:06 pm
by ats_1004
Hi I want to run a python script when a stepper motor stops.
I found example codes on website like this.
I tried but how can I print('stopped') when a stepper motor stops?

Code: Select all

from Phidget22.Phidget import *
from Phidget22.Devices.Stepper import *
import time

def onStopped(self):
ch = Stepper()
# Register for event before calling open
ch.setOnStoppedHandler(onStopped)
ch.open()
while True:
	# Do work, wait for events, etc.
	time.sleep(1)

Re: Python code for Phidget Stepper

Posted: Thu Sep 09, 2021 8:48 am
by mparadis
That code sample is incomplete (I'll look into having it updated). Here's a full program for the stopped event:

Code: Select all

from Phidget22.Phidget import *
from Phidget22.Devices.Stepper import *
import time

def onStopped(self):
	print("Stopped!")

def main():
	stepper0 = Stepper()

	stepper0.setOnStoppedHandler(onStopped)

	stepper0.openWaitForAttachment(5000)

	stepper0.setTargetPosition(10000)
	stepper0.setEngaged(True)

	try:
		input("Press Enter to Stop\n")
	except (Exception, KeyboardInterrupt):
		pass

	stepper0.close()

main()
Please note that the stopped event will only trigger when the stepper controller thinks the motor is stopped. In this example, the stopped event will trigger after the controller has sent out 10000 sixteenth-step signals to the motor. It has no way of knowing whether the motor actually got there, or if it stalled along the way. For this kind of control, you'd need an encoder on the motor to track the position to know for sure that it's stopped.