module my_uart_rx
(
	input			clk,		//25MHzÖ÷Ê±ÖÓ
	input			rst_n,		//µÍµçÆ½¸´Î»ÐÅºÅ
	input			uart_rx,	//½ÓÊÕÊý¾ÝÐÅºÅ
	output	[7:0]	rx_data,	//½ÓÊÕÊý¾Ý¼Ä´æÆ÷£¬±£´æÖ±ÖÁÏÂÒ»¸öÊý¾ÝÀ´µ½
	output			rx_int,		//½ÓÊÕÊý¾ÝÖÐ¶ÏÐÅºÅ,½ÓÊÕµ½Êý¾ÝÆÚ¼äÊ¼ÖÕÎª¸ßµçÆ½
	input			clk_bps,	//clk_bpsµÄ¸ßµçÆ½Îª½ÓÊÕ»òÕß·¢ËÍÊý¾ÝÎ»µÄÖÐ¼ä²ÉÑùµã
	output			bps_start	//½ÓÊÕµ½Êý¾Ýºó£¬²¨ÌØÂÊÊ±ÖÓÆô¶¯ÐÅºÅÖÃÎ»
);

//----------------------------------------------------------------
reg		uart_rx0,uart_rx1,uart_rx2,uart_rx3;	//½ÓÊÕÊý¾Ý¼Ä´æÆ÷
wire	neg_uart_rx;							

always @ (posedge clk or negedge rst_n)
begin 
	if(!rst_n) 
    begin
		uart_rx0 <= 1'b0;
		uart_rx1 <= 1'b0;
		uart_rx2 <= 1'b0;
		uart_rx3 <= 1'b0;
	end
	else 
    begin
		uart_rx0 <= uart_rx;
		uart_rx1 <= uart_rx0;
		uart_rx2 <= uart_rx1;
		uart_rx3 <= uart_rx2;
	end
end

assign neg_uart_rx = uart_rx3 & uart_rx2 & ~uart_rx1 & ~uart_rx0;	//½ÓÊÕµ½ÏÂ½µÑØºóneg_uart_rxÖÃ¸ßÒ»¸öÊ±ÖÓÖÜÆÚ

//----------------------------------------------------------------
reg 		bps_start_r;
reg	[3:0] 	num;	
reg 		rx_int;		//½ÓÊÕÊý¾ÝÖÐ¶ÏÐÅºÅ,½ÓÊÕµ½Êý¾ÝÆÚ¼äÊ¼ÖÕÎª¸ßµçÆ½

always @ (posedge clk or negedge rst_n)
begin
	if(!rst_n)  
    begin
		bps_start_r <= 1'bz;
		rx_int 		<= 1'b0;
	end
	else if(neg_uart_rx) 
    begin	                    //½ÓÊÕµ½´®¿Ú½ÓÊÕÏßuart_rxµÄÏÂ½µÑØ±êÖ¾ÐÅºÅ  
		bps_start_r <= 1'b1;	//Æô¶¯´®¿Ú×¼±¸Êý¾Ý½ÓÊÕ   
		rx_int 		<= 1'b1;	//½ÓÊÕÊý¾ÝÖÐ¶ÏÐÅºÅÊ¹ÄÜ
	end
	else if(num == 4'd9) 
    begin	                    //½ÓÊÕÍêÓÐÓÃÊý¾ÝÐÅÏ¢
		bps_start_r <= 1'b0;	//Êý¾Ý½ÓÊÕÍê±Ï£¬ÊÍ·Å²¨ÌØÂÊÆô¶¯ÐÅºÅ
		rx_int 		<= 1'b0;	//½ÓÊÕÊý¾ÝÖÐ¶ÏÐÅºÅ¹Ø±Õ
	end
end

assign bps_start = bps_start_r;

//----------------------------------------------------------------
reg	[7:0]	rx_data_r;		//´®¿Ú½ÓÊÕÊý¾Ý¼Ä´æÆ÷
reg	[7:0]	rx_temp_data;	//µ±Ç°½ÓÊÕÊý¾Ý¼Ä´æÆ÷

always @ (posedge clk or negedge rst_n)
begin
	if(!rst_n) 
    begin
		rx_temp_data 	<= 8'd0;
		num 			<= 4'd0;
		rx_data_r 		<= 8'd0;
	end
	else if(rx_int) 
    begin	                //½ÓÊÕÊý¾Ý´¦Àí
		if(clk_bps) 
        begin	            	
			num <= num+1'b1;
			case (num)
				4'd1: rx_temp_data[0] <= uart_rx;	//Ëø´æµÚ0bit
				4'd2: rx_temp_data[1] <= uart_rx;	//Ëø´æµÚ1bit
				4'd3: rx_temp_data[2] <= uart_rx;	//Ëø´æµÚ2bit
				4'd4: rx_temp_data[3] <= uart_rx;	//Ëø´æµÚ3bit
				4'd5: rx_temp_data[4] <= uart_rx;	//Ëø´æµÚ4bit
				4'd6: rx_temp_data[5] <= uart_rx;	//Ëø´æµÚ5bit
				4'd7: rx_temp_data[6] <= uart_rx;	//Ëø´æµÚ6bit
				4'd8: rx_temp_data[7] <= uart_rx;	//Ëø´æµÚ7bit
				default: ;
			endcase
		end
		else if(num == 4'd9) 
        begin		
			num			<= 4'd0;			//½ÓÊÕµ½STOPÎ»ºó½áÊø,numÇåÁã
			rx_data_r	<= rx_temp_data;	//°ÑÊý¾ÝËø´æµ½Êý¾Ý¼Ä´æÆ÷rx_dataÖÐ
		end
	end
end

assign rx_data = rx_data_r;	

endmodule