ESP8266 - LED - Piscar Sem Delay

Vamos imaginar que o ESP8266 tem duas tarefas a cumprir: piscar um LED e monitorar o estado de um botão que pode ser pressionado a qualquer momento. Se usarmos a função delay() (como explicado em um tutorial anterior), o ESP8266 pode perder alguns acionamentos do botão. Em outras palavras, o ESP8266 não conseguiria executar completamente a segunda tarefa.

Este tutorial ensina como fazer o ESP8266 piscar um LED e monitorar o estado de um botão sem perder nenhum dos acionamentos.

Vamos ver três exemplos e comparar as diferenças entre eles:

Este método não se limita a piscar um LED e verificar o estado do botão. Em geral, ele permite que o ESP8266 realize várias tarefas simultaneamente sem que uma bloqueie a outra.

Hardware Necessário

1×ESP8266 NodeMCU ESP-12F
1×Alternatively, ESP8266 D1 Mini NodeMCU ESP-12F
1×Alternatively, ESP8266 NodeMCU ESP-12E (Uno-form)
1×Micro USB Cable
1×Alternatively, ESP8266 NodeMCU ESP-12F (SMD-form)
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×LED Kit
1×LED (red)
1×LED Module
1×(Alternativa) Button and LED Kit
1×220Ω Resistor
1×Botão para Protoboard com Capa
1×Kit de Botões para Protoboard
1×Botão de Pressão para Painel
1×Módulo de Botão
1×Protoboard
1×Fios Jumper
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para ESP8266

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Buy Note: Use the LED Module for easier wiring. It includes an integrated resistor.

Sobre o LED e o Botão

Se você não conhece o LED e o botão (pinagem, funcionamento, programação ...), os tutoriais a seguir podem ajudar:

Diagrama de Ligação

Diagrama de ligação do LED com ESP8266 NodeMCU

This image is created using Fritzing. Click to enlarge image

Para mais informações, veja Pinagem do ESP8266 e como alimentar o ESP8266 e outros componentes.

Código ESP8266 - Com Delay

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-led-blink-without-delay */ #define BUTTON_PIN D1 // The ESP8266 pin D1 connected to button #define LED_PIN D7 // The ESP8266 pin D7 connected to led #define BLINK_INTERVAL 1000 // interval at which to blink LED (milliseconds) int led_state = LOW; // led_state used to set the LED int prev_button_state = LOW; // will store last time button was updated void setup() { Serial.begin(9600); // Configure the ESP8266 pin as a digital output pin pinMode(LED_PIN, OUTPUT); // Configure the ESP8266 pin as a digital input pin pinMode(BUTTON_PIN, INPUT); } void loop() { // if the LED is off turn it on and vice-versa: led_state == (led_state == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN, led_state); delay(BLINK_INTERVAL); // If button is pressed during this time, ESP8266 CANNOT detect int button_state = digitalRead(BUTTON_PIN); if(button_state != prev_button_state) { // print out the state of the button: Serial.println(button_state); // save the last state of button prev_button_state = button_state; } // DO OTHER WORKS HERE }

Passos Rápidos

Para começar com o ESP8266 no Arduino IDE, siga estes passos:

  • Veja o tutorial como configurar o ambiente para o ESP8266 no Arduino IDE se esta for a primeira vez que você usa o ESP8266.
  • Ligue os componentes como mostrado no diagrama.
  • Conecte a placa ESP8266 ao seu computador usando um cabo USB.
  • Abra o Arduino IDE no seu computador.
  • Escolha a placa ESP8266 correta, como (por exemplo, NodeMCU 1.0 (ESP-12E Module)), e a respectiva porta COM.
  • Conecte o cabo USB ao ESP8266 e ao PC.
  • Abra o Arduino IDE e selecione a placa e a porta corretas.
  • Copie o código e abra-o no Arduino IDE.
  • Clique no botão Upload do Arduino IDE para compilar e fazer o upload do código para o ESP8266.
Como fazer o upload do código para o ESP8266 NodeMCU usando o Arduino IDE
  • Abra o Serial Monitor.
  • Pressione o botão quatro vezes.
  • Confira o LED; ele alternará entre ligado e desligado a cada segundo.
  • Confira a saída no Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Nodemcu 1.0 (ESP-12E Module)
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Nodemcu 1.0 (ESP-12E Module)' on 'COM15')
New Line
9600 baud
1 0
Ln 11, Col 1
Nodemcu 1.0 (ESP-12E Module) on COM15
2
  • No Serial Monitor, alguns acionamentos não foram registrados. Isso acontece porque, durante o delay, o ESP8266 não consegue executar nenhuma tarefa. Consequentemente, ele não consegue detectar o evento de pressionamento.

Código ESP8266 - Sem Delay

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-led-blink-without-delay */ #define BUTTON_PIN D1 // The ESP8266 pin D1 connected to button #define LED_PIN D7 // The ESP8266 pin D7 connected to led #define BLINK_INTERVAL 1000 // interval at which to blink LED (milliseconds) int led_state = LOW; // led_state used to set the LED int prev_button_state = LOW; // will store last time button was updated unsigned long prev_time_ms = 0; // will store last time LED was updated void setup() { Serial.begin(9600); // Configure the ESP8266 pin as a digital output pin pinMode(LED_PIN, OUTPUT); // Configure the ESP8266 pin as a digital input pin pinMode(BUTTON_PIN, INPUT); } void loop() { // check to see if it's time to blink the LED; that is, if the difference // between the current time and last time you blinked the LED is bigger than // The interval at which you want to blink the LED. unsigned long time_ms = millis(); if (time_ms - prev_time_ms >= BLINK_INTERVAL) { // if the LED is off turn it on and vice-versa: led_state == (led_state == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN, led_state); // save the last time you blinked the LED prev_time_ms = time_ms; } // check button state's change int button_state = digitalRead(BUTTON_PIN); if(button_state != prev_button_state) { // print out the state of the button: Serial.println(button_state); // save the last state of button prev_button_state = button_state; } // DO OTHER WORKS HERE }

Passos Rápidos

  • Ligue os componentes como mostrado no diagrama.
  • Conecte a placa ESP8266 ao seu computador usando um cabo USB.
  • Abra o Arduino IDE no seu computador.
  • Escolha a placa ESP8266 correta, como (por exemplo, NodeMCU 1.0 (ESP-12E Module)), e a respectiva porta COM.
  • Execute o código e pressione o botão 4 vezes.
  • Confira o LED, que alternará entre LIGADO e DESLIGADO em intervalos regulares de um segundo.
  • Confira a saída no Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Nodemcu 1.0 (ESP-12E Module)
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Nodemcu 1.0 (ESP-12E Module)' on 'COM15')
New Line
9600 baud
1 0 1 0 1 0 1 0
Ln 11, Col 1
Nodemcu 1.0 (ESP-12E Module) on COM15
2
  • Todas as ocorrências urgentes foram identificadas.

Explicação do Código

Confira a explicação linha por linha contida nos comentários do código-fonte!

Adicionando Mais Tarefas

O código do ESP8266 abaixo

  • Faz dois LEDs piscarem com intervalos diferentes.
  • Verifica o estado do botão.
/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-led-blink-without-delay */ #define BUTTON_PIN D1 // The ESP8266 pin D1 connected to button #define LED_PIN_1 D6 // The ESP8266 pin D7 connected to led #define LED_PIN_2 D7 // The ESP8266 pin D7 connected to led #define BLINK_INTERVAL_1 1000 // interval at which to blink LED 1 (milliseconds) #define BLINK_INTERVAL_2 500 // interval at which to blink LED 2 (milliseconds) int led_state_1 = LOW; // led_state used to set the LED 1 int led_state_2 = LOW; // led_state used to set the LED 2 int prev_button_state = LOW; // will store last time button was updated unsigned long prev_time_ms_1 = 0; // will store last time LED 1 was updated unsigned long prev_time_ms_2 = 0; // will store last time LED 2 was updated void setup() { Serial.begin(9600); // Configure the ESP8266 pin as a digital output pin pinMode(LED_PIN_1, OUTPUT); pinMode(LED_PIN_2, OUTPUT); // Configure the ESP8266 pin as a digital input pin pinMode(BUTTON_PIN, INPUT); } void loop() { unsigned long time_ms = millis(); // check to see if it's time to blink the LED 1 if (time_ms - prev_time_ms_1 >= BLINK_INTERVAL_1) { // if the LED is off turn it on and vice-versa: led_state_1 == (led_state_1 == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN_1, led_state_1); // save the last time you blinked the LED prev_time_ms_1 = time_ms; } // check to see if it's time to blink the LED 2 if (time_ms - prev_time_ms_2 >= BLINK_INTERVAL_2) { // if the LED is off turn it on and vice-versa: led_state_2 == (led_state_2 == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN_2, led_state_2); // save the last time you blinked the LED prev_time_ms_1 = time_ms; } // check button state's change int button_state = digitalRead(BUTTON_PIN); if(button_state != prev_button_state) { // print out the state of the button: Serial.println(button_state); // save the last state of button prev_button_state = button_state; } // DO OTHER WORKS HERE }

Vídeo

Extensibilidade

Este método permite que o ESP8266 realize várias tarefas simultaneamente, sem que uma tarefa bloqueie a outra. Por exemplo, enviar uma requisição para a Internet e esperar pela resposta, enquanto também pisca LEDs indicadores e monitora o botão de cancelar.

Referências de Funções

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!