Fibonacci Stream

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.

Ports

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
);
PortDirWidthMeaning
clkinput1Clock. Everything happens on the rising edge.
resetninput1Synchronous, active-low reset.
startinput1Begin a run (sampled on the rising edge).
threshinput32Unsigned threshold, sampled together with start.
out_dataoutput32Current Fibonacci value (unsigned).
doneoutput1One-cycle pulse: out_data has just passed the threshold.

Reset

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)).

Timing (exact)

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, ....

  1. At E0 the module captures thresh. After E0, out_data = 0 and done = 0.
  2. After Ek, out_data = F(k): the value advances on every edge.
  3. Let Em be the first edge whose value F(m) is strictly greater than the captured

threshold. After Em, out_data = F(m) and done = 1, and the run is over.

  1. After Em+1, done = 0 (high for exactly one cycle). out_data holds F(m) until the

next run starts or the module is reset.

Other rules:

the captured value.

next run's E0. With start held high, runs follow one another directly.

1 at E1.

bits (the largest 32-bit Fibonacci number is F(47) = 2971215073). Thresholds of 2**31 and above do occur: the comparison is unsigned.

Timing diagram

thresh = 10: the run passes 10 at 13.

Examples

threshvalues on out_data after E0, E1, ...done at
00, 1E1
10, 1, 1, 2E3
50, 1, 1, 2, 3, 5, 8E6
100, 1, 1, 2, 3, 5, 8, 13E7
29712150720, 1, 1, ..., 1836311903, 2971215073E47

Sign up free to solve Fibonacci Stream in your browser.

More Arithmetic problems