module top ( input wire clk, input wire dir, inout wire req, output wire fin, inout wire [7:0] data ); reg dir_last; reg req_last; reg req_r; reg fin_r; reg [7:0] data_r; reg [6:0] x; reg [6:0] y; reg cntr; reg [7:0] waddr; reg [7:0] raddr; wire [7:0] command; RAM command_buffer(.wclk(clk), .rclk(clk), .waddr(waddr), .raddr(raddr), .data_in(data), .write_en(dir && req), .data_out(command)); always_ff @(posedge clk) begin dir_last <= dir; req_last <= req; req_r <= !fin_r && !dir_last; if (dir) begin x <= 0; y <= 0; fin_r <= 0; cntr <= 0; raddr <= 0; if (req && req_last) begin waddr <= waddr + 1; end else begin waddr <= 0; end end else begin cntr <= !cntr; if (cntr) begin data_r <= command; raddr <= 1 - raddr; if (x + y == 0) begin fin_r <= 1; end end else begin data_r <= ((x + y) >> 1) + 16; if (x < 127) begin x <= x + 1; end else begin x <= 0; if (y < 127) begin y <= y + 1; end else begin y <= 0; end end end end end assign req = dir ? 'Z : req_r; assign fin = fin_r; assign data = dir ? 'Z : data_r; endmodule