Medium · Arithmetic · Finite State Machines · Sequential Logic
Build a module that streams the Fibonacci sequence, one value per clock cycle, until it passes a threshold.
A start pulse captures thresh and begins a run at 0. During the run out_data steps through 0, 1, 1, 2, 3, 5, 8, ... The run ends at the first value greater than the captured threshold, and done pulses in the same cycle that value appears on out_data.
module fib_stream (
input logic clk,
input logic resetn,
input logic start,
input logic [31:0] thresh,
output logic [31:0] out_data,
output logic done
);
| Port | Dir | Width | Meaning |
|---|---|---|---|
clk | input | 1 | Clock. Everything happens on the rising edge. |
resetn | input | 1 | Synchronous, active-low reset. |
start | input | 1 | Begin a run (sampled on the rising edge). |
thresh | input | 32 | Unsigned threshold, sampled together with start. |
out_data | output | 32 | Current Fibonacci value (unsigned). |
done | output | 1 | One-cycle pulse: out_data has just passed the threshold. |
On a rising edge with resetn = 0 the module becomes idle: any run is aborted, out_data = 0 and done = 0. Reset has priority over everything else on the same edge: a start sampled together with resetn = 0 is ignored, and an edge that would have ended a run does not pulse done. A low pulse on resetn that falls and rises between two rising edges has no effect (do not use always_ff @(posedge clk or negedge resetn)).
Write F(0) = 0, F(1) = 1, F(k) = F(k−1) + F(k−2). Call the rising edge at which start = 1 is sampled while the module is idle E0, and the following rising edges E1, E2, ....
thresh. After E0, out_data = 0 and done = 0.out_data = F(k): the value advances on every edge.threshold. After Em, out_data = F(m) and done = 1, and the run is over.
done = 0 (high for exactly one cycle). out_data holds F(m) until thenext run starts or the module is reset.
Other rules:
thresh may change after E0**, so it has to be stored. The running sequence uses onlythe captured value.
start is ignored during a run, that is on the edges E1 to Em.start in the cycle where done = 1 (sampled on Em+1) is accepted: that edge is thenext run's E0. With start held high, runs follow one another directly.
thresh = 0 the run begins at 0: 0 is not greater than 0, so done comes with the1 at E1.
thresh is never larger than 2971215072, so the value that ends the run always fits in 32bits (the largest 32-bit Fibonacci number is F(47) = 2971215073). Thresholds of 2**31 and above do occur: the comparison is unsigned.
thresh = 10: the run passes 10 at 13.
thresh | values on out_data after E0, E1, ... | done at |
|---|---|---|
| 0 | 0, 1 | E1 |
| 1 | 0, 1, 1, 2 | E3 |
| 5 | 0, 1, 1, 2, 3, 5, 8 | E6 |
| 10 | 0, 1, 1, 2, 3, 5, 8, 13 | E7 |
| 2971215072 | 0, 1, 1, ..., 1836311903, 2971215073 | E47 |
Sign up free to solve Fibonacci Stream in your browser.