Dr. Peter Andrew Jamieson — Academic in an information evolution

← Back to A Random Number Every Second

testbench.sv

· Download testbench.sv · Download both files (.zip)

`timescale 1ns/1ps
// ECE 287 - Exercise 1 testbench: watch the LFSR.
// Paste this into the LEFT pane (testbench.sv) on EDA Playground.
//
// Things to try (edit and re-run):
//   1. Change SEED below. Does the sequence change? Does the period change?
//   2. Set USE_SEED to 0 so the seed is never loaded. What happens, and why?
//
// In EPWave (it opens empty): Get Signals -> scope tb -> select clk, rst,
// en_seed, number -> Append Selected. Find the clock edge where number
// becomes the seed.

module tb;

	localparam [7:0] SEED     = 8'hA5;  // try other values
	localparam       USE_SEED = 1;      // 1 = load SEED after reset, 0 = never load it

	reg clk = 1'b0;
	reg rst = 1'b0;          // active low, like KEY[2] on the board
	reg [7:0] seed = SEED;
	reg en_seed = 1'b0;
	wire [7:0] number;

	integer i;
	integer period;
	reg [7:0] first;

	lfsr dut(.clk(clk), .rst(rst), .seed(seed), .en_seed(en_seed), .number(number));

	always #10 clk = ~clk;   // 20 ns period = 50 MHz, like CLOCK_50

	initial
	begin
		$dumpfile("dump.vcd");
		$dumpvars(0, tb);

		// hold reset for a few clocks, then release it
		repeat (3) @(posedge clk);
		#1 rst = 1'b1;

		// optionally load the seed for one clock
		if (USE_SEED)
		begin
			#1 en_seed = 1'b1;
			@(posedge clk);
			#1 en_seed = 1'b0;
		end

		$display("seed loaded: %0d   (USE_SEED = %0d)", (USE_SEED ? SEED : 0), USE_SEED);
		$display(" clock | number (dec) | number (bin)");

		// print the first 20 values
		for (i = 0; i < 20; i = i + 1)
		begin
			@(posedge clk);
			#1 $display("  %3d  |     %3d      |  %b", i, number, number);
		end

		// how many clocks until the sequence comes back to the same value?
		first = number;
		period = 0;
		for (i = 0; i < 300; i = i + 1)
		begin
			@(posedge clk);
			#1 period = period + 1;
			if (number == first && period > 0)
				i = 300;   // found it, stop looking
		end
		if (number == first)
			$display("The value %0d came back after %0d clocks.", first, period);
		else
			$display("The value %0d did not come back within 300 clocks.", first);

		$finish;
	end

endmodule