The code uses the PyPortal's D3 pin to control the relay's power signal. 

// Relay is connected to PyPortal's D3 connector

Next, the code sets up an instance of the relay feed you created in the previous guide.

// Set up the 'relay feed'
AdafruitIO_Feed *relay = io.feed("relay");

This chunk of code connects your device to Adafruit IO. It sets up a message handler for the relay feed. Whenever a new value is received on the relay feed, the handleMessage function will execute. 

The code performs a relay->get() to obtain the last known value of the relay feed. This line is useful because if you lose connection for any reason, the code will set up the appliance in the correct state when it restarts.

void setup() {

  // start the serial connection

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

  Serial.print("Connecting to Adafruit IO");

  // connect to

  // set up a message handler for the 'relay' feed.
  // the handleMessage function (defined below)
  // will be called whenever a message is
  // received from adafruit io

  // wait for a connection
  while(io.status() < AIO_CONNECTED) {

  // we are connected

  // Get the last known value from the feed


Next, we have the main loop() function. The first line of the loop function calls - this line will need to be present at the top of the loop in every sketch. It helps keep a device connected to Adafruit IO, and processes any incoming data from the feeds its subscribed to.

void loop() {

  //; is required for all sketches.
  // it should always be present at the top of your loop
  // function. it keeps the client connected to
  //, and processes any incoming data.;


Whenever a new value is received on the relay feed, the handleMessage function will execute. This function prints out the new data it received 

void handleMessage(AdafruitIO_Data *data) {

  Serial.print("feed received new data <- ");

Checks if the data received by the feed matches the value published to the morning scheduled action. If there's a match, the signal pin is written HIGH which turns on the outlet.

// Check to see if the morning scheduled trigger has executed
  if (strcmp(data->toChar(), "morning") == 0) {
      Serial.println("Turning lights ON");
      digitalWrite(RELAY_POWER_PIN, HIGH);

If the morning action value was not found, check if the evening action has fired. If the evening action value was found, turn off the outlet.

Any unexpected data received by the relay feed will print an error message.

// Check to see if the evening scheduled action has executed
  else if (strcmp(data->toChar(), "night") == 0) {
      Serial.println("Turning lights OFF");
      digitalWrite(RELAY_POWER_PIN, LOW);
  else {
      Serial.println("Unexpected data received from Adafruit IO");

This guide was first published on Sep 29, 2020. It was last updated on May 21, 2024.

This page (Arduino Code Walkthrough) was last updated on Mar 08, 2024.

Text editor powered by tinymce.