Помогите! Проблема с вставкой кода из примера OneWire в Blynk

Здравствуйте!
Я использую Arduino 1.8.16
NodeMCU WeMos, DS18B20 И последние библиотеки из менеджера,
пример из библиотеки OneWire

Summary
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// https://github.com/milesburton/Arduino-Temperature-Control-Library

OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

void setup(void) {
 Serial.begin(9600);
}

void loop(void) {
 byte i;
 byte present = 0;
 byte type_s;
 byte data[12];
 byte addr[8];
 float celsius, fahrenheit;
 
 if ( !ds.search(addr)) {
   Serial.println("No more addresses.");
   Serial.println();
   ds.reset_search();
   delay(250);
   return;
 }
 
 Serial.print("ROM =");
 for( i = 0; i < 8; i++) {
   Serial.write(' ');
   Serial.print(addr[i], HEX);
 }

 if (OneWire::crc8(addr, 7) != addr[7]) {
     Serial.println("CRC is not valid!");
     return;
 }
 Serial.println();

 // the first ROM byte indicates which chip
 switch (addr[0]) {
   case 0x10:
     Serial.println("  Chip = DS18S20");  // or old DS1820
     type_s = 1;
     break;
   case 0x28:
     Serial.println("  Chip = DS18B20");
     type_s = 0;
     break;
   case 0x22:
     Serial.println("  Chip = DS1822");
     type_s = 0;
     break;
   default:
     Serial.println("Device is not a DS18x20 family device.");
     return;
 } 

 ds.reset();
 ds.select(addr);
 ds.write(0x44, 1);        // start conversion, with parasite power on at the end
 
 delay(1000);     // maybe 750ms is enough, maybe not
 // we might do a ds.depower() here, but the reset will take care of it.
 
 present = ds.reset();
 ds.select(addr);    
 ds.write(0xBE);         // Read Scratchpad

 Serial.print("  Data = ");
 Serial.print(present, HEX);
 Serial.print(" ");
 for ( i = 0; i < 9; i++) {           // we need 9 bytes
   data[i] = ds.read();
   Serial.print(data[i], HEX);
   Serial.print(" ");
 }
 Serial.print(" CRC=");
 Serial.print(OneWire::crc8(data, 8), HEX);
 Serial.println();

 // Convert the data to actual temperature
 // because the result is a 16 bit signed integer, it should
 // be stored to an "int16_t" type, which is always 16 bits
 // even when compiled on a 32 bit processor.
 int16_t raw = (data[1] << 8) | data[0];
 if (type_s) {
   raw = raw << 3; // 9 bit resolution default
   if (data[7] == 0x10) {
     // "count remain" gives full 12 bit resolution
     raw = (raw & 0xFFF0) + 12 - data[6];
   }
 } else {
   byte cfg = (data[4] & 0x60);
   // at lower res, the low bits are undefined, so let's zero them
   if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
   else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
   else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
   //// default is 12 bit resolution, 750 ms conversion time
 }
 celsius = (float)raw / 16.0;
 fahrenheit = celsius * 1.8 + 32.0;
 Serial.print("  Temperature = ");
 Serial.print(celsius);
 Serial.print(" Celsius, ");
 Serial.print(fahrenheit);
 Serial.println(" Fahrenheit");
}

работает нормально также как пример из DallasTemperature

Summary
// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 10

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

/*
* The setup function. We only start the sensors here
*/
void setup(void)
{
 // start serial port
 Serial.begin(9600);
 Serial.println("Dallas Temperature IC Control Library Demo");

 // Start up the library
 sensors.begin();
}

/*
* Main function, get and show the temperature
*/
void loop(void)
{ 
 // call sensors.requestTemperatures() to issue a global temperature 
 // request to all devices on the bus
 Serial.print("Requesting temperatures...");
 sensors.requestTemperatures(); // Send the command to get temperatures
 Serial.println("DONE");
 // After we got the temperatures, we can print them here.
 // We use the function ByIndex, and as an example get the temperature from the first sensor only.
 float tempC = sensors.getTempCByIndex(0);

 // Check if reading was successful
 if(tempC != DEVICE_DISCONNECTED_C) 
 {
   Serial.print("Temperature for the device 1 (index 0) is: ");
   Serial.println(tempC);
 } 
 else
 {
   Serial.println("Error: Could not read temperature data");
 }
}

но если интегрировать его в изменённый DHT11

Summary
#define BLYNK_TEMPLATE_ID "TMPLjEpYO1je"
#define BLYNK_DEVICE_NAME "TempMonitDemo"
#define BLYNK_AUTH_TOKEN "токен";


// Прокомментируйте это, чтобы отключить печать и сэкономить место
#define BLYNK_PRINT Serial


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

char auth[] = BLYNK_AUTH_TOKEN;

// Ваши учетные данные Wi-Fi.
// Установите пароль "" для открытых сетей.
char ssid[] = "имя";
char pass[] = "пас";

#define ONE_WIRE_BUS 10
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
BlynkTimer timer;

void sendSensor()
{
 float t = sensors.getTempCByIndex(0);

 if (isnan(t)) {
   Serial.println("Не удалось считать данные с датчика!");
   return;
 }
 Blynk.virtualWrite(V1, t);
 Serial.println(t);
}

void setup()
{
 Serial.begin(115200);
 Blynk.begin(auth, ssid, pass);
 sensors.begin();
 timer.setInterval(5000L, sendSensor);
}

void loop()
{
 Blynk.run();
 timer.run();
}

то в мониторе порта имеем

Summary
[4299] Connected to WiFi
[4299] IP: 192.168.1.36
[4299] 
   ___  __          __
  / _ )/ /_ _____  / /__
 / _  / / // / _ \/  '_/
/____/_/\_, /_//_/_/\_\
       /___/ v1.0.1 on ESP8266

[4305] Connecting to blynk.cloud:80
[4555] Ready (ping: 123ms).
25.00
25.00
25.00

при нагревании датчика показания не меняются помогите пожалуйста разобраться что к чему и как исправить

Why don’t you put the code from the void loop in the DS18B20 example into the sendSensor function (without the delay) ?

Pete.

Hey there, try this sketch :

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
char auth[] = "";
 
/* WiFi credentials */
char ssid[] = "";
char pass[] = "";
 
SimpleTimer timer;
 
 
 
#define ONE_WIRE_BUS 2 // DS18B20 on arduino pin2 corresponds to D4 on physical board "D4 pin on the ndoemcu Module"
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float temp;
float Fahrenheit=0;

void getdata()
{
  DS18B20.requestTemperatures(); 
  temp = DS18B20.getTempCByIndex(0); // Celcius
   Fahrenheit = DS18B20.toFahrenheit(temp); // Fahrenheit
  Serial.println(temp);
  Serial.println(Fahrenheit);
  Blynk.virtualWrite(V3, temp); //virtual pin V3
  Blynk.virtualWrite(V4, Fahrenheit); //virtual pin V4
}

void setup() 
{
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  DS18B20.begin();
  timer.setInterval(1000L, getdata);
}
 
void loop() 
{
  timer.run(); // Initiates SimpleTimer
  Blynk.run();
}
 

Спасибо за помощь твой код помог, но библиотека SimpleTimer из менеджера не рабочая, взял эту SimpleTimer и тогда всё заработало, таким образом мой код выглядел так:

Summary
/*************************************************************

  Это простая демонстрация отправки и получения некоторых данных.
  Обязательно ознакомьтесь с другими примерами!
 *************************************************************/

// Идентификатор шаблона, имя устройства и токен аутентификации предоставляются Blynk.Облако
// См. вкладку Информация об устройстве или настройки шаблона
#define BLYNK_TEMPLATE_ID "TMPLjEpYO1je"
#define BLYNK_DEVICE_NAME "TempMonitDemo"
#define BLYNK_AUTH_TOKEN "";


// Прокомментируйте это, чтобы отключить печать и сэкономить место
#define BLYNK_PRINT Serial


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

char auth[] = BLYNK_AUTH_TOKEN;

// Ваши учетные данные Wi-Fi.
// Установите пароль "" для открытых сетей.
char ssid[] = "";
char pass[] = "";

SimpleTimer timer;

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float temp;

void getdata()
{
  DS18B20.requestTemperatures();
  temp = DS18B20.getTempCByIndex(0);
  Serial.println(temp);
  Blynk.virtualWrite(V1, temp);
}

void setup()
{
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  DS18B20.begin();
  timer.setInterval(1000L, getdata);
}

void loop()
{
  timer.run();
  Blynk.run();
}

но если интегрировать его в пример Edgent_ESP8266
из библиотеки blynk то в мониторе каждые 3-4 нормальных показания выдаёт несколько -127, эта проблема решается увеличением интервала timer.setInterval(1000L, getdata); с 1 секунды до 5, или сменой пина датчика со 2 на 10(#define ONE_WIRE_BUS 10) после этого код работает нормально.

У ESP8266 на второй ноге обычно висит встроенный светодиод, который тоже управляется программой. Вместе с DS18B20 на одном выводе они дружить не будут, поэтому поменять 2 на 10 или другой свободный - правильное решение. Частота опроса датчика - в зависимости от желаемой точности показаний. Чем больше требуемая точность, тем реже нужно опрашивать датчик. Опрос раз в секунду работает нормально во всех случаях, по крайней мере по даташиту, до 5 можно не увеличивать, в противном случае должна быть какая-то другая проблема, а не тайминги.

The Edgent sketch uses the LED on Pin 2 in the Settings.h file, unless you change this configuration.

Pete.

Yes. If you change configuration, the LED will not lit by the blynk routine. But the LED itself + resistor will remain on pin 2 and will be involved to any routine, addressed pin 2. I’m not sure that it is a good idea to place one wire bus device at the same pin with the LED physically connected. Usually it’s a plenty of spare pins where the one wire device can be connected to.