Hi,
Heres the full code:
Servo Class:
Code: Select all
import RPi.GPIO as GPIO
import time
class ServoControl:
servoPin = 21
frequency = 50
Neutral = 7.5
Min = 2.5
Max = 12.5
CurrentPos = 7.5
TurnDistance = 1
holdtime = 0.02
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPin,GPIO.OUT)
p = None
def __init__( self):
self.p = GPIO.PWM(self.servoPin,self.frequency)
def Start(self):
self.p.start(self.Neutral)
def Stop(self):
self.p.stop()
def TurnLeft(self):
val = self.CurrentPos + self.TurnDistance
self.Turn(val)
def TurnRight(self):
val = self.CurrentPos - self.TurnDistance
self.Turn(val)
def Turn(self, val):
if (val >= self.Min and val <= self.Max):
print val
self.p.ChangeDutyCycle(val)
self.CurrentPos = val
time.sleep(self.holdtime)
def CleanUp(self):
#self.p.stop()
GPIO.cleanup()
And then i test the servo using this simple script:
Code: Select all
#!/usr/bin/python
import sys
import time
sys.path.insert(0, '/home/pi/Programs/PythonLibz')
from zServoControl import ServoControl
try:
s = ServoControl()
s.Start()
s.TurnLeft()
time.sleep(0.5)
s.TurnLeft()
time.sleep(0.5)
s.TurnLeft()
time.sleep(0.5)
s.TurnLeft()
time.sleep(1)
s.TurnRight()
time.sleep(0.5)
s.Stop # ISSUE here, servo stops working after this stop.
print "round 2"
time.sleep(3)
s.Start()
s.TurnLeft()
time.sleep(0.5)
s.TurnLeft()
time.sleep(0.5)
s.TurnLeft()
time.sleep(0.5)
s.TurnLeft()
time.sleep(1)
s.TurnRight()
time.sleep(0.5)
s.Stop
except Exception as error:
print error
finally:
s.CleanUp()
My main doubt is, can we call the start method on PWM after calling its stop method? Or does it dispose the object after the stop method is called?
Also the reason I need to Start and Stop multiple times, is because I will be using the ServoClass in a flask web app which would run 24x7 so I want to enable the servo only when I want to move it.