• Hi I wonder how to set code to do some events one by one with some delay,
    let say when I press the button would like to run first one LED1 and after some delay want to see LED2 light on when LED1 is off. As there is no simple delay was trying to use setTimeout but not working.

  • setTimeout() and setInterval() do work - using them is a totally different paradigm from Arduino's delay()

    What effect are you trying to achieve - I mean, in Arduino, you can't get away with using delay() except in very simple sketches.

    a few examples

    turn LED1 on after 1 second, after 5 seconds, turn off LED1 and turn on LED2.

    
    setTimeout("digitalWrite(LED1,1);",1000)­;
    setTimeout("digitalWrite(LED1,0);digital­Write(LED2,1);",5000); 
    
    

    or

    
    setTimeout(function () {digitalWrite(LED1,1);},1000);
    setTimeout(function () {digitalWrite(LED1,0);digitalWrite(LED2,­1);},5000); 
    
    

    or

    
    setTimeout(function () {digitalWrite(LED1,1);setTimeout(functio­n () {digitalWrite(LED1,0);digitalWrite(LED2,­1);},5000); },1000);
    
    

    or

    
    function doLED1() {
    digitalWrite(LED1,1);
    setTimeout(doLED2,4000);
    }
    function doLED2() {
    digitalWrite(LED1,0);
    digitalWrite(LED2,1);
    }
    setTimeout(doLED1,1000);
    
    

    All have same behavior, but one approach may make more sense than another in a real app.

    Worth noting that the timeouts happen when they're set to happen (well, the code gets run the next time the interpreter is idle after they're set to happen), so in this example, the behavior is still the same as the above, with the second timeout happening 5 seconds later (4 seconds after the first), even though it spends a few seconds in doSomethingSlow() - if doSomethingSlow() still hadn't finished when it was time for the second timeout (ie it took more than 4 seconds), the second timeout would run as soon as the first was done:

    
    setTimeout(function () {digitalWrite(LED1,1);doSomethingSlow();­},1000);
    setTimeout(function () {digitalWrite(LED1,0);digitalWrite(LED2,­1);},5000); 
    
    function doSomethingSlow() {
    //imagine some code that takes a couple seconds to run here
    }
    
    
  • thank you, I'll practise this, need to change the habits of arduino way ;)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

How to execute commands in sequence? one, some delay, another...

Posted by Avatar for bigplik @bigplik

Actions