题解 | #格雷码计数器#
格雷码计数器
https://www.nowcoder.com/practice/311754bcd45d42eb8d981eeddbdf1e43
`timescale 1ns/1ns
module gray_counter(
input clk,
input rst_n,
output reg [3:0] gray_out
);
//格雷码转二进制
genvar i;
wire [3:0] bin_out;
assign bin_out[3] = gray_out[3];
generate
for(i=2;i>=0;i=i-1)begin
assign bin_out[i] = bin_out[i+1] ^ gray_out[i];
end
endgenerate
//二进制计数器
reg [3:0] bin_add;
always @(posedge clk or negedge rst_n)begin
if(rst_n == 1'b0)
bin_add <= 4'd0;
else
bin_add <= bin_out + 1'b1;
end
//二进制转格雷码
wire [3:0] gray;
assign gray = bin_add ^(bin_add >> 1);
//格雷码存寄存器
always @(posedge clk or negedge rst_n)begin
if(rst_n == 1'b0)
gray_out <= 4'd0;
else
gray_out <= gray;
end
endmodule
计数器两个时钟周期变化一次。
