Клиент для openweathermap.org на основе Wemos d1 mini

Шаг 2: Работа с приложением Blynk

Создание учетную запись Blynk

Клиент для openweathermap.org на основе Wemos d1 mini

После загрузки приложения Blynk вам необходимо создать новую учетную запись. Эта учетная запись отделена от учетных записей, используемых для форумов Blynk, если у вас такой уже есть. Мы рекомендуем использовать реальный адрес электронной почты.

Зачем мне нужно создавать учетную запись?

Учетная запись необходима для сохранения ваших проектов и доступа к ним с нескольких устройств из любого места. Это также мера безопасности. Вы всегда сможете настроить свой собственный сервер Blynk.

Клиент для openweathermap.org на основе Wemos d1 mini

После того, как вы успешно вошли в свою учетную запись, начните с создания нового проекта.

Клиент для openweathermap.org на основе Wemos d1 mini

Дайте проекту имя и выберите подходящую плату (Wemos D1 Mini). Теперь нажмите «Создать».

Аутентификация

Клиент для openweathermap.org на основе Wemos d1 mini

Ваш токен аутентификации будет отправлен вам по электронной почте, и вы также сможете получить к нему доступ в настройках вашего проекта. Новый номер будет создан для каждого создаваемого вами проекта.

Setup the Arduino IDE

First we will need to download and install the latest version of the Arduino IDE. The Wemos D1 Mini uses the ESP8266 so once we have the IDE we can add the supporting ESP packages.

Install the latest version of Arduino

You can download the latest version of the Arduino IDE from the website if you do not already have it.

Mac and Windows systems have typical installation options. Linux users may benefit from this additional information on the Arduino website.

Add the ESP board manager

Once you have installed the Arduino IDE, open it up and click on preferences.

We will need to add the ESP board manager URL. Enter the following into the additional board manager URLs text box.

If you need to use multiple board managers, you can click the small icon to the right of the text box and enter multiple URLs.

Add the ESP boards

Now we can add the ESP boards by clicking the tools > board > boards manager… option on the menu.

Search for the ES8266 package and install it. Once it has installed you can close the boards manager.

Choose the board and port

Next we need to select the Wemos D1 Mini board from the tools menu. We will need to select LOLIN(WEMOS) D1 R2 & mini from the newly added ESP devices.

Finally we need to choose the correct port from the tools menu. On Mac/Linux this will appear as something like dev/cu.usbserial-xxxx and on Windows it will be COMX.

Let’s give the blink example a quick try just to make sure everything is configured correctly. Click file > examples > 01 basics > blink to load the sketch.

Once the sketch has opened, click the upload sketch button and wait a moment for the sketch to upload. If everything has been sucessful the LED on the Wemos D1 Mini should blink slowly.

Automatic mode

By default the esp device have auto sleep mode enabled. If you add the code for light sleep or modem sleep at the setup and not disable the auto mode WeMos go in sleep automaticalli after 10 seconds of delay like so:

#include "Arduino.h"
#include <ESP8266WiFi.h>
// Required for LIGHT_SLEEP_T delay mode
extern "C" {
#include "user_interface.h"
}

const char* ssid = "<your-ssid>";
const char* password = "<your-passwd>";

//The setup function is called once at startup of the sketch
void setup() {
  Serial1.begin(115200);
  while(!Serial1) { }

  Serial1.println();
  Serial1.println("Start device in normal mode!");

  WiFi.mode(WIFI_STA);

  wifi_fpm_set_sleep_type(LIGHT_SLEEP_T);

  WiFi.begin(ssid, password);
  Serial1.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial1.print(".");
  }
  Serial1.println("");
  Serial1.print("Connected to ");
  Serial1.println(ssid);
  Serial1.print("IP address: ");
  Serial1.println(WiFi.localIP());
}
unsigned long interval = 30000;
unsigned long previousMillis = millis() + interval;

void loop() {
	  unsigned long currentMillis = millis();

	  if (currentMillis - previousMillis >= interval) {
		  Serial1.println("Enter delay");

		  delay(20000);

		  Serial1.println("Exit delay");

		  WiFi.begin(ssid, password);
		  Serial1.println("");

		  // Wait for connection
		  while (WiFi.status() != WL_CONNECTED) {
			delay(500);
			Serial1.print(".");
		  }
		  Serial1.println("");
		  Serial1.print("Connected to ");
		  Serial1.println(ssid);
		  Serial1.print("IP address: ");
		  Serial1.println(WiFi.localIP());
		  previousMillis = currentMillis;

	  }
}

the result is this:

When execute delay command for the first 10 seconds nothing append, than after that sleep mode is automatic activated.

  1. WeMos D1 mini (esp8266), specs and IDE configuration
  2. WeMos D1 mini (esp8266), integrated SPIFFS Filesystem
  3. WeMos D1 mini (esp8266), debug on secondary UART
  4. WeMos D1 mini (esp8266), the three type of sleep mode to manage energy savings
  5. WeMos D1 mini (esp8266), integrated LittleFS Filesystem
  6. esp12 esp07 (esp8266): flash, pinout, specs and IDE configuration

Spread the love

7
Shares

2014 Autodesk, Inc. All rights reserved.

All use of this Service is subject to the terms and conditions of the applicable Autodesk terms of service accepted upon access of this Service.

This Service may incorporate or use background Autodesk technology components. For information about these components, click here: http://www.autodesk.com/cloud-platform-components

Trademarks

Autodesk, the Autodesk logo, and Fusion 360 are registered trademarks or trademarks of Autodesk, Inc., and/or its subsidiaries and/or affiliates.

All other brand names, product names or trademarks belong to their respective holders.

Third-Party Software Credits and Attributions

Ruby gems is Copyright (c) Chad Fowler, Rich Kilmer, Jim Weirich and others. Portions copyright (c) Engine Yard and Andre Arko

bootstrap-select.js is Copyright (C) 2013 bootstrap-select

Backbone.js is Copyright (c) 2010-2013 Jeremy Ashkenas, DocumentCloud

Apple-Style Flip Counter is Copyright (c) 2010 Chris Nanney

imagesLoaded is Copyright 2013 David DeSandro

jQuery is Copyright 2013 jQuery Foundation and other contributors http://jquery.com/

jQuery timepicker addon is Copyright (c) 2013 Trent Richardson

jQuery ColorBox is Copyright (c) 2013 Jack Moore

jQuery.gritter is Copyright (c) 2013 Jordan Boesch

Masonry is Copyright (c) 2013 David DeSandro

Underscore is Copyright (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative

Reporters & Editors

underscore_string is Copyright (c) 2011 Esa-Matti Suuronen [email protected]

Icanhaz.js is ICanHaz.js is Copyright (c) 2010 Henrik Joreteg (Mustache and Mustache.js are Copyright (c) 2009 Chris Wanstrath (Ruby) and Copyright (c) 2010 Jan Lehnardt (JavaScript) respectively)

Calendario is Copyright (c) Codrops 2014 by tympanus

All the above software components are licensed under the MIT license.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Популярные статьи  Включение и выключение нагрузки одной кнопкой

Portions relating to lightbox are licensed under Creative Commons Attribution 2.5 License (http://creativecommons.org/licenses/by/2.5/). Lightbox was authored by Lokesh Dhakar (lokeshdhakar.com).

So how can I…

Use a graphical tool to work with the Wemos D1 Mini?

I found a tutorial on Random Nerd Tutorials, that explained the full process.
The blog posts go through how to install a GUI application, flash the image to the ESP8266 (and the ESP32!) and then write code for the board.

Install uPyCraftFlash MicroPython to the ESP8266Getting started with MicroPython

Find your Wemos D1 Mini

Connect your device to a USB port, then run this command in the terminal.

You will see a lot of text wizz by, but look for something similar to this.Клиент для openweathermap.org на основе Wemos d1 mini
Notice the last line? It mentions well that is our Wemos D1 Mini. The full path to our device is
Windows users, you will need to check the Device Manager to see which COM port is in use.

Flash the firmware

This command will flash the firmware that we downloaded from the MicroPython website. The last part is where you need to type the name of the downloaded firmware. Also provide the full path to the file if it is in another directory.

Принцип работа протокола MQTT

MQTT – это «легкий» (малозатратный) протокол передачи сообщений, использующий модель издатель/подписчик (publish/subscribe) и позволяющий осуществлять передачу сообщений между множественными устройствами. Также с помощью протокола MQTT можно передавать/принимать данные и управлять различными устройствами, например, считывать информацию с датчиков. Он разработан с учетом протокола TCP, поэтому он работает существенно быстрее чем протоколы подобные HTTP. К его достоинствам можно отнести крайне низкие требования к ресурсам, малый объемом используемой памяти устройств и встроенный устойчивый (робастный) протокол обеспечения безопасности. Благодаря этим достоинствам протокол MQTT получил широкое распространение в современном мире.

Структурная схема работы протокола MQTT показана на следующем рисунке.

Клиент для openweathermap.org на основе Wemos d1 mini

Кратко рассмотрим основные функции «участников» протокола MQTT.

MQTT клиент (Client)

MQTT клиент – это любое устройство (к примеру, микроконтроллер или сервер), которое выполняет функции MQTT и взаимодействует с центральным сервером, который в данном случае называют брокером (“broker”). Брокер занимается обработкой процессов обмена данными между подключенными устройствами.

MQTT издатель (Publisher)

Клиенты, которые осуществляют передачу данных (например, датчики) называются издателями (publisher). Издатели публикуют свою информацию в определенной теме. Тема (topic) – это путь, по которому осуществляет публикация сообщений и подписка на них. После того как издатели опубликовали свою информацию в определенных темах, брокер осуществляет передачу этой информации (сообщений) подписчикам (клиентам), которые подписались на получение информации по этим темам.

MQTT подписчик (Subscriber)

MQTT подписчик подписывается на темы MQTT брокера чтобы получать сообщения из этих тем, передаваемые брокером.

Брокер Eclipse Mosquitto

Eclipse Mosquitto – это легковесный MQTT брокер с открытым исходным кодом, удобный для применения в различных проектах интернета вещей. Протокол MQTT обеспечивает низко затратную передачу информации в соответствии с моделью издатель/подписчик. Более подробно про принципы работы данного брокера вы можете прочитать на его официальном веб-сайте.

Micro SD карта на Wemos D1 mini datalogger

Схема для подключения модуля по-прежнему не нужна. Все соединения работают нормельно после сборки «сэндвича» из Wemos D1 mini (ESP8266) и Wemos D1 mini datalogger.

Проверил работу штатной библиотеки ESP8266 для работы с Micro SD картой. Тестовый пример без проблем откомпилировался и отработал. Так что модуль работает без проблем.

ВАЖНЫЙ МОМЕНТ РАБОТЫ SD карты с ESP8266!!!

Я использовал Samsung 32Gb EVO Plus отформатированную в FAT32 и с ней DataLogger не инициализировал карту. После того как отформатировал в FAT16 ESP8266 стал читать SD карту.

При этом на дешевой Micro SD «SP Elite» 16 Gb отформатированной в FAT32 проблем с чтением не возникло, ESP8266 без проблем проинициализировал карту.

В коде ниже нужно обратить внимание на CS PIN инициализации SD.init(15). На Wemos Mini D1 пин CS заведен на GPIO15, а не GPIO4

/*
  SD card read/write

  This example shows how to read and write data to and from an SD card file
  The circuit:
   SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

  created   Nov 2010
  by David A. Mellis
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

*/

#include &lt;SPI.h>
#include &lt;SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

Подключение SD карты к ESP32 описано здесь. В цело все то-же самое. Проблем возникнуть не должно.

Описание WeMos D1 R2

Клиент для openweathermap.org на основе Wemos d1 miniПлата WeMos D1, которая производится в Китае, выполнена на основе WiFi модуля ESP8266 ESP-12. На модуле имеется разъем под внешнюю WiFi антенну – благодаря этому можно расширить площадь покрытия сетью. Программирование платы осуществляется с помощью стандартной среды разработки Arduino IDE. Контроллер включает в себя процессор, периферию, оперативную память и устройства ввода/вывода. Наиболее часто микроконтроллеры применяются в компьютерной технике, бытовых приборах и других электронных устройствах. WeMos отличается дешевой стоимостью и простотой подключения и программирования.

Технические характеристики WeMos:

  • Входное напряжение 3,3В;
  • 11 цифровых выходов;
  • Микро USB выход;
  • 4 Мб флэш-памяти;
  • Наличие WiFi модуля;
  • Частота контроллера 80МГц/160МГц;
  • Рабочие температуры от -40С до 125С.

Основными областями применения контроллеров WeMos являются температурные датчики, датчики давления и другие, зарядные устройства, пульты для управления различными бытовыми приборами, системы обработки данных, робототехника. К микроконтроллеру можно подключать дополнительные компоненты – индикаторы, сенсоры, светодиоды, которые позволяют реализовывать различные проекты и расширять их возможности.

Распиновка модуля WeMos D1

  • TX;
  • RX;
  • GND земля;
  • 5В;
  • 3v3;
  • RST – reset, кнопка сброса;
  • D0 – D8 –порты общего назначения GPIO. Все пины, кроме D0, поддерживают прерывание, ШИМ, I2C.

Клиент для openweathermap.org на основе Wemos d1 mini

Wrap Up

We covered a lot of topics in this tutorial. Everything from configuring an MQTT broker, to using Node-RED to create dashboards, to wiring up a circuit and writing code for our Wemos board.

I know this tutorial was rather lengthy, but I wanted to provide some fundamental information before moving on to more complicated applications. In the next tutorial, we’re going to wire up a DC motor and control it using Node-RED. This will get us one step closer to controlling our Mobile Robot!

If you have any questions, feel free to post them below! Node-RED has a lot of features, so it’d be good to explore different ways of collecting, publishing, and processing data.

Исходный код программы (скетча)

Arduino

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define LED D0
const char* ssid = «admin»;
const char* password = «12345678»;
const char* mqtt_server = «mqtt.eclipse.org»;
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup()
{
pinMode(LED, OUTPUT);
pinMode(D1,INPUT_PULLUP);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println(«Connecting to WiFi..»);
}
Serial.print(«Connected to WiFi :»);
Serial.println(WiFi.SSID());
client.setServer(mqtt_server, mqtt_port);
client.setCallback(MQTTcallback);
while (!client.connected())
{
Serial.println(«Connecting to MQTT…»);
if (client.connect(«ESP8266»))
{
Serial.println(«connected»);
}
else
{
Serial.print(«failed with state «);
Serial.println(client.state());
delay(2000);
}
}
client.subscribe(«esp/test»);
}
void MQTTcallback(char* topic, byte* payload, unsigned int length)
{
Serial.print(«Message received in topic: «);
Serial.println(topic);
Serial.print(«Message:»);
String message;
for (int i = 0; i < length; i++)
{
message = message + (char)payload;
}
Serial.print(message);
if (message == «on»)
{
digitalWrite(LED, HIGH);
}
else if (message == «off»)
{
digitalWrite(LED, LOW);
}
Serial.println();
Serial.println(«————————«);
}
void loop()
{
if(digitalRead(D1)==0)
{
client.publish(«esp/test1», «Hello from ESP8266»);
delay(1000);
}
else;
client.loop();
}

Популярные статьи  Приспособление для формировки клина (спуска)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define LED D0

constchar*ssid=»admin»;

constchar*password=»12345678″;

constchar*mqtt_server=»mqtt.eclipse.org»;

constintmqtt_port=1883;

WiFiClientespClient;

PubSubClientclient(espClient);

voidsetup()

{

pinMode(LED,OUTPUT);

pinMode(D1,INPUT_PULLUP);

Serial.begin(115200);

WiFi.begin(ssid,password);

while(WiFi.status()!=WL_CONNECTED)

{

delay(500);

Serial.println(«Connecting to WiFi..»);

}

Serial.print(«Connected to WiFi :»);

Serial.println(WiFi.SSID());

client.setServer(mqtt_server,mqtt_port);

client.setCallback(MQTTcallback);

while(!client.connected())

{

Serial.println(«Connecting to MQTT…»);

if(client.connect(«ESP8266»))

{

Serial.println(«connected»);

}

else

{

Serial.print(«failed with state «);

Serial.println(client.state());

delay(2000);

}

}

client.subscribe(«esp/test»);

}

voidMQTTcallback(char*topic,byte*payload,unsignedintlength)

{

Serial.print(«Message received in topic: «);

Serial.println(topic);

Serial.print(«Message:»);

Stringmessage;

for(inti=;i<length;i++)

{

message=message+(char)payloadi;

}

Serial.print(message);

if(message==»on»)

{

digitalWrite(LED,HIGH);

}

elseif(message==»off»)

{

digitalWrite(LED,LOW);

}

Serial.println();

Serial.println(«————————«);

}

voidloop()

{

if(digitalRead(D1)==)

{

client.publish(«esp/test1″,»Hello from ESP8266»);

delay(1000);

}

else;

client.loop();

}

Прошивка WeMos, примеры скетчей

Мигание светодиодами

Сам скетч выглядит следующим образом:


int inputPin = D4; // подключение кнопки в контактам D4 и GND. Можно выбрать любой пин на плате

int val = 1; // включение/выключение хранения значения

void setup() {

pinMode(BUILTIN_LED, OUTPUT); // подключение светодиода, перевод в режим OUTPUT

pinMode(inputPin, INPUT); // включение пина для входных данных

}

void loop() {

val = digitalRead(inputPin); // чтение входных данных

digitalWrite(BUILTIN_LED, val); // включение/выключение светодиода по нажатию кнопки

}

Если все выполнено правильно, нужно нажать кнопку, и светодиод загорится. При повторном нажатии потухнет.

Для автоматического мигания светодиода интервалом в две секунды используется следующий код:


void setup() {

pinMode(3, OUTPUT); // инициализация контакта GPIO3 с подключенным светодиодом

}

void loop() {

digitalWrite(2, HIGH);   // светодиод загорается

delay(2000);              // ожидание в течение двух секунд

digitalWrite(2, LOW);    // светодиод гаснет

delay(2000);              // ожидание в течение двух секунд

}

WeMos и подключение к WiFi для передачи данных на удаленный сервер

В примере будет рассмотрен скетч для создания веб-сервера, благодаря которому можно управлять различными устройствами – лампами, реле, светодиодами и другими.  Для работы нужно установить библиотеку ESP8266WiFi.

Фрагменты скетча:


const char* ssid = "****"; //требуется записать имя точки доступа, к которой будет произведено подключение

const char* password = "****"; //введение пароля точки доступа, который должен содержать не менее восьми символов

WiFiServer server(80);  //создание сервера на 80 порту

WiFi.begin(ssid, password); // подключение к заданной выше точке доступа, ее имя и пароль

pinMode(3, OUTPUT);   //присоединение к пину GPIO3 и земле

while (WiFi.status() != WL_CONNECTED) //показывает статус подключения, WL_CONNECTED указывает на установку соединения;

Serial.println(WiFi.localIP()); //получение IP адреса. Его нужно ввести в строку адреса в браузере для получения доступа к управлению устройством

Serial.println(WiFi.macAddress()); //получение MAC адреса

Serial.println(WiFi.SSID()); //получение имени сети, к которой подключился WeMos

WiFiClient client = server.available(); //проверяет, подключен ли клиент

Serial.println("client");

while(!client.available()) //ожидание отправки данных от клиента

String req = client.readStringUntil('\r');

Serial.println(req);

client.flush(); //Чтение первой строки запроса

Создание точки доступа на WeMos

В данном примере модуль WeMos будет сконфигурирован в качестве самостоятельной точки доступа.

Создание точки доступа выполняется по следующему алгоритму:

  • Подключение модуля;
  • Запуск среды разработки Arduino IDE;
  • Выбор порта, частоты, размера флэш-памяти;
  • Запись с коде программы имени сети и создание пароля;
  • Компиляция и загрузка скетча;
  • Установить скорость 115200;
  • Должно произойти подключение к сети, будет получен IP и выведен в терминал;
  • Для проверки можно ввести в адресной строке в браузере IP/gpio/1, если все работает корректно, должен загореться светодиод на плате.

Фрагменты программы:



const char *ssid = «****»; //в этой строке нужно задать имя создаваемой сети

const char *password = «»; //указывается пароль сети, если не указывать пароль, то сеть будет открыта

При создании пароля важно помнить, что он должен состоять не менее чем из восьми знаков

WiFiServer server(80);

WiFi.softAP(ssid, password); //создание точки доступа с именем и паролем, которые указывались выше. Если пароль не указывался, softAP(ssid, password) меняется на softAP(ssid)

IPAddress myIP = WiFi.softAPIP(); //получение адреса IP

Serial.print(«AP IP address: «); //вывод полученного адреса в терминал

server.begin(); // запуск сервера

Deep sleep

The most common and most used modality is deep-sleep, a pratical application is to send data to a server every predefined time period.

  • You must put your device in deep-sleep
  • set a timer to wake
  • wake
  • send data
  • put device in sleep

All esp8266 (except esp01) have a pin with wake label, and through this pin connected to the RESET it will be possible to wake up the microcontroller.

WeMos D1 mini esp8266 pinout mischianti low resolution

You can se various sleep option, check your better choiche.

system_deep_sleep_set_option(0) The 108th Byte of init parameter decides whether RF calibration will be performed after the chip wakes up from Deep-sleep.
system_deep_sleep_set_option(1) The chip will make RF calibration after waking up from Deep-sleep. Power consumption is high.
system_deep_sleep_set_option(2) The chip won’t make RF calibration after waking up from Deep-sleep. Power consumption is low.
system_deep_sleep_set_option(3) The chip won’t turn on RF after waking up from Deep-sleep. Power consumption is the lowest, same as in Modem-sleep.

On WeMos D1 mini, as you can see, the pin for wake il D0.

ESP.deepsleep(0) // suspends the module until it is woken up by a spike on the RST pin
ESP.deepsleep(5 * 1000000) // wake up the module every 5 seconds
ESP.deepsleep(5000000, RF_DISABLED) // wakes up the module every 5 seconds without re-activating the WiFi modem

To wake a microcontroller you must put LOW reset PIN.

You can use a Wake pin (D0) connected to Reset to wake after some time, or you can use external button (or other) pulled up and than go LOW on key press.

After putting the esp8266 into deep sleep mode, there are 2 ways to wake it up:

  • By setting a timer
  • with a button that put low Reset pin.

WeMos D1 mini deep sleep and debug on Serial1 check Ampere

#include "Arduino.h"

//The setup function is called once at startup of the sketch
void setup() {
  Serial1.begin(115200);
  while(!Serial1) { }
  Serial1.println();
  Serial1.println("Start device in normal mode!");

  delay(5000);
  // Wait for serial to initialize.
  while(!Serial1) { }

  // Deep sleep mode for 10 seconds, the ESP8266 wakes up by itself when GPIO 16 (D0 in NodeMCU board) is connected to the RESET pin
  Serial1.println("I'm awake, but I'm going into deep sleep mode for 10 seconds");
  ESP.deepSleep(10e6);
}

void loop() {
}

The power that use device is similar to light-sleep with wake up via GPIO (6mA).

Setting up the Wemos D1 Mini & Arduino IDE

So the goal here is to get this thing working like an Arduino i.e. connected to your PC, showing a COM port, loaded into the Arduino IDE and running the famous blink sketch.

I’m a Windows user (Windows 10), so that’s what this guide is based on (suck it up Linux people, you know Windows is king):

Install the Drivers

For the D1 Mini, here is where you download the driver: https://www.wemos.cc/en/latest/ch340_driver.html

If you get some weird ‘install failed’ message, try clicking the ‘uninstall’ button first, then go for the install again – worked for me.

Клиент для openweathermap.org на основе Wemos d1 mini

Hit the uninstall button if you get any failure messages

Install the Arduino IDE

I don’t have to walk you through this one – download and install the Arduino IDE if you don’t already have it: https://www.arduino.cc/en/Main/Software

Install the ESP8266 Board Manager

We’re going to add a new bunch of boards into the Arduino IDE board manager, as the Wemos isn’t in there by default.

In the Arduino IDE, go to File > Preferences. A window will pop up, and at the bottom is a field called ‘Additional Boards Manager URLs‘.

Simply copy and paste the following into that field, then press OK:

Клиент для openweathermap.org на основе Wemos d1 mini

Simply copy and paste the highlighted text into the same field in your IDE preferences window

Популярные статьи  Как за копейки сделать штукатурку Гротто

Install the ESP8266 Library

Now we need to install the library for our Wemos.

Go to Sketch > Include Library > Manage Libraries, then in the search box enter ‘ESP8266 Platform‘.

You want to install the library called ‘ESP8266 Microgear‘ (which I’ve just noticed is by someone called ‘Chavee’. I’ve been called chavvy a few times over the years)

Клиент для openweathermap.org на основе Wemos d1 mini

Make sure you select the Microgear option

Install the Board

Next we install the boards so that they show up in the tools menu alongside the Arduinos etc.

Go to Tools > Board > Boards Manager, then search for ‘ESP8266‘.

Install the ESP8266 option (should be the only one there):

Клиент для openweathermap.org на основе Wemos d1 mini

There should only be one option to install. Easy!

Technical Definitions before we start

I also want to define a couple of terms before we begin.

MQTT (Message Queuing Telemetry Transport) is a messaging protocol that simplifies the way we communicate (publish and subscribe) to messages between machines.

In this project, we will use an open-sourced MQTT broker, called Mosquitto. I will use MQTT and Mosquitto interchangeably throughout this tutorial.

Node-RED is a flow-based development tool commonly used for Internet of Things (IoT).

We’re also going to be subscribing and publishing to topics. You can think of a topic as a message. Topics contain information that we want to send or receive. Subscribing to a topic means we’ll receive the information in. Publishing to a topic means we’re sending data out. This is always in reference to the device that’s communicating. The topic name is pretty important because it contains the data from our device. Therefore, I will be italicizing all topic names to make them easier to find.

Controller and Circuit Components

This tutorial is pretty simple, so you won’t need many components to get started. Here’s the list of materials in case you don’t have them already.

  • 4X LED’s (I’m using Red, Yellow, Green, and White colors)
  • 4X 220 Ohm resistors
  • Wemos D1 Mini (or NodeMCU)
  • Jumper Wires
  • 5K Potentiometer

One of the biggest things I can share with you, is that you don’t need a Raspberry Pi to complete this project. I’m using my computer to run MQTT and Node-RED. If you want to use the Raspberry Pi to host your communications, that’s fine as well, but it’s not necessary.

Now that we have a general understanding of the system, I’m going to split the tutorial into three parts.

Тестирование работы проекта

Для тестирования работы нашего проекта мы будем использовать Android приложение, которое мы установили ранее.

Откройте приложение MQTT и убедитесь в том, что ваш смартфон имеет соединению с сетью Интернет. Точка доступа WiFi, к которой подключается наша NodeMCU, также должна иметь соединение с сетью Интернет. Когда все соединения установлены, мы должны передать строку “Hello from ESP8266” с нашего модуля ESP8266, которая должна отобразиться в Android, после этого мы должны получить подтверждение приема. Затем мы будем передавать из Android приложения строку, которая будет включать светодиод, подключенный к NodeMCU.

Клиент для openweathermap.org на основе Wemos d1 mini

Шаг 1. Подписка на тему.

Нажмите на сохраненную опцию MQTT в приложении, которую мы настроили ранее. После этого у вас на экране должно появиться всплывающее окно, в котором будет кнопка “Subscribe to a Topic”. В программе мы дали теме название “esp/test1”. Поэтому и в Android приложении нам необходимо написать “esp/test1”.

Нажмите на Subscribe (подписаться), после чего вы увидите экран, показанный на рисунке ниже. На нем будет написано что не принято никакого сообщения (“No message received”) из темы, на которую вы подписаны.

После этого нажмите на кнопку, которая подключена к NodeMCU в нашем проекте. После этого сообщение “Hello from ESP8266” будет опубликовано в нашей теме и на экране вы увидите извещение о том, что сообщение было принято.

Шаг 2. Публикация сообщения в теме.

Для этого нажмите на кнопку вверх (UP ARROW button) в Android приложении, после чего вы увидите следующий экран.

После этого в поле ввода названия темы напишите “esp/test”, а в поле ввода текста сообщения — “on” или “off” чтобы включить или выключить светодиод.

Comments

smokey1300 commented May 20, 2020 •

REQUESTED INFORMATION

Make sure your have performed every step and checked the applicable boxes before submitting your issue. Thank you!

  • Read the Contributing Guide and Policy and the Code of Conduct
  • Searched the problem in issues
  • Searched the problem in the docs
  • Searched the problem in the forum
  • Searched the problem in the chat
  • Device used (e.g., Sonoff Basic): _____
  • Tasmota binary firmware version number used: _____
    • Pre-compiled
    • Self-compiled
  • Flashing tools used: _____
  • Provide the output of command: Backlog Template; Module; GPIO 255 :

Provide the output of the Console log output when you experience your issue; if applicable: (Please use weblog 4 for more debug information)

TO REPRODUCE

upgraded from Tasmota 6.3 now my BMP280 module doesn’t have any values. Same exact connection used GPIO4(SDA) and GPIO5(SCL) for the module

ADDITIONAL CONTEXT

The 18B20 sensor still connected to GPIO0 still working fine

(Please, remember to close the issue when the problem has been addressed)

The text was updated successfully, but these errors were encountered:

Источник

WeMos Mini

Клиент для openweathermap.org на основе Wemos d1 miniКлиент для openweathermap.org на основе Wemos d1 mini

По сравнению с Wemos D1 микроконтроллер WeMos Mini имеет меньшие габариты. Плата обладает размерами в ширину 2,5 см, а в длину 3,5 см, в то время как полная версия Wemos D1 идентична Ардуино UNO.

Распиновка WeMos D1 mini

Схема платы и расположение выходов изображены на рисунке.

Клиент для openweathermap.org на основе Wemos d1 mini

Технические характеристики WeMos Mini:

  • 11 цифровых контактов;
  • Наибольшее входное напряжение 3,2В;
  • 4 МБ памяти;
  • WiFi модуль;
  • Коннектор для внешней антенны.

Преимуществом платы является возможность сохранения соединения при низком потреблении энергии 1мА. Благодаря этому можно делать различные приборы, которые будут работать от батареек.

Шилды для WeMos Mini

Существует большое количество шилдов, которые могут быть подключены WeMos D1 mini:

  • WeMos Dual Base и WeMos Tripler Base – удваивает и утраивает основу установки шилда;
  • WeMos DS18B20 – шилд с цифровым датчиком;
  • WeMos Battery – шилд для дополнительного питания от батарейки;
  • WeMos Relay – шилд, управлящий реле;
  • WeMos OLED – шилд, оснащенный экраном OLED;
  • WeMos 1-Button – модуль, оснащенный тактовой кнопкой;
  • WeMos Micro SD-Card – шилд для добавления карты памяти микро SD;
  • WeMos Motor – шилд для двигателей до 15В;
  • WeMos DHT D4, WeMos DHT I2C, WeMos SHT30 – модули, реализующие измерение давления, температуры и влажности (первый подключается через шину onewire, второй – через I2C);
  • WeMos WS2812B RGB – шилд, реализующий управление светодиодом;
  • WeMos Matrix LED – шилд для индикации, базирующийся на матрице светодиодов;
  • WeMos Buzzer – шилд для звукового излучателя;
  • WeMos ProtoBoard – макетная плата;
  • WeMos DC Power – шилд питания.

Заключение

Платы на базе esp8266 – лучший способ организовать работу с сетью в ваших DIY проектах. Вы можете использовать большое количество разнообразных модулей и готовых плат, но WeMos – один из самых удобных способов. Плата похожа на Arduino Uno, достаточно легко подключается к датчикам и прошивается через Arduino IDE.

Уменьшенный аналог WeMos mini вообще можно назвать уникальным устройством, т.к. в очень компактном корпусе вы получаете не только почти все удобства и возможности Arduino, но и полноценный WiFi модуль. Можно даже обойтись без монтажа – просто вставляя различные модули расширения (шилды) WeMos как в матрешке, одну в другу. А недорогая цена делает эту плату абсолютным фаворитом для тех, кто делает умные устройства с возможностью выхода в интернет.

Источник

Рейтинг
( Пока оценок нет )
Денис Серебряков/ автор статьи
Понравилась статья? Поделиться с друзьями:
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: