This project connects a NodeMCU and DS18B20 together and pushes the temperature readings to ThingSpeak.

This project connects a NodeMCU and DS18B20 together and pushes the temperature readings to ThingSpeak.

 

Follow the simple sketch (attached) and run the code below :)

 

*** Note that this sketch does not incorporate a resistor, follow the link below to learn how to remove the resistor from your projects.

 

// https://pasture.io
//https://gist.github.com/teos0009/acad7d1e54b97f4b2a88
// thins link for no 4k7 resistor https://wp.josh.com/2014/06/23/no-external-pull-up-needed-for-ds18b20-temp-sensor/#more-1892

//nodeMCU v1.0 (black) with Arduino IDE
//stream temperature data DS18B20 with 1wire on ESP8266 ESP12-E (nodeMCU v1.0)
//shin-ajaran.blogspot.com
//nodemcu pinout https://github.com/esp8266/Arduino/issues/584
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

//Def
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
#define ONE_WIRE_BUS 2 // DS18B20 on arduino pin2 corresponds to D4 on physical board
//#define mySSR 0 // Solid State Relay on pin 0

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
const char* server = "api.thingspeak.com";
String apiKey ="THINGSPEAK API KEY HERE";
const char* MY_SSID = "SSID NAME HERE";
const char* MY_PWD = "SSID PASSWORD HERE";
int sent = 0;
void setup() {
Serial.begin(115200);
connectWifi();
}

void loop() {
float temp;
//char buffer[10];
DS18B20.requestTemperatures();
temp = DS18B20.getTempCByIndex(0);
//String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
Serial.print(String(sent)+" Temperature: ");
Serial.println(temp);

//if (temp != prevTemp)
//{
//sendTeperatureTS(temp);
//prevTemp = temp;
//}

sendTeperatureTS(temp);
int count = myPeriodic;
while(count--)
delay(1000);
}

void connectWifi()
{
Serial.print("Connecting to "+*MY_SSID);
WiFi.begin(MY_SSID, MY_PWD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}

Serial.println("");
Serial.println("Connected");
Serial.println("");
}//end connect

void sendTeperatureTS(float temp)
{
WiFiClient client;

if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
Serial.println("WiFi Client connected ");

String postStr = apiKey;
postStr += "&field1=";
postStr += String(temp);
postStr += "\r\n\r\n";

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(postStr.length());
client.print("\n\n");
client.print(postStr);
delay(1000);

}//end if
sent++;
client.stop();
}//end send