题解 | #ROM的简单实现#
ROM的简单实现
http://www.nowcoder.com/practice/b76fdef7ffa747909b0ea46e0d13738a
代码
`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
受组合逻辑控制,而不能写在时序逻辑里。或者改成双边沿检测。
错误代码:
// 错误代码!!!!
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;
Verilog篇题解 文章被收录于专栏
本人对牛客网verilog篇题目一些理解