module EEPROM_CONTROL (iRST , iCLK, oLED, oI2C_SCLK, iI2C_SDAT, iGO, iSW);
					
input iRST;
input iCLK;
input iGO;
output [7:0]oLED;
output oI2C_SCLK;
inout iI2C_SDAT;
input [3:0]iSW;

///Variables internes////
reg       go;
reg [6:0] SD_COUNTER;
reg       SDI;
reg       SCLK;
reg       final;
wire [3:0] valor;

///Assignacions///////////////

assign oI2C_SCLK = ((SD_COUNTER >= 4)&(SD_COUNTER <=58))? ~iCLK: SCLK; //Sortida del senyal SCLK
assign iI2C_SDAT = SDI;
assign oLED[0]= final;

assign valor=iSW[3:0];

//Primera estructura always
//Condició perque començi la comunicacio I2C
always@ (posedge iCLK or negedge iRST)
begin
   if (!iRST)
      go <= 0;
		
	else
      if(!iGO)
	    go <= 1;
		
end 

//Segona estructura always, I2C COUNTER
always@ (posedge iCLK or negedge iRST)
begin  
   if (!iRST)
	    SD_COUNTER <= 6'b0;
   else
	begin
	   if (!go)
		   SD_COUNTER <= 0;
		else 
		   if (SD_COUNTER < 60) 
			    SD_COUNTER <= SD_COUNTER+1;
   end
end	
	
//Tercera estructura always, I2C Operation

always@ (posedge iCLK or negedge iRST)
begin 
     if (!iRST)
	 begin
	  SCLK <=1;
	  SDI <=1;
	  
	  end
	  else 
	 	     
  case (SD_COUNTER)
 
		 6'd0 : begin SDI <=1; SCLK<=1; final<=1'b0;end 
		 
		 //Condició d'inici
		 6'd1 : SDI <=0;
		 6'd2 : SCLK <=0;
		 
		 //Adreça de l'escalu
		 6'd3  : SDI <=1;
		 6'd4  : SDI <=0;
		 6'd5  : SDI <=1;
		 6'd6  : SDI <=0;
		 6'd7  : SDI <=0;
		 6'd8  : SDI <=0;
		 6'd9  : SDI <=0;
		 6'd10 : SDI <=0; // 0 per escriure i 1 per llegir
		 6'd11 : SDI <=1'bz; //Slave ACK
		 //SUB ADDR (n)
		 6'd12  : SDI <=0;
		 6'd13  : SDI <=0;
		 6'd14  : SDI <=0;
		 6'd15  : SDI <=0;
		 6'd16  : SDI <=0;
		 6'd17  : SDI <=0;
		 6'd18  : SDI <=1;
		 6'd19  : SDI <=0; 
		 6'd20  : SDI <=1'bz; //Slave ACK
		 
       //DATA0 (n+1)
       6'd21  : SDI <=0;
		 6'd22  : SDI <=0;
	    6'd23  : SDI <=0;
	    6'd24  : SDI <=0;
	    6'd25  : SDI <=valor[3];
	    6'd26  : SDI <=valor[2];
	    6'd27  : SDI <=valor[1];
	    6'd28  : SDI <=valor[0];
	    6'd29  : SDI <=1'bz;  
		 
		 //DATA0 (n+2)
       6'd30  : SDI <=0;
		 6'd31  : SDI <=0;
	    6'd32  : SDI <=0;
	    6'd33  : SDI <=0;
	    6'd34  : SDI <=~valor[3];
	    6'd35  : SDI <=~valor[2];
	    6'd36  : SDI <=~valor[1];
	    6'd37  : SDI <=~valor[0];
	    6'd38  : SDI <=1'bz;  
		 
		 //DATA1 (n+3)
       6'd39  : SDI <=0;
		 6'd40  : SDI <=0;
	    6'd41  : SDI <=0;
	    6'd42  : SDI <=0;
	    6'd43  : SDI <=valor[3];
	    6'd44  : SDI <=valor[2];
	    6'd45  : SDI <=valor[1];
	    6'd46  : SDI <=~valor[0];
	    6'd47  : SDI <=1'bz;  
		 
		 //DATA1 (n+4)
       6'd48  : SDI <=valor[3];
		 6'd49  : SDI <=valor[2];
	    6'd50  : SDI <=~valor[1];
	    6'd51  : SDI <=~valor[0];
	    6'd52  : SDI <=0;
	    6'd53  : SDI <=0;
	    6'd54  : SDI <=0;
	    6'd55  : SDI <=0;
	    6'd56  : SDI <=1'bz; 
		 
	    //Condició de STOP
       6'd57 : begin SDI <= 1'b0; SCLK <= 1'b1;final=1'b1;end
		 6'd58 : SDI <= 1'b1;


	endcase

end 

endmodule 