import pigpio import sys import tty import termios import select from random import randrange, shuffle from time import sleep # How much the angle of a servo is changed at every key press ANGLE_STEP_DEGREES = 2 # Types of command for an individual servo COMMAND_ANGLE_INCREMENT = 0 # Single parameter is the angle to increment by in degrees COMMAND_ANGLE_CONVERGE = 1 # Two parameters: angle to converge on and the increment to do it by COMMAND_ANGLE_SET = 2 # Single parameter is the angle to set # Servo class class Servo(): '''Servo class''' def __init__(self, pi, gpio, name=None, limit_upper_degrees=None, limit_lower_degrees=None): '''Create a servo, needs a reference to the pigpiod class, the GPIO and a name for the servo''' self.pi = pi self.gpio = gpio self.name = name self.limit_upper_degrees = limit_upper_degrees self.limit_lower_degrees = limit_lower_degrees self.angle_at_limit = False self.angle_degrees = 0 def __enter__(self): self.Start() return self def __exit__(self, type, value, traceback): del type del value del traceback self.Stop() def _convert_pulse_width_microseconds(self, angle_degrees): '''Private: return the pulse width corresponding to a given angle''' # We loop here so that we don't overshoot the angle due to rounding loop_count = 0 angle_target_degrees = angle_degrees while loop_count < 100: loop_count += 1 _angle_degrees = angle_target_degrees if self.limit_upper_degrees: _angle_degrees = min(_angle_degrees, self.limit_upper_degrees) if self.limit_lower_degrees: _angle_degrees = max(_angle_degrees, self.limit_lower_degrees) self.angle_at_limit = (_angle_degrees != angle_degrees) pulse_width_microseconds = 1500 + (_angle_degrees / 90) * 1000 pulse_width_microseconds = max(min(pulse_width_microseconds, 2500), 500) # Turn the pulse width back into an angle and check that rounding hasn't taken us over if abs(self._convert_angle_degrees(pulse_width_microseconds)) <= abs(_angle_degrees): # Done break; else: if angle_target_degrees > 0: angle_target_degrees -= 1 else: angle_target_degrees += 1 if loop_count >= 100: print(f"WARNING: unable to set angle {angle_degrees} degrees event after {loop_count} iterations.") return pulse_width_microseconds def _convert_angle_degrees(self, pulse_width_microseconds): '''Private: return the angle corresponding to a given pulse width''' return int((pulse_width_microseconds - 1500) * 90 / 1000) def _set_angle_degrees(self, angle_degrees): '''Private: set the servo to the given angle, returning the angle set''' pulse_width_microseconds = self._convert_pulse_width_microseconds(angle_degrees) self.pi.set_servo_pulsewidth(self.gpio, pulse_width_microseconds) self.angle_degrees = self._convert_angle_degrees(pulse_width_microseconds) if self.name: print(f"'{self.name}' servo, ", end='') print(f"GPIO {self.gpio:02d}: angle {self.angle_degrees:+3d} degrees, pulse {pulse_width_microseconds:4.0f} us", end='') if self.angle_at_limit: print(" AT LIMIT", end='') print("") sleep(0.1) return self.angle_degrees 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 GetName(self): '''Get the servo name''' return self.name def IncAngleDegrees(self, angle_degrees): '''Increment the angle of a servo by a given amount (which may be negative), returning the new angle''' return self._set_angle_degrees(self.angle_degrees + angle_degrees) def SetAngleDegrees(self, angle_degrees): '''Set a servo to a given angle, returning the angle set''' return self._set_angle_degrees(angle_degrees) def GetAngleDegrees(self): '''Get the servo angle''' return self.angle_degrees def GetAngleAtLimit(self): '''Get whether we've hit a limit or not''' return self.angle_at_limit # Get keyboard input: for non-blocking input, specify a timeout value def getch(timeout_seconds=None): fd = sys.stdin.fileno() saved_settings = termios.tcgetattr(fd) try: # Switch echo off new_settings = saved_settings[:] new_settings[3] &= ~termios.ECHO termios.tcsetattr(fd, termios.TCSADRAIN, new_settings) # Set unbuffered tty.setraw(fd) x = None if timeout_seconds is None or select.select([sys.stdin], [], [], timeout_seconds)[0]: 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) # Flush anything else termios.tcflush(fd, termios.TCIFLUSH) return x # Return True if a number is non-negative def non_negative(x): return abs(x) != x # Do COMMAND_ANGLE_INCREMENT def do_command_angle_increment(servo_key, angle_increment_degrees): servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees) # Do COMMAND_ANGLE_SET def do_command_angle_set(servo_key, angle_set_degrees): loop_count = 0 angle_delta = servo_dictionary[servo_key].GetAngleDegrees() - angle_set_degrees angle_delta_sign_change = False while angle_delta != 0 and angle_delta_sign_change == False and loop_count < 100: loop_count += 1 angle_increment_degrees = ANGLE_STEP_DEGREES if angle_delta > 0: angle_increment_degrees = -angle_increment_degrees servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees) angle_delta_new = servo_dictionary[servo_key].GetAngleDegrees() - angle_set_degrees angle_delta_sign_change = (non_negative(angle_delta_new) != non_negative(angle_delta)) angle_delta = angle_delta_new if loop_count >= 100: print(f"WARNING: unable to set angle {angle_set_degrees} degrees even after {loop_count} iterations.") # Do COMMAND_ANGLE_CONVERGE def do_command_angle_converge(servo_key, angle_converge_degrees, angle_increment_degrees): angle_increment_degrees_abs = abs(angle_increment_degrees) if servo_dictionary[servo_key].GetAngleDegrees() > angle_converge_degrees: angle_increment_degrees_abs = -angle_increment_degrees_abs servo_dictionary[servo_key].IncAngleDegrees(angle_increment_degrees_abs) # Perform a command on a servo def do_command(servo_key, command_type, parameter_list): if command_type == COMMAND_ANGLE_INCREMENT: do_command_angle_increment(servo_key, parameter_list[0]) elif command_type == COMMAND_ANGLE_SET: do_command_angle_set(servo_key, parameter_list[0]) elif command_type == COMMAND_ANGLE_CONVERGE: do_command_angle_converge(servo_key, parameter_list[0], parameter_list[1]) # Do random(ish) actions def random_actions(motion_dictionary): print("Moving randomly, press another valid key to return to normal") # The lists: actions may appear multiple times to happen more frequently # Each of the lists in action_dictionary are operated in parallel # The first action list are the leaning ones, the second are the head rotations action_dictionary = {'lean': {'type_list': ['forwards', 'backwards', 'left', 'right'], 'index': 0, 'length': 0}, 'rotate': {'type_list': ['rotate_left', 'rotate_right', 'rotate_right'], 'index': 0, 'length': 0}} while True: key = getch(0.1) if key: break else: for key, value in action_dictionary.items(): if value['length'] <= 0: value['index'] += 1 # Done with this action if key == 'lean': # Have a rest between leaning actions print("Having a rest.") command_list = motion_dictionary['centre'] for command in command_list: do_command(command[0], command[1], command[2:]) if value['index'] >= len(value['type_list']): # Done all action types, shuffle the list and reset the index shuffle(value['type_list']) value['index'] = 0 value['length'] = randrange(5, 25, 1) print(f"Moving {value['type_list'][value['index']]} {value['length']} time(s).") # Do the action command_list = motion_dictionary[value['type_list'][value['index']]] for command in command_list: do_command(command[0], command[1], command[2:]) value['length'] -= 1 print("Back to normal key-presses now") return key # Clean-up: after this the servos are set to reset positions and pi is stopped def cleanup(pi, servo_dictionary): print ("Cleaning up...") if servo_dictionary: for key, servo in servo_dictionary.items(): servo.SetAngleDegrees(0) servo.Stop() if pi and pi.connected: pi.stop() # Connect to pipgiod pi = pigpio.pi() if pi.connected: # The servo dictionary servo_dictionary = {'right': Servo(pi, 17, "right", 89, -89), 'left': Servo(pi, 18, "left", 89, -89), 'head': Servo (pi, 27, "head", 50, -50)} # A dictionary of motions, each with a list of commands to do to achieve that motion # Each thing to do starts with the servo key, then the command type and finally the parameters for that command, # aside from the random motion, which goes off piste motion_dictionary = {'forwards': [('left', COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES), ('right', COMMAND_ANGLE_INCREMENT, ANGLE_STEP_DEGREES)], 'backwards': [('left', COMMAND_ANGLE_INCREMENT, ANGLE_STEP_DEGREES), ('right', COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES)], 'left': [('left', COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES), ('right', COMMAND_ANGLE_CONVERGE, 0, ANGLE_STEP_DEGREES)], 'right': [('right', COMMAND_ANGLE_INCREMENT, ANGLE_STEP_DEGREES), ('left', COMMAND_ANGLE_CONVERGE, 0, ANGLE_STEP_DEGREES)], 'rotate_left': [('head', COMMAND_ANGLE_INCREMENT, ANGLE_STEP_DEGREES)], 'rotate_right': [('head', COMMAND_ANGLE_INCREMENT, -ANGLE_STEP_DEGREES)], 'centre': [('left', COMMAND_ANGLE_SET, 0), ('right', COMMAND_ANGLE_SET, 0), ('head', COMMAND_ANGLE_SET, 0)], 'random': None} # A dictionary of actions to take for a given key press # Note: the arrow keys get mapped to 'A'/'B' for up/down, 'C'/'D' for right/left action_dictionary = {'A': 'forwards', 'B': 'backwards', 'C': 'right', 'D': 'left', 'z': 'rotate_left', 'x': 'rotate_right', 'c': 'centre', 'r': 'random'} try: # Start all of the servos for key, servo in servo_dictionary.items(): servo.Start() # Wait for keyboard input print("Press z, x or the arrow keys to move the servos, c to centre, r for random(ish), CTRL-C to exit.") key = None while True: if key is None: key = getch() if key: action = action_dictionary.get(key) key = None if action: command_list = motion_dictionary[action] if command_list: for command in command_list: do_command(command[0], command[1], command[2:]) else: # Must be random key = random_actions(motion_dictionary) else: print("Only CTRL-C, z, x, c, r or the arrow keys up, down, left, right are valid.") cleanup(pi, servo_dicionary) except KeyboardInterrupt as ex: cleanup(pi, servo_dictionary) else: print("pigpiod is not running: sudo pigpiod please!")