简单的BintoBCD模组

8位Binary转化为12位BCD

原理图



add3模组

//////////////////////////////////////////////////////////////////////////////////
// Company: Cal Poly Pomona
// Engineer: Yongyuan Zhang
// Lab 3 part A, question 1
// Create Date: 2018/05/04 10:40:12
// Description: Code of add 3 functions
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module add3(
input [3:0]x,
output reg [3:0]y
);
always@(*)
    begin
        if(x < 5)
            y = x;
        else
            y = x +3;  // y = x ^4'b0111;
    end
endmodule

8位Bin转化为BCD模组

//////////////////////////////////////////////////////////////////////////////////
// Company: Cal Poly Pomona
// Engineer: Yongyuan Zhang
// Lab 3 part A, question 2
// Create Date: 2018/05/04 10:50:14
// Description: Code of binary to bcd
//////////////////////////////////////////////////////////////////////////////////
`timescale 1ns / 1ps
module bin2bcd(
input[7:0] BIN,
output [11:0] BCD 
); 
    wire [3:0] u0,u1,u2,u3,u5;
    add3 U0(.x( {1'b0,BIN[7:5]} ),.y(u0));
    add3 U1(.x( {u0[2:0],BIN[4]} ),.y(u1));
    add3 U2(.x( {u1[2:0],BIN[3]} ),.y(u2));
    add3 U3(.x( {u2[2:0],BIN[2]} ),.y(u3));
    add3 U4(.x( {u3[2:0],BIN[1]} ),.y(BCD[4:1]));
    add3 U5(.x( {1'b0,u0[3],u1[3],u2[3]} ), .y(u5));
    add3 U6(.x( {u5[2:0],u3[3]}), . y(BCD[8:5]));

    assign BCD[0] = BIN[0]; 
    assign BCD[11:9] = {2'b00,u5[3]};
endmodule

模组TestBench

//////////////////////////////////////////////////////////////////////////////////
// Company: Cal Poly Pomona
// Engineer: Yongyuan Zhang
// Lab 3 part A, question 3
// Create Date: 2018/05/04 10:50:14
// Description: testbench for all possible conditions of the bin to bcd code
//////////////////////////////////////////////////////////////////////////////////
module tb();
    reg [7:0] BIN;
    wire [11:0] BCD;
    bin2bcd   uut(.BIN(BIN),.BCD(BCD));
    initial
    begin
    #2 BIN = 8'b0000_0000;//0
    #2 BIN = 8'b0000_1010;//10
    #2 BIN = 8'b0001_0100;//20
    #2 BIN = 8'b0010_1000;//40
    #2 BIN = 8'b0101_0000;//80
    #2 BIN = 8'b1010_0000;//160
    #2 BIN = 8'b0101_0010;//82
    #2 BIN = 8'b1111_1111;//255
    #2 BIN = 8'b0111_1010;//122
    #2 BIN = 8'b1000_1100;//140
    #2 BIN = 8'b1010_0011;//163
    #2 BIN = 8'b1110_1100;//236
    #2 BIN = 8'b1010_1111; //175
    #2 $finish;
    end
    endmodule