# [走近FPGA]之组合逻辑进阶——模块化设计

## 组合逻辑模块化设计实例1

```module seg_decoder(data_disp,seg);
input [3:0] data_disp;
output reg [7:0] seg;
always@(data_disp)
case(data_disp)
4'h0 : seg = 8'h3f;
4'h1 : seg = 8'h06;
4'h2 : seg = 8'h5b;
4'h3 : seg = 8'h4f;
4'h4 : seg = 8'h66;
4'h5 : seg = 8'h6d;
4'h6 : seg = 8'h7d;
4'h7 : seg = 8'h07;
4'h8 : seg = 8'h7f;
4'h9 : seg = 8'h6f;
4'ha : seg = 8'h77;
4'hb : seg = 8'h7c;
4'hc : seg = 8'h39;
4'hd : seg = 8'h5e;
4'he : seg = 8'h79;
4'hf : seg = 8'h71;
endcase
endmodule```

```module DIG_decoder(ctrl,sel);
input [2:0] ctrl;
output reg [5:0] sel;
always @ (ctrl)
case (ctrl)
3'd1 : sel = 6'b111110;
3'd2 : sel = 6'b111101;
3'd3 : sel = 6'b111011;
3'd4 : sel = 6'b110111;
3'd5 : sel = 6'b101111;
3'd6 : sel = 6'b011111;
default : sel = 6'b111111;
endcase
endmodule```

```module TOP(data_disp,ctrl,seg,sel);
input [3:0] data_disp;
input [2:0] ctrl;
output [7:0] seg;
output [5:0] sel;
DIG_decoder DIG_decoder(
.ctrl(ctrl),
.sel(sel)
);
seg_decoder seg_decoder(
.data_disp(data_disp),
.seg(seg)
);
endmodule```

```timescale 1ns / 1ps
module digitron_tb;
reg [3:0] data_disp;
reg [2:0] ctrl;
wire [7:0] seg;
wire [5:0] sel;
TOP uut(
.data_disp(data_disp),
.ctrl(ctrl),
.seg(seg),
.sel(sel)
);
initial begin
data_disp = 4'b0000;
ctrl = 3'b000;
end
always #20 begin
data_disp = data_disp + 1;
ctrl = ctrl + 1;
end
endmodule```

## 组合逻辑模块化设计实例2

```module comparator(ina,inb,LT,GT,EQ);
input [3:0] ina;
input [3:0] inb;
output LT;
output GT;
output EQ;
assign LT = (ina < inb) ? 1'b1 : 1'b0;
assign GT = (ina > inb) ? 1'b1 : 1'b0;
assign EQ = (ina == inb) ? 1'b1 : 1'b0;
endmodule```

```module Mux(ina,inb,sel,data_out);
input [3:0] ina;
input [3:0] inb;
input sel;
output [3:0] data_out;
assign data_out = sel ? inb : ina;
endmodule```

```module DIG_decoder(ctrl,sel);
input [1:0] ctrl;
output reg [5:0] sel;
always@(ctrl)
case(ctrl)
2'b00 : sel = 6'b111000;
2'b01 : sel = 6'b000111;
2'b10 : sel = 6'b000000;
default : sel = 6'b111111;
endcase
endmodule```

```module TOP(ina,inb,seg,sel);
input [3:0] ina;
input [3:0] inb;
output [7:0] seg;
output [5:0] sel;
wire LT;
wire GT;
wire EQ;
wire [3:0] data_disp;
comparator comparator(
.ina(ina),
.inb(inb),
.LT(LT),
.GT(GT),
.EQ(EQ)
);
Mux Mux(
.ina(ina),
.inb(inb),
.sel(LT),
.data_out(data_disp)
);
DIG_decoder DIG_decoder(
.ctrl({EQ,GT}),
.sel(sel)
);
seg_decoder seg_decoder(
.data_disp(data_disp),
.seg(seg)
);
endmodule```

```timescale 1ns / 1ps
module digitron_tb;
reg [3:0] ina;
reg [3:0] inb;
wire [7:0] seg;
wire [5:0] sel;
TOP uut(
.ina(ina),
.inb(inb),
.seg(seg),
.sel(sel)
);
initial begin
ina = 4'h0; inb = 4'h0; //ina = inb
#20
ina = 4'h5; inb = 4'h2; //ina > inb
#20
ina = 4'h7; inb = 4'h9; //ina < inb
#20
ina = 4'h6; inb = 4'h6; //ina = inb
#20
ina = 4'he; inb = 4'ha; //ina > inb
#20
ina = 4'hb; inb = 4'hf; //ina < inb
#20
\$stop;
end
endmodule```