ESP32 - Botón - Rebote

Cuando se presiona o se suelta un botón, o cuando se cambia un interruptor entre ENCENDIDO y APAGADO, su estado cambia de BAJO a ALTO (o de ALTO a BAJO) una sola vez. ¿Es correcto?

⇒ No, no es así. Eso se debe a que, en el mundo físico, cuando haces una pulsación única en un botón, el estado del botón cambia rápidamente entre nivel bajo y nivel alto varias veces en lugar de una vez. Esta es la característica mecánica y física. Este fenómeno se conoce con un nombre: chattering. El fenómeno de chattering provoca que el MCU lea múltiples pulsaciones del botón en respuesta a una pulsación real única. Esto resulta en un mal funcionamiento. El proceso para eliminar este fenómeno se llama debounce. Este tutorial muestra cómo hacerlo.

Fenómeno de conmutación inestable del ESP32

Este tutorial proporciona:

Acerca del botón

Tenemos tutoriales específicos sobre el botón. El tutorial contiene información detallada e instrucciones paso a paso sobre el pinout de hardware, el principio de funcionamiento, la conexión de cableado al ESP32 y el código para ESP32... Obtenga más información sobre ellos en los siguientes enlaces:

Diagrama de Cableado

Diagrama de cableado del botón ESP32

This image is created using Fritzing. Click to enlarge image

Si no sabe c\u00f3mo alimentar ESP32 y otros componentes, encuentre instrucciones en el siguiente tutorial: C\u00f3mo alimentar ESP32.

Para que quede claro, ejecutemos el código ESP32 SIN y CON debounce, y comparemos sus resultados

Lectura de botón sin antirrebote

Pasos R\u00e1pidos

  • Si es la primera vez que usas ESP32, consulta cómo configurar el entorno para ESP32 en Arduino IDE.
  • Realiza el cableado como en la imagen anterior.
  • Conecta la placa ESP32 a tu PC mediante un cable micro USB.
  • Abre Arduino IDE en tu PC.
  • Selecciona la placa ESP32 adecuada (p. ej. ESP32 Dev Module) y el puerto COM.
  • Copia el código a continuación y pégalo en Arduino IDE.
/* * Este código de ESP32 fue desarrollado por es.newbiely.com * Este código de ESP32 se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp32/esp32-button-debounce */ #define BUTTON_PIN 21 // GIOP21 pin connected to button // Variables will change: int lastState = LOW; // the previous state from the input pin int currentState; // the current reading from the input pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the pushbutton pin as an pull-up input // the pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed. pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { // read the state of the switch/button: currentState = digitalRead(BUTTON_PIN); if (lastState == HIGH && currentState == LOW) Serial.println("The button is pressed"); else if (lastState == LOW && currentState == HIGH) Serial.println("The button is released"); // save the the last state lastState = currentState; }
  • Compila y carga el código en la placa ESP32 haciendo clic en el botón Subir en el IDE de Arduino
Subir código al IDE de Arduino
  • Abrir el Monitor Serial en el IDE de Arduino
Cómo abrir el monitor serial en el IDE de Arduino
  • Presione el botón una vez, pero manténgalo presionado durante varios segundos y luego suéltelo.
  • Vea el resultado en el Monitor Serial. Se muestra a continuación.
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  

⇒ Como puedes ver, solo realizaste una única pulsación y liberación, pero el ESP32 lee múltiples pulsaciones y liberaciones.

※ Nota:

El fenómeno de chattering no ocurre todo el tiempo. Si no ocurre, por favor pruebe la prueba anterior varias veces.

Lectura de un botón con antirrebote

Pasos R\u00e1pidos

/* * Este código de ESP32 fue desarrollado por es.newbiely.com * Este código de ESP32 se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp32/esp32-button-debounce */ #define BUTTON_PIN 21 // GIOP21 pin connected to button #define DEBOUNCE_TIME 50 // the debounce time in millisecond, increase this time if it still chatters // Variables will change: int lastSteadyState = LOW; // the previous steady state from the input pin int lastFlickerableState = LOW; // the previous flickerable state from the input pin int currentState; // 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 serial communication at 9600 bits per second: Serial.begin(9600); // initialize the pushbutton pin as an pull-up input // the pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed. pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { // read the state of the switch/button: currentState = 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 (currentState != lastFlickerableState) { // reset the debouncing timer lastDebounceTime = millis(); // save the the last flickerable state lastFlickerableState = currentState; } if ((millis() - lastDebounceTime) > DEBOUNCE_TIME) { // 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 && currentState == LOW) Serial.println("The button is pressed"); else if(lastSteadyState == LOW && currentState == HIGH) Serial.println("The button is released"); // save the the last steady state lastSteadyState = currentState; } }
  • Compilar y subir código a la placa ESP32 haciendo clic en el botón Subir en el IDE de Arduino
  • Abrir el Monitor Serial en el IDE de Arduino
Cómo abrir el monitor serie en el IDE de Arduino
  • Mantén pulsado el botón durante varios segundos y luego suéltalo.
  • Mira el resultado en el Monitor Serial. Se muestra a continuación:
COM6
Send
The button is pressed The button is released
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

⇒ Como puedes ver, realizaste una pulsación y liberación, y el ESP32 leyó una pulsación y liberación. El rebote está eliminado.

Lo Hicimos Fácil - Código de Antirrebote de Botón ESP32 con Biblioteca

Para facilitar a los principiantes, especialmente cuando se aplica antirrebote a varios botones, hemos creado una biblioteca de botones llamada ezButton. Puedes aprender sobre la biblioteca ezButton aquí.

Código de antirrebote de botón ESP32 para un único botón

/* * Este código de ESP32 fue desarrollado por es.newbiely.com * Este código de ESP32 se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp32/esp32-button-debounce */ #include <ezButton.h> #define DEBOUNCE_TIME 50 // the debounce time in millisecond, increase this time if it still chatters ezButton button(21); // create ezButton object that attach to pin GPIO21 void setup() { Serial.begin(9600); button.setDebounceTime(DEBOUNCE_TIME); // 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 de antirrebote de botón ESP32 para varios botones

Escribamos código de debounce para tres botones.

El diagrama de cableado

Diagrama de cableado de la biblioteca de botones ESP32

This image is created using Fritzing. Click to enlarge image

/* * Este código de ESP32 fue desarrollado por es.newbiely.com * Este código de ESP32 se proporciona al público sin ninguna restricción. * Para tutoriales completos y diagramas de cableado, visite: * https://es.newbiely.com/tutorials/esp32/esp32-button-debounce */ #include <ezButton.h> #define DEBOUNCE_TIME 50 // the debounce time in millisecond, increase this time if it still chatters ezButton button1(21); // create ezButton object that attach to pin GPIO21; ezButton button2(22); // create ezButton object that attach to pin GPIO22; ezButton button3(23); // create ezButton object that attach to pin GPIO23; void setup() { Serial.begin(9600); button1.setDebounceTime(DEBOUNCE_TIME); // set debounce time to 50 milliseconds button2.setDebounceTime(DEBOUNCE_TIME); // set debounce time to 50 milliseconds button3.setDebounceTime(DEBOUNCE_TIME); // 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"); }

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

  • DEBOUNCE_TIME el valor depende del hardware. Diferentes hardware pueden usar valores diferentes.
  • El tiempo de rebote también debe aplicarse para el interruptor de encendido/apagado, el interruptor de fin de carrera, el interruptor de láminas (reed switch) y el sensor táctil ...

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