题解 | #格雷码计数器#
格雷码计数器
http://www.nowcoder.com/practice/311754bcd45d42eb8d981eeddbdf1e43
`timescale 1ns/1ns
module gray_counter(
input clk,
input rst_n,
output wire [3:0] gray_out
);
//使用Moore状态机实现
parameter s0 =8'b0000_0000,
s1 = 8'b0001_0001,
s2 = 8'b0011_0011,
s3 = 8'b0010_0010,
s4 = 8'b0110_0110,
s5 = 8'b0111_0111,
s6 = 8'b0101_0101,
s7 = 8'b0100_0100,
s8 = 8'b1100_1100,
s9 = 8'b1101_1101,
s10 = 8'b1111_1111,
s11 = 8'b1110_1110,
s12 = 8'b1010_1010,
s13 = 8'b1011_1011,
s14 = 8'b1001_1001,
s15 = 8'b1000_1000,
ss0 = 8'b0000_0001,
ss1 = 8'b0001_0011,
ss2 = 8'b0011_0010,
ss3 = 8'b0010_0110,
ss4 = 8'b0110_0111,
ss5 = 8'b0111_0101,
ss6 = 8'b0101_0100,
ss7 = 8'b0100_1100,
ss8 = 8'b1100_1101,
ss9 = 8'b1101_1111,
ss10 = 8'b1111_1110,
ss11 = 8'b1110_1010,
ss12 = 8'b1010_1011,
ss13 = 8'b1011_1001,
ss14 = 8'b1001_1000,
ss15 = 8'b1000_0000;
reg [7:0] s,nx_s;//state,next_state
reg the_count_is_crazy;
always@(posedge clk or negedge rst_n)begin
if(rst_n == 0)
s <= s0;
else
s <= nx_s;
end
always@(*)begin
case(s)
s0:nx_s = ss0;
ss0:nx_s = s1;
s1:nx_s = ss1;
ss1:nx_s = s2;
s2:nx_s = ss2;
ss2:nx_s = s3;
s3:nx_s = ss3;
ss3:nx_s = s4;
s4:nx_s = ss4;
ss4:nx_s = s5;
s5:nx_s = ss5;
ss5:nx_s = s6;
s6:nx_s = ss6;
ss6:nx_s = s7;
s7:nx_s = ss7;
ss7:nx_s = s8;
s8:nx_s = ss8;
ss8:nx_s = s9;
s9:nx_s = ss9;
ss9:nx_s = s10;
s10:nx_s = ss10;
ss10:nx_s = s11;
s11:nx_s = ss11;
ss11:nx_s = s12;
s12:nx_s = ss12;
ss12:nx_s = s13;
s13:nx_s = ss13;
ss13:nx_s = s14;
s14:nx_s = ss14;
ss14:nx_s = s15;
s15:nx_s = ss15;
ss15:nx_s = s0;
endcase
end
assign gray_out = s[7:4];
endmodule