import RPi.GPIO as GPIO from time import sleep # Servo class class Servo(): '''Servo class''' def __init__(self, gpio, frequency_hz): self._gpio = gpio self._frequency_hz = frequency_hz def __enter__(self): self.Start() return self def __exit__(self, type, value, traceback): del type del value del traceback self.Stop() def Start(self): '''Setup PWM pin as output with the given frequency and at zero angle''' GPIO.setup(self._gpio, GPIO.OUT) self._pwm = GPIO.PWM(self._gpio, self._frequency_hz) self._pwm.start(0) # Ensure PWM is started sleep(0.1) def Stop(self): '''Stop the PWM pin and clean-up GPIO''' self._pwm.stop() del self._pwm GPIO.cleanup(self._gpio) def SetAngleDegrees(self, angle_degrees): '''Set a servo to a given angle''' duty_cycle = angle_degrees / 18 + 2 GPIO.output(self._gpio, True) self._pwm.ChangeDutyCycle(min(duty_cycle, 100)) sleep(1) GPIO.output(self._gpio, False) self._pwm.ChangeDutyCycle(0) # Set standard GPIO pin names (i.e. not the physical pins of the connector, # the logical ones, so 17 means GPIO 17, which is connector pin 11) GPIO.setmode(GPIO.BCM) angle_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,> servo_list = [Servo(17, 50), Servo(18, 50)] # Step through each angle with each servo for servo_target in servo_list: with servo_target as servo: for angle in angle_list: servo.SetAngleDegrees(angle) sleep(0.1) servo.SetAngleDegrees(0)