Arduino Nano ESP32 - LED - Piscar Sem Delay

Um dos primeiros programas que os iniciantes executam é piscar um LED. A maneira mais simples de piscar um LED é usar a função delay(). Essa função impede o Arduino Nano ESP32 de fazer outras coisas. Isso é aceitável se você quer piscar apenas um único LED. No entanto, se você quer piscar mais LEDs ou fazer outros trabalhos em paralelo, não pode usar a função delay(). Precisamos de outra solução. Este tutorial mostra como fazer várias tarefas sem usar a função delay. Mais especificamente, vamos aprender como piscar um LED e verificar o estado do botão.

Vamos percorrer os três exemplos abaixo e comparar as diferenças entre eles.

Esse método pode ser aplicado para fazer o Arduino Nano ESP32 executar várias tarefas ao mesmo tempo. Piscar o LED é apenas um exemplo.

Hardware Necessário

1×Arduino Nano ESP32
1×Cabo USB Tipo-A para Tipo-C (para PC com USB-A)
1×Cabo USB Tipo-C para Tipo-C (para PC com USB-C)
1×LED Kit
1×LED (red)
1×LED Module
1×(Alternativa) Button and LED Kit
1×220Ω Resistor
1×Botão para Protoboard com Capa
1×Kit de Botões para Protoboard
1×Botão de Pressão para Painel
1×Módulo de Botão
1×Protoboard
1×Fios Jumper
1×(Opcional) Conector de Alimentação DC
1×(Recomendado) Placa de Expansão com Bornes de Parafuso para Arduino Nano
1×(Recomendado) Placa de Expansão Breakout para Arduino Nano
1×(Recomendado) Divisor de Alimentação para Arduino Nano ESP32

Or you can buy the following kits:

1×DIYables Sensor Kit (18 sensors/displays)
Divulgação: Alguns dos links desta seção são links de afiliado da Amazon. Podemos receber uma comissão pelas compras feitas por meio desses links, sem custo adicional para você. Agradecemos o seu apoio.

Buy Note: Use the LED Module for easier wiring. It includes an integrated resistor.

Sobre o LED e o Botão

Temos tutoriais específicos sobre o LED e 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 Arduino Nano ESP32... Saiba mais sobre eles nos links a seguir:

Diagrama de Ligação

Diagrama de Ligação do LED e botão com o Arduino Nano ESP32

This image is created using Fritzing. Click to enlarge image

Vamos comparar o código do Arduino Nano ESP32 que pisca o LED com e sem o uso da função delay()

Código Arduino Nano ESP32 - Com Delay

/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-led-blink-without-delay */ #define LED_PIN D5 // The Arduino Nano ESP32 pin D5 connected to LED #define BUTTON_PIN D2 // The Arduino Nano ESP32 pin D2 connected to button #define BLINK_INTERVAL 1000 // interval at which to blink LED (milliseconds) int led_state = LOW; // led_state used to set the LED int prev_button_state = LOW; // will store last time button was updated void setup() { Serial.begin(9600); // set the digital pin as output: pinMode(LED_PIN, OUTPUT); // set the digital pin as an input: pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { // if the LED is off turn it on and vice-versa: led_state = (led_state == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN, led_state); delay(BLINK_INTERVAL); // If button is pressed during this time, Arduino CANNOT detect int button_state = digitalRead(BUTTON_PIN); if (button_state != prev_button_state) { // print out the state of the button: Serial.println(button_state); // save the last state of button prev_button_state = button_state; } // DO OTHER WORKS HERE }

Passos Rápidos

Para começar com o Arduino Nano ESP32, siga estes passos:

  • Se você é novo no Arduino Nano ESP32, consulte o tutorial sobre como configurar o ambiente do Arduino Nano ESP32 na Arduino IDE.
  • Ligue os componentes conforme o diagrama fornecido.
  • Conecte a placa Arduino Nano ESP32 ao seu computador usando um cabo USB.
  • Abra a Arduino IDE no seu computador.
  • Selecione a placa Arduino Nano ESP32 e a porta COM correspondente.* Copie o código acima e cole na Arduino IDE.
  • Compile e faça o upload do código para a placa Arduino Nano ESP32 clicando no botão Upload da Arduino IDE
Como fazer upload do código do Arduino Nano ESP32 na Arduino IDE
  • Abra o Serial Monitor na Arduino IDE
Como abrir o Serial Monitor na Arduino IDE
  • Pressione o botão 4 vezes
  • Veja o LED: O LED alterna entre ON/OFF periodicamente a cada segundo
  • Veja a saída no Serial Monitor
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
1 0
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2
  • No Serial Monitor, você não verá as quatro vezes em que o estado muda para 0 (4 pressionamentos). Isso acontece porque, durante o tempo de delay, o Arduino Nano ESP32 NÃO consegue detectar a mudança.

Código Arduino Nano ESP32 - Sem Delay

/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-led-blink-without-delay */ #define LED_PIN D5 // The Arduino Nano ESP32 pin D5 connected to LED #define BUTTON_PIN D2 // The Arduino Nano ESP32 pin D2 connected to button #define BLINK_INTERVAL 1000 // interval at which to blink LED (milliseconds) int led_state = LOW; // led_state used to set the LED int prev_button_state = LOW; // will store last time button was updated unsigned long prev_millis = 0; // will store last time LED was updated void setup() { Serial.begin(9600); // set the digital pin as output: pinMode(LED_PIN, OUTPUT); // set the digital pin as an input: pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { // check to see if it's time to blink the LED; that is, if the difference // between the current time and last time you blinked the LED is bigger than // The interval at which you want to blink the LED. unsigned long current_millis = millis(); if (current_millis - prev_millis >= BLINK_INTERVAL) { // if the LED is off turn it on and vice-versa: led_state = (led_state == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN, led_state); // save the last time you blinked the LED prev_millis = current_millis; } // check button state's change int button_state = digitalRead(BUTTON_PIN); if (button_state != prev_button_state) { // print out the state of the button: Serial.println(button_state); // save the last state of button prev_button_state = button_state; } // DO OTHER WORKS HERE }

Passos Rápidos

∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Nano ESP32
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Nano ESP32' on 'COM15')
New Line
9600 baud
1 0 1 0 1 0 1 0
Ln 11, Col 1
Arduino Nano ESP32 on COM15
2
  • Todos os eventos de pressionamento foram detectados.

Explicação do Código Linha por Linha

O código do Arduino Nano ESP32 acima contém uma explicação linha por linha. Por favor, leia os comentários no código!

Adicionando Mais Tarefas

O código abaixo pisca dois LEDs com intervalos diferentes e verifica o estado do botão.

/* * Este código de Arduino Nano ESP32 foi desenvolvido por pt.newbiely.com * Este código de Arduino Nano ESP32 é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino-nano-esp32/arduino-nano-esp32-led-blink-without-delay */ #define LED_PIN_1 D6 // The Arduino Nano ESP32 pin D6 connected to LED 1 #define LED_PIN_2 D5 // The Arduino Nano ESP32 pin D5 connected to LED 2 #define BUTTON_PIN D2 // The Arduino Nano ESP32 pin D2 connected to button #define BLINK_INTERVAL_1 1000 // interval at which to blink LED 1 (milliseconds) #define BLINK_INTERVAL_2 500 // interval at which to blink LED 2 (milliseconds) int led_state_1 = LOW; // led_state used to set the LED 1 int led_state_2 = LOW; // led_state used to set the LED 2 int prev_button_state = LOW; // will store last time button was updated unsigned long prev_millis_1 = 0; // will store last time LED 1 was updated unsigned long prev_millis_2 = 0; // will store last time LED 2 was updated void setup() { Serial.begin(9600); // set the digital pin as output: pinMode(LED_PIN_1, OUTPUT); pinMode(LED_PIN_2, OUTPUT); // set the digital pin as an input: pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { unsigned long current_millis = millis(); // check to see if it's time to blink the LED 1 if (current_millis - prev_millis_1 >= BLINK_INTERVAL_1) { // if the LED is off turn it on and vice-versa: led_state_1 = (led_state_1 == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN_1, led_state_1); // save the last time you blinked the LED prev_millis_1 = current_millis; } // check to see if it's time to blink the LED 2 if (current_millis - prev_millis_2 >= BLINK_INTERVAL_2) { // if the LED is off turn it on and vice-versa: led_state_2 = (led_state_2 == LOW) ? HIGH : LOW; // set the LED with the led_state of the variable: digitalWrite(LED_PIN_2, led_state_2); // save the last time you blinked the LED prev_millis_2 = current_millis; } // check button state's change int button_state = digitalRead(BUTTON_PIN); if (button_state != prev_button_state) { // print out the state of the button: Serial.println(button_state); // save the last state of button prev_button_state = button_state; } // DO OTHER WORKS HERE }

Vídeo

Referências da Linguagem

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