/*
	SC1LED.c

	CM71xx/Z1 and CM72xx/Z2

	Toggle the LEDs of the SmartCore Evaluation Board.

	SW1 controls the blinking rate of led D2.
	SW2 controls the blinking rate of led D3.
	SW3 controls the blinking rate of led D4.
	SW4 controls the blinking rate of led D5.
	When a switch is pushed, the blinking rate of the adjacent LED increases
	to a maximum of 10/sec. When a switch is not pushed, the blinking rate of
	the adjacent LED decreases to minimum of 1/sec. The program uses
	costatements and waitfors for generating the timing.
*/

#use vdriver.lib

main() {
unsigned long rate_a, rate_b, rate_c, rate_d;
int state;

	VdInit();											// initialize the virtual driver
	rate_a = rate_b = rate_c = rate_d = 500L;	// load current rate
		
	for(;;){												// endless loop
		hitwd(); runwatch();
		costate{
			waitfor(DelayMs(10L));     // monitor inputs every 10 ms
			state = inport(CS2+1);		// get the pushbutton values SW2-SW5
			
			if( state & 0x01 ){					// SW2 not pressed...
				if( rate_a < 500L ) rate_a++;	 // increase period. max is 1.0 sec
			}else{									// SW2 pressed...
				if( rate_a >  50L ) rate_a--;	 // decrease period. min is 0.1 sec
			}
			if( state & 0x02 ){					// SW3 not pressed...
				if( rate_b < 500L ) rate_b++;	 // increase period. max is 1.0 sec
			}else{									// SW3 pressed...
				if( rate_b >  50L ) rate_b--;	 // decrease period. min is 0.1 sec
			}
			if( state & 0x04 ){					// SW4 not pressed...
				if( rate_c < 500L ) rate_c++;	 // increase period. max is 1.0 sec
			}else{									// SW4 pressed...
				if( rate_c >  50L ) rate_c--;	 // decrease period. min is 0.1 sec
			}
			if( state & 0x08 ){					// SW5 not pressed...
				if( rate_d < 500L ) rate_d++;	 // increase period. max is 1.0 sec
			}else{									// SW5 pressed...
				if( rate_d >  50L ) rate_d--;	 // decrease period. min is 0.1 sec
			}
		}
		costate{										// D2
			outport( CS1  , 1 );					 // turn on
			waitfor(DelayMs(rate_a));			 // wait at rate A
			outport( CS1  , 0 );					 // turn off
			waitfor(DelayMs(rate_a));			 // wait at rate A
		}
		costate{										// D3
			outport( CS1+1, 1 );					 // turn on
			waitfor(DelayMs(rate_b));			 // wait at rate B
			outport( CS1+1, 0 );					 // turn off
			waitfor(DelayMs(rate_b));			 // wait at rate B
		}
		costate{										// D4
			outport( CS1+2, 1 );					 // turn on
			waitfor(DelayMs(rate_c));			 // wait at rate C
			outport( CS1+2, 0 );					 // turn off
			waitfor(DelayMs(rate_c));			 // wait at rate C
		}
		costate{										// D5
			outport( CS1+3, 1 );					 // turn on
			waitfor(DelayMs(rate_d));			 // wait at rate D
			outport( CS1+3, 0 );					 // turn off
			waitfor(DelayMs(rate_d));			 // wait at rate D
		}
	}
}