//-----------------------------------------------------
 // Design Name : clock generate
 // File Name   : clock_generator.v
 // Coder       : Fred Aulich
 // Date			 : March 04 2014
 //-----------------------------------------------------
 
 module clock_generator(
 
 reset,		// TD_reset
 clk_27,		// TD_CLK27
 clk_en,		// switch input 0 from DE2 board to enable clock [pin N25]
 gpio_0,		// one of the GPIO pins on the DE2 board (GPIO-0 pin 0)[pin D25]
 gpio_1,		// one of the GPIO pins on the DE2 board (GPIO-1 pin 0)[pin D25]
 gpio_2		// one of the GPIO pins on the DE2 board (BPIO-2 pin 1)[pin J22]
);
 
 output 		reset;
 output 		gpio_0;
 output		gpio_1;
 output		gpio_2;
 
 input		clk_en;
 input		clk_27;
 
 reg			reset;
 reg			gpio_0;
 reg			gpio_1;
 reg			gpio_2;
 
 //////////////////////////////////
 ///  Internal  registers     /////
 //////////////////////////////////
 
 reg[15:0]	clk_div;
 reg			sclk;
 
 
 parameter clk_freq = 27000000;  // 27 Mhz from DE2 board
 parameter i2c_freq = 80000;     //  to get 40 Khz desired frequency
 
 
 /////////////////////////////////////////////////
 ////////// clock divider      ///////////////////
 /////////////////////////////////////////////////
 
  always @ (posedge clk_27 or negedge reset)
  begin
		if (!reset)
		begin
			clk_div <= 0;
			sclk <= 0;
		end
		
		else
		
		begin
		
			if (clk_div <  (clk_freq/i2c_freq) )  // keeps dividing until reaches desired frequency
			clk_div <= clk_div + 1;
			
			else
			begin 
					clk_div <= 0;
					sclk <= ~sclk;                 // resulting clock 40 KHz
			end
		end
	end
	
	always gpio_0 <= clk_en;  // directing switch 0 (DE2 board) to GPIO-0 header pin 0
	always gpio_1 <= clk_27;  // directing 27 MHz clock to GPIO-0 header pin 1
	always gpio_2 <= sclk;    // directing 40KHz clock to GPIO-0 header pin 2
	always reset <= clk_en;   // reset must be active high for clk_27 to run
	
	
	endmodule 