|
| 1 | +""" |
| 2 | +`servo.py` |
| 3 | +------------------ |
| 4 | +Control a servo |
| 5 | +with Adafruit IO |
| 6 | +
|
| 7 | +Requires: |
| 8 | + - Adafruit-Blinka |
| 9 | + - Adafruit-CircuitPython-PCA9685 |
| 10 | + - Adafruit-CircuitPython-Motor |
| 11 | +""" |
| 12 | +# import system libraries |
| 13 | +import time |
| 14 | + |
| 15 | +# import Adafruit Blinka |
| 16 | +from board import SCL, SDA |
| 17 | +from busio import I2C |
| 18 | + |
| 19 | +# import the PCA9685 module. |
| 20 | +from adafruit_pca9685 import PCA9685 |
| 21 | + |
| 22 | +# import the adafruit_motor library |
| 23 | +from adafruit_motor import servo |
| 24 | + |
| 25 | +# import Adafruit IO REST client |
| 26 | +from Adafruit_IO import Client, Feed, RequestError |
| 27 | + |
| 28 | +# Set to your Adafruit IO username. |
| 29 | +# (go to https://accounts.adafruit.com to find your username) |
| 30 | +ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME' |
| 31 | + |
| 32 | +# Set to your Adafruit IO key. |
| 33 | +# Remember, your key is a secret, |
| 34 | +# so make sure not to publish it when you publish this code! |
| 35 | +ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY' |
| 36 | + |
| 37 | +# Create an instance of the REST client. |
| 38 | +aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) |
| 39 | + |
| 40 | +try: # if we have a 'servo' feed |
| 41 | + servo_feed = aio.feeds('servo') |
| 42 | +except RequestError: # create a servo feed |
| 43 | + feed = Feed(name='servo') |
| 44 | + servo_feed = aio.create_feed(feed) |
| 45 | + |
| 46 | +# Create the I2C bus interface. |
| 47 | +i2c_bus = I2C(SCL, SDA) |
| 48 | + |
| 49 | +# Create a simple PCA9685 class instance. |
| 50 | +pca = PCA9685(i2c_bus) |
| 51 | + |
| 52 | +# Set the PWM frequency to 50hz. |
| 53 | +pca.frequency = 50 |
| 54 | +SERVO_CHANNEL = 0 |
| 55 | + |
| 56 | +# counter variable for the last servo angle |
| 57 | +prev_angle = 0 |
| 58 | + |
| 59 | +# set up the servo on PCA channel 0 |
| 60 | +my_servo = servo.Servo(pca.channels[SERVO_CHANNEL]) |
| 61 | + |
| 62 | + |
| 63 | +while True: |
| 64 | + # grab the `servo` feed value |
| 65 | + servo_angle = aio.receive(servo_feed.key) |
| 66 | + if servo_angle.value != prev_angle: |
| 67 | + print('received <- ', servo_angle.value, 'Degrees') |
| 68 | + # write the servo to the feed-specified angle |
| 69 | + my_servo.angle = int(servo_angle.value) |
| 70 | + prev_angle = servo_angle.value |
| 71 | + # timeout so we don't flood IO with requests |
| 72 | + time.sleep(0.5) |
0 commit comments