/******************************************************************
vwatchd.c

   Run on any Z-World board

   If using Dynamic C for DOS, make sure CPLC.LIB is
   commented out with an '*' and uncomment out VDRIVER.LIB
   in LIB.DIR.

   Demonstrates the use of virtual watchdogs

   Z-World miniature controllers come with a "watch dog timer"
   which must be "hit" periodically (if not disabled by jumpers)
   by software or a powerdown routine is executed. This allows 
   for a graceful exit to be if a program becomes stuck in an
   infinite loop.

   Virtual Watchdogs are type of timer that are counted down
   every 25 ms (on a real board) when using the virtual driver.
   If a VWD reaches zero, a powerdown routine is executed. This
   allows a program to monitor itself for several tasks being
   missed.  

   Virtual Watchdogs are defined with the function call:
      wdog = VdGetFreeWd(N);  where N = 2-255 is the starting count.

   A VWD must be "hit" with VdWdogHit(wdog) to reset the count to N
   before it reaches zero.             
   
*******************************************************************/

#use vdriver.lib              // Required 

main(){

   unsigned counter;
   int wdog1, wdog2, wdog3;
   int trigger, doneflag;

   doneflag = 0;
   trigger  = 25;
   counter  = 0;

   VdInit();                  // need virtual driver

   wdog1=VdGetFreeWd(40);
   wdog2=VdGetFreeWd(40);
   wdog3=VdGetFreeWd(40);

   printf("Virtual watchdog is about to time out!\n");
	printf("Expect \"Target not responding\" message.\n\n");
   printf("(In DOS version, message may not appear, depending\n");
   printf(" on board type, and the message is different.)\n\n");

   while(1) {

      if(counter < trigger) {
         VdWdogHit(wdog1);    // hit virtual watchdogs
         VdWdogHit(wdog2);             
         VdWdogHit(wdog3);             

         costate {
            waitfor(DelayMs(200));  
            counter++;
            printf("c1 = %05u\r", counter);
         }
      }
   }
}