Panel Cookies
yt_link
insta_link
fb_link
twitter_link

Verilog COUNTER


Verilog example - 8Bit Counter code





Go back to Verilog BLINK example:


In this exampel we count up to 256 each time we press the increase button and show the bianry result using 8 LEDs. My FPGA, Cyclone IV board has a 50MHz clock. We will ahve to make a crude debounce and count up to 40ms (2 millions pulses from clock) after each button press so we make sure there are no oscillations. Then we increase the counter register by one and the 8 bit LEDs will cahnge their value since those are connected to each bit of that register. Below, you have the entire project ready to downlaod. Open it in Quartus and create the synthesis for your FPGA. Remember to install Quartus and ModelSim, LINK HERE.



Downlaod VERILOG COUNTER project:


FPGA 8 bit counter example






//We create the module with 3 inputs, and one 8-bit output for 8 LEDs
module counter (clk, button, reset, LEDS);

//Define inputs and outputs
input clk, button, reset;
output [7:0]LEDS;

//Create register for counting the amount of times the button was pressed
reg [7:0] count;

//3 more registers used for debounce since the button will oscillate a few times when pressed
reg [24:0]counter_pressed, counter_not_pressed;
reg button_state = 1'b1;

//Give initial values to the registers. It's important otherwise there might be errors
initial begin
count <= 8'b0;
counter_pressed <= 25'b0;
counter_not_pressed <= 25'b0;
end



//Each positive edge of the clock (50MHz in this case), we enter this part of code
always @ (posedge clk or negedge reset)
begin
	if(!reset)//If the reset is negative (reset button pressed) we reset the valeus
		begin
		count <= 8'b0;
		counter_pressed<= 25'b0;
		counter_not_pressed<= 25'b0;
		end
	
	else
		begin
		//If button is negative (button pressed) and status is low we start counting	
		if(!button & !button_state)
			begin
			counter_pressed <= counter_pressed + 1'b1;		//Counting
			end

		else
			begin
			counter_pressed <= 25'b0; //If not, reset the counter
			end

		if(counter_pressed == 25'd2000000)//When 2M pulses are reached, we increase the push counter by one and reset the others
			begin
			count = count + 1'b1;
			counter_pressed <= 25'b0;
			button_state = 1'b1;
			end


		//Do the same for the positive part of button (button not pressed)
		if(button & button_state)
			begin
			counter_not_pressed <= counter_not_pressed + 1'b1;		
			end

		else
			begin
			counter_not_pressed <= 25'b0;
			end

		if(counter_not_pressed == 25'd2000000)
			begin
			counter_not_pressed <= 25'b0;
			button_state = 1'b0;
			end
		end//end of else of negative reset
end//end of always






//Finally, assign 8 bits from the counter to the 8 LEDs
assign LEDS[7:0] = count[7:0];




endmodule 


Verilog blink example:




FPGA 8 bit counter example







Affiliate Disclosure

ADVERTISERS



PCBWAY PCB service





Curso Arduino Online nivel bajo