All Collections
IoT Projects Tutorials
Control an LED remotely with an Arduino and Ubidots
Control an LED remotely with an Arduino and Ubidots
S
Written by Sergio M
Updated over a week ago

What is Arduino?

Arduino is an open-source electronics platform based on easy-to-use hardware and software. The basic board can be connected to a series of devices to expand it’s possibilities; these devices are called “shields”. For this specific tutorial we will use the Arduino WiFi Shield.

About Ubidots

If you're new around here, Ubidots is a platform that allows you to easily setup an Internet-enabled device (an Arduino in this case) to push data to the cloud and display it in the form of pretty and user friendly graphs. You can also trigger SMS or Email alerts based on your data, and share your graphs in external web or mobile applications.

What you need

  • An Arduino Board. In this case we are using the Arduino UNO 

  • The Arduino WiFi Shield

  • USB Cable

  • An LED

  • A good WiFi connection!

Getting ready

Before we start with this tutorial you have to make sure you have the Arduino IDE up and running, and that you have installed Ubidots Arduino Library.

Hands on

Put the Shield on top of the Arduino board and connect the LED: The positive end in the  digital pin 12, and the negative end in any of the pins labeled GND.

To know which is the positive (+) end of the Led, look for the longer ending as shown in the picture below. In case they are the same size, look at the flat section on the bulb as shown in the picture. This will also indicate the negative ending.

Now go on to your Ubidots account. If you don’t have one yet, you can create one here.

1. Go to the Device section to create a new device called "control", press “Add new device” and assign the name previously mentioned.  

2. Once the device is created, enter to it and create a new default variable called "led".

Once the device and the variable are created you should have something like this:

3. Go to the Dashboard section to create a new "switch" control widget to control the status of the led. Choose the device you created, the variable, press “Finish”.

Once the widget is created, you will see the widget show in the Dashboard, like below:

4. Next, copy and paste the code below into the Arduino IDE. Once pasted, assign your wifi and token parameters where indicated in the code:

 /*************************************************************************************************
 * This example get the last value of a variable from the Ubidots Cloud(www.ubidots.com) to control
 * a Led.
 *
 * Requirements:
 * 1. In the Device section, create a new device called "control"
 * 2. Into the device just created, create a new default variable called "led"
 * 3. In the Dashboard section, create a new "switch" control widget to control the led :)
 *
 * IMPORTANT NOTE: Don't forget assign your WiFi credentials, ubidots token, and the pin where the
 * led is connected
 *
 * This example is given AS IT IS without any warranty
 *
 * Made by Maria Carlina Hernandez(http://github.com/mariacarlinahernandez/)
 *************************************************************************************************/
 
 /********************************
 * Libraries included
 *******************************/
#include <WiFi.h>

/********************************
 * Constants and objects
 *******************************/
namespace {
  const char * SSID_NAME = "assign_wifi_ssid_here"; // Put here your SSID name
  const char * SSID_PASS = "assign_wifi_ssid_pass_here"; // Put here your Network password
  const char * SERVER = "industrial.api.ubidots.com";
  const char * TOKEN = "assign_your_ubidots_token"; // Assign your Ubidots TOKEN
  const char * DEVICE_LABEL = "control"; // Assign the device label to get the values of the variables
  const char * VARIABLE_LABEL = "led"; // Assign the variable label to get the last value
  const char * USER_AGENT = "ArduinoWifi";
  const char * VERSION = "1.0";
  const int PORT = 80;
  int status = WL_IDLE_STATUS;
  int LED = 12; // assign the pin where the led is connected
}


WiFiClient client;

/********************************
 * Auxiliar Functions
 *******************************/

/*
   this method makes a HTTP connection to the server
   and send request to get a data
*/

float getData(const char * variable_label) {
  /* Assigns the constans as global on the function */
  char* response; // Array to store parsed data
  char* serverResponse; // Array to store values
  float num;
  char resp_str[700]; // Array to store raw data from the server
  uint8_t j = 0;
  uint8_t timeout = 0; // Max timeout to retrieve data
  uint8_t max_retries = 0; // Max retries to make attempt connection

  /* Builds the request GET - Please reference this link to know all the request's structures https://ubidots.com/docs/api/ */
  char* data = (char *) malloc(sizeof(char) * 220);
  sprintf(data, "GET /api/v1.6/devices/%s/%s/lv", DEVICE_LABEL, variable_label);
  sprintf(data, "%s HTTP/1.1\r\n", data);
  sprintf(data, "%sHost: things.ubidots.com\r\n", data);
  sprintf(data, "%sUser-Agent: %s/%s\r\n", data, USER_AGENT, VERSION);
  sprintf(data, "%sX-Auth-Token: %s\r\n", data, TOKEN);
  sprintf(data, "%sConnection: close\r\n\r\n", data);

  /* Initial connection */
  client.connect(SERVER, PORT);
 
  /* Reconnect the client when is disconnected */
  while (!client.connected()) {
    Serial.println("Attemping to connect");
    if (client.connect(SERVER, PORT)) {
      break;
    }

    // Tries to connect five times as max
    max_retries++;
    if (max_retries > 5) {
      Serial.println("Could not connect to server");
      free(data);
      return NULL;
    }
    delay(5000);
  }

  /* Make the HTTP request to the server*/
  client.print(data);

  /* Reach timeout when the server is unavailable */
  while (!client.available() && timeout < 2000) {
    timeout++;
    delay(1);
    if (timeout >= 2000) {
      Serial.println(F("Error, max timeout reached"));
      client.stop();
      free(data);
      return NULL;
    }
  }

  /* Reads the response from the server */
  int i = 0;
  while (client.available()) {
    char c = client.read();
    //Serial.write(c); // Uncomment this line to visualize the response from the server
    if (c == -1) {
      Serial.println(F("Error reading data from server"));
      client.stop();
      free(data);
      return NULL;
    }
    resp_str[i++] = c;
  }

  /* Parses the response to get just the last value received */
  response = strtok(resp_str, "\r\n");
  while(response!=NULL) {
    j++;
    //printf("%s", response);
    response = strtok(NULL, "\r\n");
    if (j == 10) {
      if (response != NULL) {
        serverResponse = response;
      }
      j = 0;
    }
  }

  /* Converts the value obtained to a float */
  num = atof(serverResponse);
  free(data);
  /* Removes any buffered incoming serial data */
  client.flush();
  /* Disconnects the client */
  client.stop();
  /* Returns de last value of the variable */
  return num;
}

/* This methods print the wifi status */
void printWifiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

/********************************
 * Main Functions
 *******************************/

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue:
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID_NAME);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID_NAME, SSID_PASS);

    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWifiStatus();

}

void loop() {
  float value = getData(VARIABLE_LABEL);
  Serial.print("The value received form Ubidots is: ");
  Serial.println(value);
  if ( value == 1.0) {
    digitalWrite(LED, HIGH);  
  } else {
    digitalWrite(LED, LOW);
  }
  delay(1000);
}

5. Once you have assigned the wifi credentials and Ubidots token, upload the code into the board

Go to your Dashboard and press "Click to switch ON” and if everything is correct, the led on the board will illuminate.

 

To verify how your device data is connected and transmitting data, goto Tools > Serial Monitor and wait for it to load. You can see the variable is modified: 1.0 when is on and 0.0 when off.

Wrapping Up

This tutorial explained how to control an LED remotely from your Ubidots dashboard. The same code can be used to control other things attached to the Arduino, like a door openers, pet feeders, water sprinkler, locks, other triggers etc.

More examples

Here further project ideas, check out...

Do you have more IoT ideas? Create a Ubidots account and make them real today!

Originally Published in Ubidots Blog August 18, 2014.

Did this answer your question?