题目
输入一个序列,最新输入的数字为最低位,如果当前序列能被3整除,输出1,否则输出0。
例如:输入1010_1111,对应1,2,5,10,21,43,87,175,因此输出为:0000_1010.
编程思路
Last_remainder | In | Remainder | Out |
---|---|---|---|
0 | 0 | 0 | 1 |
1 | 0 | 2 | 0 |
2 | 0 | 1 | 0 |
0 | 1 | 1 | 0 |
1 | 1 | 0 | 1 |
2 | 1 | 2 | 0 |
代码
`timescale 1ns / 1ps
module sequence_divide_by_3(
input clk,
input rstn,
input data,
output divide_by_3
);
parameter Remainder_0 = 2'd0,
Remainder_1 = 2'd1,
Remainder_2 = 2'd2;
reg [1:0] state,next_state;
always @(posedge clk or negedge rstn) begin
if(!rstn) state <= Remainder_0;
else state <= next_state;
end
always @(*) begin
case(state)
Remainder_0: next_state = data ? Remainder_1 : Remainder_0;
Remainder_1: next_state = data ? Remainder_0 : Remainder_2;
Remainder_2: next_state = data ? Remainder_2 : Remainder_1;
default : next_state = Remainder_0;
endcase
end
assign divide_by_3 = (((state == Remainder_0) && (~data)) || ((state == Remainder_1) && (data)))?1'b1:1'b0;
endmodule