Еще одна погодная станция на ESP8266 Избранное
Я решил мониторить погодные показатели у себя дома. У меня уже есть богатый опыт сборки устройств на arduino и esp8266 и на esp мне понравилось больше (из-за наличия wi-fi).
для полноценной картины погодных условий нам необходимо знать температуру внутри и снаружи, давление воздуха, влажность и качество воздуха (количество CO и CO2). Показания буду считывать домашним сервером на Linux при помощи самописного скрипта и выводить через MRTG в виде графика.
Собственно детали были заказаны на Aliexpress: MP180 (температура и давление), MQ135 (качество воздуха), DTH11 (температура и влажность), DTH22 (уличная температура и влажность), 662k (стабилизаторы на 3.3 вольта). Доставка была быстрой, и уже через две недели все было готово к сборке.
К сожалению, на момент написания статьи DTH22 еще не пришел, но я оставил для него выведенный внешний разъем.
Я не буду выкладывать схему, так как нет принципиальной разницы к каким GPIO что цеплять (за исключением i2c шины, она необходима для датчика давления). Сборку начнем с впаивания esp8266 в плату с контактами, где кстати, сразу отпаяем перемычку и впаяем стабилизатор на 3.3 вольта. Как раз для этого были куплены десяток 662k стабилизаторов. Это нам очень упростит дальнейшее подключение, так как все датчики работают либо от 3.3 до 5 в, либо строго от 3.3. Получается питать всю схему можем любым напряжением и не париться, что что-то сгорит.
Для удобства, я вывел питание со стабилизатора на макетку, откуда потом развел на плюс всех устройтв.
Далее расположил все на макетной плате, чтоб было поудобнее, все впаял, развел провода сзади (плюс на плюс, GND на минус, остальное на GPIO, сопротивления для светодиодов и аналогового входа, об этом чуь позже), вывел несколько светодиодов, чтобы понимать что происходит, поставил PC спикер для понта (пищит при включении и превышении показаний).
Кстати у ESP8266 есть один аналоговый вход, но он считывает напряжение до 1 вольта. У датчика загазованности MQ135, есть два выхода - цифровой и аналоговый. Цифровой срабатывает при превышении показаний, поэтому для мониторинга он бесполезен, а второй выгод аналоговый. Вот его то мы и подключим к ESP. Но для корректной работы нам нужно собрать простой делитель напряжения на двух сопротивлениях.
После подключения и написания скетча на Adruino оказалось, что в режиме i2c могут работать не все контакты (как я ранее упоминал). В итоге мне так и не удалось заставить работать по i2c никакие GPIO кроме дефолтных (GPIO4, GPIO5). Конечно не принципиально, но пришлось разок перепаять схему.
Экранчик я решил не подключать, так как показания всегда можно посмотреть с мобильника или компьютера. Кроме того показания мониторятся с сервера (у меня дома свой сервер) и выводятся в MRTG.
Собственно сам скетч будет в самом низу, но сразу скажу, пока еще не финальная версия, так как DTH22 не пришел.
Для мониторинга температуры выбрал SimpleDHT.h, потому что с ним не глючит, а со стандартным постоянно вместо температуры "nan". Кроме того оказалось, что по одному датчику температуры и по другому (один в DHT11, другой MP180) температура отличается на 3 градуса, при этом на настольном градуснике температура равна средненму от них обоих. Я не стал заморачиваться и считаю, что верная температура, та которая средняя. Для датчика давления использовал SFE_BMP180.h. Загазованность можно просто считывать с аналогового выгода, но зависимость показаний не линейная, поэтому сложно анализировать. Для того, чтобы упростить скетч я использовал MQ135.h. Главное, после того как установите MQ135, необходимо дать ему 24 часа поработать, чтобы прогреться. Затем нужно считать нулевые значения при помощи команды:
float rzero = gasSensor.getRZero();
Как получили нулевые значения, их нужно вписать в файл MQ135.h в переменную RZERO.
Далее, давайте рассмотрим веб-страничку, которую генерит погодная станция.
Если посмотреть код страницы, в самом низу можно увидеть скрытый код. Между скрытыми элементами <!start data> и <!stop data> находятся данные для сервера.
Так проще обрабатывать.
На сервере (Linux) по крону запускается MRTG, которая стартует скрипт:
curl -s http://192.168.1.63 | sed -n '/<!start data><!/,/><!stop data>/p'|grep -v "data" > /tmp/ws.tmp grep nvAvrIntTemp /tmp/ws.tmp -A1|tail -1 grep nvHmD1 /tmp/ws.tmp -A1|tail -1 |
Ну и по аналогии получаем остальные данные. То есть вместо nvAvrIntTemp может быть, например, nvMq1, тогда мы получим не среднюю температуру, а качество воздуха. Настройку MRTG я не буду расписывать, она совершенно стандартна, но если будет интересно, выложу, хотя там ничего замороченного нет.
Скетч:
#include <Wire.h>
int led=16; // Имя хоста int MD=0;
void setup() { Serial.printf("\n\nFree memory %d\n",ESP.getFreeHeap()); // Подлючение к WiFi
if( server.hasArg("MQA") ){
// Retrieve the completed temperature measurement: status = pressure.getTemperature(T); status = pressure.startPressure(3); // Retrieve the completed pressure measurement: status = pressure.getPressure(P,T); // The pressure sensor returns abolute pressure, which varies with altitude. p0 = pressure.sealevel(P,ALTITUDE); // we're at 1655 meters (Boulder, CO) // On the other hand, if you want to determine your altitude from the pressure reading, a = pressure.altitude(P,p0); String out = ""; out =
out+="\n\n<!start data><!\ //---
server.send ( 200, "text/html", out );
void Alarm() |
Всем спасибо. Продолжение следует...
277 комментарии
-
KlioFoep 16.01.2021 04:25 Комментировать
buy viagra online no prescription testimonials of viagra users viagra no prescrittion viagra coupons cipla viagra review buy viagra australia online no prescription viagra free mail canada viagra en portland no online viagra expiration red viagra what works as good as viagra buy viagra professional australia best price on generic viagra ? viagra free trial getting viagra in cape town
-
Yzphisz 15.01.2021 07:33 Комментировать
non prescription viagra buy viagra energy drinks information and health risks
tv dr viagra price interaction between viagra lisinopril -
wooBalry 14.01.2021 12:47 Комментировать
https://135649128-675766634858992234.preview.editmysite.com/uploads/1/3/5/6/135649128/free_fortnite_skins_2021_gen_mod.pdf
Informative Tips on Finding A good Desktop Computer For A great Deal
When buying a computer, you may enter the accrual and see rows and rows of desktop machines. This can depart you feeling vertigo as you try to decipher which is your best bet. then again of facing this dilemma, use the tips below to craft a plan which helps you acquire a great deal.
When searching for a desktop computer be sure to shop around. bearing in mind the growing popularity of laptops, tablets, and mobile devices, desktops have fallen out of favor. As such, sales are struggling. Use this to your advantage and look for the best deals out there with purchasing a extra desktop computer.
If you bearing in mind playing games online and desire to buy a gaming computer, you obsession to recall some things. create sure the computer has a video card that's good, a memory of a minimum of 4 GB, and a unconditional display that's high. There are next keyboards that are build up to maximize your experience.
As you look for the right desktop computer for your needs, pay near attention to your expected type of Internet membership as competently as whether or not a potential desktop model has a modem. If you are not able to be close to to broadband due to your location, you will obsession a modem. Otherwise, you can purchase a computer that does not have one.
If you want to save keep on your desktop computer, see into buying a refurbished model. These computers are ones that have been unconditional at the factory and are often offered at a steep discount. These are usually offered by the computer brands upon their own websites, as a result agree to a see since you buy a additional computer.
If you desire to extend the simulation of your potential desktop computer, make sure you pick one that is upgradeable. There are more than a few desktops these days that seal permission to the inner workings of the machine. That means no execution to upgrade. Check that you've got right of entry prior to buying.
If you craving a more powerful computer, look in areas listed as "gaming" or "entertainment" computers. These will have more RAM and faster processors which can handle these tasks. If you purchase a computer listed as an "everyday" machine, you'll locate that it just doesn't liven up taking place to your needs.
Try online comparison shopping following you habit a desktop computer. Using comparison sites that behave what a sure model offers across complex brands can back you you find where to buy. It can plus save you a lot of money. certain sites may find the money for useful additions and pardon shipping.
The computer world keeps changing, and a desktop computer is now cheaper than a lot of laptops. You can get a good computer for below 500 dollars. buy it from a trusted increase to ensure that full withhold is offered.
When buying a used computer, be positive to receive it apart to check every of its components. look at the ports, the exploit and the boards inside to look if whatever obvious is wrong. Don't know what to see for? Check out Google Images past you go to the seller.
Find out if the desktop computer you want has included programs. You compulsion to know what they are. You need to know if it has a word processor or spreadsheet program that you will use. This is important to many for their work. Also, locate out if the software included are full versions or demos. The demos expire after 30 or 90 days, which require you to purchase the full versions yourself.
KW:
Sexy Fortnite Skins 2021
Free Fortnite Skins 2021
Fortnite Skins Free 2021
FORTNITE How To Get Free Skins 2021
How To Get Free Skins On FORTNITE 2021
How To Get Free Skins In FORTNITE 2020 2021 -
Jvcxduamy 14.01.2021 09:09 Комментировать
buyng viagra in sydney risk of generic viagra viagracheap buy generic viagra in usa viagra 4free cialis viagra sales buying viagra in toronto viagra cheap generic cialis viagra uk price comparison viagra cialis levitra viagra canada head office food viagra viagra edmonton viagra 50 pills what works as well as viagra
-
-
JahesBet 13.01.2021 14:20 Комментировать
cialis dosage side effects tag search
cialis reviews forum faq
cialis lowest price
- cialis female
https://cialisboss.com/# - cialis for sale
cialis cheapest online prices no registered users and -
Fgvdguaps 13.01.2021 06:11 Комментировать
ed meds online without doctor prescription legit online pharmacy best drugstore eye cream
-
Uzlblay 12.01.2021 19:52 Комментировать
how does hiv sprea treatment for std - levitra pills mfryln Ytcfs62.
-
-