题解 | #格雷码计数器#
格雷码计数器
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] cnt; always@(posedge clk or negedge rst_n) if(!rst_n)begin cnt <= 4'd0; end else if(flag)begin if(cnt >= 4'd15) cnt <= 4'd0; else cnt <= cnt + 1'd1; end reg [1:0] flag; always@(posedge clk or negedge rst_n) if(!rst_n) flag <= 1'b0; else flag <= ~flag; always@(*) gray_out <= cnt^(cnt >> 1); // always@(*) // case(cnt) // 0:gray_out <= 4'b0000; // 1:gray_out <= 4'b0001; // 2:gray_out <= 4'b0011; // 3:gray_out <= 4'b0010; // 4:gray_out <= 4'b0110; // 5:gray_out <= 4'b0111; // 6:gray_out <= 4'b0101; // 7:gray_out <= 4'b0100; // 8:gray_out <= 4'b1100; // 9:gray_out <= 4'b1101; // 10:gray_out <= 4'b1111; // 11:gray_out <= 4'b1110; // 12:gray_out <= 4'b1010; // 13:gray_out <= 4'b1011; // 14:gray_out <= 4'b1001; // 15:gray_out <= 4'b1000; // default:; // endcase endmodule