module uart_tx
#(
	parameter BAUDRATE = 115200,
	parameter CLK_RATE = 50000000
)
(
    input	wire		clk,
	
	// uart
    output  reg			tx,
	
	// data
    input	wire		tx_en,
    input	wire [7:0]	tx_data,
	output	reg			tx_ready
);

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


// ²¨ÌØÂÊ¼ÆÊýÆ÷
always@(posedge clk)
begin
	if(!start)
		clk_cnt <= 0;
	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(tx_en) // ´«Êä¿ªÊ¼
        start <= 1;
    else if(cnt == 10) // ´«Êä½áÊø
        start <= 0;
end

// Êý¾Ý¼Ä´æ
always@(posedge clk)
begin
	if(tx_en && !start)
		data <= tx_data;
end

// ×´Ì¬¼ÆÊýÆ÷
always@(posedge clk)
begin
    if(!start)
		cnt <= 0;
	else if(clk_en)
        cnt <= cnt + 1;
end

// ´®¿Ú·¢ËÍ
always@(posedge clk)
begin
    case(cnt)
		0: tx <= 1'b1;    // ·¢ËÍÍ£Ö¹Î»(ÉÏµç×´Ì¬).
        1: tx <= 1'b0;    // ´«Êä¿ªÊ¼
        2: tx <= data[0]; // ·¢ËÍÊý¾ÝµÚ1Î»
        3: tx <= data[1]; // ·¢ËÍÊý¾ÝµÚ2Î»
        4: tx <= data[2]; // ·¢ËÍÊý¾ÝµÚ3Î»
        5: tx <= data[3]; // ·¢ËÍÊý¾ÝµÚ4Î»
        6: tx <= data[4]; // ·¢ËÍÊý¾ÝµÚ5Î»
        7: tx <= data[5]; // ·¢ËÍÊý¾ÝµÚ6Î»
        8: tx <= data[6]; // ·¢ËÍÊý¾ÝµÚ7Î»
        9: tx <= data[7]; // ·¢ËÍÊý¾ÝµÚ8Î»
        10:tx <= 1'b1;    // ·¢ËÍÍ£Ö¹Î»
    endcase
end

// ·¢ËÍÄ£¿é¿ÉÓÃ
always@(posedge clk)
begin
	if(tx_en)
		tx_ready <= 0;
	else
		tx_ready <= !start;
end

endmodule