Skip to content

Instantly share code, notes, and snippets.

@suarezvictor
Created October 2, 2022 03:20
Show Gist options
  • Save suarezvictor/2038c38b4a843ac77d54b5dac913b78b to your computer and use it in GitHub Desktop.
Save suarezvictor/2038c38b4a843ac77d54b5dac913b78b to your computer and use it in GitHub Desktop.
#example from https://pramode.in/2016/10/05/random-bitstream-using-lfsr/
from migen import *
MAX_PERIOD = 50000
def new_val(lfsr):
bit = ((lfsr >> 0) ^ \
(lfsr >> 2) ^ \
(lfsr >> 3) ^ \
(lfsr >> 5)) & 1
return (lfsr >> 1) | (bit << 15)
m = Module()
lfsr = Signal(16, reset=0xACE1)
counter = Signal(max=MAX_PERIOD)
period = Signal(max=MAX_PERIOD, reset=MAX_PERIOD)
led1 = Signal()
m.comb += led1.eq(lfsr[0])
m.sync += If(counter == 0,
counter.eq(period),
lfsr.eq(new_val(lfsr))
).Else(counter.eq(counter-1))
// Machine-generated using Migen2C - do not edit!
#include "migen2c.h"
MODULE top(
u1& led1,
const u1& sys_clk,
const u1& sys_rst
) {
u16 lfsr = 44257;
u16 counter = 0;
u16 period = 50000;
//NOTE: execution is suspended/resumed at the always statement
while(always(sys_clk)) {
/*assign*/ led1 = bit_slice<0>(lfsr);
if ((counter == 0)) {
counter = period;
lfsr = ((lfsr >> 1) | ((((((lfsr >> 0) ^ (lfsr >> 2)) ^ (lfsr >> 3)) ^ (lfsr >> 5)) & 1) << 15));
} else {
counter = (counter - 1);
}
if (sys_rst) {
lfsr = 44257;
counter = 0;
}
}
}
#include <stdio.h>
#include "dut.cc"
int main()
{
unsigned clk_counter = 0, sum = 0;
u1 sys_clk = 0, sys_rst = 0;
u1 led1 = 0;
auto module1 = top(led1, sys_clk, sys_rst);
for(;;)
{
module1.clock();
sum += led1;
++clk_counter;
if(clk_counter >= 1000000000)
break;
}
printf("count %d, sum %d\n", clk_counter, sum);
return 0;
}
/* Machine-generated using Migen */
module top(
output led1,
input sys_clk,
input sys_rst
);
reg [15:0] lfsr = 16'd44257;
reg [15:0] counter = 16'd0;
reg [15:0] period = 16'd50000;
// synthesis translate_off
reg dummy_s;
initial dummy_s <= 1'd0;
// synthesis translate_on
assign led1 = lfsr[0];
always @(posedge sys_clk) begin
if ((counter == 1'd0)) begin
counter <= period;
lfsr <= ((lfsr >>> 1'd1) | ((((((lfsr >>> 1'd0) ^ (lfsr >>> 2'd2)) ^ (lfsr >>> 2'd3)) ^ (lfsr >>> 3'd5)) & 1'd1) <<< 4'd15));
end else begin
counter <= (counter - 1'd1);
end
if (sys_rst) begin
lfsr <= 16'd44257;
counter <= 16'd0;
end
end
endmodule
#include "Vtop.h"
int main()
{
unsigned clk_counter = 0, sum = 0;
// Init verilator
Vtop* g_top = new Vtop;
for(;;)
{
g_top->sys_clk = 0;
g_top->eval();
sum += g_top->led1;
++clk_counter;
if(clk_counter >= 1000000000)
break;
g_top->sys_clk = 1;
g_top->eval();
}
printf("count %d, sum %d\n", clk_counter, sum);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment