Project tutorial
IoT Arduino YUN Ambient Sensor Adafruit I/O MQTT

IoT Arduino YUN Ambient Sensor Adafruit I/O MQTT © GPL3+

This tutorial shows how you can connect Arduino YUN to the Adafruit IO platform for sharing the DHT-11 sensor values.

  • 2,254 views
  • 2 comments
  • 2 respects

Components and supplies

Apps and online services

Adafruit Adafrut I/O MQTT Dashboard

About this project

This tutorial shows how you can connect Arduino YUN to the Adafruit IO platform for sharing the DHT-11 sensor value, the photoresistor value, and also control the LED on board, a relay, and a PWM output. The PWM output can control the brightness of a light or the speed of a motor.

For using an Arduino YUN with this tutorial, you must have connected the Arduino YUN to your LAN and then to internet. If Arduino is not connected to internet, the tutorial not work.

Step 1: Sign Up on Adafruit IO

The MQTT protocol is the best method for IoT now. It's simple; it's a complete method to connect the objects to the cloud through the internet. Adafruit Industries have created a library and platform to use that protocol with Arduino ESP and other hardware. To use this platform you must subscribe to Adafruit IO service. Go to Adafruit IO (https://io.adafruit.com/). Then sign up for free. Then follow the instructions. After you can see the Dashboard and try the functions of Adafruit IO. Now you can create a new Dashboard using the button "Create Dashboard". You must name the Dashboard "Arduino". After we add the values to the dashboard.

Step 2: Download the software

For uploading the code on Arduino YUN, you can download the official Arduino IDE. https://github.com/adafruit/Adafruit_IO_Arduino and install it manually, or install the library via "Manage Library".

To install the library by manual process:

  • First quit the Arduino application.
  • Then uncompress the ZIP file containing the library. For example, if you're installing a library called "ArduinoParty", uncompress ArduinoParty.zip. It should contain a folder called ArduinoParty, with files like ArduinoParty.cpp and ArduinoParty.h inside. (If the .cpp and .h files aren't in a folder, you'll need to create one. In this case, you'd make a folder called "ArduinoParty" and move into it all the files that were in the ZIP file, like ArduinoParty.cpp and ArduinoParty.h.)
  • Drag the ArduinoParty folder into this folder (your libraries folder). Under Windows, it will likely be called "My Documents\Arduino\libraries". For Mac users, it will likely be called "Documents/Arduino/libraries". On Linux, it will be the "libraries" folder in your sketchbook.

To install a new library into your Arduino IDE you can use the Library Manager (available from IDE version 1.6.2).

  • Open the IDE and click to the "Sketch" menu and then Include Library > Manage Libraries.
  • Then the library manager will open and you will find a list of libraries that are already installed or ready for installation. In this example, we will install the Bridge library.
  • Scroll the list to find it, then select the version of the library you want to install. Sometimes only one version of the library is available. If the version selection menu does not appear, don't worry: it is normal.
  • Finally click on install and wait for the IDE to install the new library. Downloading may take time depending on your connection speed.
  • Once it has finished, an Installed tag should appear next to the Bridge library. You can close the library manager.

Now you can see the library Adafruit MQTT on the Arduino IDE.

Step 3: Connect the sensor to Arduino YUN

To use Arduino YUN with this tutorial, you must have connected the Arduino YUN to your LAN and then to internet. If Arduino is not connected to internet, the tutorial not work.

Connect the photoresistor like in photo. Connect the photoresistor to input pin A0. Now connect the DHT-11 to the Arduino YUN. See the photo. Pay attention to connect the sensor to the board, you can burn the sensor or the Arduino YUN board. Then connect the PWM (pin number 3) to the LED, and pin number 4 to the relay. After connect the relay to the 5V of Arduino pin.

Step 4: Upload the code

There are two file in the tutorial. One is the example file by Adafruit MQTT library, the other is the file to use Arduino YUN with DHT-11 sensor, LED, PWM and relay,

Copy the code and modify the WifiSSID, PWD, and the Adafruit IO key.

Try first the first Adafruit Sketch; after you can try the DHT-11 code.

Upload the code, then open serial monitor. You can see the debugger messages.

Step 5: Setup your Dashboard

If that's okay, you can surf to http://io.adafruit.com and see your Dashboard called "Arduino". Now you can populate the Dashboard with feeds, and add the relay, LED and PWM controls.

To add the sensor blocks, you can click + symbol, and after add the block that you want. For the value of sensors, you can use Gauge block; for the relay and buttons, you can create buttons with "onoff" and "relay" as names. For the PWM output, you can create a slider with "slider" as its name.

Code

Test Adafruit IO Arduino YUNArduino
/***************************************************
  Adafruit MQTT Library Arduino Yun Example

  Make sure your Arduino Yun is connected to a WiFi access point which
  has internet access.  Also note this sketch uses the Console class
  for debug output so make sure to connect to the Yun over WiFi and
  open the serial monitor to see the console output.

  Works great with the Arduino Yun:
  ----> https://www.adafruit.com/products/1498

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
#include <Bridge.h>
#include <Console.h>
#include <YunClient.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"


/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    "...your AIO username (see https://accounts.adafruit.com)..."
#define AIO_KEY         "...your AIO key..."

/************ Global State (you don't need to change this!) ******************/

// Create a YunClient instance to communicate using the Yun's brighe & Linux OS.
YunClient client;

// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM    = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM  = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM  = AIO_KEY;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);

/****************************** Feeds ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
const char PHOTOCELL_FEED[] PROGMEM = AIO_USERNAME "/feeds/photocell";
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, PHOTOCELL_FEED);

// Setup a feed called 'onoff' for subscribing to changes.
const char ONOFF_FEED[] PROGMEM = AIO_USERNAME "/feeds/onoff";
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, ONOFF_FEED);

/*************************** Sketch Code ************************************/

void setup() {
  Bridge.begin();
  Console.begin();
  Console.println(F("Adafruit MQTT demo"));

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&onoffbutton);
}

uint32_t x=0;

void loop() {
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  // this is our 'wait for incoming subscription packets' busy subloop
  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(1000))) {
    if (subscription == &onoffbutton) {
      Console.print(F("Got: "));
      Console.println((char *)onoffbutton.lastread);
    }
  }

  // Now we can publish stuff!
  Console.print(F("\nSending photocell val "));
  Console.print(x);
  Console.print("...");
  if (! photocell.publish(x++)) {
    Console.println(F("Failed"));
  } else {
    Console.println(F("OK!"));
  }

  // ping the server to keep the mqtt connection alive
  if(! mqtt.ping()) {
    Console.println(F("MQTT Ping failed."));
  }

  delay(1000);

}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Console.print("Connecting to MQTT... ");

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Console.println(mqtt.connectErrorString(ret));
       Console.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
  }
  Console.println("MQTT Connected!");
}
Arduino YUN codeArduino
/***************************************************
  Adafruit MQTT Library Arduino Yun Example

  Make sure your Arduino Yun is connected to a WiFi access point which
  has internet access.  Also note this sketch uses the Console class
  for debug output so make sure to connect to the Yun over WiFi and
  open the serial monitor to see the console output.

  Works great with the Arduino Yun:
  ----> https://www.adafruit.com/products/1498

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
#include <Bridge.h>
#include <Console.h>
#include <YunClient.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "DHT.h"


/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883
#define AIO_USERNAME    “xxxx”
#define AIO_KEY         “xxxxxxxxxxxxxx”

// Umidità esterno
#define DHTPIN 2 
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

// Relay
#define relay 4
#define pwmout 3

/************ Global State (you don't need to change this!) ******************/

// Create a YunClient instance to communicate using the Yun's brighe & Linux OS.
YunClient client;

// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM    = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM  = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM  = AIO_KEY;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);

/****************************** Feeds ***************************************/

// Setup a feed called 'photocell' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
const char PHOTOCELL_FEED[] PROGMEM = AIO_USERNAME "/feeds/photocell";
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, PHOTOCELL_FEED);
const char HUMIDITY_FEED[] PROGMEM = AIO_USERNAME "/feeds/humidity";
Adafruit_MQTT_Publish humidity = Adafruit_MQTT_Publish(&mqtt, HUMIDITY_FEED);
const char TEMPERATURE_FEED[] PROGMEM = AIO_USERNAME "/feeds/temperature";
Adafruit_MQTT_Publish temperature = Adafruit_MQTT_Publish(&mqtt, TEMPERATURE_FEED);

// Setup a feed called 'onoff' for subscribing to changes.
const char ONOFF_FEED[] PROGMEM = AIO_USERNAME "/feeds/onoff";
Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, ONOFF_FEED);

const char RELAY_FEED[] PROGMEM = AIO_USERNAME "/feeds/relay";
Adafruit_MQTT_Subscribe relaybutton = Adafruit_MQTT_Subscribe(&mqtt, RELAY_FEED);

const char SLIDER_FEED[] PROGMEM = AIO_USERNAME "/feeds/slider";
Adafruit_MQTT_Subscribe slider = Adafruit_MQTT_Subscribe(&mqtt, SLIDER_FEED);
/*************************** Sketch Code ************************************/

void setup() {
  Bridge.begin();
  Console.begin();
  Console.println(F("Adafruit MQTT demo"));

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&relaybutton);
  mqtt.subscribe(&onoffbutton);
  mqtt.subscribe(&slider);
}

float photo = 0;

void loop() {
  photo = analogRead(0);
  photo = map(photo,0,1023,0,100);
  
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  // this is our 'wait for incoming subscription packets' busy subloop
  Adafruit_MQTT_Subscribe *subscription;
  
  while ((subscription = mqtt.readSubscription(5000))) {
        
    if (subscription == &slider) {
      Console.print(F("Slider: "));
      Console.println((char *)slider.lastread);
      uint16_t sliderval = atoi((char *)slider.lastread);
      analogWrite(pwmout, sliderval);
    }
    
    if (subscription == &relaybutton) {
      Console.print(F("Relay: "));
      Console.println((char *)relaybutton.lastread);
    }
    if (strcmp((char *) relaybutton.lastread, "ON") == 0) {
      digitalWrite(relay, HIGH);
    }
    else
    {
      digitalWrite(relay, LOW);
    }
    
    if (subscription == &onoffbutton) {
      Console.print(F("Got: "));
      Console.println((char *)onoffbutton.lastread);
    }
    if (strcmp((char *) onoffbutton.lastread, "ON") == 0) {
      digitalWrite (13, HIGH);
    }
    else
    {
      digitalWrite(13,LOW);
    }

  // Now we can publish Photo!
  Console.print(F("\nSending photocell val "));
  Console.print(photo);
  Console.print("...");
  if (! photocell.publish(photo)) {
    Console.println(F("Failed"));
  } else {
    Console.println(F("OK!"));
  }
  
  // Now we can publish Umi!
  Console.print(F("\nSending Umidity val "));
  Console.print(h);
  Console.print("...");
  if (! humidity.publish(h)) {
    Console.println(F("Failed"));
  } else {
    Console.println(F("OK!"));
  }
  
  // Now we can publish Temp!
  Console.print(F("\nSending Temperature val "));
  Console.print(t);
  Console.print("...");
  if (! temperature.publish(t)) {
    Console.println(F("Failed"));
  } else {
    Console.println(F("OK!"));
  }
  
  // ping the server to keep the mqtt connection alive
  if(! mqtt.ping()) {
    Console.println(F("MQTT Ping failed."));
  }

  delay(1000);

  }
    if(! mqtt.ping()) {
    mqtt.disconnect();
  }
}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Console.print("Connecting to MQTT... ");

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Console.println(mqtt.connectErrorString(ret));
       Console.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
  }
  Console.println("MQTT Connected!");
}
Adafruit I/O test on Github
https://github.com/adafruit/Adafruit_IO_Arduino

Comments

Similar projects you might like

Android App-Based Home Automation System Using IOT

Project tutorial by Team Autoshack

  • 24,839 views
  • 17 comments
  • 75 respects

Multiple mode Environmental Sensor Deck with MKR1000

Project tutorial by Team ConsoleTeam

  • 11,330 views
  • 13 comments
  • 46 respects

Smart Home Sensor Node

Project tutorial by vincent wong

  • 8,222 views
  • 3 comments
  • 16 respects

Arduino Temperature - Humidity - Rain Sensor

Project showcase by Rick_Findus

  • 7,425 views
  • 6 comments
  • 13 respects

Arduino UNO MQTT Meteo Station

Project tutorial by Giovanni Gentile

  • 5,008 views
  • 0 comments
  • 4 respects
Add projectSign up / Login