Thursday, August 10, 2017

Getting Started with Arduino and the ThingSpeak Cloud

In this video we look at how to use Arduino with the ThingSpeak IoT, cloud, and analytics platform. In the video we look at two use cases of ThingSpeak. For the first use case we log wireless sensor data to the cloud and perform post processing on the data using MATLAB. In the second use case we monitor a room with a wireless motion detector setup and have ThingSpeak send out a Tweet if any movement is detected in the room.



//*****************Arduino code from video**********************************
/*
This sketch was created for a video tutorial on the ForceTronics YouTube that shows how to use Arduino with the ThingSpeak cloud
This code is public domain and free for anybody to use or modify at their own risk

Note this code was leveraged from:
 Arduino --> ThingSpeak Channel via MKR1000 Wi-Fi
 Created: May 7, 2016 by Hans Scharler (http://www.nothans.com)
*/
   
#include <SPI.h>
#include <WiFi101.h> //This sketch should work with any Arduino or shield that can use the WiFi101 library

char ssid[] = "YourNetwork"; //  your network SSID (name)
char pass[] = "YourPassword"; // your network password

int status = WL_IDLE_STATUS;

// Initialize the Wifi clients
WiFiClient tClient; //this one is used to post temperature data
WiFiClient mClient; //this one is used to post motion detection data

// ThingSpeak Settings
char server[] = "api.thingspeak.com";
String writeAPIKey = "YourWriteKey";

//Timing variables for tracking temperature posting
unsigned long tempLastConnectionTime = 0; // track the last connection time
const unsigned long tempPostingInterval = 295000L; // post temp ADC value just under every 5 min

//Timing and logic variables for tracking temperature posting
unsigned long mLastConnectionTime = 0; // track the last connection time
const unsigned long mPostingInterval = 30000L; //checks to see if motion was detected every 30 sec
bool mReset = true; //tracks if motion detection has been reset

void setup() {
  pinMode(2,INPUT); //digital pin used to read output of motion detector
  pinMode(6,OUTPUT); //LED pin used to know when data is sent to cloud
  
  // attempt to connect to Wifi network
  while ( status != WL_CONNECTED) {
    // Connect to WPA/WPA2 Wi-Fi network
    status = WiFi.begin(ssid, pass);
    // wait 10 seconds for connection
    delay(10000);
  }
}

void loop() {
  //timer to know when it is time to post temp data to cloud
  if (millis() - tempLastConnectionTime > tempPostingInterval) {
    digitalWrite(6,HIGH); //Use the LED to see if Arduino gets heldup posting data to the cloud
    tempHttpRequest(); //function that formats data strings and posts data to ThingSpeak cloud
    digitalWrite(6,LOW);
  }

  if (millis() - mLastConnectionTime > mPostingInterval) {
    digitalWrite(6,HIGH); //Use the LED to see if Arduino gets heldup posting data to the cloud
    if(digitalRead(2) && mReset) { //if motion was detected post it
      mReset = false; //motion detected so reset variable
      mHttpRequest(); //if true motion was detected so post to cloud
    }
    else mReset = true; //reset logic tracker
    
    digitalWrite(6,LOW);
  }

}

//Posts temp data to thingspeak cloud
void tempHttpRequest() {
  // read analog pin 0 with temp sensor connected
  int sensorValue = analogRead(0);

  // create data string to send to ThingSpeak
 String data = String("field1=" + String(sensorValue, DEC)); 

  // POST data to ThingSpeak
  if (tClient.connect(server, 80)) {
    tClient.println("POST /update HTTP/1.1");
    tClient.println("Host: api.thingspeak.com");
    tClient.println("Connection: close");
    tClient.println("User-Agent: ArduinoWiFi/1.1");
    tClient.println("X-THINGSPEAKAPIKEY: "+writeAPIKey);
    tClient.println("Content-Type: application/x-www-form-urlencoded");
    tClient.print("Content-Length: ");
    tClient.print(data.length());
    tClient.print("\n\n");
    tClient.print(data);
     // close any connection before sending a new request
    tClient.stop();
    // note the last connection time
    tempLastConnectionTime = millis();
  }
}

//posts motion detection data to thingspeak cloud
void mHttpRequest() {

  // create data string to send to ThingSpeak, we always send a one here to indicate motion detected
 String data = String("field2=" + String(1,DEC)); 

  // POST data to ThingSpeak
  if (mClient.connect(server, 80)) {
    mClient.println("POST /update HTTP/1.1");
    mClient.println("Host: api.thingspeak.com");
    mClient.println("Connection: close");
    mClient.println("User-Agent: ArduinoWiFi/1.1");
    mClient.println("X-THINGSPEAKAPIKEY: "+writeAPIKey);
    mClient.println("Content-Type: application/x-www-form-urlencoded");
    mClient.print("Content-Length: ");
    mClient.print(data.length());
    mClient.print("\n\n");
    mClient.print(data);
     // close any connection before sending a new request
    mClient.stop();
    // note the last connection time
    mLastConnectionTime = millis();
  }
}

%*************************MATLAB code from video***************************
% Channel ID to read raw ADC temp data from
readChannelID = chanID;
% Temperature Field ID
TemperatureFieldID = 1;

% Channel Read API Key 
readAPIKey = 'YourReadKey';

% Channel ID to write temp data to:
writeChannelID = [chanID];
% API key for write channel:
writeAPIKey = 'YourWriteKey';

%Read raw ADC temp data
aDC = thingSpeakRead(readChannelID, 'Fields', TemperatureFieldID, 'ReadKey', readAPIKey);

%Convert raw 10 bit ADC data to voltage
volt = aDC*(3.3/1023);

%Using analog temp sensor TMP36
%calculate temp in C, .75 volts is 25 C. 10mV per degree
 if volt < .75 
     temp = 25 - ((.75-volt)/.01); %if below 25 C
 elseif volt == .75 
         temp = 25;
 else 
     temp = 25 + ((volt -.75)/.01);  %if above 25
 end

% Convert to Fahrenheit
tempF = (9/5*temp) + 32;

%This writes temp value to below console for debugging
display(tempF);

%write temp F value to channel
thingSpeakWrite(writeChannelID, 'Fields',1,'Values',tempF, 'Writekey', writeAPIKey);