Files
hardware/Logisim/Chatper7_hw1_C1C2/count.v
2025-12-31 19:35:06 +08:00

128 lines
2.0 KiB
Verilog

`timescale 10ns/1ns
module DTouch (
input clk,
input rst_n,
input d,
output reg q
);
always @(posedge clk or negedge rst_n) begin
if (!rst_n)
q <= 0; // 初始复位为 0
else
q <= d;
end
endmodule
//when c1 = 0
module mode3(
input c2,
input clk,
input rst_n,
output q1, q0
);
wire d0i, d1i;
wire q0i, q1i;
assign d1i = ((!q1i) && (!q0i) && c2) || ((!q1i) && (q0i) && (!c2));
assign d0i = ((!q1i) && (!q0i) && (!c2)) || ((q1i) && (!q0i) && (c2)) ;
DTouch dd0(.clk(clk), .rst_n(rst_n), .d(d0i), .q(q0i));
DTouch dd1(.clk(clk), .rst_n(rst_n), .d(d1i), .q(q1i));
assign q0 = q0i;
assign q1 = q1i;
endmodule
//when c1 = 1
module mode4(
input c2,
input clk,
input rst_n,
output q1, q0
);
wire d0i, d1i;
wire q0i, q1i;
assign d1i = ((!q1i) && (!q0i)) || ((q1i) && (q0i));
assign d0i = ((q0i) && (!c2)) || ((!q0i) && (c2));
DTouch dd0(.clk(clk), .rst_n(rst_n), .d(d0i), .q(q0i));
DTouch dd1(.clk(clk), .rst_n(rst_n), .d(d1i), .q(q1i));
assign q0 = q0i;
assign q1 = q1i;
endmodule
module main;
reg clk = 0;
reg rst_n = 0;
reg c1 = 0, c2 = 0;
wire q1, q0;
// 时钟生成
always #2 clk = ~clk;
// 实例化两个模块,但只选择一个输出
wire q1_m3, q0_m3;
wire q1_m4, q0_m4;
mode3 u_mode3 (
.c2(c2),
.clk(clk),
.rst_n(rst_n),
.q1(q1_m3),
.q0(q0_m3)
);
mode4 u_mode4 (
.c2(c2),
.clk(clk),
.rst_n(rst_n),
.q1(q1_m4),
.q0(q0_m4)
);
// 根据 c1 选择哪个模块的输出
assign q1 = (c1 == 0) ? q1_m3 : q1_m4;
assign q0 = (c1 == 0) ? q0_m3 : q0_m4;
// 测试输入控制
initial begin
$dumpfile("count_out.vcd");
$dumpvars(0, main);
// 添加复位:保持一段时间再释放
rst_n = 0;
#4 rst_n = 1;
// 测试序列
#4 c1 = 0; c2 = 0;
#10 c2 = 1;
#10 c2 = 0;
#10 c2 = 1;
#10 c2 = 0;
#10 c1 = 1; c2 = 0;
#10 c2 = 1;
#10 c2 = 0;
#10 c2 = 1;
#10 c2 = 0;
#20 $finish;
end
endmodule