题解 | #格雷码计数器#
格雷码计数器
https://www.nowcoder.com/practice/311754bcd45d42eb8d981eeddbdf1e43
`timescale 1ns/1ns module gray_counter( input clk, input rst_n, output reg [3:0] gray_out ); reg [4:0] bin; reg flag; always@(posedge clk or negedge rst_n)//不需要使用状态机,状态机本质上也是bcd码,无法避免。 //此外本题其实应该从1开始计数,否则gray码会慢一拍。但是testbench是这样的,所以将就从0开始了。 //上述分析不一定正确,望指正。 if(!rst_n) bin<=0; else if(~flag) bin<=bin+1; always@(posedge clk or negedge rst_n)//似乎要两拍才加1 if(!rst_n) flag<=0; else flag<=~flag; always@(posedge clk or negedge rst_n) if(!rst_n) gray_out<=0; else gray_out<=bin^(bin>>1); endmodule
不需要使用状态机,状态机本质上也是bcd码,无法避免。
此外本题其实应该从1开始计数,否则gray码会慢一拍。但是testbench是这样的,所以将就从0开始了。
上述分析不一定正确,望指正。