Hendra Kusumah
Published © GPL3+

The Force of Things

Control all of your Things using "The Force." Also monitor your "Force" activity with ubidots.

IntermediateShowcase (no instructions)15 hours3,476
The Force of Things

Things used in this project

Story

Read more

Schematics

The Controlled Things

The Fritzing schematic

Code

photon-get-ubi.ino

Arduino
#include "HttpClient/HttpClient.h"
#include "application.h"

#define VARIABLE_ID "YOUR-VARIABLE-ID"
#define TOKEN "YOUR-UBIDOTS-TOKEN"

HttpClient http;
int value_index = 0;
String value_string, value;   // We'll use these strings to parse the response from Ubidots
float f_value;
unsigned int nextTime = 0;    // Next time to contact the server

http_header_t headers[] = {
    { "Content-Type", "application/json" },
    { NULL, NULL } // NOTE: Always terminate headers will NULL
};

http_request_t request;
http_response_t response;

void setup() {
    request.hostname = "things.ubidots.com";
    request.port = 80;
    request.path = "/api/v1.6/variables/"VARIABLE_ID"/values?page_size=1&token="TOKEN;  // Note "page_size=1" asks Ubidots only for the last value
    Serial.begin(9600);
}

void loop() {
    if (nextTime > millis()) {
        return;
    }

    // Make Get request
    http.get(request, response, headers);

    if (response.status == 200){

        // Look for the index of the JSON string "value:"
        value_index = response.body.indexOf("\"value\": ");

        // Chop the response from that index, until the end of the response string
        value_string = response.body.substring(value_index);

        // Get the value that is between the nine (9) characters of "\"-v-a-l-u-e-\"-: " and the next comma
        value = value_string.substring(9, value_string.indexOf(","));

        // See the value in the serial console, then cast it to a float (most sensor readings have decimals!)
        Serial.println(value);
        f_value = value.toFloat();

        if (f_value > 0){
            // Add your custom function to turn on the lights here
            Serial.println("Lights turned ON");
        }
        else{
            // Add your custom function to turn off the lights here
            Serial.println("Lights turned OFF");
        }

    }
    else {
        Serial.println("The server rejected the request with the response:");
        Serial.println(response.status);
        Serial.println(response.body);
    }

    nextTime = millis() + 1000;
}

Credits

Hendra Kusumah

Hendra Kusumah

30 projects • 126 followers
Love hacking and making new things from IoT to robotics

Comments