How can I write Verilog code for an 8x1 mux using 2x1 mux?

Viewed 55

I am having trouble creating Verilog code for a 8x1 mux using a 2x1. I have placed my code below:

Design Code:

    module MUX2to1(in, sel, out);
  input [1:0]in;
  input wire sel;
  output reg out;
  
  always@(*) begin 
    if (sel == 1'b0)
      out = in[0];
    else 
      out = in[1];
  end 
endmodule
 
module MUX4to1(in, sel, out);
  input [3:0]in;
  input [1:0]sel;
  output out
  
  wire [1:0] MUX_outputs;
  
  MUX2to1 M0 (in[1:0], sel[0], MUX_outputs[0]);
  MUX2to1 M1 (in[3:2], sel[0], MUX_outputs[1]);
  MUX2to1 M2 (MUX_outputs, sel[1], out;
endmodule 
              
module mux8to1(in , sel, out);
  input [7:0] in;
    input [2:0] sel;
    output out;

    wire mux[2:0];

  mux4to1 m1 (in[7:4],sel[1:0], MUX_outputs[0]);
  mux4to1   m2 (in[3:0],sel[1:0], MUX_outputs[1]);
    mux2to1 m3 (mux_1,mux_2,sel[2],out);
endmodule

Testbench

module MUX8to1_tb();
  reg [7:0] in;
  reg [1:0] sel;
  
  wire out;
  
  MUX8to1 uut (in, sel, out);
  
  initial begin 
    $dumpfile("dump.vcd");
    $dumpfile(0,in);
    $dumpfile(0,sel);
    $dumpfile(0,out);
    in = 4'b1010;
    sel = 2'b00;
   #100;
    sel = 2'b01;
   #100;
    sel = 2'b10;
    #100;
    sel = 2'b11;
    #100;
  end
endmodule 

I am using EDA playground to complete this assignment. If anyone can provide a simpler way to do this, please let me know.

1 Answers

If anyone can provide a simpler way to do this, please let me know.

Always write Verilog code using the highest level of abstraction. There is no need for submodules when creating a simple mux. All of the design modules can be replaced by a single module: mux8to1

module mux8to1 (
    input [7:0] in,
    input [2:0] sel,
    output out
);
    assign out = in[sel];
endmodule

module MUX8to1_tb();
  reg [7:0] in;
  reg [2:0] sel;
  wire out;
  
  mux8to1 uut (in, sel, out);
  
  initial begin 
    $dumpfile("dump.vcd");
    $dumpvars;
    in = 8'b0000_1010;
    sel = 3'b000;
   #100;
    sel = 3'b001;
   #100;
    sel = 3'b010;
    #100;
    sel = 3'b011;
    #100;
  end
endmodule 

I also made some changes to the testbench. Instead of calling $dumpfile multiple times, you likely meant to call $dumpvars. sel should be a 3-bit signal to match the mux input.

Here is the complete running code on EDAPlaygraound.

Related