Arduino Nano - LED - Parpadeo sin retardo

Imaginemos que Arduino Nano tiene dos tareas por realizar: parpadear un LED y vigilar el estado de un botón que puede ser pulsado en cualquier momento. Si usamos la función delay() (como se explicó en un tutorial anterior), Arduino Nano podría pasar por alto algunas de las pulsaciones del botón. En otras palabras, Arduino Nano no es capaz de completar plenamente la segunda tarea.

Este tutorial te enseña cómo hacer que una placa Arduino Nano parpadee un LED y detectar el estado de un botón sin perder ningún evento de pulsación.

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

Este método no se limita solo a parpadear un LED y comprobar el estado del botón. En general, permite que Arduino Nano realice varias tareas simultáneamente sin bloquearse entre sí.

Hardware Requerido

1×Official Arduino Nano
1×Alternatively, DIYables ATMEGA328P Nano Development Board
1×Cable USB A a Mini-B
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 Arduino Nano
1×(Recomendado) Placa de Expansión Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentación para Arduino Nano

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ás familiarizado con el LED y el botón (incluyendo la disposición de pines, la funcionalidad y la programación), los siguientes tutoriales pueden ayudar:

Diagrama de Cableado

Diagrama de cableado del LED para Arduino Nano

This image is created using Fritzing. Click to enlarge image

Ver La mejor forma de alimentar Arduino Nano y otros componentes.

Código de Arduino Nano - con retardo

/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-led-blink-without-delay */ const int LED_PIN = 5; // The number of the LED pin const int BUTTON_PIN = 2; // The number of the button pin const long 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); // set the digital pin as output: pinMode(LED_PIN, OUTPUT); // set the digital pin as an input: 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, Arduino 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

  • Conecta tu Arduino Nano a tu computadora usando un cable USB.
  • Inicia el IDE de Arduino, selecciona la placa correcta y el puerto correcto.
  • Copia el código y ábrelo en el IDE de Arduino.
  • Haz clic en el botón Subir en el IDE de Arduino para compilar y subir el código al Arduino Nano.
Cómo subir código al Arduino Nano
  • Abre el Monitor Serial.
  • Presiona el botón cuatro veces.
  • Observa el LED; se alternará entre encendido y apagado 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, algunos momentos de pulsación no se registraron. Esto se debe a que durante el tiempo de demora, Arduino Nano no puede realizar ninguna acción. En consecuencia, no puede detectar el evento de pulsación.

Código de Arduino Nano - Sin Demora

/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-led-blink-without-delay */ const int LED_PIN = 5; // The number of the LED pin const int BUTTON_PIN = 2; // The number of the button pin const long 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); // set the digital pin as output: pinMode(LED_PIN, OUTPUT); // set the digital pin as an input: 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

  • Ejecuta el código y pulsa el botón cuatro veces.
  • Observa el LED; cambiará entre ENCENDIDO y APAGADO a intervalos 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 cuestiones urgentes.

Explicación del código

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

Añadir más tareas

El código de Arduino Nano a continuación realiza lo siguiente:

  • Hace parpadear dos LEDs con intervalos diferentes.
  • Verifica el estado del botón.
/* * Este código de Arduino Nano fue desarrollado por es.newbiely.com * Este código de Arduino Nano se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/arduino-nano/arduino-nano-led-blink-without-delay */ const int LED_PIN_1 = 5; // The number of the LED 1 pin const int LED_PIN_2 = LED_BUILTIN; // The number of the LED 2 pin const int BUTTON_PIN = 2; // The number of the button pin const long BLINK_INTERVAL_1 = 1000; // interval at which to blink LED 1 (milliseconds) const long 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); // set the digital pin as output: pinMode(LED_PIN_1, OUTPUT); pinMode(LED_PIN_2, OUTPUT); // set the digital pin as an input: 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_2 = 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 puede usarse para permitir que Arduino Nano ejecute múltiples tareas de forma concurrente, sin que una tarea bloquee el progreso de la otra. Por ejemplo, enviar una solicitud a Internet y esperar la respuesta, mientras se parpadean simultáneamente algunos 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!