If statement and assiging wires in Verilog

删除回忆录丶 提交于 2019-12-06 03:17:00

First thing to ask is: are you trying to use those wires as inputs? Or are you using those as connections? Second thing: Do you want a synthesizable code? And you cant assign wires inside an always block, you have to use reg

So an opinion is:

//**************************************************************************************
module(a, b, out); //You have to define an interface, and all Verilog modules starts with module 
input val[1:0]; //you have to use [] in order to indicate the length. In this case 2 bits, since you want to ask for 00;
input a;
input b;
output out;

reg x;

always @* //NOTE: You are describing combo logic, since there is no clock signal
begin

      if(val == 2'b00)
        x = a;
      else if(val == 2'b01)
        x = b;
      else 
        x = 0; //If you are describing combo logic, you have to cover ALL val cases, in                     order to evade latches

end

assign out = x; //This is how you assign values in Verilog

endmodule

wires can only be assigned by assign statements, which can not be used with if statements. If you change x to reg type, then you will be able to assign it in an always block.

This will synthesize exactly the same, a common misconception is that a reg type variable implies a register, but it just changes the way the value is assigned.

Alternatively, you can use an assign statement with ternary operator ?:, if you want it to remain as a wire type:

assign x = (val==0) ?   a : 
           (val==1) ?   b : 
                      'bx ;

First of all, I didn't notice any input or output ports in your module. Nor did I notice a proper module declaration with a beginning and end.

However, assuming your module is defined as follows, with inputs a,b, and val and output x:

module myfirstmodule (
  input       a,
  input       b,
  input [1:0] val,
  output      x
);

// Assign a or b to x based upon val
assign x = (val == 2'b00) ? a : 
           (val == 2'b01) ? b :
           0; // Since val can take on values 00,01,10, and 11, we define all possible cases

endmodule

The assign statement serves as a conditional block like an if statement you are probably used to in popular programming languages such as C or C++.

The assign operator works as such:

  1. Assign my value to other values based upon if certain conditions are true.

The above assign operator works as follows:

If val == 2'b00, assign x to the value of a.

Else If val == 2'01, assign x to the value of b.

Else val = 0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!