Wednesday, 20 June 2012

Binary Counter in Verilog | BASYS2

Now that we have the blinking LED in Verilog up and running, we can do an advanced version of the same project; a binary counter using the LED's.
Also this time I will be using the push button to increment the counter. So every time the push button is pressed the counter will be incremented by 1, the LED's will present the binary counter.

The code for the program is shown below:
module button_binary(
    input clock,
    input reset,
  input button,
    output led,
    output led2,
    output led3,
    output led4,
    output led5,
    output led6,
    output led7,
    output led8

reg [7:0]count;

always @ (posedge button or posedge reset)
  if (reset)
   count <= 0;
  else if (button)
   count <= count + 1;
assign led = count[0];
assign led2 = count[1];
assign led3 = count[2];
assign led4 = count[3];
assign led5 = count[4];
assign led6 = count[5];
assign led7 = count[6];
assign led8 = count[7];


The above program is so simple it needs no commenting, the thing to note here though is the always block. In place of the usual clock I used the push button (always @ posedge button). This is not the best method, but if I use clock here without any debouncing mechanism the counter will not be accurate, i.e. every time the push button is pressed due to the bouncing problem related to push buttons the counter will be incremented many times for each time it is pressed.

I will design the de-bouncing circuit in a later post.

The .ucf file for the above design for the basys2 board is shown below:

# Pin assignment for LEDs
NET "led8" LOC = "g1" ; 
NET "led7" LOC = "p4" ; 
NET "led6" LOC = "n4" ; 
NET "led5" LOC = "n5" ; 
NET "led4" LOC = "p6" ; 
NET "led3" LOC = "p7" ; 
NET "led2" LOC = "m11" ; 
NET "led" LOC = "m5" ; 

# Pin assignment for pushbutton switches
NET "reset" LOC = "a7"; 
NET "button" LOC = "m4"; 

# Pin assignment for clock
NET "clock" LOC = "b8"; 

The working of the above code is shown below:


  1. Dear Faraz,
    I have been trying your code in a DE 2 115 altera board, no error shows in the code but nothing happens when in the board . (I have done the pin configuration correctly)

  2. Khandaker, if the code shows no error then then the only thing left is something went wrong in the implementation. I recommend you read up on the proper implementation procedure of the IDE you are using and also to verify again if the .ucf file is accurate.

    Also when you say no error, does that also mean that the simulation is working as it should?