ESP32 - Vários Botões

Este tutorial ensina você a programar um ESP32 para usar vários botões ao mesmo tempo sem depender da função delay(). O tutorial oferece código em dois métodos:

Vamos demonstrar com quatro botões. No entanto, você pode ajustar facilmente o código para dois botões, três botões, cinco botões ou até mais.

Sobre o Botão

Temos tutoriais específicos sobre o botão. Cada tutorial contém informações detalhadas e instruções passo a passo sobre a pinagem do hardware, o princípio de funcionamento, a ligação ao ESP32, o código do ESP32... Saiba mais sobre eles nos links a seguir:

Diagrama de Ligação

Diagrama de Ligação de vários botões com ESP32

This image is created using Fritzing. Click to enlarge image

Se você não sabe como alimentar o ESP32 e outros componentes, veja as instruções no tutorial a seguir: Como alimentar o ESP32.

Código ESP32 - Vários Botões com debounce

Ao lidar com vários botões, a complexidade pode aumentar em situações específicas:

Felizmente, a biblioteca ezButton simplifica esse processo, cuidando internamente do debounce e dos eventos do botão. Isso poupa os usuários de gerenciar marcas de tempo e variáveis ao usar a biblioteca. Além disso, usar um array de botões pode deixar o código mais claro e curto.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-multiple-button */ #include <ezButton.h> #define BUTTON_PIN_1 25 // The ESP32 pin GPIO25 connected to the button 1 #define BUTTON_PIN_2 26 // The ESP32 pin GPIO26 connected to the button 2 #define BUTTON_PIN_3 27 // The ESP32 pin GPIO27 connected to the button 3 #define BUTTON_PIN_4 14 // The ESP32 pin GPIO14 connected to the button 4 ezButton button1(BUTTON_PIN_1); // create ezButton object for button 1 ezButton button2(BUTTON_PIN_2); // create ezButton object for button 2 ezButton button3(BUTTON_PIN_3); // create ezButton object for button 3 ezButton button4(BUTTON_PIN_4); // create ezButton object for button 4 void setup() { Serial.begin(9600); button1.setDebounceTime(100); // set debounce time to 100 milliseconds button2.setDebounceTime(100); // set debounce time to 100 milliseconds button3.setDebounceTime(100); // set debounce time to 100 milliseconds button4.setDebounceTime(100); // set debounce time to 100 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 button4.loop(); // MUST call the loop() function first // get button state after debounce int button1_state = button1.getState(); // the state after debounce int button2_state = button2.getState(); // the state after debounce int button3_state = button3.getState(); // the state after debounce int button4_state = button4.getState(); // the state after debounce /* Serial.print("The button 1 state: "); Serial.println(button1_state); Serial.print("The button 2 state: "); Serial.println(button2_state); Serial.print("The button 3 state: "); Serial.println(button3_state); Serial.print("The button 4 state: "); Serial.println(button4_state); */ 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"); if (button4.isPressed()) Serial.println("The button 4 is pressed"); if (button4.isReleased()) Serial.println("The button 4 is released"); }

Passos Rápidos

  • Se esta é a primeira vez que você usa o ESP32, veja como configurar o ambiente para o ESP32 no Arduino IDE.
  • Faça a ligação como na imagem acima.
  • Conecte a placa ESP32 ao seu PC por um cabo USB Type-C
  • Abra o Arduino IDE no seu PC.
  • Selecione a placa ESP32 correta (por exemplo, ESP32 Dev Module) e a porta COM.
  • Clique no ícone Libraries na barra lateral esquerda do Arduino IDE.
  • Pesquise “ezButton” e encontre a biblioteca de botão da ArduinoGetStarted
  • Clique no botão Install para instalar a biblioteca ezButton.
Biblioteca de botão para ESP32
  • Copie o código acima e cole-o no Arduino IDE.
  • Compile e faça upload do código para a placa ESP32 clicando no botão Upload no Arduino IDE
Como fazer upload do código ESP32 no Arduino IDE
  • Abra o Serial Monitor no Arduino IDE
  • Pressione e solte os botões um por um
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
The button 1 is pressed The button 1 is released The button 2 is pressed The button 2 is released The button 3 is pressed The button 3 is released The button 4 is pressed The button 4 is released
Ln 11, Col 1
ESP32 Dev Module on COM15
2

Código ESP32 - Vários Botões usando array

Podemos melhorar o código apresentado usando um array de botões. O código a seguir mostra como esse array gerencia os objetos de botão.

/* * Este código de ESP32 foi desenvolvido por pt.newbiely.com * Este código de ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp32/esp32-multiple-button */ #include <ezButton.h> #define BUTTON_NUM 4 // the number of buttons #define BUTTON_PIN_1 25 // The ESP32 pin GPIO25 connected to the button 1 #define BUTTON_PIN_2 26 // The ESP32 pin GPIO26 connected to the button 2 #define BUTTON_PIN_3 27 // The ESP32 pin GPIO27 connected to the button 3 #define BUTTON_PIN_4 14 // The ESP32 pin GPIO14 connected to the button 4 ezButton buttonArray[] = { ezButton(BUTTON_PIN_1), ezButton(BUTTON_PIN_2), ezButton(BUTTON_PIN_3), ezButton(BUTTON_PIN_4) }; void setup() { Serial.begin(9600); for (byte i = 0; i < BUTTON_NUM; i++) { buttonArray[i].setDebounceTime(100); // set debounce time to 100 milliseconds } } void loop() { for (byte i = 0; i < BUTTON_NUM; i++) buttonArray[i].loop(); // MUST call the loop() function first for (byte i = 0; i < BUTTON_NUM; i++) { // get button state after debounce int button_state = buttonArray[i].getState(); // the state after debounce /* Serial.print("The button "); Serial.print(i + 1); Serial.print(": "); Serial.println(button_state); */ if (buttonArray[i].isPressed()) { Serial.print("The button "); Serial.print(i + 1); Serial.println(" is pressed"); } if (buttonArray[i].isReleased()) { Serial.print("The button "); Serial.print(i + 1); Serial.println(" is released"); } } }

Vídeo

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