题解 | #格雷码计数器#
格雷码计数器
https://www.nowcoder.com/practice/311754bcd45d42eb8d981eeddbdf1e43
通过计数器和状态机简洁实现4位格雷码,个人认为添加一个cnt比添加8个状态好一些
`timescale 1ns/1ns module gray_counter( input clk, input rst_n, output reg [3:0] gray_out ); parameter S0 = 4'b 0000; parameter S1 = 4'b 0001; parameter S2 = 4'b 0011; parameter S3 = 4'b 0010; parameter S4 = 4'b 0110; parameter S5 = 4'b 0111; parameter S6 = 4'b 0101; parameter S7 = 4'b 0100; parameter S8 = 4'b 1100; parameter S9 = 4'b 1101; parameter S10 = 4'b 1111; parameter S11 = 4'b 1110; parameter S12 = 4'b 1010; parameter S13 = 4'b 1011; parameter S14 = 4'b 1001; parameter S15 = 4'b 1000; reg cnt; reg [3:0] curr_state,next_state; always @(posedge clk or negedge rst_n) begin if(!rst_n) cnt <= 1'b0; else cnt <= ~cnt; end always @(posedge clk or negedge rst_n) begin if(!rst_n) curr_state <= S0; else curr_state <= next_state; end always @(*)(1444584) begin if(!rst_n) next_state <= S0; else case(curr_state) S0 : next_state <= cnt ? S1 : S0; S1 : next_state <= cnt ? S2 : S1; S2 : next_state <= cnt ? S3 : S2; S3 : next_state <= cnt ? S4 : S3; S4 : next_state <= cnt ? S5 : S4; S5 : next_state <= cnt ? S6 : S5; S6 : next_state <= cnt ? S7 : S6; S7 : next_state <= cnt ? S8 : S7; S8 : next_state <= cnt ? S9 : S8; S9 : next_state <= cnt ? S10 : S9; S10 : next_state <= cnt ? S11 : S10; S11 : next_state <= cnt ? S12 : S11; S12 : next_state <= cnt ? S13 : S12; S13 : next_state <= cnt ? S14 : S13; S14 : next_state <= cnt ? S15 : S14; S15 : next_state <= cnt ? S0 : S15; endcase end always @(*)begin if(!rst_n) gray_out <= 4'b0000; else gray_out <= curr_state; end endmodule