How to blink led and run another code at same time?

Multi tool use
Multi tool use












1















I had written a code to calculate rpm of the motors using IR sensor and
Arduino nano and displaying it on OLED . With that I want an LED to
blink always. Here is the code what I did:



You can skip the declarations and setup() part. Just move directly
to loop(). I have problem in loop. In loop(), only LED goes on
blinking and further rpm calculation with OLED displaying codes are not
performed.



#include "avr/sleep.h"
#include "avr/power.h"
#include "SPI.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET 4

Adafruit_SSD1306 display(OLED_RESET);

int led = 12;
int in = 13;
int pushbutton=10;
unsigned long duration = 0;
float rpm = 0;
float rpm_a = 0;
int counter = 0;
int present = 0;
int previous = 0;
unsigned long elapsed = 0;
unsigned long elapsed_prev = 0;
int disabled = 0;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(in,INPUT);
pinMode(pushbutton,INPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(35,1);
display.print("xyz");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(25,13);
display.print("abc");
display.display();

delay(5000);

display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("RPMmeter");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();

elapsed = micros();
}

void loop()
{
/** led blink part **/
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(70);
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(900);

/** led blink part over and rpm calculation and displaying on
* oled part starts **/

if(digitalRead(pushbutton))
{
//Arduino low power enabled
if(disabled==0)
{
sleep_disable();
disabled = 1;
}
if (digitalRead(in) == 1 && previous == 0)
{
previous = 1;
duration = elapsed - elapsed_prev;
elapsed_prev = micros();
}
if (digitalRead(in) == 1 && previous == 1)
{
previous = 1;
}
if (digitalRead(in) == 0 && previous == 1)
{
previous = 0;
}
if (digitalRead(in) == 0 && previous == 0)
{
previous = 0;
elapsed = micros();
}

rpm = 60000000/duration;

//We add a small error in the rpm value (in this case +-2)
if ((rpm_a-2) < rpm && rpm < (rpm_a+2))
{
rpm_a = rpm;
counter = counter + 1;
if (counter == 50)
{
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("JARVIS RPMmeter");
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();
counter = 0;
}
}
if (!( (rpm_a-2) < rpm && rpm < (rpm_a+2)))
{
rpm_a=rpm;
}

}//end if pushbutton=1
else {
display.display();
display.clearDisplay();
delay(10);
duration = 0;
rpm = 0;
rpm_a = 0;
counter = 0;
present = 0;
previous = 0;
//Arduino low power enabled
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
disabled = 0;
}
}


This was the code. The problem is without that led blinking code
part in the loop, the code works fine, but if we include that LED
blinking part, the code doesn't move further. I mean only LED goes on
blinking and further codes are not performed. Why is it so? And how to
make both rpm calculation with display on OLED as well as LED
blinking
happen through a single code simultaneously?










share|improve this question




















  • 2





    Don't use delay. Instead non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. How this is done is described in many many tutorials and also questions on this site.

    – chrisl
    Dec 30 '18 at 20:41











  • @userLP, it would help if you would pick the answer which proved to be correct and mark it such so future visitors will know which answer worked for you.

    – st2000
    Dec 31 '18 at 16:24
















1















I had written a code to calculate rpm of the motors using IR sensor and
Arduino nano and displaying it on OLED . With that I want an LED to
blink always. Here is the code what I did:



You can skip the declarations and setup() part. Just move directly
to loop(). I have problem in loop. In loop(), only LED goes on
blinking and further rpm calculation with OLED displaying codes are not
performed.



#include "avr/sleep.h"
#include "avr/power.h"
#include "SPI.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET 4

Adafruit_SSD1306 display(OLED_RESET);

int led = 12;
int in = 13;
int pushbutton=10;
unsigned long duration = 0;
float rpm = 0;
float rpm_a = 0;
int counter = 0;
int present = 0;
int previous = 0;
unsigned long elapsed = 0;
unsigned long elapsed_prev = 0;
int disabled = 0;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(in,INPUT);
pinMode(pushbutton,INPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(35,1);
display.print("xyz");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(25,13);
display.print("abc");
display.display();

delay(5000);

display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("RPMmeter");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();

elapsed = micros();
}

void loop()
{
/** led blink part **/
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(70);
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(900);

/** led blink part over and rpm calculation and displaying on
* oled part starts **/

if(digitalRead(pushbutton))
{
//Arduino low power enabled
if(disabled==0)
{
sleep_disable();
disabled = 1;
}
if (digitalRead(in) == 1 && previous == 0)
{
previous = 1;
duration = elapsed - elapsed_prev;
elapsed_prev = micros();
}
if (digitalRead(in) == 1 && previous == 1)
{
previous = 1;
}
if (digitalRead(in) == 0 && previous == 1)
{
previous = 0;
}
if (digitalRead(in) == 0 && previous == 0)
{
previous = 0;
elapsed = micros();
}

rpm = 60000000/duration;

//We add a small error in the rpm value (in this case +-2)
if ((rpm_a-2) < rpm && rpm < (rpm_a+2))
{
rpm_a = rpm;
counter = counter + 1;
if (counter == 50)
{
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("JARVIS RPMmeter");
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();
counter = 0;
}
}
if (!( (rpm_a-2) < rpm && rpm < (rpm_a+2)))
{
rpm_a=rpm;
}

}//end if pushbutton=1
else {
display.display();
display.clearDisplay();
delay(10);
duration = 0;
rpm = 0;
rpm_a = 0;
counter = 0;
present = 0;
previous = 0;
//Arduino low power enabled
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
disabled = 0;
}
}


This was the code. The problem is without that led blinking code
part in the loop, the code works fine, but if we include that LED
blinking part, the code doesn't move further. I mean only LED goes on
blinking and further codes are not performed. Why is it so? And how to
make both rpm calculation with display on OLED as well as LED
blinking
happen through a single code simultaneously?










share|improve this question




















  • 2





    Don't use delay. Instead non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. How this is done is described in many many tutorials and also questions on this site.

    – chrisl
    Dec 30 '18 at 20:41











  • @userLP, it would help if you would pick the answer which proved to be correct and mark it such so future visitors will know which answer worked for you.

    – st2000
    Dec 31 '18 at 16:24














1












1








1








I had written a code to calculate rpm of the motors using IR sensor and
Arduino nano and displaying it on OLED . With that I want an LED to
blink always. Here is the code what I did:



You can skip the declarations and setup() part. Just move directly
to loop(). I have problem in loop. In loop(), only LED goes on
blinking and further rpm calculation with OLED displaying codes are not
performed.



#include "avr/sleep.h"
#include "avr/power.h"
#include "SPI.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET 4

Adafruit_SSD1306 display(OLED_RESET);

int led = 12;
int in = 13;
int pushbutton=10;
unsigned long duration = 0;
float rpm = 0;
float rpm_a = 0;
int counter = 0;
int present = 0;
int previous = 0;
unsigned long elapsed = 0;
unsigned long elapsed_prev = 0;
int disabled = 0;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(in,INPUT);
pinMode(pushbutton,INPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(35,1);
display.print("xyz");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(25,13);
display.print("abc");
display.display();

delay(5000);

display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("RPMmeter");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();

elapsed = micros();
}

void loop()
{
/** led blink part **/
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(70);
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(900);

/** led blink part over and rpm calculation and displaying on
* oled part starts **/

if(digitalRead(pushbutton))
{
//Arduino low power enabled
if(disabled==0)
{
sleep_disable();
disabled = 1;
}
if (digitalRead(in) == 1 && previous == 0)
{
previous = 1;
duration = elapsed - elapsed_prev;
elapsed_prev = micros();
}
if (digitalRead(in) == 1 && previous == 1)
{
previous = 1;
}
if (digitalRead(in) == 0 && previous == 1)
{
previous = 0;
}
if (digitalRead(in) == 0 && previous == 0)
{
previous = 0;
elapsed = micros();
}

rpm = 60000000/duration;

//We add a small error in the rpm value (in this case +-2)
if ((rpm_a-2) < rpm && rpm < (rpm_a+2))
{
rpm_a = rpm;
counter = counter + 1;
if (counter == 50)
{
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("JARVIS RPMmeter");
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();
counter = 0;
}
}
if (!( (rpm_a-2) < rpm && rpm < (rpm_a+2)))
{
rpm_a=rpm;
}

}//end if pushbutton=1
else {
display.display();
display.clearDisplay();
delay(10);
duration = 0;
rpm = 0;
rpm_a = 0;
counter = 0;
present = 0;
previous = 0;
//Arduino low power enabled
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
disabled = 0;
}
}


This was the code. The problem is without that led blinking code
part in the loop, the code works fine, but if we include that LED
blinking part, the code doesn't move further. I mean only LED goes on
blinking and further codes are not performed. Why is it so? And how to
make both rpm calculation with display on OLED as well as LED
blinking
happen through a single code simultaneously?










share|improve this question
















I had written a code to calculate rpm of the motors using IR sensor and
Arduino nano and displaying it on OLED . With that I want an LED to
blink always. Here is the code what I did:



You can skip the declarations and setup() part. Just move directly
to loop(). I have problem in loop. In loop(), only LED goes on
blinking and further rpm calculation with OLED displaying codes are not
performed.



#include "avr/sleep.h"
#include "avr/power.h"
#include "SPI.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET 4

Adafruit_SSD1306 display(OLED_RESET);

int led = 12;
int in = 13;
int pushbutton=10;
unsigned long duration = 0;
float rpm = 0;
float rpm_a = 0;
int counter = 0;
int present = 0;
int previous = 0;
unsigned long elapsed = 0;
unsigned long elapsed_prev = 0;
int disabled = 0;

void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(in,INPUT);
pinMode(pushbutton,INPUT);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(35,1);
display.print("xyz");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(25,13);
display.print("abc");
display.display();

delay(5000);

display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("RPMmeter");
display.display();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();

elapsed = micros();
}

void loop()
{
/** led blink part **/
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(70);
digitalWrite(led, HIGH);
delay(70);
digitalWrite(led, LOW);
delay(900);

/** led blink part over and rpm calculation and displaying on
* oled part starts **/

if(digitalRead(pushbutton))
{
//Arduino low power enabled
if(disabled==0)
{
sleep_disable();
disabled = 1;
}
if (digitalRead(in) == 1 && previous == 0)
{
previous = 1;
duration = elapsed - elapsed_prev;
elapsed_prev = micros();
}
if (digitalRead(in) == 1 && previous == 1)
{
previous = 1;
}
if (digitalRead(in) == 0 && previous == 1)
{
previous = 0;
}
if (digitalRead(in) == 0 && previous == 0)
{
previous = 0;
elapsed = micros();
}

rpm = 60000000/duration;

//We add a small error in the rpm value (in this case +-2)
if ((rpm_a-2) < rpm && rpm < (rpm_a+2))
{
rpm_a = rpm;
counter = counter + 1;
if (counter == 50)
{
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("JARVIS RPMmeter");
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,19);
display.println("RPM:");
display.setCursor(80,19);
display.println(rpm);
display.display();
counter = 0;
}
}
if (!( (rpm_a-2) < rpm && rpm < (rpm_a+2)))
{
rpm_a=rpm;
}

}//end if pushbutton=1
else {
display.display();
display.clearDisplay();
delay(10);
duration = 0;
rpm = 0;
rpm_a = 0;
counter = 0;
present = 0;
previous = 0;
//Arduino low power enabled
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
disabled = 0;
}
}


This was the code. The problem is without that led blinking code
part in the loop, the code works fine, but if we include that LED
blinking part, the code doesn't move further. I mean only LED goes on
blinking and further codes are not performed. Why is it so? And how to
make both rpm calculation with display on OLED as well as LED
blinking
happen through a single code simultaneously?







arduino-uno programming arduino-nano






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 30 '18 at 20:49









Edgar Bonet

24.5k22445




24.5k22445










asked Dec 30 '18 at 20:28









userLPuserLP

62




62








  • 2





    Don't use delay. Instead non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. How this is done is described in many many tutorials and also questions on this site.

    – chrisl
    Dec 30 '18 at 20:41











  • @userLP, it would help if you would pick the answer which proved to be correct and mark it such so future visitors will know which answer worked for you.

    – st2000
    Dec 31 '18 at 16:24














  • 2





    Don't use delay. Instead non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. How this is done is described in many many tutorials and also questions on this site.

    – chrisl
    Dec 30 '18 at 20:41











  • @userLP, it would help if you would pick the answer which proved to be correct and mark it such so future visitors will know which answer worked for you.

    – st2000
    Dec 31 '18 at 16:24








2




2





Don't use delay. Instead non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. How this is done is described in many many tutorials and also questions on this site.

– chrisl
Dec 30 '18 at 20:41





Don't use delay. Instead non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. How this is done is described in many many tutorials and also questions on this site.

– chrisl
Dec 30 '18 at 20:41













@userLP, it would help if you would pick the answer which proved to be correct and mark it such so future visitors will know which answer worked for you.

– st2000
Dec 31 '18 at 16:24





@userLP, it would help if you would pick the answer which proved to be correct and mark it such so future visitors will know which answer worked for you.

– st2000
Dec 31 '18 at 16:24










4 Answers
4






active

oldest

votes


















2














While executing the 'Delay' commands your arduino doesn't really do anything. The best thing you can do is have a look at BlinkWithoutDelay and adapt your code accordingly.






share|improve this answer































    2














    Look at my answer to a similar question. Apply the same principle to your problem:




    • Move each task (blinking; calculating RPM) into its own separate function.

    • Make loop() call those functions as often as possible.

    • Make each function decide whether it is time to do its task, do it or not, and return.

    • Those functions must never wait.


    This kind of program organization - called non-blocking - is extendable to as many tasks as you wish, until you run out of memory, or the processor runs out of time to do everything as fast as you need it to (that will be a great many more than the two you've described!).






    share|improve this answer































      2














      There are a few options to use millis() for this.
      Is it okay if I change the 900ms into a multiple of 70ms? Then I can count intervals of 70ms.



      // blink led: 70ms on, then 70ms off, then 70ms on, then 910ms off

      unsigned long previousMillis;
      int count = 0;

      void setup() {
      pinMode(13, OUTPUT);
      }

      void loop() {
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis >= 70) {
      previousMillis = currentMillis;

      switch(count) {
      case 0:
      digitalWrite(13, HIGH);
      break;
      case 1:
      digitalWrite(13, LOW);
      break;
      case 2:
      digitalWrite(13, HIGH);
      break;
      case 3:
      digitalWrite(13, LOW);
      break;
      }
      count++;

      if(count >= 16)
      count = 0;
      }
      }


      When the values of the intervals are in a array, then the code is probably smaller.



      // blink led: 70ms on, 70ms off, 70ms on, 900ms off

      unsigned long previousMillis;
      const int intervals[4] = {70, 70, 70, 900};
      int index = 0;


      void setup() {
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH); // turn led on, after 70ms it will be turned off
      }

      void loop() {
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis >= intervals[index]) {
      previousMillis = currentMillis;

      int level = (index % 2) == 0 ? LOW : HIGH;
      digitalWrite(13, level);

      index++;

      if(index > 3)
      index = 0;
      }
      }


      This second sketch is smaller, but I prefer the first one.






      share|improve this answer

































        0














        The only thing that I can see that makes your code faulty is the fact that you use a if statement to check if your button is pushed and then you have a lot of code to be executed in that statement rather set up a bool outside of your loop and set it with the if function then use a while to do all the rest of the work that was in your if statement that way when the button is released the code will still be executed and when it is pressed again it will happen again



        Almost forgot the good stuff yes the blinkwithoutdelay is the way to go on the blink code






        share|improve this answer























          Your Answer






          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("schematics", function () {
          StackExchange.schematics.init();
          });
          }, "cicuitlab");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "540"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2farduino.stackexchange.com%2fquestions%2f60178%2fhow-to-blink-led-and-run-another-code-at-same-time%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          While executing the 'Delay' commands your arduino doesn't really do anything. The best thing you can do is have a look at BlinkWithoutDelay and adapt your code accordingly.






          share|improve this answer




























            2














            While executing the 'Delay' commands your arduino doesn't really do anything. The best thing you can do is have a look at BlinkWithoutDelay and adapt your code accordingly.






            share|improve this answer


























              2












              2








              2







              While executing the 'Delay' commands your arduino doesn't really do anything. The best thing you can do is have a look at BlinkWithoutDelay and adapt your code accordingly.






              share|improve this answer













              While executing the 'Delay' commands your arduino doesn't really do anything. The best thing you can do is have a look at BlinkWithoutDelay and adapt your code accordingly.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 30 '18 at 20:55









              ON5MF JurgenON5MF Jurgen

              20916




              20916























                  2














                  Look at my answer to a similar question. Apply the same principle to your problem:




                  • Move each task (blinking; calculating RPM) into its own separate function.

                  • Make loop() call those functions as often as possible.

                  • Make each function decide whether it is time to do its task, do it or not, and return.

                  • Those functions must never wait.


                  This kind of program organization - called non-blocking - is extendable to as many tasks as you wish, until you run out of memory, or the processor runs out of time to do everything as fast as you need it to (that will be a great many more than the two you've described!).






                  share|improve this answer




























                    2














                    Look at my answer to a similar question. Apply the same principle to your problem:




                    • Move each task (blinking; calculating RPM) into its own separate function.

                    • Make loop() call those functions as often as possible.

                    • Make each function decide whether it is time to do its task, do it or not, and return.

                    • Those functions must never wait.


                    This kind of program organization - called non-blocking - is extendable to as many tasks as you wish, until you run out of memory, or the processor runs out of time to do everything as fast as you need it to (that will be a great many more than the two you've described!).






                    share|improve this answer


























                      2












                      2








                      2







                      Look at my answer to a similar question. Apply the same principle to your problem:




                      • Move each task (blinking; calculating RPM) into its own separate function.

                      • Make loop() call those functions as often as possible.

                      • Make each function decide whether it is time to do its task, do it or not, and return.

                      • Those functions must never wait.


                      This kind of program organization - called non-blocking - is extendable to as many tasks as you wish, until you run out of memory, or the processor runs out of time to do everything as fast as you need it to (that will be a great many more than the two you've described!).






                      share|improve this answer













                      Look at my answer to a similar question. Apply the same principle to your problem:




                      • Move each task (blinking; calculating RPM) into its own separate function.

                      • Make loop() call those functions as often as possible.

                      • Make each function decide whether it is time to do its task, do it or not, and return.

                      • Those functions must never wait.


                      This kind of program organization - called non-blocking - is extendable to as many tasks as you wish, until you run out of memory, or the processor runs out of time to do everything as fast as you need it to (that will be a great many more than the two you've described!).







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Dec 30 '18 at 23:13









                      JRobertJRobert

                      10.1k21036




                      10.1k21036























                          2














                          There are a few options to use millis() for this.
                          Is it okay if I change the 900ms into a multiple of 70ms? Then I can count intervals of 70ms.



                          // blink led: 70ms on, then 70ms off, then 70ms on, then 910ms off

                          unsigned long previousMillis;
                          int count = 0;

                          void setup() {
                          pinMode(13, OUTPUT);
                          }

                          void loop() {
                          unsigned long currentMillis = millis();

                          if(currentMillis - previousMillis >= 70) {
                          previousMillis = currentMillis;

                          switch(count) {
                          case 0:
                          digitalWrite(13, HIGH);
                          break;
                          case 1:
                          digitalWrite(13, LOW);
                          break;
                          case 2:
                          digitalWrite(13, HIGH);
                          break;
                          case 3:
                          digitalWrite(13, LOW);
                          break;
                          }
                          count++;

                          if(count >= 16)
                          count = 0;
                          }
                          }


                          When the values of the intervals are in a array, then the code is probably smaller.



                          // blink led: 70ms on, 70ms off, 70ms on, 900ms off

                          unsigned long previousMillis;
                          const int intervals[4] = {70, 70, 70, 900};
                          int index = 0;


                          void setup() {
                          pinMode(13, OUTPUT);
                          digitalWrite(13, HIGH); // turn led on, after 70ms it will be turned off
                          }

                          void loop() {
                          unsigned long currentMillis = millis();

                          if(currentMillis - previousMillis >= intervals[index]) {
                          previousMillis = currentMillis;

                          int level = (index % 2) == 0 ? LOW : HIGH;
                          digitalWrite(13, level);

                          index++;

                          if(index > 3)
                          index = 0;
                          }
                          }


                          This second sketch is smaller, but I prefer the first one.






                          share|improve this answer






























                            2














                            There are a few options to use millis() for this.
                            Is it okay if I change the 900ms into a multiple of 70ms? Then I can count intervals of 70ms.



                            // blink led: 70ms on, then 70ms off, then 70ms on, then 910ms off

                            unsigned long previousMillis;
                            int count = 0;

                            void setup() {
                            pinMode(13, OUTPUT);
                            }

                            void loop() {
                            unsigned long currentMillis = millis();

                            if(currentMillis - previousMillis >= 70) {
                            previousMillis = currentMillis;

                            switch(count) {
                            case 0:
                            digitalWrite(13, HIGH);
                            break;
                            case 1:
                            digitalWrite(13, LOW);
                            break;
                            case 2:
                            digitalWrite(13, HIGH);
                            break;
                            case 3:
                            digitalWrite(13, LOW);
                            break;
                            }
                            count++;

                            if(count >= 16)
                            count = 0;
                            }
                            }


                            When the values of the intervals are in a array, then the code is probably smaller.



                            // blink led: 70ms on, 70ms off, 70ms on, 900ms off

                            unsigned long previousMillis;
                            const int intervals[4] = {70, 70, 70, 900};
                            int index = 0;


                            void setup() {
                            pinMode(13, OUTPUT);
                            digitalWrite(13, HIGH); // turn led on, after 70ms it will be turned off
                            }

                            void loop() {
                            unsigned long currentMillis = millis();

                            if(currentMillis - previousMillis >= intervals[index]) {
                            previousMillis = currentMillis;

                            int level = (index % 2) == 0 ? LOW : HIGH;
                            digitalWrite(13, level);

                            index++;

                            if(index > 3)
                            index = 0;
                            }
                            }


                            This second sketch is smaller, but I prefer the first one.






                            share|improve this answer




























                              2












                              2








                              2







                              There are a few options to use millis() for this.
                              Is it okay if I change the 900ms into a multiple of 70ms? Then I can count intervals of 70ms.



                              // blink led: 70ms on, then 70ms off, then 70ms on, then 910ms off

                              unsigned long previousMillis;
                              int count = 0;

                              void setup() {
                              pinMode(13, OUTPUT);
                              }

                              void loop() {
                              unsigned long currentMillis = millis();

                              if(currentMillis - previousMillis >= 70) {
                              previousMillis = currentMillis;

                              switch(count) {
                              case 0:
                              digitalWrite(13, HIGH);
                              break;
                              case 1:
                              digitalWrite(13, LOW);
                              break;
                              case 2:
                              digitalWrite(13, HIGH);
                              break;
                              case 3:
                              digitalWrite(13, LOW);
                              break;
                              }
                              count++;

                              if(count >= 16)
                              count = 0;
                              }
                              }


                              When the values of the intervals are in a array, then the code is probably smaller.



                              // blink led: 70ms on, 70ms off, 70ms on, 900ms off

                              unsigned long previousMillis;
                              const int intervals[4] = {70, 70, 70, 900};
                              int index = 0;


                              void setup() {
                              pinMode(13, OUTPUT);
                              digitalWrite(13, HIGH); // turn led on, after 70ms it will be turned off
                              }

                              void loop() {
                              unsigned long currentMillis = millis();

                              if(currentMillis - previousMillis >= intervals[index]) {
                              previousMillis = currentMillis;

                              int level = (index % 2) == 0 ? LOW : HIGH;
                              digitalWrite(13, level);

                              index++;

                              if(index > 3)
                              index = 0;
                              }
                              }


                              This second sketch is smaller, but I prefer the first one.






                              share|improve this answer















                              There are a few options to use millis() for this.
                              Is it okay if I change the 900ms into a multiple of 70ms? Then I can count intervals of 70ms.



                              // blink led: 70ms on, then 70ms off, then 70ms on, then 910ms off

                              unsigned long previousMillis;
                              int count = 0;

                              void setup() {
                              pinMode(13, OUTPUT);
                              }

                              void loop() {
                              unsigned long currentMillis = millis();

                              if(currentMillis - previousMillis >= 70) {
                              previousMillis = currentMillis;

                              switch(count) {
                              case 0:
                              digitalWrite(13, HIGH);
                              break;
                              case 1:
                              digitalWrite(13, LOW);
                              break;
                              case 2:
                              digitalWrite(13, HIGH);
                              break;
                              case 3:
                              digitalWrite(13, LOW);
                              break;
                              }
                              count++;

                              if(count >= 16)
                              count = 0;
                              }
                              }


                              When the values of the intervals are in a array, then the code is probably smaller.



                              // blink led: 70ms on, 70ms off, 70ms on, 900ms off

                              unsigned long previousMillis;
                              const int intervals[4] = {70, 70, 70, 900};
                              int index = 0;


                              void setup() {
                              pinMode(13, OUTPUT);
                              digitalWrite(13, HIGH); // turn led on, after 70ms it will be turned off
                              }

                              void loop() {
                              unsigned long currentMillis = millis();

                              if(currentMillis - previousMillis >= intervals[index]) {
                              previousMillis = currentMillis;

                              int level = (index % 2) == 0 ? LOW : HIGH;
                              digitalWrite(13, level);

                              index++;

                              if(index > 3)
                              index = 0;
                              }
                              }


                              This second sketch is smaller, but I prefer the first one.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Dec 31 '18 at 17:06

























                              answered Dec 30 '18 at 22:44









                              JotJot

                              2,3531618




                              2,3531618























                                  0














                                  The only thing that I can see that makes your code faulty is the fact that you use a if statement to check if your button is pushed and then you have a lot of code to be executed in that statement rather set up a bool outside of your loop and set it with the if function then use a while to do all the rest of the work that was in your if statement that way when the button is released the code will still be executed and when it is pressed again it will happen again



                                  Almost forgot the good stuff yes the blinkwithoutdelay is the way to go on the blink code






                                  share|improve this answer




























                                    0














                                    The only thing that I can see that makes your code faulty is the fact that you use a if statement to check if your button is pushed and then you have a lot of code to be executed in that statement rather set up a bool outside of your loop and set it with the if function then use a while to do all the rest of the work that was in your if statement that way when the button is released the code will still be executed and when it is pressed again it will happen again



                                    Almost forgot the good stuff yes the blinkwithoutdelay is the way to go on the blink code






                                    share|improve this answer


























                                      0












                                      0








                                      0







                                      The only thing that I can see that makes your code faulty is the fact that you use a if statement to check if your button is pushed and then you have a lot of code to be executed in that statement rather set up a bool outside of your loop and set it with the if function then use a while to do all the rest of the work that was in your if statement that way when the button is released the code will still be executed and when it is pressed again it will happen again



                                      Almost forgot the good stuff yes the blinkwithoutdelay is the way to go on the blink code






                                      share|improve this answer













                                      The only thing that I can see that makes your code faulty is the fact that you use a if statement to check if your button is pushed and then you have a lot of code to be executed in that statement rather set up a bool outside of your loop and set it with the if function then use a while to do all the rest of the work that was in your if statement that way when the button is released the code will still be executed and when it is pressed again it will happen again



                                      Almost forgot the good stuff yes the blinkwithoutdelay is the way to go on the blink code







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 1 at 12:28









                                      Tjaart van aswegenTjaart van aswegen

                                      14




                                      14






























                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Arduino Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid



                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.


                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function () {
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2farduino.stackexchange.com%2fquestions%2f60178%2fhow-to-blink-led-and-run-another-code-at-same-time%23new-answer', 'question_page');
                                          }
                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          1qUn,0,G,yQlUBDzU5KL1Ta6MaTP3OqylkZpadWxa7jWfB,XdYOkES27G2,YnQvtMkyY,NCnW,UNs 9gorKzcv58LlPnib
                                          MfVXn1,wBi,cJdDArT3YUJzsU

                                          Popular posts from this blog

                                          Monofisismo

                                          Angular Downloading a file using contenturl with Basic Authentication

                                          Olmecas