//总体代码
`timescale 1ns/1ns

module pulse_detect(
	input 				clk_fast	, 
	input 				clk_slow	,   
	input 				rst_n		,
	input				data_in		,

	output  		 	dataout
);

reg pulse_mux;  //翻转电路
reg pulse_reg1;
reg pulse_reg2;
reg pulse_reg3;

always @(posedge clk_fast or negedge rst_n) begin
	if(!rst_n) begin
		pulse_mux <= 1'b0;
	end
	else if(data_in) begin
		pulse_mux <= ~pulse_mux;
	end
end

//两级寄存器打拍同步
always @(posedge clk_slow or negedge rst_n) begin
	if(!rst_n) begin
		pulse_reg1 <= 1'b0;
	end
	else begin
		pulse_reg1 <= pulse_mux;
	end
end

always @(posedge clk_slow or negedge rst_n) begin
	if(!rst_n) begin
		pulse_reg2 <= 1'b0;
	end
	else begin
		pulse_reg2 <= pulse_reg1;
	end
end

//因为跨时钟域电路在打完两拍后才能稳定,所以需要加上第三个寄存器,与第二个寄存器的结果组合来恢复脉冲
always @(posedge clk_slow or negedge rst_n) begin
	if(!rst_n) begin
		pulse_reg3 <= 1'b0;
	end
	else begin
		pulse_reg3 <= pulse_reg2;
	end
end

assign dataout = pulse_reg3 ^ pulse_reg2;
endmodule