Страницы Назад 1 2 3 Далее
Чтобы отправить ответ, вы должны войти или зарегистрироваться
РСС
Сообщений с 26 по 50 из 55
26 2020-01-30 23:04:48
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
Замените строки:
if(reg_t2 >= temper1 + gis){ind2=» ВКЛ»;}
if(reg_t2<= temper1 — gis){ind2=» ВЫКЛ»;}
на
if(reg_t2 >= temper2 + gis){ind2=» ВКЛ»;}
if(reg_t2<= temper2 — gis){ind2=» ВЫКЛ»;}
27 Ответ от nikola_supra 2020-01-31 18:21:30 (2020-01-31 20:02:56 отредактировано nikola_supra)
- nikola_supra
- Новый участник
- Неактивен
- Зарегистрирован: 2020-01-30
- Сообщений: 2
Re: Умный дом
Спасибо, действительно неточность была в этих строках.
Подскажите пожалуйста, как возможно реализовать изменение цвета шрифта, желательно с примером.
Например:
Для страницы терморегулятора, Нагрев: «ВКЛ» — зеленым, «ВЫКЛ» — красным.
Для страницы управления реле, Выход реле (состояние) «ON» — зеленым, «OFF» — красным и подсветить соответственным цветом кнопки.
Для страницы реле времени, состояние реле, ON» — зеленым, «OFF» — красным.
28 Ответ от liman324 2020-02-14 21:30:36
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
andrys пишет:
Так я сразу написал, давайте закажу на ваш адрес, заодно и внесу поддержку сайту, и поработаем вместе. Я уже 2 года играюсь с этим — нет мне помощника-программиста. У меня есть наработки, могу выслать для изучения.
Есть некоторые результаты работы над ENC28J60
У меня все работает!!!
29 Ответ от andrys 2020-03-10 22:49:31
- andrys
- Участник
- Неактивен
- Зарегистрирован: 2019-09-16
- Сообщений: 94
Re: Умный дом
Приветствую. Повторил на ESP8266, работает. Не разберусь с временем сети интернет: время сети соответствует (19.49), а интернета нет. Какое значение нужно написать в #20 строке кода ? Мне нужно время московское. Сейчас показывает 22.49.
30 Ответ от liman324 2020-03-10 22:52:40
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
NTPClient timeClient(ntpUDP, «pool.ntp.org», 21600,3600123);
NTPClient timeClient(ntpUDP, «pool.ntp.org», 21600-3600,3600123);
31 Ответ от andrys 2020-03-10 23:27:00 (2020-03-10 23:36:49 отредактировано andrys)
- andrys
- Участник
- Неактивен
- Зарегистрирован: 2019-09-16
- Сообщений: 94
Re: Умный дом
сделал: NTPClient timeClient(ntpUDP, «pool.ntp.org», 21600-3600,3600123);// 21600 — временной сдвиг в секундах от UTC
показывает 22.36 — не получается.
32 Ответ от andrys 2020-03-10 23:39:05 (2020-03-10 23:42:57 отредактировано andrys)
- andrys
- Участник
- Неактивен
- Зарегистрирован: 2019-09-16
- Сообщений: 94
Re: Умный дом
И вкладка реле времени получается работает от времени интернета.
Мне нужно значение уменьшить на 7200 сек. Но какое ?
33 Ответ от liman324 2020-03-11 06:14:55
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
Вкладка реле работает с временем интернета. Уменьшайте параметр 21600 до нужного Вам времени, до 18000 это на час или 14400 на 2 часа
34 Ответ от andrys 2020-03-12 21:31:13
- andrys
- Участник
- Неактивен
- Зарегистрирован: 2019-09-16
- Сообщений: 94
Re: Умный дом
Все работает правильно: включается и выключается во время. Теперь вкладка «Управление реле». В столбике Выход реле кнопок нет, а только написано N/A. Как исправить ?
35 Ответ от liman324 2020-03-12 21:35:28
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
Значит реле задействовано во вкладке реле времени, установите время вкл и выкл 00:00 00:00 для активации его во вкладке управление реле.
36 Ответ от andrys 2020-03-12 21:39:04
- andrys
- Участник
- Неактивен
- Зарегистрирован: 2019-09-16
- Сообщений: 94
Re: Умный дом
Да, все отлично заработало. Спасибо.
37 Ответ от VEFF 2020-11-03 23:41:28
- VEFF
- Новый участник
- Неактивен
- Зарегистрирован: 2020-11-03
- Сообщений: 3
Re: Умный дом
Здравствуйте. При попытке повторить проект из статьи компилятор обругал 108 строку кода:
'class NTPClient' has no member named 'getFormattedDate'
Подскажите пожалуйста, что я не сделал?
38 Ответ от liman324 2020-11-03 23:46:50
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
Проверьте наличие библиотек. Библиотека изменена, скачивайте с источника — http://rcl-radio.ru/wp-content/uploads/ … master.zip
39 Ответ от VEFF 2020-11-03 23:55:51
- VEFF
- Новый участник
- Неактивен
- Зарегистрирован: 2020-11-03
- Сообщений: 3
Re: Умный дом
Библиотеку скачал, добавил. При повторном добавлении пишет, что данная библиотека уже есть.
40 Ответ от liman324 2020-11-04 00:01:35
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
‘class NTPClient’ has no member named ‘getFormattedDate’
ошибка — getFormattedDate — функция не определена в библиотеке NTPClient
удалите все файлы библиотеки и установите по новой библиотеку
41 Ответ от VEFF 2020-11-04 00:34:09
- VEFF
- Новый участник
- Неактивен
- Зарегистрирован: 2020-11-03
- Сообщений: 3
Re: Умный дом
Спасибо за совет! Компилятор побороть удалось.
Если вдруг у кого-то аналогичная проблема на «окнах» случиться — проверяйте наличие библиотек (и, соответственно, удаляйте) в папке «Документы» и в папке программы по умолчанию (у меня в корне системного диска). Соответственно, пока я из обоих папок не поудалял старые библиотеки — новая не подтягивалась.
42 Ответ от Georgii 2020-12-04 20:46:14
- Georgii
- Новый участник
- Неактивен
- Зарегистрирован: 2020-12-04
- Сообщений: 1
Re: Умный дом
Здравствуйте.
Не могу скомпилировать скетч . Пишет, » Ошибка компиляции для платы NodeMCU 1.0 (ESP-12E Module).»
Опытным путем определил, что виновны библиотеки:DallasTemperature.h и OneWire.h. Пробовал разные, ничего не получается. Старые удалял. Не могли бы вы дать ссылки на необходимые библиотеки.
Без этих библиотек и всем, что с ними связано, скетч компилируется и плата прошивается. Все работает, кроме терморегулятора.
Спасибо.
43 Ответ от liman324 2020-12-04 21:18:37
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
У меня компиляция проходит без ошибок, вот библиотеки которые я использую:
Данный контент доступен только зарегистрированным пользователям.
Данный контент доступен только зарегистрированным пользователям.
44 Ответ от Marsrel_nv 2021-06-10 13:53:08
- Marsrel_nv
- Новый участник
- Неактивен
- Зарегистрирован: 2021-06-10
- Сообщений: 1
Re: Умный дом
Подскажите, что нужно изменить в скетче для термо контроля на охлаждение?
45 Ответ от yucan 2021-11-08 15:57:21
- yucan
- Новый участник
- Неактивен
- Зарегистрирован: 2021-11-08
- Сообщений: 5
Re: Умный дом
Здравствуйте! Какою версию IDE нужно использовать для загрузки скетча? У меня компиляция не проходит. Использую библиотеки постом выше.
Arduino: 1.8.5 (Windows 7), Плата:»NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200″
D:arduino-1.8.5portablesketchbook2chanal_thermo2chanal_thermo.ino: In function ‘void loop()’:
2chanal_thermo:107: error: ‘class NTPClient’ has no member named ‘getFormattedDate’
t = timeClient.getFormattedDate();
^
2chanal_thermo:108: error: ‘class NTPClient’ has no member named ‘getFormattedDate’
date_time = timeClient.getFormattedDate();
^
exit status 1
‘class NTPClient’ has no member named ‘getFormattedDate’
Этот отчёт будет иметь больше информации с
включенной опцией Файл -> Настройки ->
«Показать подробный вывод во время компиляции»
46 Ответ от liman324 2021-11-09 16:52:16
- liman324
- Administrator
- Неактивен
- Зарегистрирован: 2019-08-21
- Сообщений: 3,102
Re: Умный дом
Я использую Arduino IDE 1.8.9
47 Ответ от yucan 2021-11-10 15:16:39
- yucan
- Новый участник
- Неактивен
- Зарегистрирован: 2021-11-08
- Сообщений: 5
Re: Умный дом
Понятно. У меня версия IDE 1.8.5, но и в версии 1.8.9 компиляция не проходит. Ошибки в 107 и в 108 строках
48 Ответ от yucan 2021-11-10 17:06:07 (2021-11-10 17:08:12 отредактировано yucan)
- yucan
- Новый участник
- Неактивен
- Зарегистрирован: 2021-11-08
- Сообщений: 5
Re: Умный дом
Ошибка — getFormattedDate — функция не определена в библиотеке NTPClient…
А вот с функцией getFormattedTime компиляция проходит без ошибок.
49 Ответ от yucan 2021-11-10 17:12:09
- yucan
- Новый участник
- Неактивен
- Зарегистрирован: 2021-11-08
- Сообщений: 5
Re: Умный дом
Всё, скомпилировалось. Заменил библиотеку NTPClient master на более новую
50 Ответ от yucan 2021-11-11 15:18:54 (2021-11-11 15:19:28 отредактировано yucan)
- yucan
- Новый участник
- Неактивен
- Зарегистрирован: 2021-11-08
- Сообщений: 5
Re: Умный дом
Здравствуйте! Всё заработало, спасибо автору. Ещё вопрос — гистерезис один градус?
Страницы Назад 1 2 3 Далее
Чтобы отправить ответ, вы должны войти или зарегистрироваться
In this tutorial we’ll show you how to get date and time using the ESP32 and Arduino IDE. Getting date and time is especially useful in data logging to timestamp your readings. If your ESP32 project has access to the Internet, you can get date and time using Network Time Protocol (NTP) – you don’t need any additional hardware.
Note: there’s an easier and updated guide to get date and time with the ESP32 with the pre-installed time.h library: ESP32 NTP Client-Server: Get Date and Time (Arduino IDE).
Before proceeding with this tutorial you should have the ESP32 add-on installed in your Arduino IDE. Follow one of the following tutorials to install the ESP32 on the Arduino IDE, if you haven’t already.
- Installing the ESP32 Board in Arduino IDE (Windows instructions)
- Installing the ESP32 Board in Arduino IDE (Mac and Linux instructions)
NTP Client Library
The easiest way to get date and time from an NTP server is using an NTP Client library. For that we’ll be using the NTP Client library forked by Taranais. Follow the next steps to install this library in your Arduino IDE:
- Click here to download the NTP Client library. You should have a .zip folder in your Downloads
- Unzip the .zip folder and you should get NTPClient-master folder
- Rename your folder from NTPClient-master to NTPClient
- Move the NTPClient folder to your Arduino IDE installation libraries folder
- Finally, re-open your Arduino IDE
Getting Date and Time from NTP Server
Here we provide a sample code to get date and time from the NTP Server. This example was modified from one of the library examples.
/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
Based on the NTP Client library example
*********/
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
timeClient.setTimeOffset(3600);
}
void loop() {
while(!timeClient.update()) {
timeClient.forceUpdate();
}
// The formattedDate comes with the following format:
// 2018-05-28T16:00:13Z
// We need to extract date and time
formattedDate = timeClient.getFormattedDate();
Serial.println(formattedDate);
// Extract date
int splitT = formattedDate.indexOf("T");
dayStamp = formattedDate.substring(0, splitT);
Serial.print("DATE: ");
Serial.println(dayStamp);
// Extract time
timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
Serial.print("HOUR: ");
Serial.println(timeStamp);
delay(1000);
}
View raw code
To get more NTP examples, in the Arduino IDE, go to File > Examples > NTPClient.
How the Code Works
Let’s take a quick look at the code to see how it works. First, you include the libraries to connect to Wi-Fi and get time and create an NTP client.
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
Setting SSID and password
Type your network credentials in the following variables, so that the ESP32 is able to establish an Internet connection and get date and time from the NTP server.
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Preparing NTP Client
The following two lines define an NTP Client to request date and time from an NTP server.
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
Then, initialize String variables to save the date and time.
String formattedDate;
String dayStamp;
String timeStamp;
In the setup() you initialize the Serial communication at baud rate 115200 to print the results:
Serial.begin(115200);
These next lines connect the ESP32 to your router.
// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Next, initialize the NTP client to get date and time from an NTP server.
timeClient.begin();
You can use the setTimeOffset() method to adjust the time for your timezone in seconds.
timeClient.setTimeOffset(3600);
Here are some examples for different timezones:
- GMT +1 = 3600
- GMT +8 = 28800
- GMT -1 = -3600
- GMT 0 = 0
These next lines ensure that we get a valid date and time:
while(!timeClient.update()) {
timeClient.forceUpdate();
}
Note: sometimes the NTP Client retrieves 1970. To ensure that doesn’t happen we need to force the update.
Getting date and time
Then, convert the date and time to a readable format with the getFormattedDate() method:
formattedDate = timeClient.getFormattedDate();
The date and time are returned in the following format:
2018-04-30T16:00:13Z
If you want to get date and time separately, you need to split that string. The “T” letter separates the date from the time, so we can easily split that String. That’s what we do in these next lines.
// Extract date
int splitT = formattedDate.indexOf("T");
dayStamp = formattedDate.substring(0, splitT);
Serial.println(dayStamp);
// Extract time
timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
Serial.println(timeStamp);
The date is saved on the dayStamp variable, and the time on the timeStamp variable.The time is requested and printed in every second.
Testing the Code
Upload the code to the ESP32. Make sure you have the right board and COM port selected. After uploading the code, press the ESP32 “Enable” button, and you should get the date and time every second as shown in the following figure.
Wrapping Up
In this tutorial we’ve shown you how to easily get date and time with the ESP32 on the Arduino IDE using an NTP server. The code provided is not useful by itself. The idea is to use the example provided in this guide in your own projects to timestamp your sensor readings.
This method only works if the ESP32 is connected to the Internet. If your project doesn’t have access to the internet, you need to use other method. You can use an RTC module like the DS1307.
We have other tutorials related with ESP32 that you may also like:
- Learn ESP32 with Arduino IDE Course
- ESP32 Data Logging Temperature to MicroSD Card
- ESP32 Publish Sensor Readings to Google Sheets
- Build an All-in-One ESP32 Weather Station Shield
- Getting Started with ESP32 Bluetooth Low Energy (BLE)
- ESP32 with LoRa using Arduino IDE
Thanks for reading.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Closed
lutfisan opened this issue
Jul 20, 2017
· 17 comments
Closed
get year, month, day
#36
lutfisan opened this issue
Jul 20, 2017
· 17 comments
Comments
how to get year, month, and day?
I added a function to do exactly that, the only dependency being #include <time.h>
.
String NTPClient::getFullFormattedTime() { time_t rawtime = this->getEpochTime(); struct tm * ti; ti = localtime (&rawtime); uint16_t year = ti->tm_year + 1900; String yearStr = String(year); uint8_t month = ti->tm_mon + 1; String monthStr = month < 10 ? "0" + String(month) : String(month); uint8_t day = ti->tm_mday; String dayStr = day < 10 ? "0" + String(day) : String(day); uint8_t hours = ti->tm_hour; String hoursStr = hours < 10 ? "0" + String(hours) : String(hours); uint8_t minutes = ti->tm_min; String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes); uint8_t seconds = ti->tm_sec; String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds); return yearStr + "-" + monthStr + "-" + dayStr + " " + hoursStr + ":" + minuteStr + ":" + secondStr; }
The output seems right:
2017-07-22 19:20:25
What you guys think? This should be added to the main code?
Best Regards.
EDIT: editted the function to use less memory and use the same Epoch time for every calculation.
it’s work perfect, i think you should add it to your code
you might add this
int NTPClient::getYear() {
time_t rawtime = this->getEpochTime();
struct tm * ti;
ti = localtime (&rawtime);
int year = ti->tm_year + 1900;
return year;
}
int NTPClient::getMonth() {
time_t rawtime = this->getEpochTime();
struct tm * ti;
ti = localtime (&rawtime);
int month = (ti->tm_mon + 1) < 10 ? 0 + (ti->tm_mon + 1) : (ti->tm_mon + 1);
return month;
}
int NTPClient::getDate() {
time_t rawtime = this->getEpochTime();
struct tm * ti;
ti = localtime (&rawtime);
int month = (ti->tm_mday) < 10 ? 0 + (ti->tm_mday) : (ti->tm_mday);
return month;
}
enavascalmell and jwouda reacted with hooray emoji
phurkornt and markub3327 reacted with heart emoji
I agree with @Testato that this is not the purpose of the library, however this conversion is pretty useful for time-stamping and it’s pretty handy to have it working out of the box, without the need for other conversions.
I also ran the benchmarks: the getFormattedTime()
runs in about 100 microseconds, whereas getFullFormattedTime()
is about 450 microseconds. Not very good, but not bad either.
@sandeepmistry Could you please add the suggested changed to the library?
Hi Everyone, i had a problem while adding the new public method to the NTPclient.cpp and NTPClient.h
once i added the code, the compiler gets error when processing this file.
I added the functions to the .cpp file and the header into the public section of .h file
How can i fix it?
thanks
NTPClient.zip
@Gund77 , as I stated, my workaround makes use of the C standard time library.
You can fix it by adding #include <time.h>
in your header file. Your NTPClient.h’s first 6 lines should look like this:
#pragma once #include "Arduino.h" #include <time.h> #include <Udp.h>
For anyone that still comes to this topic seeking for help, please use the fork implementation on Github taranais/NTPClient. He implements the function getFormattedDate()
that returns the time formatted in ISO 8601.
Sorry, My mistate. I included Time.h library as last in the list so the compiler do not find the declaration while parsing the NTP library.
Anyway, switching the inclusions position the problem persist. i got error again. It might be a sintax error, but i cant find where… can you please send me your NTP Client.h and .cpp files?
thank you so much.
@Gund77 , it is a syntax error… You don’t use the namespace when declaring a function inside the class declaration (header file). Instead of using:
/** * @return time formatted like `DD:MM:YYYY` */ String NTPClient::getFormattedDate() ; /** * @return time formatted like `DD:MM:YYYY hh:mm:ss` */ String NTPClient::getFullFormattedTime(); int NTPClient::getYear(); int NTPClient::getMonth(); int NTPClient::getDate();
You should declare them as:
/** * @return time formatted like `hh:mm:ss` */ String getFormattedTime(); /** * @return time formatted like `DD:MM:YYYY` */ String getFormattedDate(); /** * @return time formatted like `DD:MM:YYYY hh:mm:ss` */ String getFullFormattedTime(); int getYear(); int getMonth(); int getDate();
Working version of NTPClient.zip
the function getFullFormattedTime ir returnning time formatted like YYYY:MM:DD hh:mm:ss
and my output is in epoctime 1970-01-01 00:00:49
i dont understand why dont return the real date and time…
i was debuging the code and the function forceUpdate return false by timeout.
@thiagoarreguy I consider that replacing an NTP server is a good choice.
Hi,
Does it take into account the leap years?
Thanks! I was looking for a feature like this!
Please add this to the main file. When will it be standard available?
In the mean time I got it working…..
Since I didn’t want to modify the library, I adapted the code snippet to work inside main.cpp:
// https://github.com/arduino-libraries/NTPClient/issues/36
String getTimeStampString() {
time_t rawtime = timeClient.getEpochTime();
struct tm * ti;
ti = localtime (&rawtime);
uint16_t year = ti->tm_year + 1900;
String yearStr = String(year);
uint8_t month = ti->tm_mon + 1;
String monthStr = month < 10 ? "0" + String(month) : String(month);
uint8_t day = ti->tm_mday;
String dayStr = day < 10 ? "0" + String(day) : String(day);
uint8_t hours = ti->tm_hour;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
uint8_t minutes = ti->tm_min;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
uint8_t seconds = ti->tm_sec;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
return yearStr + "-" + monthStr + "-" + dayStr + " " +
hoursStr + ":" + minuteStr + ":" + secondStr;
}
I am closing this issue since there are solutions available as code snippets as well as in user-forks. It would be great if some brave soul would create a pull request so that we can add this functionality to this library as well.
Hi Everyone, i had a problem while adding the new public method to the NTPclient.cpp and NTPClient.h
once i added the code, the compiler gets error when processing this file.I added the functions to the .cpp file and the header into the public section of .h file
How can i fix it?
thanks
NTPClient.zip
I have fix your code, you can download this file
NTPClient.tar.gz
#include <Wire.h>
#include «Adafruit_LiquidCrystal.h»
#include <BMP085.h>
#include «stDHT.h»
#include <OneWire.h> //подключаем библиотеку
DHT sens(DHT22); // Указать датчик DHT11, DHT21 или DHT22. (несколько датчиков вписывать не нужно)
// Подключать можно только одинаковые датчики, то есть нельзя использовать одновременно DHT11 и DHT22
BMP085 dps = BMP085();
OneWire ds(8); // Номер ноги к которой подключили датчик
long int Temperature = 0, Pressure = 0;
// initialize the library with the numbers of the interface pins
Adafruit_LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup()
{
Serial.begin(9600);
pinMode(6, INPUT);
digitalWrite(2, HIGH);
pinMode(7, INPUT);
digitalWrite(3, HIGH);
Wire.begin();
delay(1000);
dps.init();
// set up the LCD’s number of rows and columns:
lcd.begin(20, 4);
}
void loop()
{
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if ( !ds.search(addr)) {
ds.reset_search();
delay(250);
return;
}
for( i = 0; i < 8; i++) {
Serial.write(‘ ‘);
}
if (OneWire::crc8(addr, 7) != addr[7]) {
return;
}
// Первый байт ROM указывает, какой чип
switch (addr[0]) {
case 0x10:
type_s = 1;
break;
case 0x28:
type_s = 0;
break;
case 0x22:
type_s = 0;
break;
default:
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1);
delay(1000);
present = ds.reset();
ds.select(addr);
ds.write(0xBE);
for ( i = 0; i < 9; i++) {
data = ds.read();
}
// Преобразование данных в фактическую температуру
int16_t raw = (data[1] << | data[0];
if (type_s) {
raw = raw << 3;
if (data[7] == 0x10) {
raw = (raw & 0xFFF0) + 12 — data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7;
else if (cfg == 0x20) raw = raw & ~3;
else if (cfg == 0x40) raw = raw & ~1;
}
celsius = (long int)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
dps.getPressure(&Pressure);
dps.getTemperature(&Temperature);
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 0);
Serial.print(«Давление: «);
Serial.print(Pressure/133.3); //Выводим давление в мм.рт ст
Serial.print(» мм.рт стt»);
Serial.print(«Температура:»);
Serial.print(Temperature*0.1); // Температуру в градусах Цельсия
Serial.print(» *Ct»);
lcd.print(«DABLENIE «);
lcd.print(Pressure/133.3); //Выводим давление в мм.рт ст
lcd.setCursor(0, 1);
Serial.print(» Температура на улице = «);
Serial.print(celsius);
Serial.print(» *C «);
lcd.print(«TIn «);
lcd.print(Temperature*0.1);
lcd.setCursor(10, 1);
lcd.print(«TOut «);
lcd.print(celsius);
lcd.setCursor(0, 2);
int t = sens.readTemperature(6); // чтение датчика на пине 2
int h = sens.readHumidity(6); // чтение датчика на пине 2
delay(2000);
int t2 = sens.readTemperature(7); // чтение датчика на пине 3
int h2 = sens.readHumidity(7); // чтение датчика на пине 3
Serial.print(«Влажность на улице: «);
Serial.print(h);
Serial.print(» % «);
Serial.print(«Температура на улице: «);
Serial.print(t);
Serial.print(» *C «);
Serial.print(«Влажность в квартире: «);
Serial.print(h2);
Serial.print(» % «);
Serial.print(«Температура в квартире: «);
Serial.print(t2);
Serial.println(» *C «);
lcd.print(«HumIn «);
lcd.print(h2); //Выводим давление в мм.рт ст
lcd.setCursor(10, 2);
lcd.print(«HumOut «);
lcd.print(h); //Выводим давление в мм.рт ст
delay(5000);
}
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
This might be a longshot before I replace this library but hey maybe someone here have some clues.
I’m using the latest version of this library in various projects. This works reliably for even the long run with the first server not with the second. With the second it works sometimes then at 1 point it decides not to, even if I restart the ESP8266 many times.
Just don’t get it why. From my laptop or from other workstations both NTP servers providing the correct date, also there are no firewalls. The working version is even an older one.
WORKING SERVER
ii ntp 1:4.2.6.p5+dfsg-2+deb7u7 amd64 Network Time Protocol daemon and utility programs
ntpdate -d 1.2.3.4
23 Nov 18:10:12 ntpdate[937]: ntpdate 4.2.8p10@1.3728-o Sun Feb 25 21:22:56 UTC 2018 (1)
transmit(1.2.3.4)
receive(1.2.3.4)
transmit(1.2.3.4)
receive(1.2.3.4)
transmit(1.2.3.4)
receive(1.2.3.4)
transmit(1.2.3.4)
receive(1.2.3.4)
server 1.2.3.4, port 123
stratum 2, precision -23, leap 00, trust 000
refid [1.2.3.4], delay 0.05536, dispersion 0.00018
transmitted 4, in filter 4
reference time: e5479db3.59bf632e Tue, Nov 23 2021 18:04:51.350
originate timestamp: e5479efa.89d517e5 Tue, Nov 23 2021 18:10:18.538
transmit timestamp: e5479efa.86ca5636 Tue, Nov 23 2021 18:10:18.526
filter delay: 0.05574 0.05536 0.05550 0.05571
0.00000 0.00000 0.00000 0.00000
filter offset: -0.00356 -0.00356 -0.00334 -0.00325
0.000000 0.000000 0.000000 0.000000
delay 0.05536, dispersion 0.00018
offset -0.003561
23 Nov 18:10:18 ntpdate[937]: adjust time server 1.2.3.4 offset -0.003561 sec
BROKEN SERVER
ii ntp 1:4.2.8p10+dfsg-3+deb9u2 armhf Network Time Protocol daemon and utility programs
ntpdate -d 1.2.3.5
23 Nov 18:11:08 ntpdate[2079]: ntpdate 4.2.8p10@1.3728-o Sun Feb 25 21:22:56 UTC 2018 (1)
transmit(1.2.3.5)
receive(1.2.3.5)
transmit(1.2.3.5)
receive(1.2.3.5)
transmit(1.2.3.5)
receive(1.2.3.5)
transmit(1.2.3.5)
receive(1.2.3.5)
server 1.2.3.5, port 123
stratum 3, precision -20, leap 00, trust 000
refid [1.2.3.5], delay 0.02670, dispersion 0.00012
transmitted 4, in filter 4
reference time: e5479a5b.b6d2279b Tue, Nov 23 2021 17:50:35.714
originate timestamp: e5479f33.12da26e4 Tue, Nov 23 2021 18:11:15.073
transmit timestamp: e5479f33.1433e734 Tue, Nov 23 2021 18:11:15.078
filter delay: 0.02676 0.02670 0.02708 0.02684
0.00000 0.00000 0.00000 0.00000
filter offset: -0.00617 -0.00596 -0.00574 -0.00606
0.000000 0.000000 0.000000 0.000000
delay 0.02670, dispersion 0.00012
offset -0.005969
23 Nov 18:11:15 ntpdate[2079]: adjust time server 1.2.3.5 offset -0.005969 sec
It is also not a network connection issue, the ESP8266 can connect to the wifi fine it just can’t get the time from the NTP for some reason.
Any ideas how to proceed with this?