Arduino Code

The adafruitio_16_servo example uses pin 2 by default, and that can be modified by changing the SERVO_PIN define at the top of the sketch.

Download: file
// pin used to control the servo
#define SERVO_PIN 2

The next chunk of code sets up an instance of the Servo class, and also an instance of the Adafruit IO Feed class for a feed called servo.

Download: file
// create an instance of the servo class
Servo servo;

// set up the 'servo' feed
AdafruitIO_Feed *servo_feed = io.feed("servo");

In the setup function, we attach a function called handleMessage to the servo_feed, which will be called whenever your device receives messages for that feed. We also tell the servo class which pin we are using with the servo.attach() method.

The code will wait until you have a valid connection to Adafruit IO before continuing with the sketch. If you have any issues connecting, check config.h for any typos in your username or key.

Download: file
void setup() {

  // start the serial connection
  Serial.begin(115200);

  // wait for serial monitor to open
  while(! Serial);

  // tell the servo class which pin we are using
  servo.attach(SERVO_PIN);

  // connect to io.adafruit.com
  Serial.print("Connecting to Adafruit IO");
  io.connect();

  // set up a message handler for the 'servo' feed.
  // the handleMessage function (defined below)
  // will be called whenever a message is
  // received from adafruit io.
  servo_feed->onMessage(handleMessage);

  // wait for a connection
  while(io.status() < AIO_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  // we are connected
  Serial.println();
  Serial.println(io.statusText());

}

Next, we have the main loop() function. The first line of the loop function calls io.run(); this line will need to be present at the top of your loop in every sketch. It helps keep your device connected to Adafruit IO, and processes any incoming data.

Download: file
void loop() {
  // io.run(); is required for all sketches.
  // it should always be present at the top of your loop
  // function. it keeps the client connected to
  // io.adafruit.com, and processes any incoming data.
  io.run();
}

The final chunk of code is the handleMessage function. This is the function that is called whenever servo_feed gets a message.

We use the data->toInt() function to convert the incoming data to an int, and set the angle of the servo to that value using servo->write(). We also check to make sure that the incoming angle value is not less than 0, or greater than 180.

Download: file
      // this function is called whenever a 'servo' message
// is received from Adafruit IO. it was attached to
// the servo feed in the setup() function above.
void handleMessage(AdafruitIO_Data *data) {

  // convert the data to integer
  int angle = data->toInt();

  // make sure we don't exceed the limit
  // of the servo. the range is from 0
  // to 180.
  if(angle < 0)
    angle = 0;
  else if(angle > 180)
    angle = 180;

  servo.write(angle);

}
    

If you would like your servo to switch directions, you can subtract the angle from 180, and write the result to the servo.

Download: file
 servo.write(180 - angle);

Upload the sketch to your board, and open the Arduino Serial Monitor. Your board should now connect to Adafruit IO.

Download: file
Connecting to Adafruit IO....

Adafruit IO connected.

Change the slider value on your Adafruit IO dashboard, and you should see the servo change position depending on the value you send.

"""
`servo.py`
========================================================================

Control a servo with Adafruit IO
Tutorial Link: https://learn.adafruit.com/adafruit-io-basics-servo

Adafruit invests time and resources providing this open source code.
Please support Adafruit and open source hardware by purchasing
products from Adafruit!

Author(s): Brent Rubell for Adafruit Industries
Copyright (c) 2018 Adafruit Industries
Licensed under the MIT license.
All text above must be included in any redistribution.

Dependencies:
    - Adafruit_Blinka
        (https://github.com/adafruit/Adafruit_Blinka)
    - Adafruit_CircuitPython_PCA9685
        (https://github.com/adafruit/Adafruit_CircuitPython_PCA9685)
    - Adafruit_CircuitPython_Motor
        (https://github.com/adafruit/Adafruit_CircuitPython_Motor)
"""

# import system libraries
import time

# import Adafruit Blinka
from board import SCL, SDA
from busio import I2C

# import the PCA9685 module.
from adafruit_pca9685 import PCA9685

# import the adafruit_motor library
from adafruit_motor import servo

# import Adafruit IO REST client
from Adafruit_IO import Client, Feed, RequestError

# Set to your Adafruit IO username.
# (go to https://accounts.adafruit.com to find your username)
ADAFRUIT_IO_USERNAME = 'YOUR_AIO_USERNAME'

# Set to your Adafruit IO key.
# Remember, your key is a secret,
# so make sure not to publish it when you publish this code!
ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY'

# Create an instance of the REST client.
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

try: # if we have a 'servo' feed
    servo_feed = aio.feeds('servo')
except RequestError: # create a servo feed
    feed = Feed(name='servo')
    servo_feed = aio.create_feed(feed)

# Create the I2C bus interface.
i2c_bus = I2C(SCL, SDA)

# Create a simple PCA9685 class instance.
pca = PCA9685(i2c_bus)

# Set the PWM frequency to 50hz.
pca.frequency = 50
SERVO_CHANNEL = 0

# counter variable for the last servo angle
prev_angle = 0

# set up the servo on PCA channel 0
my_servo = servo.Servo(pca.channels[SERVO_CHANNEL])


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, 'Degrees')
        # 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)
This guide was first published on Feb 21, 2017. It was last updated on Feb 21, 2017. This page (Arduino Code) was last updated on Sep 22, 2019.