ESP8266 - LED - Parpadeo sin retardo

Imaginemos que ESP8266 tiene dos tareas por realizar: parpadear un LED y monitorear el estado de un botón que puede ser presionado en cualquier momento. Si usamos la función delay() (como se explicó en un tutorial anterior), ESP8266 podría perder algunas pulsaciones del botón. En otras palabras, ESP8266 no podría ejecutar completamente la segunda tarea.

Este tutorial le enseña cómo hacer que el ESP8266 parpadee un LED y monitorizar el estado de un botón sin perder ninguna de sus pulsaciones.

Vamos a repasar tres ejemplos y a comparar las diferencias entre ellos:

Este método no se limita solo a parpadear un LED y a comprobar el estado del botón. En general, permite que el ESP8266 realice varias tareas de forma simultánea sin bloquearse entre ellas.

Hardware Requerido

1×ESP8266 NodeMCU
1×Cable USB Tipo-A a Tipo-C (para PC USB-A)
1×Cable USB Tipo-C a Tipo-C (para PC USB-C)
1×LED Kit
1×LED (red)
1×LED Module
1×220Ω Resistor
1×Botón para Protoboard con Tapa
1×Kit de Botón para Protoboard
1×Botón Pulsador de Panel
1×Módulo de Botón Pulsador
1×Protoboard
1×Cables Puente
1×(Recomendado) Placa de Expansión de Terminales de Tornillo para ESP8266
1×(Recomendado) Divisor de Alimentación para ESP8266 Tipo-C

Or you can buy the following kits:

1×DIYables Sensor Kit (30 sensors/displays)
1×DIYables Sensor Kit (18 sensors/displays)
Divulgación: Algunos de los enlaces proporcionados en esta sección son enlaces de afiliado de Amazon. Podemos recibir una comisión por las compras realizadas a través de estos enlaces sin costo adicional para usted. Apreciamos su apoyo.

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

Acerca de LED y Botón

Si no está familiarizado con el LED y con el botón (disposición de pines, funcionalidad, programación ...), los siguientes tutoriales pueden ayudar:

Diagrama de Cableado

Diagrama de cableado de LED para ESP8266 NodeMCU

This image is created using Fritzing. Click to enlarge image

Para obtener m\u00e1s informaci\u00f3n, consulte Pines del ESP8266 y c\u00f3mo alimentar ESP8266 y otros componentes.

Código ESP8266 - Con Retardo

/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.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 }

Pasos R\u00e1pidos

Para empezar con ESP8266 en el IDE de Arduino, siga estos pasos:

  • Consulta el tutorial cómo configurar el entorno para ESP8266 en Arduino IDE si es la primera vez que usas ESP8266.
  • Conecta los componentes tal como se muestran en el diagrama.
  • Conecta la placa ESP8266 a tu ordenador mediante un cable USB.
  • Abre Arduino IDE en tu ordenador.
  • Elige la placa ESP8266 correcta, como (p. ej. NodeMCU 1.0 (Módulo ESP-12E)), y su puerto COM respectivo.
  • Conecta el cable USB a la ESP8266 y al ordenador.
  • Inicia Arduino IDE, selecciona la placa y el puerto correctos.
  • Copia el código y ábrelo en Arduino IDE.
  • Haz clic en el botón Subir en Arduino IDE para compilar y subir el código al ESP8266.
Cómo subir código al ESP8266 NodeMCU usando el IDE de Arduino
  • Abre el Monitor Serial.
  • Pulsa el botón cuatro veces.
  • Observa el LED; se encenderá y apagará cada segundo.
  • Verifica la salida en el Monitor Serial.
COM6
Send
1 0
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • En el Monitor Serial, algunas pulsaciones no se registraron. Esto se debe a que, durante la demora, el ESP8266 no puede realizar ninguna tarea. En consecuencia, no puede detectar el evento de pulsación.

Código ESP8266 - Sin demora

/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.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 }

Pasos R\u00e1pidos

  • Conecta los componentes tal como se muestra en el diagrama.
  • Conecta la placa ESP8266 a tu computadora usando un cable USB.
  • Abre el Arduino IDE en tu computadora.
  • Elige la placa ESP8266 correcta, como (p. ej. NodeMCU 1.0 (ESP-12E Module)), y su puerto COM correspondiente.
  • Ejecuta el código y pulsa el botón 4 veces.
  • Observa el LED, que alternará entre ENCENDIDO y APAGADO a intervalos regulares de un segundo.
  • Revisa la salida en el Monitor Serial.
COM6
Send
1 0 1 0 1 0 1 0
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • Se identificaron todas las ocurrencias de asuntos urgentes.

Explicación del código

¡Consulta la explicación línea por línea que se encuentra en los comentarios del código fuente!

Añadiendo más tareas

El código ESP8266 que se muestra a continuación hace

  • Hace que dos LEDs parpadeen con intervalos diferentes.
  • Verifica el estado del botón.
/* * Este código de ESP8266 NodeMCU fue desarrollado por es.newbiely.com * Este código de ESP8266 NodeMCU se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.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 }

Video Tutorial

Estamos considerando crear tutoriales en video. Si considera que los tutoriales en video son importantes, suscríbase a nuestro canal de YouTube para motivarnos a crear los videos.

Extensibilidad

Este método permite al ESP8266 realizar varias tareas al mismo tiempo, sin que una tarea bloquee a otra. Por ejemplo, enviar una solicitud a Internet y esperar la respuesta, mientras también se parpadean los indicadores LED y se supervisa el botón de cancelación.

Referencias de funciones

※ NUESTROS MENSAJES

  • No dude en compartir el enlace de este tutorial. Sin embargo, por favor no use nuestro contenido en otros sitios web. Hemos invertido mucho esfuerzo y tiempo en crear el contenido, ¡por favor respete nuestro trabajo!