CRC Algorithm discusses how CRC error control encoder works. Now we're going to provide a simple implementation of CRC encoding in Verilog. Here we assume the bit length of information data to be encoded is 16, and the Generated Code is 4 steps.
module crc_encoder (crc_done, crc_start, crc_code, di, gc, clk, rst_);
parameter DataL = 16; //data length
parameter GcL = 4; //generated code length
output crc_done;
output [GcL - 1:0] crc_code;
input crc_start;
input [DL - 1:0] di;
input [GcL - 1:0] gc;
input clk;
input rst_;
reg crc_encode_enable; //crc encoding enable if this signal is high
reg [3:0] crc_encode_cnt; //width of the counter relies on the size of input data.
reg [GcL - 1:0] crc_shf;
assign crc_done = crc_encode_cnt == DL - 1;
always @ (posedge clk) begin
if (rst_)
crc_encode_cnt <= 0;
else if (crc_done)
crc_encode_cnt <= 0;
else if (crc_start | crc_encode_enable)
crc_encode_cnt <= crc_encode_cnt + 1;
end
always @ (posedge clk) begin
if (rst_)
crc_encode_enable <= 0;
else if (crc_start | crc_done)
crc_encode_enable <= crc_start;
end
always @ (posedge clk) begin
if (rst_)
crc_shf <= 0;
else if (crc_start)
crc_shf <= 0;
else if (crc_encode_enable)
crc_shf <= { crc_shf[GcL - 2:0], di[DL - 1] } ^ ({GCL{crc_shf[GcL - 1]}} & gc);
end
always @ (posedge clk) begin
if (rst_)
crc_code <= 0;
else if (crc_done)
crc_code <= crc_shf;
end
endmodule