Skip to content

Verilog Examples

Leonard Pfeiffer edited this page Oct 24, 2023 · 40 revisions

Module

module <name> #(
    <parameters>
)(
    <ports>
);
    <constant-parameters>
    <registers/wires>
    <instances>
    <processes>
    <assignents>
endmodule

Ports

input <name1>,                // Input
input [x:y] <name2>, <name3>, // Multiple array "x downto y" inputs
inout reg <name4>,            // Simultaneus in- and output register
output <name4>                // Output

Registers / Wires

reg <type> <name1>, <name2>; // Registers (Save Data at end of clock cycle)
wire <type> [x:y] <name3>;   // Wire "from x downto y" (Transmits data almost instantly)
reg a = 0;                   // With initial value this time (mostly for sim)

Parameters

parameter <type> <name>;            // Generic (in port definition)
parameter <type> <name> = <value>;  // Constant
localparam <type> <name> = <value>; // Only inside module

Instantionation

<module> #(
    <parameter-ass1>,
    <parameter-ass2>
) <instance> (
    <port-ass1>,
    <port-ass2>
);

Assignments

.<port>(<connection/value>)
.<parameter(<connection/value>)

Values

0 // Logical zero
1 // Logical one
x // Unknown/undefined
z // What the actual f*ck

Types and actually useful values

Values and their types

-7 46 123      // Integer
1.3 0.2 3e-5   // Real
"Hello kitty!" // String

Radix

d46 D23 // Decimal
hFA HAE // Hexadecimal
o17 O77 // Octal
b10 b01 // Binary

Length

32'd46      // 32 bit filled with decimal 46
8'b10101010 // "10101010" in binary as 8 bit
18'o777777  // 18 bits of ones from octal

Types why is this a subcategory

// Can be interpreted by totally not stupid compiler that will produce untraceable errors
real    // Obvious
string  // Obvious
time    // For simulations
event   // I don't know
integer // Why not in first place?

Processes

Always @

always @ (<condition>) <actions>

Conditions

If

if (<condition1>) begin
    <code1>
end else if (<condition>) begin
end else begin
end

Switch / Case

case (<expr>)
    <value1> : begin
        <code1>
    end
    <value2> : begin
        <code2>
    end
    default : begin
        <code3>
    end
endcase
case (sel)
    2'bxz : out = a;
    2'bzx : out = b;
    2'bxx : out = c;
    default : out = 0;
endcase

Clock

posedge clk // Rising edge of clock
negedge clk // Falling edge o clock
posedge rst // Rising edge of reset

Assignments

Assign all indices

assign x = '1;        // Assign all indexes to logical one
assign x = 25'd69;    // lol
assign x = a ? b : c; // Best of them all: Assign a if b (condition) else assign c to x

Package

package <name>
    <parameters>
    <functions?>
    <types>
endpackage

Type

typedef logic [x:y] <name1>;             // Arrays
typedef enum state {<e1>, <e2>} <name2>; // For united state machines
typedef enum {<e1>, <e2>} <name3>;       // Not a state enum bruh
typedef enum [x:y] {<e1>, <e2>} <name4>; // Enum with specified range
Clone this wiki locally