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












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









New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    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
    15 hours ago
















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









New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    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
    15 hours ago














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









New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











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









New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 15 hours ago









Edgar Bonet

24k22344




24k22344






New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 16 hours ago









userLP

62




62




New contributor




userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






userLP is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    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
    15 hours ago














  • 1




    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
    15 hours ago








1




1




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
15 hours ago




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
15 hours ago










3 Answers
3






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














    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, 910ms off

    unsigned long previousMillis;
    const int intervals[4] = {70, 70, 70, 910};
    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














      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





















        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
        });


        }
        });






        userLP is a new contributor. Be nice, and check out our Code of Conduct.










        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

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        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 15 hours ago









            ON5MF

            20916




            20916























                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, 910ms off

                unsigned long previousMillis;
                const int intervals[4] = {70, 70, 70, 910};
                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, 910ms off

                  unsigned long previousMillis;
                  const int intervals[4] = {70, 70, 70, 910};
                  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, 910ms off

                    unsigned long previousMillis;
                    const int intervals[4] = {70, 70, 70, 910};
                    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, 910ms off

                    unsigned long previousMillis;
                    const int intervals[4] = {70, 70, 70, 910};
                    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 13 hours ago

























                    answered 13 hours ago









                    Jot

                    2,0791517




                    2,0791517























                        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 13 hours ago









                            JRobert

                            9,84811036




                            9,84811036






















                                userLP is a new contributor. Be nice, and check out our Code of Conduct.










                                draft saved

                                draft discarded


















                                userLP is a new contributor. Be nice, and check out our Code of Conduct.













                                userLP is a new contributor. Be nice, and check out our Code of Conduct.












                                userLP is a new contributor. Be nice, and check out our Code of Conduct.
















                                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.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • 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







                                Popular posts from this blog

                                Morgemoulin

                                Scott Moir

                                Souastre