Sensor not working: Blynk in combination with DHT21 (Si7021 by Itead Sonoff TH16)

I’m trying to get the Sonoff TH16 to work with Blynk, but the sensor is not functioning. See below.

//#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
//#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <DHT.h>                // DHT thermocouple/ humidity sensor
#include <BlynkSimpleEsp8266.h>

// Pins for blynk
#define VPIN V1               // For Relay
#define VPIN_T V2             // For temperature data
#define VPIN_H V3             // For humidity data
#define VPIN_HIC V4             // For temperature in farenheit
#define VPIN_tag V20          // For all relays in a tag
//DHT setup
#define DHTPIN 14   // what digital pin we're connected to
#define DHTTYPE DHT21   // DHT 21 (AM2301) SI7021 itead with change in DHT.ccp
// On/off callbacks, PINS
boolean verwarmingState = 0;
boolean switchReset = true;   // Flag indicating that the hardware button has been released
const int buttonPin = 0;      // Pin for hardware momentary switch. On when grounded
const int relayPin =  12;// Relay switching pin. Relay is pin 12 xxGPIO5 is D1 the number of the Relay pin on the NodeMCU (this one chosen for testing)
const int ledPin =  13;// On / Off indicator LED. Onboard LED is 13 on Sonoffthe number of the LED pin (D4 op NodeMCU)
// variables will change
int buttonState = LOW;          // variable for reading the pushbutton status
int lastButtonState = HIGH;     // previous state of the button
int relayState = LOW;
int relayStatus = 0;
int ledState = LOW;
int volts = 0;
int valueForBridge;
long lastTime = 0;              // the last time the output pin was toggled
long debounce = 200;            // the debounce time, increase if the output flickers
int requestedTemp = 0;
// Define DHT, Blynk timer
BlynkTimer timer;             // Blynk timer
DHT dht(DHTPIN, DHTTYPE);     // Define DHT
// Your WiFi credentials.
// Set password to "" for open networks.
const char* ssid     = "xx";
const char* password = "xxx";
char auth[] = "xxxx";



WidgetLED led1(V8); // Widget Relay LED

BLYNK_WRITE(V1) { // Widget relay button
  relayStatus = param.asInt();
  if (relayStatus == 1) {
    relayState = HIGH;
  }
  else {
    relayState = LOW;
  }
} // end - BLYNK_WRITE(V1)

void pushButton() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && lastButtonState == LOW && millis() - lastTime > debounce) {
    if (relayState == HIGH) {
      relayState = LOW;
      Blynk.virtualWrite(V1, 0);
    }
    else {
      relayState = HIGH;
      Blynk.virtualWrite(V1, 1);
    }
    lastTime = millis();
  }
  digitalWrite(relayPin, relayState); // Relay open/close - digital pin 12

  lastButtonState = buttonState;
} //end - pushButton()

void ledStatus() { // Widget LED - relay status
  ledState = digitalRead(relayPin);
  if (ledState == HIGH)
    led1.on();
  else
    led1.off();
}
BLYNK_WRITE(V10)
{
  requestedTemp = param.asInt();
  Serial.print("requested Temp: ");
  Serial.print(requestedTemp);
}
void checkTemp() {
  // Wait a few seconds between measurements.
 delay(2000);
  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);
  // 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;
  }
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  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("Heat index: ");
  Serial.print(hic);
  Serial.println(" *C ");
  Blynk.virtualWrite(VPIN_T, t);
  Blynk.virtualWrite(VPIN_H, h);
  Blynk.virtualWrite(VPIN_HIC, hic);
}
void setup() {
  Serial.begin(112500);
  Serial.println("DHT21 (si7021 itead) test!");

  Blynk.begin(auth, ssid, password);
  while (Blynk.connect() == false) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }
  pinMode(buttonPin, INPUT);  // on/off button
  pinMode(relayPin, OUTPUT);  // relay
  pinMode(ledPin, OUTPUT);    // led
  digitalWrite(ledPin, LOW);  // always on
  //timer.setInterval(1000, ButtonCheck);
  timer.setInterval(2000, checkTemp);
  // DHT beginning
  dht.begin();
}
void loop() {
  Blynk.run();
  pushButton();
  ledStatus();
  timer.run();
}

I’m trying to get a Si7021 sensor from Itead(Sonoff) to get to work in Blynk. The sensor works fine as long as I don’t include Blynk connect code in the sketch.
Hardware: Sonoff TH16 (ESP8266EX) upload via USB to Serial FTDI232
Blynk library 0.5.4 in Arduino IDE
DHT library modified (in DHT.cpp replaced delay(20); with delayMicroseconds(500); //time to set dataline low)

I tested many variations and found out that:

  • When flashed without Blynk.begin(auth, ssid, password); sensor works fine
  • When flashed with Blynk.begin(auth, ssid, password); sensor stops, no more readings possible
  • When this occurs: re-flashing sketch without Blynk (“Tools/Erase flash: Sketch Only”) doesn’t get sensor to work.
  • Re-flashing (sketch without Blynk) with “Tools/Erase flash: All Flash Contents” sensor starts working again.

I’ve tried two different Si7021 sensors, same result.
Both sensors work perfectly with the original Sonoff firmware.

Could there be a conflict in the flash memory (???). Any suggestions for a solution?

In the first place I’d delete the delay(2000); from checkTemp().

@IBK, OK, taken out of the checkTemp() function. Did not change the problematic behaviour.

Update: I could get it to work with a different DHT library: TroykaDHT.h (Thanks Igor Dementiev!)

To use this library with the Si7021 sensor from Itead-Sonoff one has to change the TroykaDHT.cpp file as follows:
line 34 delay(18); to be replaced by delayMicroseconds(500);

I have tried the code you have posted in your previous post without success.
Even checked the TroykaDHT.h nothing.

I cannot get the sonoff th16 get working with si7021.

Can you give mi any other hint?
After I get the temp sensor working I will go with blynk.

Did you modify the TroykaDHT.cpp file as below:

And when flashing:
tools
erase flash
choose: all flash contents

Thank for the reply. Actually i have missed the “Microseconds” = *delayMicroseconds(500);

Here we go:

 
 #include <TroykaDHT.h>
 DHT dht(14, DHT21);
 
 void setup()
 {
 
   Serial.begin(115200);
   dht.begin();
 }
 
 void loop()
 {
 
   dht.read();
 
   switch(dht.getState()) {
     // всё OK
     case DHT_OK:
       // выводим показания влажности и температуры
       Serial.print("Temperature = ");Serial.print(dht.getTemperatureC());Serial.println(" C \t");
       
       Serial.print("Humidity = ");Serial.print(dht.getHumidity());Serial.println(" %");
       break;
     // ошибка контрольной суммы
     case DHT_ERROR_CHECKSUM:
       Serial.println("Checksum error");
       break;
     // превышение времени ожидания
     case DHT_ERROR_TIMEOUT:
       Serial.println("Time out error");
       break;
     // данных нет, датчик не реагирует или отсутствует
     case DHT_ERROR_NO_REPLY:
       Serial.println("Sensor not connected");
       break;
   }
   
   delay(2000);
 }

I don’t see any blynk function in your sketch.

Hi,
I have a similar problem. Also use Sonoff TH16 with a D18B20. Unfortunately, even with me no temperature is displayed, or 85.0 ° C which is wrong. It can not really be on the Lib, she works in another sketch.

Which GPIO original is used with the Sonoff TH16 for the D18B20? Should actually be GPIO14, right?

Here is my sketch and a picture of Blynkapp

PS: The red dot above is normal because another ESP is not currently connected. With the Sonoff I can switch the relay and it works too. Only just temperature display does not work

// # include <ESP8266mDNS.h>
#include <WiFiUdp.h>
// # include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <BlynkSimpleEsp8266.h>

#define ONE_WIRE_BUS 14
OneWire oneWire (ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
Dallas Temperature sensors (& oneWire);
// Pins for blynk
#define VPIN V1 // For Relay

#define VPIN_tag V20 // For all relays in a day

boolean verwarmingState = 0;
boolean switchReset = true; // Flag indicating that the hardware button has been released
const int buttonPin = 0; // Pin for hardware momentary switch. On when grounded
const int relayPin = 12; // Relay switching pin. Relay is pin 12 xxGPIO5 is the number of the relay pin on the NodeMCU (this one used for testing)
const int ledPin = 13; // On / Off indicator LED. Onboard LED is 13 on Sonoffthe number of the LED pin (D4 op NodeMCU)

int buttonState = LOW; // variable for reading the pushbutton status
int lastButtonState = HIGH; // previous state of the button
int relayState = LOW;
int relayStatus = 0;
int ledState = LOW;
int volts = 0;
int valueForBridge;
long lastTime = 0; // the last time the output pin was toggled
long debounce = 200; // the debounce time, increase if the output flickers
int requestedTemp = 0;
// Define DHT, Blynk timer
Blynk Timer Timer; // Blynk timer
char auth [] = "XXXXXXXXXX";
char ssid [] = "XXXXXXXXX";
char password [] = "XXXXXXXXXX";



Widget LED led1 (V8); // Widget Relay LED

BLYNK_WRITE (V1) {// Widget relay button
  relayStatus = param.asInt ();
  if (relayStatus == 1) {
    relayState = HIGH;
  }
  else {
    relayState = LOW;
  }
} // end - BLYNK_WRITE (V1)

void pushButton () {
  buttonState = digitalRead (buttonPin);
  if (buttonState == HIGH && lastButtonState == LOW && millis () - lastTime> debounce) {
    if (relayState == HIGH) {
      relayState = LOW;
      Blynk.virtualWrite (V1, 0);
    }
    else {
      relayState = HIGH;
      Blynk.virtualWrite (V1, 1);
    }
    lastTime = millis ();
  }
  digitalWrite (relayPin, relayState); // Relay open / close - digital pin 12

  lastButtonState = buttonState;
} // end - pushButton ()

void ledStatus () {// Widget LED - relay status
  ledState = digitalRead (relayPin);
  if (ledState == HIGH)
    led1.on ();
  else
    led1.off ();
}
void setup () {
  Serial.begin (112500);
  Serial.println ("DHT21 (si7021 itead) test!");
  sensors.begin ();
  Blynk.begin (auth, ssid, password, IPAddress (192, 168, 0, 19), 8080);
  
  pinMode (buttonPin, INPUT); // on / off button
  pinMode (relayPin, OUTPUT); // relay
  pinMode (ledPin, OUTPUT); // led
  digitalWrite (ledPin, LOW); // always on
  
}
void loop ()
  {
    Blynk.run ();
  }
  
void disptemp () {
    float temp;
    temp = sensors.getTempCByIndex (0);
    sensors.requestTemperatures ();
    Blynk.virtualWrite (V12, (sensors.getTempCByIndex (0)));
    push button ();
    LEDStatus ();
    timer.run ();
}

First a big thank you to “khoih”. Through his posts from “Local blynk server on Raspberry pi 3”

Now runs my local Blynkserver with Java 11 and server-0.41.11.jar after complete rebuild with Raspian Buster

Unfortunately, I’m still stuck with the Sonoff TH16. Here simply no temperature is output by the D18B20 sensor. Maybe someone could look at my sketch from above again. Many thanks

Hi,

Your sketch looks a little bit strange and I wonder how it can display anything. May be you post the different sketch from what you show on Blynk App (for example Humidity and Air Pressure). But anyway, let’s concentrate on DS18B20 display.

  1. First, disptemp() didn’t get called. Whatever displayed on Blynk App is just noise.
  2. The no-use-yet timer.run() is placed inside disptemp().

I suggest you use a BlynkTimer (not Blynk Timer like above) to poll, read and send to Blynk Server / App to display

The temporary code could be:

// To fix at beginning
BlynkTimer timer; // Blynk Timer
.....

void setup () {
  Serial.begin (112500);
  Serial.println ("DHT21 (si7021 itead) test!");
  
  pinMode (buttonPin, INPUT); // on / off button
  pinMode (relayPin, OUTPUT); // relay
  pinMode (ledPin, OUTPUT); // led
  digitalWrite (ledPin, LOW); // always on
  
  
  sensors.begin ();
  Blynk.begin (auth, ssid, password, IPAddress (192, 168, 0, 19), 8080);
    
  timer.setInterval(5000L, disptemp);
  
}
void loop ()
  {
    Blynk.run ();
    timer.run ();
  }
  
void disptemp () {
    float temp;
    sensors.requestTemperatures ();
    temp = sensors.getTempCByIndex (0);

    if (isnan(temp))
      Serial.println("read_TH_sensor: DS18B20 temp is NAN");
    else
    {
      Serial.printf("read_TH_sensor: DS18B20 temp = %5.2f\n", temp); 
      Blynk.virtualWrite (V12, String(temp, 1));
    }    
}

I didn’t check the logic of the sketch, only temp display logic. Another note is to be careful with typo error, such as push button (); or Blynk Timer.

If you have more issue, it’s better open a new issue.

1 Like