Arduino - LED - Piscar Sem Delay

Imagine que o Arduino precisa fazer duas tarefas: piscar o LED e verificar o estado do botão, que pode ser pressionado a qualquer momento. Se usarmos a função delay() (descrita em um tutorial anterior), o Arduino pode perder alguns eventos de pressionamento. Em outras palavras, o Arduino não consegue fazer totalmente a segunda tarefa.

Neste tutorial, vamos aprender como o Arduino pisca o LED e verifica o estado do botão sem perder nenhum evento de pressionamento.

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

※ Nota:

  • Este método não serve apenas para piscar o LED e verificar o estado do botão. De forma geral, este método permite que o Arduino faça várias tarefas ao mesmo tempo sem que uma bloqueie a outra.
  • Este tutorial traz um conhecimento aprofundado que ajuda você a entender o princípio de funcionamento. Para facilitar, você pode usar a biblioteca Arduino - LED.

Sobre o LED e o Botão

Se você não conhece o LED e o botão (pinagem, como funcionam, como programar...), aprenda sobre eles nos seguintes tutoriais:

Diagrama de Ligação

Diagrama de ligação do LED com Arduino

This image is created using Fritzing. Click to enlarge image

Código Arduino - Com Delay

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino/arduino-led-blink-without-delay */ // constants won't change: const int LED_PIN = 3; // the number of the LED pin const int BUTTON_PIN = 7; // the number of the button pin const long BLINK_INTERVAL = 1000; // interval at which to blink LED (milliseconds) // Variables will change: int ledState = LOW; // ledState used to set the LED int previousButtonState = 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); } void loop() { // if the LED is off turn it on and vice-versa: ledState = (ledState == LOW) ? HIGH : LOW; // set the LED with the ledState of the variable: digitalWrite(LED_PIN, ledState); delay(BLINK_INTERVAL); // If button is pressed during this time, Arduino CANNOT detect int currentButtonState = digitalRead(BUTTON_PIN); if(currentButtonState != previousButtonState) { // print out the state of the button: Serial.println(currentButtonState); // save the last state of button previousButtonState = currentButtonState; } // DO OTHER WORKS HERE }

Passos Rápidos

  • Conecte o Arduino ao PC por meio do cabo USB
  • Abra o Arduino IDE e selecione a placa e a porta corretas
  • Copie o código acima e abra-o no Arduino IDE
  • Clique no botão Upload do Arduino IDE para carregar o código no Arduino
Arduino IDE - Como carregar o código
  • Abra o Serial Monitor
  • Pressione o botão 4 vezes
  • Observe o LED: o LED alterna entre LIGADO/DESLIGADO a cada segundo
  • Veja a saída no Serial Monitor
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
1 0
Ln 11, Col 1
Arduino Uno on COM15
2
  • No Serial Monitor, alguns pressionamentos foram perdidos. Isso acontece porque, durante o tempo de delay, o Arduino NÃO CONSEGUE fazer nada. Por isso, ele não consegue detectar o evento de pressionamento.

Código Arduino - Sem Delay

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino/arduino-led-blink-without-delay */ // constants won't change: const int LED_PIN = 3; // the number of the LED pin const int BUTTON_PIN = 7; // the number of the button pin const long BLINK_INTERVAL = 1000; // interval at which to blink LED (milliseconds) // Variables will change: int ledState = LOW; // ledState used to set the LED int previousButtonState = LOW; // will store last time button was updated unsigned long previousMillis = 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); } 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 currentMillis = millis(); if (currentMillis - previousMillis >= BLINK_INTERVAL) { // if the LED is off turn it on and vice-versa: ledState = (ledState == LOW) ? HIGH : LOW; // set the LED with the ledState of the variable: digitalWrite(LED_PIN, ledState); // save the last time you blinked the LED previousMillis = currentMillis; } // check button state's change int currentButtonState = digitalRead(BUTTON_PIN); if(currentButtonState != previousButtonState) { // print out the state of the button: Serial.println(currentButtonState); // save the last state of button previousButtonState = currentButtonState; } // DO OTHER WORKS HERE }

Passos Rápidos

  • Execute o código acima e pressione o botão 4 vezes
  • Observe o LED: o LED alterna entre LIGADO/DESLIGADO a cada segundo
  • Veja a saída no Serial Monitor
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
1 0 1 0 1 0 1 0
Ln 11, Col 1
Arduino Uno on COM15
2
  • Todos os eventos de pressionamento foram detectados.

Explicação do Código

Leia a explicação linha por linha nos comentários do 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 foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino/arduino-led-blink-without-delay */ // constants won't change: const int LED_PIN_1 = 3; // the number of the LED 1 pin const int LED_PIN_2 = LED_BUILTIN; // the number of the LED 2 pin const int BUTTON_PIN = 7; // the number of the button pin const long BLINK_INTERVAL_1 = 1000; // interval at which to blink LED 1 (milliseconds) const long BLINK_INTERVAL_2 = 500; // interval at which to blink LED 2 (milliseconds) // Variables will change: int ledState_1 = LOW; // ledState used to set the LED 1 int ledState_2 = LOW; // ledState used to set the LED 2 int previousButtonState = LOW; // will store last time button was updated unsigned long previousMillis_1 = 0; // will store last time LED 1 was updated unsigned long previousMillis_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); } void loop() { unsigned long currentMillis = millis(); // check to see if it's time to blink the LED 1 if (currentMillis - previousMillis_1 >= BLINK_INTERVAL_1) { // if the LED is off turn it on and vice-versa: ledState_1 = (ledState_1 == LOW) ? HIGH : LOW; // set the LED with the ledState of the variable: digitalWrite(LED_PIN_1, ledState_1); // save the last time you blinked the LED previousMillis_1 = currentMillis; } // check to see if it's time to blink the LED 2 if (currentMillis - previousMillis_2 >= BLINK_INTERVAL_2) { // if the LED is off turn it on and vice-versa: ledState_2 = (ledState_2 == LOW) ? HIGH : LOW; // set the LED with the ledState of the variable: digitalWrite(LED_PIN_2, ledState_2); // save the last time you blinked the LED previousMillis_2 = currentMillis; } // check button state's change int currentButtonState = digitalRead(BUTTON_PIN); if(currentButtonState != previousButtonState) { // print out the state of the button: Serial.println(currentButtonState); // save the last state of button previousButtonState = currentButtonState; } // DO OTHER WORKS HERE }

Vídeo

Extensibilidade

Este método pode ser usado para que o Arduino faça várias tarefas ao mesmo tempo sem que uma bloqueie a outra. Por exemplo, enviar uma requisição para a Internet e esperar a resposta; enquanto espera a resposta, piscar alguns LEDs indicadores e verificar o botão de cancelar.

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