实验一 选择器
2选1多路选择器

逻辑表达式:y=(∼s&a)∣(s&b)y=(\sim s\&a)|(s\&b)y=(∼s&a)∣(s&b)
逻辑电路:

数据流建模
数据流建模主要是通过连续赋值语句 assign 来描述电路的功能
module m_mux21(a,b,s,y);
input a,b,s; // 声明3个wire型输入变量a,b,和s,其宽度为1位。
output y; // 声明1个wire型输出变量y,其宽度为1位。
assign y = (~s&a)|(s&b); // 实现电路的逻辑功能。
endmodule
仿真代码:
#include "verilated.h"
#include "verilated_vcd_c.h"
#include "obj_dir/Vmux21.h"
VerilatedContext* contextp = NULL;
VerilatedVcdC* tfp = NULL;
static Vmux21* top;
void step_and_dump_wave(){
top->eval();
contextp->timeInc(1);
tfp->dump(contextp->time());
}
void sim_init(){
contextp = new VerilatedContext;
tfp = new VerilatedVcdC;
top = new Vmux21;
contextp->traceEverOn(true);
top->trace(tfp, 0);
tfp->open("dump.vcd");
}
void sim_exit(){
step_and_dump_wave();
tfp->close();
}
int main() {
sim_init();
top->s=0; top->a=0; top->b=0; step_and_dump_wave(); // 将s,a和b均初始化为“0”
top->b=1; step_and_dump_wave(); // 将b改为“1”,s和a的值不变,继续保持“0”,
top->a=1; top->b=0; step_and_dump_wave(); // 将a,b分别改为“1”和“0”,s的值不变,
top->b=1; step_and_dump_wave(); // 将b改为“1”,s和a的值不变,维持10个时间单位
top->s=1; top->a=0; top->b=0; step_and_dump_wave(); // 将s,a,b分别变为“1,0,0”,维持10个时间单位
top->b=1; step_and_dump_wave();
top->a=1; top->b=0; step_and_dump_wave();
top->b=1; step_and_dump_wave();
sim_exit();
}
编译:
verilator -Wall --cc --exe --build main.cpp mux21.v --trace
波形:

结构化建模
结构化建模主要通过逐层实例化子模块的方式来描述电路的功能
module my_and(a,b,c);
input a,b;
output c;
assign c = a & b;
endmodule
module my_or(a,b,c);
input a,b;
output c;
assign c = a | b;
endmodule
module my_not(a,b);
input a;
output b;
assign b = ~a;
endmodule
module mux21b(a,b,s,y);
input a,b,s;
output y;
wire l, r, s_n; // 内部网线声明
my_not i1(.a(s), .b(s_n)); // 实例化非门,实现~s
my_and i2(.a(s_n), .b(a), .c(l)); // 实例化与门,实现(~s&a)
my_and i3(.a(s), .b(b), .c(r)); // 实例化与门,实现(s&b)
my_or i4(.a(l), .b(r), .c(y)); // 实例化或门,实现(~s&a)|(s&b)
endmodule
行为建模
行为建模是通过类似面向过程的编程语言来描述电路的行为。例如,在Verilog中也可以用if语句来实现2选1多路选择器的行为
module mux21c(a,b,s,y);
input a,b,s;
output reg y; // y在always块中被赋值,一定要声明为reg型的变量
always @ (*)
if(s==0)
y = a;
else
y = b;
endmodule
//或者使用条件表达式
module mux21d(a,b,s,y);
input a,b,s;
output y; // y不用声明为reg型的了。
assign y = s ? b : a;
endmodule
真正的描述电路 = 实例化 + 连线,所以请尽量不要使用“行为级建模”
4选1多路选择器

module mux41(a,s,y);
input [3:0] a; // 声明一个wire型输入变量a,其变量宽度是4位的。
input [1:0] s; // 声明一个wire型输入变量s,其变量宽度是2位的。
output reg y; // 声明一个1位reg型的输出变量y。
always @ (s or a)
case (s)
0: y = a[0];
1: y = a[1];
2: y = a[2];
3: y = a[3];
default: y = 1'b0;
endcase
endmodule
测试代码:
#include "verilated.h"
#include "verilated_vcd_c.h"
#include "obj_dir/Vmux41.h"
VerilatedContext* contextp = NULL;
VerilatedVcdC* tfp = NULL;
static Vmux41* top

最低0.47元/天 解锁文章
2493

被折叠的 条评论
为什么被折叠?



