题解 | #格雷码计数器#
格雷码计数器
https://www.nowcoder.com/practice/311754bcd45d42eb8d981eeddbdf1e43
`timescale 1ns/1ns module gray_counter( input clk, input rst_n, output reg [3:0] gray_out ); reg cnt0 ; always@(posedge clk or negedge rst_n) begin if(!rst_n) cnt0 <= 'd0; else cnt0 <= cnt0 + 'd1 ; end reg [3:0] cnt1 ; always@(posedge clk or negedge rst_n) begin if(!rst_n) cnt1 <= 'd0; else if(cnt0 == 'd0) cnt1 <= cnt1 + 'd1 ; end always@(posedge clk or negedge rst_n) begin if(!rst_n) gray_out = 'd0; else if(cnt0 == 'd1) gray_out = cnt1 ^ {1'b0,cnt1[3:1]} ; end endmodule