// clockgen.v
// (c) 2016 David R. Hunter
//
// 02/06/16
// clock generator module
// with parameterized divisor
// uses an enable based flip-flop design
module clockgen(reset_n,enable,clkin,clkout,pulse);
  input 		reset_n;        // reset input
  input  	enable;			 // clock enable
  input 		clkin;          // input clock
  output 	clkout;         // output clock
  output 	pulse;			 // single pulse every time count rolls over
  parameter Nbits = 3;		 // number of bits for the clock
  parameter Divisor = 8;    // clock divisor value

  reg  clkout;
  reg  pulse;
  reg  [Nbits-1:0]counter;        // clock counter
  wire count_reset;
 
	// create a 50% duty cycle output
  always @(posedge clkin or negedge reset_n)
	 begin
		if (!reset_n)
			clkout <= 1'b0;
		else
			clkout <= (counter > (Divisor/2 - 1));
	 end

  assign count_reset = reset_n ? (counter == Divisor) : 1'b1;
	 
  // use a count up counter for the clock
  always @(posedge clkin)
	 begin
		if (count_reset)
			counter <= 0;
		else if (enable)
			counter <= counter + 1;
	 end

  // create a pulse on the opposite edge that occurs every time the count rolls over
  always @(negedge clkin)
	begin
		if (count_reset && reset_n)		// if roll over and not in reset
			pulse <= 1;
		else
			pulse <= 0;
	end
  
endmodule

