(数字逻辑笔记)用Verilog实现一个简单ALU(组合逻辑)

实验描述:

输入:两个4位二进制数,代表两个操作数A,B;一个3位控制信号operation,代表ALU要进行的运算。本实验中,ALU可以实现8种运算:

输出:4位结果,1位进位

operation | F

000 | A + B

001 | A - B

010 | B + 1

011 | B - 1

100 | NOT A

101 | A XOR B

110 | A AND B

111 | A OR B

实现代码:

/*********************
*    By VastCosmic
*    2021/12/26
*********************/

module ALU(A,B,operation,result,cout);
    input[3:0] A;
	input[3:0] B;
	input[2:0] operation;
	output reg[3:0] result;
	output reg cout;
 
    always @(A or B or operation) 
    begin
        case(operation) 
        //A+B
        3'b000: begin result <= A + B;end 	    
        //A-B
	    3'b001: begin result <= A - B;end
        //B+1
	    3'b010: begin result <= B + 1;end
        //B-1
	    3'b011: begin result <= B - 1;end
        //NOT A
	    3'b100: begin result <= ~A;end
        //A XOR B
	    3'b101: begin result = A ^ B;end     
        //A AND B
	    3'b110: begin result = A & B;end
        //A OR B
	    3'b111: begin result = A | B;end
        endcase
    end
endmodule

TestBench:

/*********************
*    By VastCosmic
*    2021/12/26
*********************/

`timescale 1ns/10ps
module ALU_tb;
reg [3:0] A;
reg [3:0] B;
reg [2:0] operation;
wire [3:0] result;
wire cout;

ALU ALU(A,B,operation,result,cout);
initial 
    begin
        A<=0000;B<=0000;operation <= 000;       //initial
        #10   A<=0001;B<=0001;operation <= 000; //A + B 0010
        #10   A<=0001;B<=0001;operation <= 001; //A - B 0000
        #10   A<=0001;B<=0001;operation <= 010; //B + 1 0010
        #10   A<=0001;B<=0001;operation <= 011; //B - 1 0000
        #10   A<=1001;B<=0001;operation <= 100; //NOT A 0110
        
        #10   A<=0001;B<=0010;operation <= 101; //A XOR B 
        
        #10   A<=0001;B<=0001;operation <= 110; //A AND B 
        #10   A<=0001;B<=0000;operation <= 110; //A AND B
        
        #10   A<=0001;B<=0000;operation <= 111; //A OR B 
        #10   A<=0000;B<=0000;operation <= 111; //A OR B
        #10   $stop;    
    end
endmodule

使用Vivado进行仿真:

仿真波形:

(数字逻辑笔记)用Verilog实现一个简单ALU(组合逻辑)_第1张图片

你可能感兴趣的:(fpga开发,verilog,硬件工程)