代码

`timescale 1ns/1ns
module rom(
	input clk,
	input rst_n,
	input [7:0]addr,
	
	output [3:0]data
);
    reg [3:0] myROM [7:0];
    always@(posedge clk or negedge rst_n) begin
        if(~rst_n) begin
            myROM[0] <= 0;
            myROM[1] <= 2;
            myROM[2] <= 4;
            myROM[3] <= 6;
            myROM[4] <= 8;
            myROM[5] <= 10;
            myROM[6] <= 12;
            myROM[7] <= 14;
        end
        else begin
            myROM[0] <= myROM[0];
            myROM[1] <= myROM[1];
            myROM[2] <= myROM[2];
            myROM[3] <= myROM[3];
            myROM[4] <= myROM[4];
            myROM[5] <= myROM[5];
            myROM[6] <= myROM[6];
            myROM[7] <= myROM[7];
        end
    end
    
    assign data = myROM[addr];
endmodule

简析

很简单的题目。不过题目没说明,在时钟的非上升沿,addr变换时data也要跟着变化,如下图。所以data受组合逻辑控制,而不能写在时序逻辑里。或者改成双边沿检测。
alt

错误代码:

    // 错误代码!!!!
    reg [3:0] myROM [7:0];
    reg [3:0] data_r;
    always@(posedge clk or negedge rst_n) begin
        if(~rst_n) begin
            myROM[0] <= 0;
            myROM[1] <= 2;
            myROM[2] <= 4;
            myROM[3] <= 6;
            myROM[4] <= 8;
            myROM[5] <= 10;
            myROM[6] <= 12;
            myROM[7] <= 14;
            data_r   <= 0;
        end
        else
            data_r   <= myROM[addr];
    end
    assign data = data_r;