Arduino Nano - Botón - Rebote

Cuando se presiona o se suelta un botón, o se cambia un interruptor, los principiantes a menudo suponen que su estado cambia de bajo a alto o de alto a bajo. En realidad, esto no siempre es el caso. Debido a características mecánicas y físicas, el estado del botón (o interruptor) puede alternar rápidamente entre bajo y alto varias veces en respuesta a un solo evento. Este fenómeno se conoce como rebote. El rebote puede hacer que una sola pulsación se lea como varias pulsaciones, provocando un mal funcionamiento en ciertas aplicaciones.

fenómeno de rechinamiento

El método para eliminar este problema se conoce como debouncing o debounce. Este tutorial te enseña cómo hacerlo al usar el botón con Arduino Nano. Aprenderemos a través de los siguientes pasos:

Hardware Requerido

1×Official Arduino Nano
1×Alternatively, DIYables ATMEGA328P Nano Development Board
1×Cable USB A a Mini-B
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.

Acerca del botón

Si no estás familiarizado con los botones (disposición de pines, funcionalidad, programación, etc.), los siguientes tutoriales pueden ayudar:

Diagrama de Cableado

Diagrama de cableado del botón Arduino Nano

This image is created using Fritzing. Click to enlarge image

Observemos y contrastemos el código del Arduino Nano para ambos casos: con y sin anti-rebote, así como sus respectivos comportamientos.

Lectura del botón sin rebote

Antes de adentrarte en el concepto de debouncing, echa un vistazo al código sin debouncing y observa su comportamiento.

Pasos R\u00e1pidos

  • Conecta un cable USB al Arduino Nano y a tu PC.
  • Inicia el IDE de Arduino y elige la placa y el puerto correctos.
  • Copia el código que se muestra a continuación y ábrelo en el IDE de Arduino.
/* * 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-button-debounce */ #define BUTTON_PIN 2 // The number of the pushbutton pin int prev_button_state = LOW; // The previous state from the input pin int button_state; // The current reading from the input pin void setup() { // Initialize the Serial to communicate with the Serial Monitor. Serial.begin(9600); // Configure the Arduino Nano pin as a pull-up input // The pull-up input pin is HIGH when the button is open and LOW when pressed. pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { // read the state of the switch/button: button_state = digitalRead(BUTTON_PIN); if(prev_button_state == HIGH && button_state == LOW) Serial.println("The button is pressed"); else if(prev_button_state == LOW && button_state == HIGH) Serial.println("The button is released"); // save the the last state prev_button_state = button_state; }
  • Haz clic en el botón Cargar en el IDE de Arduino para compilar y cargar el código en la placa Arduino Nano.
Subir código al IDE de Arduino
  • Abre el monitor serie.
  • Mantén pulsado el botón durante unos segundos, luego suéltalo.
  • Prueba varias veces.
  • Revisa el resultado en el monitor serie.
COM6
Send
The button is pressed The button is pressed The button is pressed The button is released The button is released
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

A veces, solo presionaste y soltaste el botón una vez. Sin embargo, Arduino Nano lo interpreta como varias pulsaciones y liberaciones. Este es el fenómeno de rebote mencionado al inicio del tutorial. Veamos cómo solucionarlo en la próxima parte.

Lectura de un botón con antirrebote

El código que se muestra a continuación aplica el método llamado debounce para evitar el fenómeno de rebote.

/* * 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-button-debounce */ #define BUTTON_PIN 2 // The number of the pushbutton pin const int DEBOUNCE_DELAY = 50; // The debounce time; increase if the output flickers int lastSteadyState = LOW; // The previous steady state from the input pin int lastFlickerableState = LOW; // The previous flickerable state from the input pin int button_state; // The current reading from the input pin // The following variables are unsigned longs because the time, measured in // milliseconds, will quickly become a bigger number than can be stored in an int. unsigned long lastDebounceTime = 0; // The last time the output pin was toggled void setup() { // Initialize the Serial to communicate with the Serial Monitor. Serial.begin(9600); // Configure the Arduino Nano pin as a pull-up input // The pull-up input pin is HIGH when the button is open and LOW when pressed. pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { // read the state of the switch/button: button_state = digitalRead(BUTTON_PIN); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited long enough // since the last press to ignore any noise: // If the switch/button changed, due to noise or pressing: if (button_state != lastFlickerableState) { // reset the debouncing timer lastDebounceTime = millis(); // save the the last flickerable state lastFlickerableState = button_state; } if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: // if the button state has changed: if (lastSteadyState == HIGH && button_state == LOW) Serial.println("The button is pressed"); else if (lastSteadyState == LOW && button_state == HIGH) Serial.println("The button is released"); // save the the last steady state lastSteadyState = button_state; } }

Pasos R\u00e1pidos

  • Copia el código anterior y ábrelo con el Arduino IDE.
  • Haz clic en el botón Subir del IDE de Arduino para compilar y cargar el código al Arduino Nano.
  • Abre el Monitor Serial.
  • Continúa presionando el botón durante unos segundos, luego suéltalo.
  • Mira el resultado en el Monitor Serial.
COM6
Send
The button is pressed The button is released
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

Como puedes observar, empujaste y soltaste el botón solo una vez. El Arduino Nano lo detecta como una única pulsación y liberación. El ruido se elimina.

Lo Hicimos Fácil - Código de Rebote de Botón para Arduino Nano con Biblioteca

Hemos diseñado una biblioteca, ezButton, para facilitar a quienes están comenzando, especialmente cuando se trata de manejar múltiples botones. Puede obtener más información sobre la biblioteca ezButton aquí.

Código de antirrebote de botón para Arduino Nano de un solo botón

#include <ezButton.h> ezButton button(2); // create ezButton object for pin 2; void setup() { Serial.begin(9600); button.setDebounceTime(50); // set debounce time to 50 milliseconds } void loop() { button.loop(); // MUST call the loop() function first if(button.isPressed()) Serial.println("The button is pressed"); if(button.isReleased()) Serial.println("The button is released"); }

Código antiprebote de botones para Arduino Nano para múltiples botones

/* * 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-button-debounce */ #include <ezButton.h> ezButton button1(6); // create ezButton object for pin 6; ezButton button2(7); // create ezButton object for pin 7; ezButton button3(8); // create ezButton object for pin 8; void setup() { Serial.begin(9600); button1.setDebounceTime(50); // set debounce time to 50 milliseconds button2.setDebounceTime(50); // set debounce time to 50 milliseconds button3.setDebounceTime(50); // set debounce time to 50 milliseconds } void loop() { button1.loop(); // MUST call the loop() function first button2.loop(); // MUST call the loop() function first button3.loop(); // MUST call the loop() function first if(button1.isPressed()) Serial.println("The button 1 is pressed"); if(button1.isReleased()) Serial.println("The button 1 is released"); if(button2.isPressed()) Serial.println("The button 2 is pressed"); if(button2.isReleased()) Serial.println("The button 2 is released"); if(button3.isPressed()) Serial.println("The button 3 is pressed"); if(button3.isReleased()) Serial.println("The button 3 is released"); }

El esquema del código anterior: La ilustración del cableado del código:. La representación visual del cableado del código:

Diagrama de cableado de Arduino Nano con varios botones

This image is created using Fritzing. Click to enlarge image

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

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.

Conocimientos Adicionales

  • El valor de DEBOUNCE_DELAY varía según las características físicas de cada botón. Es posible que diferentes botones usen valores diferentes.

Extensibilidad

La técnica de anti-rebote puede utilizarse con un interruptor, un sensor táctil y más.

※ 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!