NRZI diagram[2]
First part is encoder, second part is decoder. Small modification is in the bit_stream sampling part.
Some comments:
1. use DFF to buffer the input
2. use 1'b1 instead of 1, because during synthesis, 1 will be viewed as integer type:
example, like adder, cnt + 1'b1; 1'b1 will get extended to align with cnt.
if for assignment, cnt <= 1;// 1 will get truncated to align with cnt, better to use 1'b1
NRZI encoder
//file: nrzi.v
//author: rui
//comments: input serial input
//output nrzi code
//algorithm: nrzi0 means change, nrzi1 means no change
`timescale 1ns/1ns
module nrzi(input bstream, clk, rst_n,
output reg nrzi_code);
reg nrzi_temp, bstream_temp;
always@(bstream_temp or bstream) begin
nrzi_temp = ~(bstream_temp ^ bstream); // 0: change, 1: no change
end
always@(posedge clk or negedge rst_n) begin
if(!rst_n)
begin
nrzi_code <= 1; bstream_temp <= bstream;
end
else
begin
nrzi_code <= nrzi_temp; bstream_temp <= bstream;
end
end
endmodule
//author: rui
//comments: input serial input
//output nrzi code
//algorithm: nrzi0 means change, nrzi1 means no change
`timescale 1ns/1ns
module nrzi(input bstream, clk, rst_n,
output reg nrzi_code);
reg nrzi_temp, bstream_temp;
always@(bstream_temp or bstream) begin
nrzi_temp = ~(bstream_temp ^ bstream); // 0: change, 1: no change
end
always@(posedge clk or negedge rst_n) begin
if(!rst_n)
begin
nrzi_code <= 1; bstream_temp <= bstream;
end
else
begin
nrzi_code <= nrzi_temp; bstream_temp <= bstream;
end
end
endmodule
testbench
//file: nrzi_top.v
//author: rui
//comments: testbench for nrzi encode
`include "nrzi.v"
`timescale 1ns/1ns
module nrzi_top;
reg bit_stream=0;
reg clk=1, rst_n=1;
wire nrzi_code;
nrzi encoder1(.bstream(bit_stream), .clk(clk), .rst_n(rst_n), .nrzi_code(nrzi_code));
always #5 clk = ~clk;
initial begin
#5 rst_n = 0;
#20 rst_n = 1;
end
initial begin
repeat(20) #10 bit_stream = $random;
#10 $finish;
end
initial begin
$dumpfile("nrzi.vcd");
$dumpvars;
end
endmodule
//author: rui
//comments: testbench for nrzi encode
`include "nrzi.v"
`timescale 1ns/1ns
module nrzi_top;
reg bit_stream=0;
reg clk=1, rst_n=1;
wire nrzi_code;
nrzi encoder1(.bstream(bit_stream), .clk(clk), .rst_n(rst_n), .nrzi_code(nrzi_code));
always #5 clk = ~clk;
initial begin
#5 rst_n = 0;
#20 rst_n = 1;
end
initial begin
repeat(20) #10 bit_stream = $random;
#10 $finish;
end
initial begin
$dumpfile("nrzi.vcd");
$dumpvars;
end
endmodule
Simulation result
Reference
[1]http://www.ece.msstate.edu/~reese/EE8993/lectures/verilog_rtl/verilog_rtl.pdf