DS18B20 example is working, my sketch not

Hey guys,

I am using a DS18B20 sensor to measure the temperature of water.
Following sketch is working well:

/*
    DS18B20 Basic Code
    Temperatur auslesen mit einem DS18B20 Temperaturfühlers
    Created by cooper, 2020
    my.makesmart.net/user/cooper
*/

#include <OneWire.h>
#include <DallasTemperature.h>

// Der PIN D2 (GPIO 4) wird als BUS-Pin verwendet
#define ONE_WIRE_BUS 12

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);

// In dieser Variable wird die Temperatur gespeichert
float temperature;


void setup(){
  Serial.begin(115200);

  // DS18B20 initialisieren
  DS18B20.begin();
}

void loop(){
  
  DS18B20.requestTemperatures();
  temperature = DS18B20.getTempCByIndex(0);

  // Ausgabe im seriellen Monitor
  Serial.println(String(temperature) + " °C");

  // 5 Sekunden warten
  delay(5000);

}

But my own sketch, which contains also a BMP and a display must have a mistake.
Here it is:

/*
    ForbiddenBit.com

    NodeMCU and Display ST7735

  luft mit datenleitung auf D2 und einem 4.7k widerstand


  VCC - 3V
  GND - GND
  SDA - D2
  SCL - D1

  CSB und SDO werden nicht verwendet

***************************************************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiUdp.h>
#include <NTPClient.h>                              // include NTPClient library
#include <time.h>                                   // time() ctime()
#include <Wire.h>
//  --------  Libraries required to use the Display  ---------------
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>
//  --------  Libraries required to use the BMP  ---------------
#include <Adafruit_BMP280.h>

//  --------  Libraries required to use the DS18S20 Sensor  ---------------

#include <OneWire.h>
#include <DallasTemperature.h>

// -----------  Display pins  --------------------------------------
#define TFT_CS         15
#define TFT_RST        0
#define TFT_DC         2
//HC-SR04

#define ECHO 10    // D1 pin 5  (SD3 - pin 10)
#define TRIG 16   // D0

long duration;  // Variable um die Zeit der Ultraschall-Wellen zu speichern
float distance; // Variable um die Entfernung zu berechnen


//Sensor Wasser
// Der PIN D2 (GPIO 4) wird als BUS-Pin verwendet
#define ONE_WIRE_BUS 12  //D2/4 funktioniert

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); //Those things are for the display

#define BMP_SCK  (13)
#define BMP_MISO (12)
#define BMP_MOSI (11)
#define BMP_CS   (10)


Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);



float temperature2 = 0;
const short int BUILTIN_LED1 = 1; //GPIO1
String temp = "";  //temporär
String packet = "";
String received = "";
long lastMsg = 0;
char msg[50];
int value = 0;
int loops = 0;
String t = "";
float temperature = 0;
float humidity = 0;
char tempString[8];
String displaytmp = "true";


//WIFI
const char *ssid     = "sdgfsdfgsdfgsdf";                                //your Wifi SSID
const char *password = "sdfgsdfgsdfg";
const char* deviceName = "esp8266_aqua";
// Define NTP properties
#define NTP_ADDRESS  "de.pool.ntp.org"              // change this to whatever pool is closest (see ntp.org)
#define MY_TZ "CET-1CEST,M3.5.0/02,M10.5.0/03"      //Timezone
time_t now;                                         // this is the epoch
tm tm;                                              // the structure tm holds time information in a more convient way



const char* mqtt_server = "192.168.178.44";
const int mqttPort = 1883;
const char* mqttUser = "mosq";
const char* mqttPassword = "44904490";
//mqqt ende

// WiFi connect timeout per AP. Increase when connecting takes longer.
const uint32_t connectTimeoutMs = 5000;

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store

unsigned long previousMillis = 0;                   // will store last time updated
const long interval = 15000;                        // interval at which to run   muss 15000 sein
unsigned long currentMillispub = 0;                 //
unsigned long previousMillispub = 0;                // will store last time updated
unsigned long intervalpub = 3000;                   // interval at which to publish again
unsigned long previousMillisLED = 0;                // will store last time LED was updated
unsigned long intervalLED = 1000;                   // interval at which to blink (milliseconds)
int ledState = LOW;

WiFiClient espClient;
PubSubClient client(espClient);




void setup() {
  pinMode(BUILTIN_LED1, OUTPUT); // Initialize the BUILTIN_LED1 pin as an output
  digitalWrite(BUILTIN_LED1, HIGH); // Turn the LED off by making the voltage HIGH
  pinMode(TRIG, OUTPUT);  // TRIG-Pin: Output
  pinMode(ECHO, INPUT);   // ECHO-Pin: Input
  Serial.begin(115200);





  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  reconnect();
  configTime(MY_TZ, NTP_ADDRESS);
  ntp();
  unsigned status;

  Serial.println(F("BMP280 test"));

  //if (!bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) {
  if (!bmp.begin(0x76)) {
    Serial.println(F("Could not find a valid BMP280 sensor, check wiring or "
                     "try a different address!"));
    while (1) delay(10);
  }

  /* Default settings from datasheet. */
  bmp.setSampling(Adafruit_BMP280::MODE_NORMAL,     /* Operating Mode. */
                  Adafruit_BMP280::SAMPLING_X2,     /* Temp. oversampling */
                  Adafruit_BMP280::SAMPLING_X16,    /* Pressure oversampling */
                  Adafruit_BMP280::FILTER_X16,      /* Filtering. */
                  Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */


  // DS18B20 initialisieren
  DS18B20.begin();
  DS18B20.requestTemperatures();            //for testing purposes
  temperature = DS18B20.getTempCByIndex(0); //for testing purposes
  // Ausgabe im seriellen Monitor
  Serial.println(String(temperature) + " °C"); //for testing purposes
  
  //Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); //Those things are for the display
  //tft.initR(INITR_GREENTAB);
  tft.initR(INITR_BLACKTAB);
  //digitalWrite(powerLatch, HIGH);

  client.setServer(mqtt_server, mqttPort);



}

void callback(char* topic, byte* payload, unsigned int length) {
  String sTopic = String(topic);
  Serial.print("topic empfangen: ");
  Serial.println(String(topic));


  if (sTopic == "aqua/received") {

    temp = "";

    for (int i = 0; i < length; i++) {
      temp += ((char)payload[i]);
    }
    received = temp;
    Serial.println(received);

  }

}

void setup_wifi() {
  Serial.println("Connecting Wifi");

  WiFi.disconnect();                                  //Prevent connecting to wifi based on previous configuration

  WiFi.hostname(deviceName);                          // DHCP Hostname (useful for finding device for static lease)
  //WiFi.config(staticIP, subnet, gateway, dns);
  WiFi.begin(ssid, password);

  WiFi.mode(WIFI_STA);                                //WiFi mode station (connect to wifi router only

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {



    unsigned long currentMillisLED = millis();

    delay(100);
    Serial.print(".");

  }
  Serial.println("Wifi connected");
}
void reconnect() {

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi not connected!");
    void setup_wifi();
  }
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    //  uint32_t chipid=ESP.getChipId();
    char clientid[25];
    snprintf(clientid, 25, "WIFI-Display-%08X", "12345"); //this adds the mac address to the client for a unique id
    Serial.print("Client ID: ");
    Serial.println(clientid);
    if (client.connect(clientid)) {
      Serial.println("connected");


      client.subscribe("aqua/received");

    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 1 second before retrying
      delay(1000);
    }
  }
}

void loop() {


  if (WiFi.status() == WL_CONNECTED) {                            //blink blue LED while wifi is connected

    unsigned long currentMillisLED = millis();

    if (currentMillisLED - previousMillisLED > intervalLED) {
      // save the last time you blinked the LED
      previousMillisLED = currentMillisLED;
      ledState = !ledState;
      // if the LED is off turn it on and vice-versa:
      if (ledState == HIGH) {
        digitalWrite(LED_BUILTIN, LOW);
        intervalLED = 100;
      } else {
        digitalWrite(LED_BUILTIN, HIGH);
        intervalLED = 3000;
      }
    }
  }
  reconnect();



  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {

    Serial.print("received momentan: ");
    Serial.println(received);

    if ( loops < 2) {  //240 = 1h


      loops += 1;
      Serial.print("Loops: ");
      Serial.println(loops);
      ntp();
      Serial.print("Zeit: ");
      Serial.println(t);

    }
    if (loops >= 2) {  //240 =  1h
      measure();
      ntp();
      convert2Json();  //werte werden in den json string überführt, daher können sie jetzt genullt werden
      loops = 0;

    }

    Serial.println("intervall");

    if (displaytmp == "true") {
      displaytemp();
    } else {
      displaywater();
    }

    previousMillis = currentMillis;
  }
  if (received == "true") {
    measure();
    ntp();
    Serial.print("received jetzt: ");
    Serial.println(received);
    Serial.println("publish werte zu smartphone");
    //client.publish("aqua/display/temperatur", tempString);
    //client.publish("aqua/display/zeit", t.c_str());
    received = "false";


  }
  client.loop();



  // previousMillis = currentMillis;
}
// 5 Sekunden warten
//delay(5000);


void convert2Json()
{
  // Temperature in Celsius
  temperature2 = bmp.readTemperature();
  packet = "";


  packet.concat(("{\"temp\": "));
  packet.concat(temperature2);


  packet.concat("}");
  Serial.println(packet);
  //client.publish("sensors/room/aqua", packet.c_str());
  Serial.println("sensors/room/aqua  published");
}

void displaytemp() {
  Serial.println("displaytemp");
  measure();
  DS18B20.requestTemperatures();
  temperature = DS18B20.getTempCByIndex(0);

  // Ausgabe im seriellen Monitor
  Serial.println(String(temperature) + " °C Aqua");
  Serial.println(String(temperature2) + " °C Zimmer");
  // --------  TEST TEXT  -------------------------------------------
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextWrap(false);
  tft.setCursor(10, 5);    //Horiz/Vertic
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_CYAN);
  tft.print("Aquarium");

  tft.setCursor(15, 25);    //Horiz/Vertic
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_WHITE);
  tft.print("Live-Daten");

  tft.setCursor(5, 45);    //Horiz/Vertic
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_YELLOW);
  tft.print("Zimmer");
  tft.setCursor(10, 65);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(String(temperature2) + " C");

  tft.setCursor(5, 93);    //Horiz/Vertic
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_YELLOW);
  tft.print("Wasser");
  tft.setCursor(7, 115);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(String(temperature) + " C");

  // tft.fillRect(0, 138 , 48, 10, ST77XX_WHITE);
  tft.setCursor(7, 140);    //Horiz/Vertic
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_WHITE);
  tft.print("Maximalwerte Wasser");
  tft.setCursor(7, 152);    //Horiz/Vertic
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_RED);
  tft.print("Max: ");
  tft.setCursor(32, 152);
  tft.setTextColor(ST77XX_WHITE);
  tft.print("25.79");
  tft.setTextColor(ST77XX_RED);
  tft.setCursor(67, 152);
  tft.print("Min: ");
  tft.setCursor(92, 152);
  tft.setTextColor(ST77XX_WHITE);
  tft.print("19.87");
  displaytmp = "false";


}

void displaywater() {

  Serial.println("displaywater");
  hcsr04();

  // Ausgabe im seriellen Monitor
  Serial.println(String(temperature) + " °C Aqua");
  Serial.println(String(temperature2) + " °C Zimmer");
  // --------  TEST TEXT  -------------------------------------------
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextWrap(false);
  tft.setCursor(10, 5);    //Horiz/Vertic
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_CYAN);
  tft.print("Aquarium");

  tft.setCursor(15, 25);    //Horiz/Vertic
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_WHITE);
  tft.print("Live-Daten");

  tft.setCursor(5, 45);    //Horiz/Vertic
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_YELLOW);
  tft.print("Wasser-");
  tft.setCursor(10, 65);
  tft.setTextColor(ST77XX_YELLOW);
  tft.print("level");
  tft.setCursor(10, 85);
  tft.setTextColor(ST77XX_CYAN);
  tft.print(String(distance) + "cm");


  tft.setCursor(5, 113);    //Horiz/Vertic
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_YELLOW);
  tft.print("Volumen");
  tft.setCursor(7, 135);
  tft.setTextColor(ST77XX_CYAN);
  tft.print("234 l");
  displaytmp = "true";

}

void ntp()
{
  //Seperate the components of the time/date for using it to trigger the event of setzero()".
  //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  time(&now);                               // read the current time
  localtime_r(&now, &tm);                   // update the structure tm with the current time
  Serial.print("year:");
  Serial.print(tm.tm_year + 1900);          // years since 1900
  Serial.print("\tmonth:");
  Serial.print(tm.tm_mon + 1);              // January = 0 (!)
  Serial.print("\tday:");
  Serial.print(tm.tm_mday);                 // day of month
  Serial.print("\thour:");
  Serial.print(tm.tm_hour);                 // hours since midnight  0-23
  Serial.print("\tmin:");
  Serial.print(tm.tm_min);                  // minutes after the hour  0-59
  Serial.print("\tsec:");
  Serial.print(tm.tm_sec);                  // seconds after the minute  0-61*
  Serial.print("\twday");
  Serial.println(tm.tm_wday);               // days since Sunday 0-6

  //  date = String(tm.tm_mday) + "." + String(tm.tm_mon + 1) + "." + String(tm.tm_year + 1900);
  // savedate = String(tm.tm_mon + 1) + String(tm.tm_year + 1900) + ".csv";
  t = String(tm.tm_hour) + ":" + String(tm.tm_min) + ":" + String(tm.tm_sec);

  if (tm.tm_isdst == 1)                     // Daylight Saving Time flag
    Serial.print("\tDST");
  else
    Serial.print("\tstandard");
  Serial.println();

}
void measure() {
  // Temperature in Celsius
  temperature2 = bmp.readTemperature();
  // Convert the value to a char array

  dtostrf(temperature2, 1, 2, tempString);
  Serial.print("Temperature: ");
  Serial.println(tempString);
  // Pressure
  /*    pressure = (bmp.readPressure()/ 100.0F);
      // Convert the value to a char array
      char pressureString[8];
      dtostrf(pressure, 1, 2, pressureString);
      Serial.print("Pressure: ");
      Serial.println(pressureString);
  */


}

void hcsr04() {

  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);

  // TRIG-Pin ist HIGH für 10 Microsekunden
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  // Liest das ECHO aus und speichert die Zeit von Senden / Empfangen in Microsekunden
  duration = pulseIn(ECHO, HIGH);


  // Berechnung der Entfernung
  // Da der Weg doppel ist: Hinweg - Rückweg, muss der Wert durch 2 geteilt werden
  distance = duration * 0.034 / 2;

  // Anzeige der Entfernung im seriellen Monitor
  Serial.println("Entfernung: " + String(distance) + "cm");
}

in the void setup() part I placed this for testing purposes.

  DS18B20.requestTemperatures();            //for testing purposes
  temperature = DS18B20.getTempCByIndex(0); //for testing purposes
  // Ausgabe im seriellen Monitor
  Serial.println(String(temperature) + " °C"); //for testing purposes

that works.
But in the loop part I want to call displaytemp(); where the temperature measurement should happen but it just does not. I don't know why. The output is -127. That's the value what happens if the sensor is not connected.

Any ideas?
Sorry, the code is pretty long.

aka BMP_MISO

Can you describe a little bit???

oh, I see. Can I just remove that?

I removed

//#define BMP_SCK  (13)
//#define BMP_MISO (12)
//#define BMP_MOSI (11)
//#define BMP_CS   (10)

But it still does not work

Time to start debugging.

For something like this, I'd use
#if 0
...
#endif

To selectively disable sections of the code

Ok, I found out it has something to do with the display. If I comment out
tft.initR(INITR_BLACKTAB);
then the problem does not appear.

I can't find any usefull information about this. THe display seems to block the GPIO12. Does anyone has an idea?

Or do I have to try another gpio? all D-GPIOs (D0, D1, D2, D...) are still in use :frowning:
Or maybe IT is possible to use A0 for sensor readings of BMP or ds18b20

If you are using the following NodeMCU, then be sure about the wiring connections of your DS18B20 sensor and the BMP280 sensor. Check that they do not share any line.

Hi,
Up until when during developing your code did you notice the DS18B20 was not working?

You have a large code that you must have developed in stages.

Tom... :grinning: :+1: :coffee: :australia:

I added the display after everything was working. As i said, as soon as I outcomment the display, the sensor starts working. can I somehow safe some or even one gpio to change the wiring of the temp sensor? The display must somehow block gpio 12 (Hardware spi) even it is not connected to gpio 12.
I fear i have to switch to esp32.
I have esp8266 nodemcu v3 at the moment

Well you have it mapped in your code see below where <<<<==== here is printed.

//Sensor Wasser
// Der PIN D2 (GPIO 4) wird als BUS-Pin verwendet
#define ONE_WIRE_BUS 12  //D2/4 funktioniert    <<<<<<<<<<<<<<<<<<===== here

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); //Those things are for the display

#define BMP_SCK  (13)
#define BMP_MISO (12)     <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ===== here
#define BMP_MOSI (11)
#define BMP_CS   (10)

Move the DS18B20 to another pin.

Tom... :grinning: :+1: :coffee: :australia:

Hey Tom,

maybe you have not read it. I removed that whole part. Even If I remove everything corresponding BMP it does not work. And also, there is no regular D-pin left. :frowning: