/* C-language version of COIN TOSSER example
   Hardware interface: 		PM5 = Pushbutton SW (Click to toss coin)
                      			PM4 = Head/Tail Outcome LED
                      			PTT = 8 LEDs displaying # tails
PTAD= 8 LEDs displaying # heads */
#include <mc9s12c128.h>     /* derivative information */
#pragma LINK_INFO DERIVATIVE "mc9s12c128"
void delay20ms(void);     /* This "function prototype statement" lets the compiler know
						  that a function called "delay20ms( )" which accepts no arguments
						  and returns now arguments will follow the main program. */
void main(void) 
{
  unsigned char coin,nr_heads, nr_tails;
  DDRT = 0xff;	  		//Make PTT and PTAD all outputs
  ATDDIEN = 0xff;		//Enable all pins of PORTAD for digital I/O
  DDRAD = 0xff;			//Make PORTAD all digital outputs
  DDRM  = 0x10;   		//Make PM4 = output (LED) 
                  				//and make PM5 = input (SWITCH).
  PERM = 0x00;    		//Disable internal pullup on SW input PM5.
  nr_heads = 0;	  		//Initialize the RAM locations (variables) nr_heads and nr_tails to zero.
  nr_tails = 0; 
  PTT = 0;		    		//Set all output pins to zero.
  PTAD = 0;
  PTM = 0;
  for(;;)
  {
     coin = 0;    			//Variable "coin" indicates outcome
     do
       {
          coin = coin ^ 1;       					//Toggle LSB of coin variable
       } while ((PTM & 0x20) == 0x20); 		//until SW (on PM5) is pressed.
     delay20ms();  						   	//Delay 20 ms to debounce SW press.
     while ((PTM & 0x20) == 0); 	//Wait here until SW released
     delay20ms();						     	//Delay 20 ms to debounce SW release.
     if ((coin & 1) == 1)
      {
      	 nr_heads++;							//If heads outcome,
      	 PTM = PTM | 0b00010000;  			//increment nr_heads, PM4 = 1 (LED on)
      	 PTAD = nr_heads;      				//and update nr_heads on PTT output port.
      } 
     else
      {        
      	 nr_tails++;							//If tails outcome, 
      	 PTM = PTM & 0b11101111;  			//increment nr_tails, PM4 = 0 (LED off)
      	 PTT = nr_tails;						//and update nr_tails on PTAD output port.       	   
      }
  }
                 
}
void delay20ms(void)						//This routine simply wastes time
{										            //providing switch debouncing delay.
  unsigned int i;
  for(i=0;i<40000;i++);
}	

