Python code for Phidget Stepper

What do you need Phidgets to do for you?
ats_1004
Fresh meat
Posts: 1
Joined: Wed Sep 08, 2021 6:58 pm
Contact:

Python code for Phidget Stepper

Postby ats_1004 » Wed Sep 08, 2021 7:06 pm

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)

User avatar
mparadis
Site Admin
Posts: 864
Joined: Fri Oct 28, 2011 12:17 pm
Contact:

Re: Python code for Phidget Stepper

Postby mparadis » Thu Sep 09, 2021 8:48 am

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.


Return to “Phidgets”

Who is online

Users browsing this forum: No registered users and 1 guest