module uart_rx
#(
	parameter BAUDRATE = 115200,
	parameter CLK_RATE = 50000000
)
(
    input	wire		clk,
	
	// uart
    input	wire		rx,
	
	// data
    output  reg			rx_en,
    output  reg [7:0]	rx_data
);

reg start;
reg clk_en;
reg [3:0] cnt;
reg [7:0] data;
reg [1:0] rx_d;
reg [31:0] clk_cnt;

// ±ßÑØ¼ì²â
always@(posedge clk)
begin
    rx_d <= {rx_d[0],rx};
end

// Êý¾Ý´«Êä¿ØÖÆ
always@(posedge clk)
begin
    if(rx_d == 2'b10) // ¼ì²âµ½ÏÂ½µÑØ´«Êä¿ªÊ¼
        start <= 1;
    else if(cnt == 9) // Êý¾Ý½ÓÊÕÍê³É
        start <= 0;
end

// ²¨ÌØÂÊ¼ÆÊýÆ÷
always@(posedge clk)
begin
	if(!start)
		clk_cnt <= (CLK_RATE / (BAUDRATE*2)); // ÖÐ¼ä²ÉÑù
	else if(clk_cnt == CLK_RATE / BAUDRATE - 1)
		clk_cnt <= 0;
	else
		clk_cnt <= clk_cnt + 1;
end

// ²¨ÌØÂÊ¼ÆÊýÆ÷
always@(posedge clk)
begin
	clk_en <= (clk_cnt == CLK_RATE / BAUDRATE - 1);
end

// ½ÓÊÕÊý¾Ý¼ÆÊýÆ÷
always@(posedge clk)
begin
	if(!start)
        cnt <= 0;
	else if(clk_en)
        cnt <= cnt + 1;
end

// ½ÓÊÕÊý¾Ý²ÉÑù
always@(posedge clk)
if(clk_en)
begin
    case(cnt)
        1: data[0] <= rx;
        2: data[1] <= rx;
        3: data[2] <= rx;
        4: data[3] <= rx;
        5: data[4] <= rx;
        6: data[5] <= rx;  
        7: data[6] <= rx;    
        8: data[7] <= rx;
    endcase   
end

// Êý¾ÝÊä³öÊ¹ÄÜ
always@(posedge clk)
begin
    rx_en <= (start && cnt == 9);
end

// Êý¾ÝÊä³ö
always@(posedge clk)
begin
    if(cnt == 9)
        rx_data <= data;
end

endmodule