Caveat here I am not a programmer in any fashion.
I wanted to start to grow veg and being not the responsible person to remember to water and look after plants I decided to make things simple for me. Also as I have a strange obsession to see graphs I wanted to be able to log all sensors and see them in a pretty graph (No reason why, just like graphs).
With this is mind I thought I would start in testing how to log to a web provider like www.thingspeak.com
After looking into many tutorials and not liking seeing the libraries for the ESP8266 I thought I would go through the pain in hacking them all to make it work for what I want it to do. Below is the code I eventually came up with.
This code is just a simple connect to services and create some random numbers that posts to the website in two fields. It can be easily adapted and refined (call all fields in a single function once you know how many you need).
Hope this helps and I will try and answer questions if I can.
This script will create two random numbers and post each number in Field 1 and Field 2 then wait 2 mins. The free version needs to wait 15 seconds before you can post so hence the Delay between calling the other sendData command in Void Loop.
All your code will be in [VOID LOOP] and then just amend the sendData as needed but make sure you create enough Fields in ThingSpeak
I hope this can help someone.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define WIFI_SSID "Your SSID" //Set your Wifi name
#define WIFI_PASS "Your Password" //Set your Wifi Password
#define SERIAL_BAUDRATE 9600
#define TSKEY "Your Creation API Key" // Thingspeak Key
#define IP "184.106.153.149" // thingspeak.com
int Random = 0;
long randNumber;
int brightness;
int Field;void setup() {
Serial.begin(SERIAL_BAUDRATE);
wifiSetup();
}void loop() {
randNumber = random(10, 20);
Field = 1;
sendData (String(Field), String(randNumber));
randNumber = random(10, 20);
delay(30000);
Field = 2;
sendData (String(Field), String(randNumber));
delay(120000);
}void wifiSetup() {
// Set WIFI module to STA mode
WiFi.mode(WIFI_STA);// Connect
Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASS);// Wait
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(100);
}
Serial.println();// Connected!
Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}void sendData(String Field, String tBrightness){
HTTPClient http;
String cmd = "http://api.thingspeak.com/update?key=";
cmd += TSKEY;
cmd += "&field";
cmd += Field;
cmd += "=";
cmd += tBrightness;
http.begin(cmd);
Serial.print ("Sending: ");
Serial.println (cmd);
int httpCode = http.POST(cmd); //Send the request
String payload = http.getString(); //Get the response payload
Serial.println (payload);
delay(2000);
if(Serial.find("Error")){
return;
}
}