Arduino UNO R4 - Vários Botões

Arduino UNO R4 vários botões

Este guia mostra como usar um Arduino UNO R4 com vários botões ao mesmo tempo, sem a função delay(), para fazer o debounce. O guia oferece o código de duas maneiras diferentes:

Vamos usar cinco botões como exemplo. Você pode mudar isso facilmente para dois botões, quatro botões ou até mais.

Sobre o Botão

Oferecemos um guia detalhado sobre botões, que aborda as conexões de hardware, como eles funcionam, a ligação com o Arduino UNO R4 e como escrever o código. Saiba mais aqui:

Diagrama de Ligação

Diagrama de Ligação de vários botões com Arduino UNO R4

This image is created using Fritzing. Click to enlarge image

Veja A melhor forma de alimentar o Arduino Uno R4 e outros componentes.

Código Arduino UNO R4 - Vários Botões com debounce

Ao usar vários botões, as situações podem ficar complexas.

  • Aplicações que precisam de debounce de botão
  • Aplicações que precisam identificar quando os botões são pressionados ou soltos

A biblioteca ezButton simplifica o trabalho com botões ao tratar o debounce e os eventos dos botões internamente. Os usuários não precisam se preocupar em gerenciar timestamps e variáveis ao usar esta biblioteca. Além disso, usar vários botões pode deixar o código mais claro e mais curto.

/* * Este código de Arduino UNO R4 foi desenvolvido por pt.newbiely.com * Este código de Arduino UNO R4 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-uno-r4/arduino-uno-r4-multiple-button */ #include <ezButton.h> #define BUTTON_NUM 5 // the number of buttons #define BUTTON_PIN_1 2 // The Arduino UNO R4 pin connected to the button 1 #define BUTTON_PIN_2 3 // The Arduino UNO R4 pin connected to the button 2 #define BUTTON_PIN_3 4 // The Arduino UNO R4 pin connected to the button 3 #define BUTTON_PIN_4 5 // The Arduino UNO R4 pin connected to the button 4 #define BUTTON_PIN_5 6 // The Arduino UNO R4 pin connected to the button 5 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 ezButton button5(BUTTON_PIN_5); // create ezButton object for button 5 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 button5.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 button5.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 int button5_state = button5.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); Serial.print("The button 5 state: "); Serial.println(button5_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"); if (button5.isPressed()) Serial.println("The button 5 is pressed"); if (button5.isReleased()) Serial.println("The button 5 is released"); }

Passos Rápidos

Siga estas instruções passo a passo:

  • Se esta é a primeira vez que você usa o Arduino Uno R4 WiFi/Minima, consulte o tutorial sobre como configurar o ambiente para o Arduino Uno R4 WiFi/Minima na Arduino IDE.
  • Conecte o Arduino Uno R4 aos botões de acordo com o diagrama fornecido.
  • Conecte a placa Arduino Uno R4 ao seu computador usando um cabo USB.
  • Abra a Arduino IDE no seu computador.
  • Selecione a placa Arduino Uno R4 apropriada (por exemplo, Arduino Uno R4 WiFi) e a porta COM.
  • Clique no ícone Libraries no lado esquerdo da Arduino IDE.
  • Procure por ezButton e localize a biblioteca de botão criada por ArduinoGetStarted.com.
  • Clique no botão Install para instalar a biblioteca ezButton.
Biblioteca de botão para Arduino UNO R4
  • Copie o código e cole-o na Arduino IDE.
  • Clique no botão Upload na Arduino IDE para compilar e fazer upload do código para a placa Arduino UNO R4.
Como fazer upload do código do Arduino UNO R4 na Arduino IDE
  • Abra o Serial Monitor na Arduino IDE.
  • Pressione e solte cada botão, um de cada vez.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno R4 WiFi
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno R4 WiFi' 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 The button 5 is pressed The button 5 is released
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2

Código Arduino UNO R4 - Vários Botões usando array

Podemos melhorar o código acima usando um array de botões.

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