1. if 语句下嵌套一层case
代码如下:
`timescale 1ns/1ps
module test_case(
//input
sys_clk,
sys_rst_n,
a,
b,
c,
d,
e,
f,
g,
//output
y
);
input [3:0] a;
input [3:0] b;
input [3:0] c;
input [3:0] d;
input [3:0] e;
input [3:0] f;
input [3:0] g;
input sys_clk;
input sys_rst_n;
output reg [3:0] y;
reg [2:0] cnt ;
always @(posedge sys_clk or negedge sys_rst_n)
begin
if (!sys_rst_n) begin
cnt <= 3'd0;
end else if (cnt == 3'd6) begin
cnt <= 3'd0;
end else begin
cnt <= cnt + 3'd1;
end
end
always @(posedge sys_clk or negedge sys_rst_n)
begin
if (!sys_rst_n) begin
y <= 3'd0;
end else begin
case (cnt)
3'd0: begin
y <= a;
end // 2'd0:
3'd1: begin
y <= b;
end // 2'd1:
3'd2: begin
y <= c;
end // 2'd2:
3'd3: begin
y <= d;
end // 2'd3:
3'd4: begin
y <= e;
end // 2'd4:
3'd5: begin
y <= f;
end // 2'd5:
3'd6: begin
y <= g;
end // 2'd6:
endcase // cnt
end
end
endmodule // test_case
综合生成的电路如下:
2.if语句下嵌套一层case再嵌套一层if
代码如下:
`timescale 1ns/1ps
module test_case(
//input
sys_clk,
sys_rst_n,
a,
b,
c,
d,
e,
f,
g,
//output
y
);
input [3:0] a;
input [3:0] b;
input [3:0] c;
input [3:0] d;
input [3:0] e;
input [3:0] f;
input [3:0] g;
input sys_clk;
input sys_rst_n;
output reg [3:0] y;
reg [2:0] cnt ;
always @(posedge sys_clk or negedge sys_rst_n)
begin
if (!sys_rst_n) begin
cnt <= 3'd0;
end else if (cnt == 3'd6) begin
cnt <= 3'd0;
end else begin
cnt <= cnt + 3'd1;
end
end
always @(posedge sys_clk or negedge sys_rst_n)
begin
if (!sys_rst_n) begin
y <= 3'd0;
end else begin
case (cnt)
3'd0: begin
y <= a;
end // 2'd0:
3'd1: begin
y <= b;
end // 2'd1:
3'd2: begin
y <= c;
end // 2'd2:
3'd3: begin
y <= d;
end // 2'd3:
3'd4: begin
if( e > f ) begin
y <= g;
end else if ( a > b ) begin
y <= 3'd0;
end
end // 2'd6:
endcase // cnt
end
end
endmodule // test_case
生成的电路图如下:
3.case语句嵌套case
代码如下:
`timescale 1ns/1ps
module test_case(
//input
sys_clk,
sys_rst_n,
a,
b,
c,
d,
e,
f,
g,
//output
y
);
input [3:0] a;
input [3:0] b;
input [3:0] c;
input [3:0] d;
input [3:0] e;
input [3:0] f;
input [3:0] g;
input sys_clk;
input sys_rst_n;
output reg [3:0] y;
reg [2:0] cnt ;
always @(posedge sys_clk or negedge sys_rst_n)
begin
if (!sys_rst_n) begin
cnt <= 3'd0;
end else if (cnt == 3'd6) begin
cnt <= 3'd0;
end else begin
cnt <= cnt + 3'd1;
end
end
always @(posedge sys_clk or negedge sys_rst_n)
begin
if (!sys_rst_n) begin
y <= 3'd0;
end else begin
case (cnt)
3'd0: begin
y <= a;
end // 2'd0:
3'd1: begin
y <= b;
end // 2'd1:
3'd2: begin
y <= c;
end // 2'd2:
3'd3: begin
y <= d;
end // 2'd3:
3'd4: begin
case (e)
4'd0001: y <= f;
4'd0010: y <= g;
4'd0100: y <= 3'd2;
4'd1000: y <= 3'd3;
endcase
end
endcase // cnt
end
end
endmodule // test_case
电路图如下: