-1

I opted to try doing this with Thingspeak Library instead, which @gre_gor suggested early on. Worked much easier!

Here's working code for anyone else trying to do this. I used the MKR1000.

#include "ThingSpeak.h"
#include <SPI.h>
#include <WiFi101.h>
#include "DHT.h"

char ssid[] = "XXXXXX";    //  your network SSID (name) 
    char pass[] = "XXXXXXX";   // your network password
    int status = WL_IDLE_STATUS;
    WiFiClient  client;

unsigned long myChannel = CHANNEL;
const char * myReadAPIKey = "READKEY";
const char * myWriteAPIKey = "WRITEKEY";

#define DHTPIN 1   
#define DHTTYPE DHT11
DHT dht(DHTPIN,DHTTYPE);

void setup() {
  // put your setup code here, to run once:
 Serial.begin(9600);
WiFi.begin(ssid, pass);
 ThingSpeak.begin(client);
  delay(10000);

}

void loop() {
 printWifiStatus();
    Serial.println("Reading Sensor Data... ");

  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
    float water = ThingSpeak.readFloatField(myChannel, 4);

   delay(100);

    Serial.print("Writing to ThingSpeak... ");
    ThingSpeak.setField(1, (float)h);
    ThingSpeak.setField(2, (float)t);
    ThingSpeak.setField(3, (float)f);
    Serial.print("... ");
    ThingSpeak.writeFields(myChannel, myWriteAPIKey);
     delay(5000);

  Serial.print("Current temp is: "); 
  Serial.print(f);
  Serial.print(" *F and ");  
  Serial.print(t);
  Serial.println(" *C"); 
  Serial.print("Humidity: "); 
  Serial.print(h);
  Serial.println("% "); 
  Serial.print("Water Signal: "); 
  Serial.print(water);
  Serial.println(" seconds");

  Serial.println("Function complete, time to rest.");
  delay(10000); // Hibernate [To Do]

}

void printWifiStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

------------ ORIGINAL MESSAGE ------------------------------------------------

I've been banging my head against this for a week now and I have made no progress.

I'm trying to convert this code to also read a field on Thingspeak and print to serial (as well as run a pump based on the output). I've tried a handful of guides and recreating it from other projects to no avail. Is there a straightforward method?

#include <SPI.h> //you don't need this as we arn't using the shiled just chip
#include <WiFi101.h>
#include "DHT.h"

#define DHTPIN 1    // what pin we're connected to, pin1 is 5th pin from end
#define floatswitch 7 // float switch
// soil moisture sensor
int soilPin = 2;
int soilPower = 6; //Variable for Soil moisture Power

// light sensor

// Uncomment whatever DHT sensor type you're using!
#define DHTTYPE DHT11  // DHT 11
//#define DHTTYPE DHT21  // DHT 21
//#define DHTTYPE DHT22  // DHT 22

DHT dht(DHTPIN,DHTTYPE);

String apiKey ="XXXXXXX"; // api from ThingSpeak

char ssid[] = "XXXXX"; //  your network SSID (name)
char pass[] = "XXXXX";    //your network password
int keyIndex = 0;     // your network key Index number (needed only for WEP)

//#define WEBSITE "api.thingspeak.com"

//int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
char server[] = "api.thingspeak.com";    // name address for Google (using DNS)

// this function powers and reads the moisture sensor to avoid sensor corrosion. 
//int readSoil()
//{ 
  //  digitalWrite(soilPower, HIGH);//turn D7 "On"
    //int val = analogRead(soilPin);//Read the SIG value form sensor 
   // return val;//send current moisture value
   // digitalWrite(soilPower, LOW);//turn D7 "Off"
//}


// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
WiFiClient client;

void setup() {
  pinMode(floatswitch,INPUT_PULLUP);

  //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
  }

}



void loop() {   

pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT
 // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
//Connect to WPA/WPA2 network.Change this line if using open/WEP network
WiFi.begin(ssid, pass);
digitalWrite(soilPower, HIGH);//turn D7 "On"
    // wait 5 seconds for connection:
    delay(5000);  
  Serial.println("Connected to wifi");
  printWifiStatus();


// READ STUFF

String url = "/channels/358435/field/6/last.txt";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + server + "\r\n" +
        "Connection: close\r\n\r\n");
    String channelData = client.readStringUntil('\n');
// READ STUFF


  int h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  int t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  int f = dht.readTemperature(true);
  int x = digitalRead(floatswitch);
//This is a function used to get the soil moisture content
  int s = analogRead(soilPin);
  int w = 5; 


  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f))
  {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Soil Moisture: ");
  Serial.print(s);
  Serial.print(" *F ");
  Serial.print("Float Switch: ");
  Serial.print(x);
  Serial.print("channelData");
  Serial.println();


Serial.println("Starting connection to server..."); 
  // if you get a connection, report back via serial:
  if (client.connect(server, 80)) {




    Serial.println("connected to server");


          client.print(F("POST "));
          client.print("/update?key=apiKey&field1=" 
          +               (String) h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
                                   );

          String tsData = "field1="   //need the length to give to ThingSpeak
          +             (String)  h
          +  "&field2=" +(String) t
          +  "&field3=" +(String) f
          +  "&field4=" +(String) s
          +  "&field5=" +(String) x
          +  "&field6=" +(String) w
        ; 


          client.print("POST /update HTTP/1.1\n");  
          client.print("Host: api.thingspeak.com\n");
          client.print("Connection: close\n");
          client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
          client.print("Content-Type: application/x-www-form-urlencoded\n");
          client.print("Content-Length: ");
          client.print(tsData.length());  //send out data string legth to ts
          client.print("\n\n");
          client.print(tsData);
          client.stop();
          digitalWrite(soilPower, LOW);//turn D7 "Off"
          delay(200);
          Serial.println("Function complete, time to rest");
          WiFi.disconnect(); 

//This is where to put the sleep and hibernate stuff 

          delay(20000);

//hibernate stuff ^^^^
    } 

}


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");
}
  • 1
    Why not use a library and check the examples? – gre_gor Nov 29 '17 at 19:18
  • Sorry, I should have mentioned that. Trying not to get stuck with the Thingspeak library as I've read it gets buggy when other libraries update. Also trying to remain platform agnostic so I can plug this into Adafruit.io, AWS or whatever other data platforms come along down the road. – Mulcch Nov 29 '17 at 20:20
  • Thanks @Juraj I ddi try working through that and another question on SE here, but it came down to basically the following, but still didn't work. String data = "GET /channels/344468/fields/1/last"; Serial.println(data); – Mulcch Nov 29 '17 at 21:01
  • post the code of modified sketch – Juraj Nov 30 '17 at 5:05
0

You need to construct a client object and pass in a URL. Then, wait for a response and read data in from the client. Here is the main concept.

const char host[] = "api.thingspeak.com";

WiFiClient client;

const int httpPort = 80;

if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
}

String url = "/channels/1417/field/1/last.txt";

client.print(String("GET ") + url + " HTTP/1.1\r\n" +
        "Host: " + host + "\r\n" +
        "Connection: close\r\n\r\n");

while(client.available()) {
    String channelData = client.readStringUntil('\n');
    // do something with the data 

}

Make sure to include a Read API key if your channel is not public. Also, check out CheerLights project examples for more ideas on how to do this. Many CheerLights projects read data from a a ThingSpeak channel.

  • Thanks iohans! Tried dropping it in betweet brackets of // READ STUFF still working on it though, but first time it has still sent data while trying to do a GET request. – Mulcch Dec 4 '17 at 0:04
  • There is a lot to tighten up in your code. Move these lines to set up – iohans Dec 4 '17 at 2:33
  • pinMode(soilPower, OUTPUT);//Set D7 as an OUTPUT // attempt to connect to Wifi network: Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); //Connect to WPA/WPA2 network.Change this line if using open/WEP network WiFi.begin(ssid, pass); digitalWrite(soilPower, HIGH);//turn D7 "On" // wait 5 seconds for connection: delay(5000); Serial.println("Connected to wifi"); printWifiStatus(); – iohans Dec 4 '17 at 2:36
  • Also, you need the while client available to read the data into your string variable. The get is asynchronous, so the data is not ready immediately. You should separate read from write, and clear the client for each connection. – iohans Dec 4 '17 at 2:39
  • You've given me a lot of homework, thank you! Going to dig in tonight. One question about getting that into Setup, I want this to hibernate for several hours and turn off the wifi et all. Should I still move that to setup or put it in a separate loop like the printwifi status if I'm thinking about power saving. – Mulcch Dec 4 '17 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.