I am used to programming in VHDL and I want to know the "best" way to do some types of actions that I use in VHDL in Verilog. I suppose that each of these could be their own dedicated question, but I thought it would be nice to have a collection of these for people just to see a bunch of Verilog examples in one place rather than spread across 5 questions. Thanks.
Here are some examples that I would like to see best practices for:
Replacement for Others:
I know that for signal assignments in Verilog, you can do:
data <= 'b0;
This assigns all bits in data to zero, and if data changes its width it still works. Neat trick, but what about when instantiating a module and tying an input to zero? E.G.
Data_Module UUT
(
.Data(8'h00), //'b0 doesn't work here
Replacement for Attributes:
Writing flexible code is nice, so I like to define my port widths based on generics such that if the port widths change all it takes is a quick update of the generic and everything still works. I often have VHDL code like this:
signal some_data : std_logic_vector(g_DATA_WIDTH+g_GENERIC-1 downto 0);
signal some2 : std_logic_vector(some_data'length-1 downto 0);
-- OR I may have this:
left_bit <= some_data'left;
Long when/else chain:
This one gives me troubles. Is the best way to do this to set up a combinational always block and use a case-statement on index? That seems like a lot of code. Using the ?
operator can lead to some illegible code, so I prefer not to do that for long when/else chains.
some_data <= X"01" when index = 0 else
X"04" when index = 1 else
X"02" when index = 2 else
X"F0";
Assertions:
How can I trigger a modelsim assertion in Verilog? I often use these on my VHDL FIFOs to check for overflow/underflow conditions. E.G.
assert NOT_FIFO_OVERFLOW report "FIFO has overflowed, that's a bad thing" severity failure;
Generate Blocks:
In VHDL, it's nice to be able to generate a block of code based on a generic, or completely remove it if that generic is not present. E.G.
g_LFSR_3 : if g_Num_Bits = 3 generate
w_XNOR <= r_LFSR(3) xnor r_LFSR(2);
end generate g_LFSR_3;
g_LFSR_4 : if g_Num_Bits = 4 generate
w_XNOR <= r_LFSR(4) xnor r_LFSR(3);
end generate g_LFSR_4;
State Machine Enumeration:
In Verilog, do I really need to create parameters
for each individual state? If that's the best way to do it, I'll do it, but it seems like a lot. I like that in VHDL you can create a type that just contains each state and then create a state machine signal of that type.
Creating Integers:
Often I have code like this:
signal Row_Count : integer range 0 to c_TOTAL_ROWS-1 := 0;
What's the best way to do this in Verilog? Do I need to take the log base 2 of c_TOTAL_ROWS to find the max width of it then define a reg
based on this? That seems like a lot of work. I believe that Verilog creates 32-bit integers by default, but I do not want to generate extra logic if I do not need to. Also I like that if I exceed the expected range, my Modelsim simulation will crash.