MUX4_1 works as follows:
-
Select the "din" according to the value of "sel"
-
When the asynchronous reset key is pressed (rst_n == 0), the output is in a high resistance state.
-
The 4 option 1 data selector is implemented with task, function and case respectively.
code :
module MUX4_1 (
input clk ,
input rst_n ,
input [3:0] din_1 ,
input [3:0] din_2 ,
input [3:0] din_3 ,
input [3:0] din_4 ,
input [1:0] sel ,
output reg [3:0] dout //reg,If it is not reg, the task cannot be get a value
);
/***********************task***********************/
// task f_1 ;
// input [1:0] sel_r ;
// output [3:0] dout_r ;
// case (sel_r)
// 0 : dout_r <= din_1 ;// = or <=
// 1 : dout_r <= din_2 ;
// 2 : dout_r <= din_3 ;
// 3 : dout_r <= din_4 ;
// default: dout_r <= 4'bzzzz ;
// endcase
// endtask
// always @(posedge clk or negedge rst_n)begin
// if(~rst_n)begin
// dout <= 4'bzzzz ;
// end else begin
// f_1 (sel,dout) ;
// end
// end
/***********************function***********************/
// function [3:0] f_1 ;
// input [1:0] sel_r ;
// begin
// case (sel_r)
// 0 : f_1 = din_1 ;// = or <= You can only use =. Otherwise, an error will be reported. Functions cannot contain non-blocking assignments.
// 1 : f_1 = din_2 ;
// 2 : f_1 = din_3 ;
// 3 : f_1 = din_4 ;
// default: f_1 = 4'bzzzz ;
// endcase
// end
// endfunction
// always @(posedge clk or negedge rst_n) begin
// if(~rst_n)begin
// dout <= 4'bzzzz ;
// end else begin
// dout <= f_1(sel) ;
// end
// end
/***********************case***********************/
always @(posedge clk or negedge rst_n) begin
if(~rst_n) begin
dout <= 4'bzzzz ;
end else begin
case (sel)
0 : dout <= din_1 ;
1 : dout <= din_2 ;
2 : dout <= din_3 ;
3 : dout <= din_4 ;
default: dout <= 4'bzzzz ;
endcase
end
end
endmodule
testbench :
`timescale 1ns/1ps
module test();
reg clk ;
reg rst_n ;
reg [3:0] din_1 ;
reg [3:0] din_2 ;
reg [3:0] din_3 ;
reg [3:0] din_4 ;
reg [1:0] sel ;
wire [3:0] dout ;
parameter CYCLE = 20 ;
MUX4_1 MUX4_1_insert (
.clk ( clk ) ,
.rst_n ( rst_n ) ,
.din_1 ( din_1 ) ,
.din_2 ( din_2 ) ,
.din_3 ( din_3 ) ,
.din_4 ( din_4 ) ,
.sel ( sel ) ,
.dout ( dout )
);
initial begin
clk = 1'b1 ;
rst_n = 1'b1 ;
#( CYCLE * 5 ) ;
rst_n = 1'b0 ;
din_1 = 4'b0001 ;
din_2 = 4'b0010 ;
din_3 = 4'b0100 ;
din_4 = 4'b1000 ;
#( CYCLE * 5 ) ;
rst_n = 1'b1 ;
#( CYCLE ) ;
sel = 0 ;
#( CYCLE * 10 ) ;
sel = 1 ;
#( CYCLE * 10 ) ;
sel = 2 ;
#( CYCLE * 10 ) ;
sel = 3 ;
#( CYCLE * 10 ) ;
$stop ;
end
always #(CYCLE / 2) clk = ~clk ;
endmodule