The imports for this guide are similar to the other guides in this series involving analog PWM output (Color, Analog Output), except this time it uses an extra library: adafruit-circuitpython-motor
import time # system from board import SCL, SDA # blinka from busio import I2C from adafruit_pca9685 import PCA9685 # PCA Module from Adafruit_IO import Client, Feed, RequestError # adafruit io from adafruit_motor import servo # servo library
By default, the servo channel is on channel 0 of the PCA9685. If you'd like to change this, you can do so by modifying the SERVO_CHANNEL variable at the top of the code:
SERVO_CHANNEL = 0
Before we run the script, we'll need to change ADAFRUIT_IO_USERNAME
and ADAFRUIT_IO_KEY
to the username and key for your Adafruit IO account.
# Set to your Adafruit IO username. ADAFRUIT_IO_USERNAME = 'YOUR_IO_USERNAME' # Set to your Adafruit IO key. ADAFRUIT_IO_KEY = 'YOUR_IO_KEY'
Next, we set up the PCA9685 by creating an I2C bus, and passing that into a PCA9685 class. Then, we set the PWM frequency.
i2c_bus = I2C(SCL, SDA) pca = PCA9685(i2c_bus) pca.frequency = 50
Then, we instantiate a servo object called my_servo:
my_servo = servo.Servo(pca.channels[SERVO_CHANNEL])
in the while True loop, we first grab the servo feed value. Then, we compare it against the previous feed value. If it the feed value is different from the previous value, we set the servo angle to the feed's value.
while True: # grab the `servo` feed value servo_angle = aio.receive(servo_feed.key) if servo_angle.value != prev_angle: print('received <- ', servo_angle.value) # write the servo to the feed-specified angle my_servo.angle = int(servo_angle.value) prev_angle = servo_angle.value # timeout so we don't flood IO with requests time.sleep(0.5)
Unlike the Arduino example code, we don't need to handle the servo going past it's maximum or minimum angle, the adafruit-circuitpython-motor library handles that for us.
Change the slider value on your Adafruit IO dashboard, and you should see the values output from your terminal:
received <- 120 Degrees received <- 70 Degrees received <- 30 Degrees received <- 90 Degrees
You should also observe the servo change position depending on what value you send:
Page last edited March 08, 2024
Text editor powered by tinymce.