One of the things I love about the Linkit is it's speed for networking. From the WiFi provisioning, to managing TCP/HTTP connections, it responds really fast. So let's see it in action!
Coding
The following code will read the A0 analog input on the Linkit One board, and send the value to the Ubidots IoT Cloud. In this case, I plugged a potentiometer using a Grove Kit.
I used the Arduino 1.5.7 in OSX with the Linkit One Library installed. Please refer to Linkit's resources to install their library in your Arduino IDE.
First, let's define some constants and add the required libraries:
#include <LTask.h>
#include <LWiFi.h>
#include <LWiFiClient.h>
#define WIFI_AP "Abriles_LTE"
#define WIFI_PASSWORD "12345678"
#define WIFI_AUTH LWIFI_WPA // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP.
// Ubidots information
#define URL "things.ubidots.com"
#define TOKEN "6ZImU622GhkhgdscutlSnMd8ayOkjgRps" // replace with your Ubidots token generated in your profile tab
#define VARIABLEID "5570c29a7625424f27703355" // Replace with your the ID of the Ubidots variable
Then we setup the WiFi and Serial communications (to see what's going on in the device through a serial terminal):
void setup()
{
LTask.begin();
LWiFi.begin();
Serial.begin(9600);
// keep retrying until connected to AP
Serial.println("Connecting to AP");
while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
{
delay(1000);
}
}
Then, the main loop just reads the analog input A0 and passes the value as a String to the Ubidots function:
void loop()
{
save_value(String(analogRead(A0)));
// delay(500); // Set here the desired update frequency
}
The Ubidots function looks like this:
void save_value(String value){
Serial.println("Sending value to Ubidots...");
LWiFiClient c;
while (!c.connect(URL, 80))
{
Serial.println("Retrying to connect...");
delay(100);
}
String data = "{\"value\":"+ value + "}";
String thisLength = String(data.length());
// Build HTTP POST request
c.print("POST /api/v1.6/variables/");
c.print(VARIABLEID);
c.print("/values?token=");
c.print(TOKEN);
c.println(" HTTP/1.1");
c.println("Content-Type: application/json");
c.println("Content-Length: " + thisLength);
c.print("Host: ");
c.println(URL);
c.print("\n" + data);
c.print(char(26));
// read server response
while (c){
Serial.print((char)c.read());
}
c.stop();
}
Below you'll find the entire code! You can replace the A0 with any other sensor, and you'll be able to see the data in real time in your Ubidots account.
Comments