//--------------------------------------------------------------------------------------------------
//
// Title       : EncoderControl
// Design      : U4
// Author      : SJensen
// Company     : MBARI
//
//-------------------------------------------------------------------------------------------------
//
// File        : c:\projects\genosensor\2g\cplds\rvavle\rvalve\u4\src\EncoderControl.v
// Generated   : Fri Apr 30 12:00:42 2004
// From        : interface description file
// By          : Itf2Vhdl ver. 1.20
//
//-------------------------------------------------------------------------------------------------
//
// Description : 
//
//-------------------------------------------------------------------------------------------------
`timescale 1ps / 1ps

//{{ Section below this comment is automatically maintained
//   and may be overwritten
//{module {EncoderControl}}
module EncoderControl ( DRVSTATr ,DAV ,Reset ,Shift ,DRVCTLw ,Start ,Eclk ,Mclk );

parameter bits =  4'd10;
parameter divisor =  4'd3 ;

input DRVSTATr ;
wire DRVSTATr ;
input Reset ;
wire Reset ;
input DRVCTLw ;
wire DRVCTLw ;
input Start ;
wire Start ;
input Mclk ;
wire Mclk ;

output DAV ;
wire DAV ;
output Shift ;
wire Shift ;
output Eclk ;
wire Eclk ;

//}} End of automatically maintained section

// -- Enter your statements here -- //

reg SS;	 
reg [3:0] divider; 
reg CEr;
reg [3:0] BitCounter;
reg Eclkr;
wire Stop;
wire start;
reg DAVr;		
reg Shiftr;

assign Stop = (Eclk & (BitCounter == bits)); 
assign Eclk = Eclkr;
assign Shift = Shiftr;
assign DAV = (DRVSTATr) ? DAVr : 1'bz;
assign start = Start & DRVCTLw;

always @ (negedge Mclk)
	begin
		if (Reset | Stop) SS <= 1'b0;
		else if (start) SS <= 1'b1;
		else SS <= SS;	 
		
		if (Reset) 
			begin
				CEr <= 1'b0;
				Shiftr <= 1'b0;
			end
		else if (divider >= divisor) 
			begin
				CEr <= 1'b1;
				Shiftr <= Eclkr;
			end
		else 
			begin
				CEr <= 1'b0;	
				Shiftr <= 1'b0;
			end
		
		if (Reset | start) DAVr <= 1'b0;
		else if ((BitCounter == bits) & Eclk) DAVr <= 1'b1;
		else  DAVr <= DAVr;		
	end				  
	
always @ (posedge Mclk)
	begin
		if (Reset | SS) divider <= 4'b0;
		if (SS) 
			if (divider >= divisor) divider <= 4'b0;
			else divider <= divider + 4'd1;
		
		if (Reset | !SS) Eclkr <= 1'b1;
		else if (CEr) Eclkr <= !Eclkr;
		else Eclkr <= Eclkr;
			
		if (Reset | !SS)  BitCounter <= 4'd0;
		else if (Shiftr) BitCounter <= BitCounter + 4'd1;	
//		else if (CEr & Eclkr) BitCounter <= BitCounter + 4'd1;	
		else BitCounter <= BitCounter;	 		
	end									 
	
endmodule

