题解 | #格雷码计数器#
格雷码计数器
https://www.nowcoder.com/practice/311754bcd45d42eb8d981eeddbdf1e43
`timescale 1ns/1ns module gray_counter( input clk, input rst_n, output reg [3:0] gray_out ); //格雷码转二进制 reg [3:0] gray2bin; wire [3:0] gray; always @(posedge clk or negedge rst_n)begin if(rst_n == 1'b0) begin gray2bin <= 4'b0; end else begin gray2bin[3] = gray[3]; gray2bin[2] = gray[2]^gray2bin[3]; gray2bin[1] = gray[1]^gray2bin[2]; gray2bin[0] = gray[0]^gray2bin[1]; end end //二进制加一 reg [3:0] cnt; always @(posedge clk or negedge rst_n)begin if(rst_n == 1'b0) begin cnt <= 4'b0; end else begin cnt <= gray2bin + 1'b1; end end //二进制转格雷码 assign gray = (cnt >> 1) ^ cnt; always @(posedge clk or negedge rst_n)begin if(rst_n == 1'b0) begin gray_out <= 4'b0; end else begin gray_out <= gray; end end endmodule