Go Down

Topic: Which timer library to use for several seconds of delay (Read 2 times) previous topic - next topic

allanonmage

It had been a while since I last worked on this, so my statement of activating a timer for 2 - 10 seconds was kind of misleading.  I need to pulse the outputs for about 500 ms.  The 2 - 10 second measurements are made using a polling timer as suggested.

marco_c

#6
Oct 08, 2012, 06:02 am Last Edit: Oct 08, 2012, 07:53 am by marco_c Reason: 1
Quote
Can you create a function inside of loop() & reference that function within loop()?


Yes you can. No matter where you are the value of millis() returned comes from the same place.

Quote
Turns out it stops the program just like a delay()


Only if you are (locally) looping to wait for the time to expire in the loop, which is what you are doing. Then you may as well use delay().

To state the obvious, your code:
Code: [Select]
  while(!exitThis){
    if(millis() >= (timeStart + duration)){
      digitalWrite(pin, HIGH);
      exitThis = true;
    } // end if
  } // end while()


needs to change to this:
Code: [Select]
    if(millis() >= (timeStart + duration)){
      digitalWrite(pin, HIGH);
    } // end if


The while statement blocks you so that you cannot do anything else. The whole while with millis() thing is just like delay().

The structure of your code looks like it could benefit from you getting familiar with Finite State Machines, as your application seems to be based on doing a sequence of things followed by waiting for an external input that changes the current state and what needs to be 'done' before moving to a new state. The easiest way to implement these are with case statements and you should be able to reuse a lot of your existing code. Google the term or search these forums as there is always a lot of discussion on FSM.

Edit:
Here is a link by majenko http://hacking.majenko.co.uk/finite-state-machine
Arduino libraries http://arduinocode.codeplex.com
Parola hardware & library http://parola.codeplex.com

guix

#7
Oct 08, 2012, 07:06 am Last Edit: Oct 08, 2012, 04:55 pm by guix Reason: 1
Not sure, but maybe this will help you?
Code: [Select]

unsigned long elapsed;
bool pinstate;

void InvertState(unsigned long duration)
{
 if (millis() - elapsed >= duration)
 {
   pinstate = !pinstate;
   elapsed = millis();
 }

 print(pinstate ? ("I'm HIGH") : ("I'm LOW"));
}

void loop()
{
 InvertState(500);
}


Edit: Thanks Coding Badly and PaulS, I have some difficulties with all those data types.. :)

Coding Badly

[font=Courier New]unsigned int elapsed;
...
void InvertState( unsigned int duration )
...
[/font]

PaulS


[font=Courier New]unsigned int elapsed;
...
void InvertState( unsigned int duration )
...
[/font]


Actually, int should be long.

Go Up