How to implement a loop

I need to implement something like a loop. When the system starts I will check for a condition, if the condition is met then I will to something, then hibernate. If the condition is not met I will hibernate and set the alarm of the real time clock. When the system wakes I want to perform the same check again and this is what I want to do constantly: check, sleep, wake up, check, sleep, wake up…

What is the best way to do this with FEZ Spider?

Thank you in advance!

Arnold aka Teodor17,

Do you want to go into a hibernating state (ie, low power) or just wait for a time in the future and check again?

Maybe using a statemachine?

In the simplest case

while (true)
{
     if (conditionIsTrue)
     {
          ProcessCondition();
     }
     Thread.Sleep(5 * 1000); // sleep for five seconds
}

@ mhectorgato: I do want to hibernate and use the low power class of the premium library. Buut I am not sure how exactly I should write my code so that when the system wakes up the same procedure starts again, and again… Do you have any ideas?

@ Mike: I want to use hibernate and not just sleep the system. Anyway, I also wanted to use this while loop but the problem is that this loop blocks the whole programe, doesn’t it? If for example I get a signal from an interrupt pin I would not be able to process it because the while loop is blocking my code? Am I right? I need some kind of non-blocking loop and I do not know how to implement it…

I hope that you guys can help me!

“blocking loop” is not a valid concept. A loop is a loop, it never ends, by definition, unless the loop is broken by something. A wake-up by interrupt happens outside the loop and doesn’t necessarily interact with the loop, but allows the processor to pick up where it was at. You should research hibernate and test that out - I haven’t seen a specific example that might highlight this for you but have you searched codeshare or the forum for any?

https://www.ghielectronics.com/docs/141/low-power

2 Likes

@ Teodor17 -

Coding your loop in a seperate Thread wont block the whole program.

As an example, you can add a MyLoopClass with a Start() method :


public class MyLoopClass
{
  public void Start()
  {
    while(true) {...}
  }
}

And then call it to start from another thread…


...
MyLoopClass _class = new MyLoopClass ();
(new Thread(new ThreadStart(MyLoopClass.Start))).Start();

@ LouisCpro: Thank you for your good suggestion. I will either use a second thread or just use a timer which I am going to start after the system has waken up.

@ Teodor17 -

Be careful that NETMF is not a RT OS, so that in certain cases, if you do not know in advance how much ime the treatment will take, it is a better practice to use a “while(true)” instead of a timer, cause then, you will not have to manage the timer re-entrance and treatment concurrency !