斐波那契数列

斐波那契数列

alu.v

ALU模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
module alu (
input [31:0] a, // 操作数
input [31:0] b, // 操作数
input [3:0] op, // 操作类型
output reg [31:0] f, // 结果
output c // 是否跳转
);
always @(*) begin
case (op)
4'b0000: f=32'b0;
4'b0001: f=a+b;
4'b0010: f=a-b;
4'b0011: f=a&b;
4'b0100: f=a|b;
4'b0101: f=a^b;
default: f=32'b0;
endcase
end

assign c = |f; // 如果 f != 0 则 c = 1

endmodule

fib.v

斐波那契数列模块
f(n) = f(n-1) + f(n-2)
c 代码

1
2
3
4
5
6
7
8
9
10
11
12
int f (int n) {
int ra = 1, rb = 1;
int count = 3;
int wf = ra + rb;
while (count < n) {
wf = ra + rb;
ra = rb;
rb = wf;
count++;
}
return wf;
}

verilog 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module fib (
input clk, // 脉冲
input rst, // 复位
input [3:0] n, // 参数
output [31:0] result // 结果 result = f(n)
);
reg [31:0] ra, rb; // 加法器的两个输入
wire [31:0] wf; // 加法器的输出 wf = ra+rb
reg [3:0] count; // 计数

reg [1:0] status, nextstatus;

always @(posedge clk) begin
// 描述对应当前状态
if (rst == 1'b1) begin
// 如果复位信号生效,则当前状态为初始化
status <= 2'b00;
end else begin
// 否则,状态为下一状态
status <= nextstatus;
end
end

always @(*) begin
// 描述下一状态
case (status)
2'b00 : nextstatus <= 2'b01;
2'b01 : nextstatus <= 2'b10;
2'b10 : nextstatus <= 2'b01;
endcase
end

always @(*) begin
// 描述输出
case (status)
2'b00 : begin
ra = 32'b1;
rb = 32'b1;
count = 4'b0011;
end
2'b01 : begin
if (count < n) begin
rb = ra;
ra = wf;
count = count + 1;
end
end
2'b10 : begin
if (count < n) begin
rb = ra;
ra = wf;
count = count + 1;
end
end
endcase
end

assign result = wf;

alu add(.a(ra), .b(rb), .op(4'b0001), .f(wf)); // wf = ra+rb

endmodule

斐波那契数列
http://yjh-2860674406.github.io/2022/09/08/编程/Verilog/斐波那契数列/
Author
Ye JinHua
Posted on
September 8, 2022
Licensed under