Skip to content

Instantly share code, notes, and snippets.

@MDevolution
Created May 5, 2020 21:05
Show Gist options
  • Save MDevolution/aae9e78c69c3a48e10353d10fc0ef5c5 to your computer and use it in GitHub Desktop.
Save MDevolution/aae9e78c69c3a48e10353d10fc0ef5c5 to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ThingSpeak.h>
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
unsigned long myChannelNumber = ; // Replace the 0 with your channel ID
const char* myWriteAPIKey = ""; // Paste your ThingSpeak Write API Key between the quotes
const char* MY_SSID = "";
const char* MY_PWD = "";
WiFiClient client;
//========================================
// SETUP
//========================================
void setup() {
Serial.begin(9600);
while (!Serial);
connectWifi();
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}
//========================================
// LOOP
//========================================
void loop() {
// Connect or reconnect to WiFi
if(WiFi.status() != WL_CONNECTED)
connectWifi();
// Read Temperature
DS18B20.requestTemperatures();
float temp = DS18B20.getTempCByIndex(0);
String reply = (String)"Temperature: " + (String)temp + (String)"°C";
Serial.println(reply);
//Send Temeprature
sendTemperatureTS(temp);
// Wait 20 seconds before sending a new value
delay(20000);
}
//========================================
// CONNECT TO WIFI
//========================================
void connectWifi(){
Serial.print("\nConnecting to "+*MY_SSID);
WiFi.begin(MY_SSID, MY_PWD);
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected");
}
//========================================
// SEND TEMPERATURE TO THINGSPEAK
//========================================
void sendTemperatureTS(float temp){
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different
// pieces of information in a channel. Here, we write to field 1.
int x = ThingSpeak.writeField(myChannelNumber, 1, temp, myWriteAPIKey);
// Check the return code
if(x == 200){
Serial.println("Channel update successful.");
}
else{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment