ESP8266 - Vários Botões

Este tutorial ensina você a programar um ESP8266 para trabalhar com vários botões ao mesmo tempo, sem depender da função delay(). Em detalhes, vamos aprender:

Vamos usar três botões como exemplo. Você pode modificá-lo com facilidade para dois botões, quatro botões ou até mais.

Sobre o Botão

Se você não está familiarizado com botões (pinagem, funcionamento, como programar ...), os tutoriais a seguir podem dar mais informações:

Diagrama de Ligação

Diagrama de ligação de vários botões com ESP8266 NodeMCU

This image is created using Fritzing. Click to enlarge image

Para mais informações, veja Pinagem do ESP8266 e como alimentar o ESP8266 e outros componentes.

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

Ao usar vários botões, as coisas podem ficar complicadas em certos cenários:

Felizmente, a biblioteca ezButton simplifica esse processo, gerenciando internamente o debounce e os eventos do botão. Isso livra o usuário da tarefa de gerenciar timestamps 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 ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-multiple-button */ #include <ezButton.h> #define BUTTON_PIN_1 D5 // The ESP8266 pin connected to the button 1 #define BUTTON_PIN_2 D6 // The ESP8266 pin connected to the button 2 #define BUTTON_PIN_3 D7 // The ESP8266 pin connected to the button 3 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 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 } 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 // 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 /* 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); */ 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"); }

Passos Rápidos

Para começar com o ESP8266 na Arduino IDE, siga estes passos:

  • Veja o tutorial como configurar o ambiente para ESP8266 na Arduino IDE se esta for a sua primeira vez usando o ESP8266.
  • Ligue os componentes como mostrado no diagrama.
  • Conecte a placa ESP8266 ao seu computador usando um cabo USB.
  • Abra a Arduino IDE no seu computador.
  • Escolha a placa ESP8266 correta, como (ex.: NodeMCU 1.0 (ESP-12E Module)), e a respectiva porta COM.
  • Faça a ligação como na imagem acima.
  • Conecte a placa ESP8266 ao seu PC por meio de um cabo USB
  • Abra a Arduino IDE no seu PC.
  • Selecione a placa ESP8266 certa (ex.: ESP8266 Uno) e a porta COM.
  • Clique no ícone Libraries na barra à esquerda da Arduino IDE.
  • Pesquise “ezButton”, depois encontre a biblioteca de botão do ArduinoGetStarted
  • Clique no botão Install para instalar a biblioteca ezButton.
Biblioteca de botão para ESP8266 NodeMCU
  • Copie o código acima e cole na Arduino IDE.
  • Compile e faça o upload do código para a placa ESP8266 clicando no botão Upload na Arduino IDE
Como fazer upload do código ESP8266 NodeMCU na Arduino IDE
  • Abra o Serial Monitor na Arduino IDE
  • Pressione e solte os botões um por um
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Nodemcu 1.0 (ESP-12E Module)
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Nodemcu 1.0 (ESP-12E 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
Ln 11, Col 1
Nodemcu 1.0 (ESP-12E Module) on COM15
2

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

Podemos melhorar o código acima usando um array de botões. O código a seguir usa esse array para lidar com os objetos de botão.

/* * Este código de ESP8266 NodeMCU foi desenvolvido por pt.newbiely.com * Este código de ESP8266 NodeMCU é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/esp8266/esp8266-multiple-button */ #include <ezButton.h> #define BUTTON_NUM 3 // the number of buttons #define BUTTON_PIN_1 D5 // The ESP8266 pin connected to the button 1 #define BUTTON_PIN_2 D6 // The ESP8266 pin connected to the button 2 #define BUTTON_PIN_3 D7 // The ESP8266 pin connected to the button 3 ezButton buttonArray[] = { ezButton(BUTTON_PIN_1), ezButton(BUTTON_PIN_2), ezButton(BUTTON_PIN_3) }; 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!