//
// File: user_updown3.v
// Date: 10-Nov-05
// Author: I. Chuang <ichuang@mit.edu>
//
// user interface module: up/down counter controlled by buttons
// This version has a reset and initial value, and accepts an index
// specifying which digit should be incremented
module user_updown3(clk,reset,data,b_up,b_down,initval,incidx);
parameter NBIT = 8;
parameter NDIGIT = NBIT/4;
parameter RATE = 80000;
parameter NMAX = ((1<<NBIT)-1);
parameter NMIN = 0;
input clk, b_up, b_down,reset;
input [NBIT-1:0] initval; // initial value for register on reset
input [NDIGIT-1:0] incidx; // index specifying digit to increment
output [NBIT-1:0] data; // data register
// provide an NBIT value (data) which can be changed by
// user buttons up and down.
//
// we debounce the buttons here.
reg [NBIT-1:0] data;
reg [31:0] pcount;
wire bflag = (pcount == RATE) ? 1 : 0;
wire up,down;
wire [NBIT-1:0] dx = (1<<(incidx*4)); // delta for specified digit
debounce dbu(1'b0,clk,b_up,up);
debounce dbd(1'b0,clk,b_down,down);
always @(posedge clk)
begin
pcount <= bflag ? 0 : pcount + 1;
data <= ( reset ? initval
: (down & bflag) ? (data>=(NMIN+dx) ? data-dx : data)
: (up & bflag) ? ((data+dx)<=NMAX ? data+dx : data)
: data);
end
endmodule // user_updown