AXI数据流计算CRC16的代码


module crc16_coder_8bit(
input 				clk,
input 				rst_n,
input 				din_last,
input				din_valid,
input		[7:0]	din_data,
output 	reg			dout_last,
output	reg			dout_valid,
output 	reg	[7:0]	dout_data
);

parameter [15:0]	POLY = 16'h1021;// or 16'h8005

reg	[15:0]		crc_remainder;
reg	[2:0]		state;
reg	[3:0]		bit_cnt;

wire	[15:0]	tmp[8:0];

wire	[7:0]	shift_in = (state==2)? 8'd0:din_data;

assign	tmp[0] = crc_remainder;
assign	tmp[1] = tmp[0][15]? {tmp[0][14:0],shift_in[7]}^POLY : {tmp[0][14:0],shift_in[7]};
assign	tmp[2] = tmp[1][15]? {tmp[1][14:0],shift_in[6]}^POLY : {tmp[1][14:0],shift_in[6]};
assign	tmp[3] = tmp[2][15]? {tmp[2][14:0],shift_in[5]}^POLY : {tmp[2][14:0],shift_in[5]};
assign	tmp[4] = tmp[3][15]? {tmp[3][14:0],shift_in[4]}^POLY : {tmp[3][14:0],shift_in[4]};
assign	tmp[5] = tmp[4][15]? {tmp[4][14:0],shift_in[3]}^POLY : {tmp[4][14:0],shift_in[3]};
assign	tmp[6] = tmp[5][15]? {tmp[5][14:0],shift_in[2]}^POLY : {tmp[5][14:0],shift_in[2]};
assign	tmp[7] = tmp[6][15]? {tmp[6][14:0],shift_in[1]}^POLY : {tmp[6][14:0],shift_in[1]};
assign	tmp[8] = tmp[7][15]? {tmp[7][14:0],shift_in[0]}^POLY : {tmp[7][14:0],shift_in[0]};

reg	din_last_r;
always @ (posedge clk)
	din_last_r<=din_last;

always @ (posedge clk or negedge rst_n)
begin
	if(~rst_n) begin
		crc_remainder<=0;
		state<=0;
		dout_last<=1;
		dout_data<=0;
		dout_valid<=0;
		bit_cnt<=0;
	end
	else begin
		case(state)
		//开始运算
		0:begin
			if({din_last_r,din_last}==2'b10) begin
				dout_last<=0;
				dout_data<=din_data;
				dout_valid<=din_valid;
				state<=1;
				crc_remainder<=din_valid? {8'd0,din_data} : 16'd0;
			end
		end
		//运算过程
		1:begin
			dout_data<=din_data;
			dout_valid<=din_valid;
			if(din_valid) crc_remainder<=tmp[8];
			if(din_last) begin
				bit_cnt<=0;
				state<=2;
			end
		end
		//尾部补16个0继续运算,算出余数
		2:begin
			dout_valid<=0;
			crc_remainder<=tmp[8];
			if(bit_cnt<8)
				bit_cnt<=bit_cnt+8;
			else
				state<=3;
		end
		//输出余数
		3:begin
			dout_data<=crc_remainder>>bit_cnt;
			dout_valid<=1;
			bit_cnt<=bit_cnt-8;
			if(bit_cnt==0) begin
				dout_last<=1;
				state<=4;
			end
		end
		4:begin
			dout_valid<=0;
			state<=0;
		end
		default:state<=0;
		endcase
	end
end

endmodule

你可能感兴趣的:(fpga开发)