Ang Li | e20bfbc | 2022-05-20 15:17:54 -0400 | [diff] [blame] | 1 | module bcd2bin ( |
| 2 | input wire clk, |
| 3 | input wire reset, |
| 4 | input wire start, |
| 5 | input wire [3:0] bcd1, |
| 6 | input wire [3:0] bcd0, |
| 7 | output reg ready, |
| 8 | output reg done_tick, |
| 9 | output wire [6:0] bin |
| 10 | ); |
| 11 | |
| 12 | // symbolic state declaration |
| 13 | localparam [1:0] idle = 2'b00, |
| 14 | op = 2'b01, |
| 15 | done = 2'b10; |
| 16 | |
| 17 | // signal declaration |
| 18 | reg [1:0] state_reg, state_next; |
| 19 | reg [6:0] bin_reg, bin_next; |
| 20 | reg [3:0] n_reg, n_next; |
| 21 | reg [3:0] bcd1_reg, bcd0_reg; |
| 22 | reg [3:0] bcd1_next, bcd0_next; |
| 23 | |
| 24 | // FSMD state & data registers |
| 25 | always @(posedge clk) |
| 26 | if (reset) |
| 27 | begin |
| 28 | state_reg <= idle; |
| 29 | bin_reg <= 0; |
| 30 | n_reg <= 0; |
| 31 | bcd1_reg <= 0; |
| 32 | bcd0_reg <= 0; |
| 33 | end else begin |
| 34 | state_reg <= state_next; |
| 35 | bin_reg <= bin_next; |
| 36 | n_reg <= n_next; |
| 37 | bcd1_reg <= bcd1_next; |
| 38 | bcd0_reg <= bcd0_next; |
| 39 | end |
| 40 | |
| 41 | // FSMD next-state logic |
| 42 | always @* |
| 43 | begin |
| 44 | // defaults |
| 45 | state_next = state_reg; |
| 46 | ready = 1'b0; |
| 47 | done_tick = 1'b0; |
| 48 | bin_next = bin_reg; |
| 49 | bcd0_next = bcd0; // route in bcd1 input |
| 50 | bcd1_next = bcd1; // route in bcd0 input |
| 51 | n_next = n_reg; |
| 52 | |
| 53 | case (state_reg) |
| 54 | idle: begin |
| 55 | ready = 1'b1; |
| 56 | if (start) begin |
| 57 | state_next = op; |
| 58 | n_next = 4'b0111; // iterate 7 times |
| 59 | end |
| 60 | end |
| 61 | op: begin |
| 62 | bin_next = {bcd0_reg[0], bin_reg[6:1]}; // right shift in lowest bit from bcd0_reg |
| 63 | bcd1_next = {1'b0, bcd1_reg[3:1]}; // right shift in 0 to bcd1 |
| 64 | // right shift in bcd1[0] into bcd0, if bcd0 > 4, subtract 3 |
| 65 | bcd0_next = ({bcd1_reg[0], bcd0_reg[3:1]} > 4) ? ({bcd1_reg[0], bcd0_reg[3:1]} - 4'b0011) : {bcd1_reg[0], bcd0_reg[3:1]}; |
| 66 | |
| 67 | n_next = n_reg - 1; // decrement n |
| 68 | if (n_next==0) |
| 69 | state_next = done; |
| 70 | end |
| 71 | done: begin |
| 72 | done_tick = 1'b1; |
| 73 | state_next = idle; |
| 74 | end |
| 75 | default: |
| 76 | state_next = idle; |
| 77 | endcase |
| 78 | end |
| 79 | |
| 80 | // assign output |
| 81 | assign bin = bin_reg; |
| 82 | |
| 83 | endmodule |