Verilog计算ram中的奇数和偶数

时间:2016-11-24 15:20:11

标签: verilog

我使用quartus 2 9.1。我在verilog上有一个单端口RAM程序,我添加了reg

  

即使

检查数字是奇数还是第一位,它的总和为1或0。我需要通过数据输入在RAM中输入16个数字,然后计算多少个奇数和偶数。但我试过像:

output wire [4:0] count;
count = count + data[0]; //to count odd numbers, then i could take away from 16 and get even number - in simulation its just 0 or 1..

或类似的东西:

output wire [4:0] count;
always @*
begin
if(data[0])
even=1;
else
    begin
    even=0;
    count = count + 1;
    end
end

但是数不要显示sumaliton奇数或偶数的数字..我的代码:

   module kok 
( 
input [7:0] data, 
input [5:0] addr, 
input we, clk, 
output [7:0] q, 
output reg even 
); 

// Declare the RAM variable 
reg [7:0] ram[63:0]; 

// Variable to hold the registered read address 
reg [5:0] addr_reg; 

always @ (posedge clk) 
begin 
// Write 
if (we) 
ram[addr] <= data; 

addr_reg <= addr; 

end 

always @(posedge data) 
begin 
even = data[0]; 
end 

// Continuous assignment implies read returns NEW data. 
// This is the natural behavior of the TriMatrix memory 
// blocks in Single Port mode. 
assign q = ram[addr_reg]; 

endmodule

2 个答案:

答案 0 :(得分:0)

计数器需要处于定时进程(即总是在@posedge clk内)。因此,计数器也需要是reg(而不是wire)。您还需要弄清楚应该重新启动计数器的条件,以及是否需要考虑溢出条件等。这取决于您的实际使用情况。

答案 1 :(得分:0)

我对您的问题的理解是您想要一个输出count信号,该信号计算您有一个偶数值的次数。

创建top_level

module top (
     input [7:0] data, 
     input [5:0] addr, 
     input we
);
  reg clk= 1;
  initial begin
    forever #5 clk = ~clk;
  end

  reg reset_count = 0;
  initial begin
    #5 reset_count = 1'b1;
    #20 reset_count = 1'b0;
  end

  kok u_kok (.clk(clk),
             .data(data),
             .addr(addr),
             .we(we),
             .reset_count(reset_count)
             );
endmodule

将此添加到module_kok

module kok 
( 
input       reset_count,
input [7:0] data, 
input [5:0] addr, 
input we, clk, 
output [7:0] q, 
output reg even,
output reg [4:0] count
); 

// Declare the RAM variable 
reg [7:0] ram[63:0]; 

// Variable to hold the registered read address 
reg [5:0] addr_reg; 

always @ (posedge clk) 
begin 
// Write 
if (we) 
  ram[addr] <= data; 
addr_reg <= addr; 
end 

always @(posedge clk) 
begin
  even <= data[0]; 
end

  always @(posedge even or posedge reset_count)
begin
  if (reset_count) begin
    count <= 'h0;
  end
  else begin
    count <= count+1'b1;
  end
end


// Continuous assignment implies read returns NEW data. 
// This is the natural behavior of the TriMatrix memory 
// blocks in Single Port mode. 
assign q = ram[addr_reg]; 

endmodule

请注意,在计数器溢出之前,您只能计数到2 ** 5 = 32。

以下是一个工作示例:https://www.edaplayground.com/x/qRs