import pigpio import sys import tty import termios from time import sleep # Labels for the servos: these are indexes into the servo_list array SERVO_UP_DOWN = 0 SERVO_LEFT_RIGHT = 1 # How much the angle of a servo is changed at every key press ANGLE_STEP_DEGREES = 5 # Servo class class Servo(): '''Servo class''' def __init__(self, pi, gpio): self._pi = pi self._gpio = gpio def __enter__(self): self.Start() return self def __exit__(self, type, value, traceback): del type del value del traceback self.Stop() def Start(self): '''Set pin to be an output with no servo pulses''' self._pi.set_mode(self._gpio, pigpio.OUTPUT) self._pi.set_servo_pulsewidth(self._gpio, 0) def Stop(self): '''Stop the servo''' self._pi.set_servo_pulsewidth(self._gpio, 0) def SetAngleDegrees(self, angle_degrees): '''Set a servo to a given angle, returning the angle set''' pulse_width_microseconds = 1500 + (angle_degrees / 90) * 1000 pulse_width_microseconds = max(min(pulse_width_microseconds, 2500), 500) self._pi.set_servo_pulsewidth(self._gpio, pulse_width_microseconds) #print(f"GPIO {self._gpio:02d}: angle {angle_degrees:+3d} degrees, pulse {pulse_width_microseconds:4.0f} us") sleep(0.1) return int((pulse_width_microseconds - 1500) * 90 / 1000) # Get keyboard input def getch(): fd = sys.stdin.fileno() saved_settings = termios.tcgetattr(fd) try: tty.setraw(fd) x = sys.stdin.read(1) # Check for arrow keys (start with 0x1b) if x == '\x1b': # Read two more characters sys.stdin.read(1) # Discard the '[' x = sys.stdin.read(1) # Raise SIGINT if CTRL-C (ASCII 0x03) elif x == '\x03': termios.tcsetattr(fd, termios.TCSADRAIN, saved_settings) raise KeyboardInterrupt # Won't get to this line finally: termios.tcsetattr(fd, termios.TCSADRAIN, saved_settings) return x # Clean-up: after this the servos are set to reset positions and pi is stopped def cleanup(pi, servo_list): print ("Cleaning up...") if servo_list: for servo in servo_list: servo.SetAngleDegrees(0) servo.Stop() if pi and pi.connected: pi.stop() # Connect to pipgiod pi = pigpio.pi() if pi.connected: # The servo list: the servo at index 0 is treated as the up/down servo, index 1 the left/right servo servo_list = [Servo(pi, 17), Servo(pi, 18)] # A dictionary of actions to take for a given key press # The arrow keys get mapped to 'A'/'B' for up/down, 'C'/'D' for left/right action_list = {'A': (SERVO_UP_DOWN, ANGLE_STEP_DEGREES, "up"), 'B': (SERVO_UP_DOWN, -ANGLE_STEP_DEGREES, "down"), 'C': (SERVO_LEFT_RIGHT, ANGLE_STEP_DEGREES, "right"), 'D': (SERVO_LEFT_RIGHT, -ANGLE_STEP_DEGREES, "left")} try: # Start all of the servos for servo in servo_list: servo.Start() # A list to hold the angle of all servos, where none means "no pulses" servo_angle_list = [None] * len(servo_list) # Wait for keyboard input print("Press keys to move the servos, CTRL-C to exit.") while True: key = getch() if key: action = action_list.get(key) if action: servo_index = action[0] angle_step = action[1] descriptive_text = action[2] print(f"Moving {descriptive_text} {abs(angle_step)}ish degrees...", end='') angle = angle_step if servo_angle_list[servo_index]: angle = servo_angle_list[servo_index] + angle_step angle = servo_list[servo_index].SetAngleDegrees(angle) print(f" now at {angle} degrees.") servo_angle_list[servo_index] = angle else: print("Only up, down, left, right arrow keys (or CTRL-C) are valid.") cleanup(pi, servo_list) except KeyboardInterrupt as ex: cleanup(pi, servo_list) else: print("pigpiod is not running: sudo pigpiod please!")