2

I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.


Here is the code i need to reproduce in a working format

void loop(){
  runfor(500){
    DigitalWrite(5,HIGH);   //this is the command to be executed in other 
                            //function
  }
}
void runfor(uint32_t duration){
  int timer = millis();
  while((millis()-timer)<=duration){
  //DigitalWrite(5,HIGH); will execute here
  }
}

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds

4

EDIT due to misunderstanding the question.

If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your runfor() function to accept a pointer-to-a-function parameter.

typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

void runfor(uint32_t duration, callback_function patternCode){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
    patternCode();
  }
}

void pattern1() {
  // Light pattern #1
}

void pattern2() {
  // Light pattern #2
}

void setup() {
  // Setup code
}

void loop() {
  runfor(1000, pattern1);
  runfor(2000, pattern2);
}

ORIGINAL ANSWER

Your starting pseudo-code is nearly there.

void runfor(uint32_t duration){
  uint32_t timer = millis();
  while ((millis()-timer)<=duration) {
    //get these commands from caller function
  }
}

Changes I made:

  1. change int to uint32_t to accommodate all possible values of millis().

  2. change for keyword to while, which is the correct keyword for the loop type you want.

  3. added semicolon after your timer assignment, per C syntax.

  • Im sorry, I'll edit my post. Thanks for informing! – A.Shetye Aug 22 '18 at 16:28
  • I’m not sure I understand. What kind of answer are you looking for? – jose can u c Aug 22 '18 at 16:30
  • jose can u c I mean a reform to the code so it basically 'accepts' function from say loop() and runs the commands in the ensuing { } braces. Also can you please post comments on my questions to the question comments so that others can understand? – A.Shetye Aug 22 '18 at 16:32
  • 1
    Your timer variable wants to be uint32_t. – Majenko Aug 22 '18 at 16:34
  • @A.Shetye The code sample provided in the answer does what you are asking. Your initial example in the question was very close to correct already! – jose can u c Aug 22 '18 at 17:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.