Changes

KFLOP C Programs

1,163 bytes added, 17:26, 19 July 2016
/* Added non-blocking example of operations continually in a forever Loop */
==Performing multiple Operations continually in a forever Loop==
It doesn't make logical sense to have more than one forever loop in a program.  That would be like saying to someone go and check if any mail arrived over and over forever and then when you are done with that go and check if someone is at the back door over and over forever.  Obviously the back door will never get around to being checked.  <br /> <br /> The solution is to create a single loop that checks two things each time through the loop.   #1 go check the mail, #2 go check the back door, # 3 repeat.   Using this technique any number of things can be continuously performed in a single loop.  <br /> <br /> There is one catch with this technique. None of the operations should "block" or take a significant amount of time to perform.  If you were to perform an operation that took a long time to complete all the other continuous operations would be blocked and go unserviced for that period of time.  If it is required to do something that takes a significant amount of time then the solution is to break it down into pieces (states) that can be each performed in an insignificant amount of time.  For example say you wish to activate a lubrication relay for 2 seconds each time a button is pushed.  Instead of delaying 2 seconds you would instead record the time the relay was turned on, then go off and do other things while frequently returning to see if it is time to turn the relay off.  Below is an example to cycle an IO bit continuously based on timeNote that although this is a complete example for testing you would normally already have a forever loop in your Initialization program.  In that case only add the ServiceTimerSequence Function to your Initialization Program and add the Function call to your existing forever loop. <pre class="brush:c">#include "KMotionDef.h" void ServiceTimerSequence(void); main(){ for (;;) // loop forever { WaitNextTimeSlice(); // execute loop once every time slice ServiceTimerSequence(); // service the timer sequencing } // end of forever loop}  // sequence an IO Bit Based on Time in a non-blocking manner #define TIME_ON 5.0 //seconds#define CYCLE_TIME 15.0 //seconds#define OUTPUT_BIT 46 // which IO bit to drivevoid ServiceTimerSequence(void){ static double T0=0.0; // remember the last time we turned on double T=Time_sec(); // get current Time_sec if (T0==0.0 || T > T0 + CYCLE_TIME) T0=T; // set start time of cycle if (T < T0 + TIME_ON) // are we within the TIME_ON section of the cycle? SetBit(OUTPUT_BIT); //yes else ClearBit(OUTPUT_BIT); //no}</pre>
Bureaucrat, administrator
469
edits