VL8 使用generate…for语句简化代码
`timescale 1ns/1ns module gen_for_module( input [ 7:0] data_in , output [ 7:0] data_out ); genvar i; generate for(i = 0; i < 8; i = i + 1) begin : bit_reverse assign data_out[i] = data_in[7 - i]; end endgenerate endmodule
VL9 使用子模块实现三输入数的大小比较
`timescale 1ns/1ns module main_mod( input clk , input rst_n , input [ 7:0] a , input [ 7:0] b , input [ 7:0] c , output [ 7:0] d ); wire [ 7:0] m,n ; sub_module sub_ab( .clk (clk ), .rst_n (rst_n ), .a (a ), .b (b ), .c (m ) ); sub_module sub_mc( .clk (clk ), .rst_n (rst_n ), .a (b ), .b (c ), .c (n ) ); sub_module sub_mn( .clk (clk ), .rst_n (rst_n ), .a (m ), .b (n ), .c (d ) ); endmodule module sub_module ( input clk , input rst_n , input [ 7:0] a , input [ 7:0] b , output reg [ 7:0] c ); always @(posedge clk or negedge rst_n) begin if(!rst_n)begin c <= 8'd0; end else begin if(a <= b) begin c <= a; end else begin c <= b; end end end endmodule
VL10 使用函数实现数据大小端转换
`timescale 1ns/1ns module function_mod( input clk , input rst_n , input [ 3:0] a , input [ 3:0] b , output [ 3:0] c , output [ 3:0] d ); function [3:0] reverse; input [ 3:0] data_in ; integer i; begin for (i = 0;i<4 ;i = i + 1 ) begin reverse[i] = data_in[3-i]; end end endfunction assign c = reverse(a); assign d = reverse(b); endmodule
02 组合逻辑
VL11 4位数值比较器电路
`timescale 1ns/1ns module comparator_4( input [3:0] A , input [3:0] B , output wire Y2 , //A>B output wire Y1 , //A=B output wire Y0 //A<B ); reg Y2_tmp,Y1_tmp,Y0_tmp; always @(A or B) begin if(A > B) begin Y2_tmp = 1; Y1_tmp = 0; Y0_tmp = 0; end else if (A < B) begin Y2_tmp = 0; Y1_tmp = 0; Y0_tmp = 1; end else if(A == B) begin Y2_tmp = 0; Y1_tmp = 1; Y0_tmp = 0; end end assign Y2 = Y2_tmp; assign Y1 = Y1_tmp; assign Y0 = Y0_tmp; endmodule
VL12 4bit超前进位加法器电路
`timescale 1ns/1ns module lca_4( input [3:0] A_in , input [3:0] B_in , input C_1 , output wire CO , output wire [3:0] S ); wire [3:0] G_i; wire [3:0] P_i; wire [3:0] C_i; assign G_i = A_in & B_in; assign P_i = A_in ^ B_in; assign C_i[0] = G_i[0] | P_i[0]&C_1; assign C_i[1] = G_i[1] | P_i[1]&G_i[0] | P_i[1]&P_i[0]&C_1; assign C_i[2] = G_i[2] | P_i[2]&G_i[1] | P_i[2]&P_i[1]&G_i[0] | P_i[2]&P_i[1]&P_i[0]&C_1; assign C_i[3] = G_i[3] | P_i[3]&G_i[2] | P_i[3]&P_i[2]&G_i[1] | P_i[3]&P_i[2]&P_i[1]&(G_i[0] | P_i[0]&C_1); assign S[0] = P_i[0] ^ C_1; assign S[1] = P_i[1] ^ C_i[0]; assign S[2] = P_i[2] ^ C_i[1]; assign S[3] = P_i[3] ^ C_i[2]; assign CO = C_i[3]; endmodule