////////////////////////////////////////////////////////////////////////////////////////////
// Company:			TAIR
// Engineer:		Zaytsev Mikhail
// 
// Create Date:		24/04/2024 
// Design Name: 
// Module Name:		TempRead 
// Project Name:	SB_TMSG44V1_FPGA
// Target Devices:	Board: SB_TMSG44v1. FPGA: GW1N-LV9PG256C6/I5
// Tool versions:
// Description:		The module reads data from the temperature sensor over the 
//					I2C interface once every 42 µs and sendts the temperaure 
//					value over the MisoTemp_o line if FlagDirectTempRead is active.
// Dependencies:	
// Revision: 
// Revision 1.0 - File Created
// Additional Comments: 
//
////////////////////////////////////////////////////////////////////////////////////////////
module TempRead (
	input Clk24Mhz_i,
	input Rst_i,

	input ClkSpi_i,
	input FlagDirectTempRead_i,

	output I2cScl_o,
	inout I2cSda_io,

	output MisoTemp_o
);

//==========================================
// Registers
//==========================================
reg tempReq;
reg [15:0] tempDataReadback;
reg	[9:0] cntI2c;

//==========================================
// Wires
//==========================================
wire [15:0] tempData;
wire tempDataValid;

//==========================================
// Parameters
//==========================================

//==========================================
// Assignments
//==========================================

//==========================================================================//
//									CODING									//
//==========================================================================//
TempI2cMaster TempI2cMaster_inst (
	.i_clk				(Clk24Mhz_i),
	.i_rst_n			(~Rst_i),
	.i_addr				(3'b000),
	.i_ptr				(2'b00),
	.i_req				(tempReq),
	.o_data				(tempData),
	.o_data_valid		(tempDataValid),
	.SCK				(I2cScl_o),
	.SDA				(I2cSda_io)
);

always @(posedge Clk24Mhz_i) begin
	if (Rst_i) begin
		tempDataReadback <= 0;
	end
	else if (tempDataValid) begin
		tempDataReadback[10:0] <= tempData[15:5];
	end
end

always @(posedge Clk24Mhz_i) begin
	if(Rst_i) begin
		cntI2c <= 0;
	end 
	else if(tempDataValid) begin
		cntI2c <= 0;
	end 
	else begin
		cntI2c <= cntI2c + 1;
	end
end

always @(posedge Clk24Mhz_i) begin
	if (Rst_i) begin
		tempReq <= 0;
	end
	else if (&cntI2c) begin
		tempReq <= 1;
	end
	else begin
		tempReq <= 0;
	end
end

SpiReadback SpiReadback_TempReg (
	.ClkSpi_i		(ClkSpi_i),
	.Rst_i			(Rst_i),
	.RegData_i		( {8'h00, tempDataReadback} ),
	//.RegData_i	( {8'h00, 16'h9999} ), //for debug
	.FlagDirect_i	(FlagDirectTempRead_i),
	.Miso_o			(MisoTemp_o)
);

endmodule