code.py
1 # SPDX-FileCopyrightText: 2019 Carter Nelson for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 # Example code for using analog feedback value to seek a position 6 import board 7 import pwmio 8 from simpleio import map_range 9 from adafruit_motor import servo 10 from analogio import AnalogIn 11 12 # Demo angles 13 angles = [0, 180, 0, 45, 180] 14 15 # Pin setup 16 SERVO_PIN = board.A1 17 FEEDBACK_PIN = board.A5 18 19 # Calibration setup 20 CALIB_MIN = 18112 21 CALIB_MAX = 49408 22 ANGLE_MIN = 0 23 ANGLE_MAX = 180 24 25 # Setup servo 26 pwm = pwmio.PWMOut(SERVO_PIN, duty_cycle=2 ** 15, frequency=50) 27 servo = servo.Servo(pwm) 28 servo.angle = None 29 30 # Setup feedback 31 feedback = AnalogIn(FEEDBACK_PIN) 32 33 def get_position(): 34 return map_range(feedback.value, CALIB_MIN, CALIB_MAX, ANGLE_MIN, ANGLE_MAX) 35 36 def seek_position(position, tolerance=2): 37 servo.angle = position 38 39 while abs(get_position() - position) > tolerance: 40 pass 41 42 print("Servo feedback seek example.") 43 for angle in angles: 44 print("Moving to {}...".format(angle), end="") 45 seek_position(angle) 46 print("Done.")