Arduino UNO R4 - LED - Piscar Sem Delay

Imagine que o Arduino UNO R4 precisa fazer duas tarefas: piscar um LED e detectar quando um botão é pressionado. Se usarmos a função delay(), o Arduino UNO R4 pode perder alguns acionamentos do botão. Neste tutorial, vamos aprender a fazer o Arduino UNO R4 piscar um LED e monitorar um botão para garantir que ele detecte todos os acionamentos do botão.

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

Arduino UNO R4 Piscar LED

※ Nota:

  • Este método faz mais do que apenas piscar o LED e verificar o estado do botão. Ele permite que o Arduino UNO R4 execute várias tarefas ao mesmo tempo, sem interrupções.
  • Este tutorial traz informações detalhadas para ajudar você a aprender como funciona. Para simplificar, você pode usar a biblioteca de LED para Arduino UNO R4.

Sobre o LED e o Botão

Saiba mais sobre o LED e o botão (pinagem, como funcionam, como programar, etc.) nestes tutoriais:

Diagrama de Ligação

Diagrama de Ligação do LED 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 - Com Delay

/* * 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-blink-led-without-delay */ #define LED_PIN 3 // The Arduino UNO R4 pin connected to the LED #define BUTTON_PIN 7 // The Arduino UNO R4 pin connected to the 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

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.
  • Faça a ligação dos componentes 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.
  • Copie o código fornecido e cole-o na Arduino IDE.
  • Clique no botão Upload na Arduino IDE para transferir o código para o Arduino UNR R4.
Arduino IDE - Como Fazer Upload do Código
  • Abra o Serial Monitor.
  • Pressione o botão quatro vezes.
  • Observe o LED: Ele liga e desliga a cada segundo.
  • Confira o que aparece no Serial Monitor.
∞
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
1 0
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
  • Alguns acionamentos do botão não apareceram no Serial Monitor porque o Arduino UNO R4 não consegue fazer nenhuma tarefa durante um delay. Por isso, ele deixa de detectar esses acionamentos.

Código Arduino UNO R4 - Sem Delay

/* * 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-blink-led-without-delay */ #define LED_PIN 3 // The Arduino UNO R4 pin connected to the LED #define BUTTON_PIN 7 // The Arduino UNO R4 pin connected to the 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 1 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() { unsigned long current_millis = millis(); // check to see if it's time to blink the LED 1 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

Siga estas instruções passo a passo:

  • Faça upload do código fornecido para o Arduino Uno R4
  • Pressione o botão quatro vezes.
  • Observe o LED: Ele alterna entre LIGADO e DESLIGADO a cada segundo.
  • Confira a saída no Serial Monitor.
∞
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
1 0 1 0 1 0 1 0
Ln 11, Col 1
Arduino Uno R4 WiFi on COM15
2
  • Todos os acionamentos do botão foram detectados.

Explicação do Código

A explicação está na seção de comentários do código Arduino acima.

Adicionando Mais Tarefas

Este código faz dois LEDs piscarem em tempos diferentes e também verifica se um botão foi pressionado.

/* * 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-blink-led-without-delay */ #define LED_PIN_1 3 // The Arduino UNO R4 pin connected to the LED 1 #define LED_PIN_2 4 // The Arduino UNO R4 pin connected to the LED 2 #define BUTTON_PIN 7 // The Arduino UNO R4 pin connected to the 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

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