I am new at object oriented programming.I am working with Raspberry pi and I am building many classes which have different GPIO pins. I don’t know how to build setup and pwm comands. All of them should stay out of the classes or should I put them in init function for each class? How will it change for OOP in init function? Can you show me an example on this code?
GPIO.setup(33, GPIO.OUT)
pwmservo=GPIO.PWM(33,50)
pwmservo.start(6)
class zmove(object):
def __init__(self):
pass
def update(self,angle):
duty=float(angle)/10.0+2.5
pwmservo.ChangeDutyCycle(duty)
time.sleep(0.3)
Question: gpio setup and pwm commands in init function of a class?
class PWMServo:
"""
Base class doing setup and get PWM instance
"""
def __init__(self, pin):
GPIO.setup(pin, GPIO.OUT)
self.pwm = GPIO.PWM(pin, 50)
self.pwm.start(6)
def change_duty_cycle(self, duty):
self.pwm.ChangeDutyCycle(duty)
time.sleep(0.3)
class ZMove(PWMServo):
"""
Inherit from class PWMServo
ZMove use PIN 33
"""
def __init__(self):
super().__init__(pin=33)
self.pwm.start(6)
def update(self,angle):
duty=float(angle)/10.0+2.5
self.change_duty_cycle(duty)
if __name__ == '__main__':
zmove = ZMove()
zmove.update(45.0)
# Or, call direct
zmove.change_duty_cycle(45.0/10.0+2.5)