Lets make a counter module but unlike before lets make it standalone code that can be used and modified without affecting the inputs and outputs - that way when we need a counter we can just re-use the counter module code and not have to re-write it every time...unless we have a specific requirement to do so.
Here is a simple diagram of what I hope to achieve:
We will have four LEDS changing state depending on the counter output. The clock is our input and the LEDS are the outputs. The part we need to write is the counter module, before we do that though lets think about what we would want in a counter - Lets discuss counter requirements:
Range of the counter - How big a value will we need to count to before we need the count to reset and start again.
Resolution of the counter - What units do we want to count in: Units, Tens, Hundreds, Thousands, Binary???
Count direction - Do we want to count up from a value or count down from a value?
Load - Do we want to be able to start counting from a value other than zero??
Reset - Do we want to be able to reset the count at any time?
Overflow - Do we want to be able to detect if the count reached the maximum value and then started again?
What we are describing here is the behaviour of the counter. This is one way of coding in a hardware description language - The other method is known as structural where the structure of the logic gates needed to realise the function is described.
Before the advent of microcontrollers and FPGA there was (and still is) a very popular integrated circuit that I used called the 74LS163. It was a four bit binary counter with a ripple carry output. That means it could count from zero to fifteen in binary when a positive edged pulse was detected at the CLK pin. Each time an edge is detected the count increased by 1. When the count reached 16 an output was set known as the ripple carry output or RCO. This allowed a designer to cascade the devices together to make a 32 bit counter or a 48 bit counter, or even a 64 bit counter. I'm going to write some verilog code which reproduces the behaviour of the 74LS163 just as an exercise.
The datasheet for a 74LS163 is here just in case people are interested:
74LS163 Datasheet
The inputs for a 74LS163 are:
Here is the verilog code to describe the 74LS163:
// 74LS163 Binary counter module binary_counter(input a, b, c, d, enp, ent, load, clear, clk, output qa, qb, qc, qd, rco ); always @(posedge clk) begin//start the count on the rising clock edge if (!clear) begin {qd, qc, qb, qa} <=4'b0; //if clear is low, set the count outputs to 0 end if (clear &&!load) begin //if load is set low, set count output to match the input {qd, qc, qb, qa} <= {d,c,b,a}; end if (clear && load && enp && ent) begin//if clear, load, ent and enp are set high, increment the count by one {qd, qc, qb, qa} <= {qd, qc, qb, qa} +1; end end assign rco = ent ? qa && qb && qc && qd :0; // if the count has reached 15 and ent set high set rco high endmodule
Lets explain the code:
We have made a module called binary_counter. It has inputs called a, b, c, d, enp, ent, load, clear and clk. It also has outputs called qa, qb, qc, qd and rco. The module section details the inputs and the outputs of the module and their types.
The next section always @(posedge clk) is similar to the main loop in a high level language. This is the description of the circuit that will be free running forever:
When a positive clock edge is detected on the clk input the follwing checks are performed:
Is the clear low? If it is low then set all the outputs to zero.
Is the clear high and the load low? If this is true then set the outputs qa, qb qc and qd to match the inputs a, b, c, d.
Is the clear high, load high enp high and ent high? If this is true then add one to the count value of bits on the outputs qa, qb, qc and qd.
Has the count reached 15 and has there been another clock edge? If this is true set the outputs to zero and set rco high.
If we were to flash this code to the ulx3s it would work...there is a little more code to write before we could use it. It isn't particularly practical though...If we needed a 4 bit binary counter we could just buy one and use it....not recreate it in FPGA fabric...that would be a bit of a waste of resources. The reason I've mentioned it is I want to illustrate the method of describing what is required.
I have found two methods for writing verilog code. The first method is to calculate the logic function required, then draw a diagram of it (structural implementation) and then write verilog code.
The other way is to draw a diagram which describes the behaviour of what is required and then write verilog code. Either method can be applied...I find the latter behavioural method easier.
Going back to our requirements:
Range of the counter - How big a value will we need to count to before we need the count to reset and start again.
It actually doesn't matter. We can decide when to start, stop and reset the count!
Resolution of the counter - What units do we want to count in: Units, Tens, Hundreds, Thousands, Binary???
Again, it doesn't matter. We can decide what increments we use!
Count direction - Do we want to count up from a value or count down from a value?
This time it matters, we can write code which describes both behaviours but we will need an input to set the count direction.
Load - Do we want to be able to start counting from a value other than zero??
This function was useful when using discrete devices with fixed range and resolution. We don't need this anymore as we can have any range and resolution we like.
Reset - Do we want to be able to reset the count at any time?
Yes! We will need an input to be able to start the counter from zero.
Overflow - Do we want to be able to detect if the count reached the maximum value and then started again?
This function was useful when using discrete devices with fixed range and resolution. We don't need this anymore as we can have any range and resolution we like.
Here is a diagram of what our counter would look like:
From this we can write the module statement for our counter:
module up_down_counter(
input clk, // 25 MHz clock input from the top module input reset, // reset input from the top module input up_down, // count up or down from the top module output [24:0] count_output // counter output to be passed to top module );
Next we need an internal signal to act as a register which stores the result of the count process depending on whether the count is up or down, whether the reset is active (high) or a clock edge has been detected...
reg [24:0] count = 0;
Now we need to write the code that describes the actual counting process:
begin if(reset) count <= 0; else if(~up_down) count <= count + 1; else count <= count - 1; end assign count_output = count; endmodule
Here is the entire code for the module just in case it is needed:
module up_down_counter( input clk, // 25 MHz clock input from the top module input reset, // reset input from the top module input up_down, // count up or down from the top module output [24:0] count_output // counter output to be passed to top module ); reg [24:0] count = 0; // Register for the counter always @(posedge clk or posedge reset) begin if(reset) count <= 0; else if(~up_down) count <= count + 1; else count <= count - 1; end assign count_output = count; endmodule
So we have written a module which will count up or down to any value in unit increments...Copy and paste the code into a text file and call it up_down_counter.v
I used this folder:
C:\msys64\src\Alex\ulx3s\Multiple Counters
Now we need to write some code that calls our new counter module and supply the modules with the inputs needed and then couple the outputs to something we can physically see...LEDS!
Before we do that though we should really update our original diagram to reflect the module code we have written because it will help us write our top module.
The up_down counter module looks like this in diagram form:
Now we are going to use this information to update the top level diagram to implement some verilog code which flashes the LEDS at different rates. Here is the diagram:
From the diagram we can now work out what our top module inputs will be:
Clock, Reset, Up / Down
The outputs are LED 0, LED 1, LED 2 and LED 3
From here we are going to write the top.v code which will call the counter module we wrote earlier and attach the inputs and outputs. Before we do that though it is a good idea to simulate the module code to make sure it works as intended.
There are many simulation programs available for verilog. I decided to use the iverilog program which is well documented. The software is written and maintained by Stephen Williams and it is released under the GNU GPL license. I should also mention that I'm using the Windows 10 operating system...
I downloaded it from here: http://bleyer.org/icarus/
I then followed the instructions and read up some tutorials on how to use it. It wasn't too complicated!
I used the instructions from here:
https://www.swarthmore.edu/NatSci/mzucker1/e15_f2014/iverilog.html
Make sure that iverilog is added to your path in Windows! Now we need to write some code which tests the module.
This is known as a test bench and it is some more verilog code:
// Testbench Verilog code for up-down counter //`timescale 1ns/100ps `include "up_down_counter.v" //include the file which contains the module to be tested // create a test bench module with the inputs and the output(s) module up_down_counter_testbench(); reg clk, reset,up_down; wire [24:0] count_output; // instantiate the module to be tested with inputs and output(s) up_down_counter counter_one (clk, reset, up_down, count_output); // tell the simulator what we want the simulation file to be called // and to get data for all variables initial begin $dumpfile("test.vcd"); $dumpvars; end // monitor the variables so we can see some text output from the simulation initial $monitor("At time %t, count_output = %h (%0d)", $time, count_output, count_output); // create a clock running for 10 seconds high and 10 seconds low initial begin clk=0; forever #10 clk=~clk; end //exercise the inputs at suitable points in time and finish the simulation initial begin reset=1; up_down=0; #20; reset=0; #120; up_down=1; #500 $finish; end endmodule
Create a text file called up_down_counter_tb.v and paste the above code into it. Save the file in the same directory as the other verilog code already written...I used:
C:\msys64\src\Alex\ulx3s\Multiple Counters
The comments for the code should be fairly self explanatory. Now it is time to run the simulation:
Open a command prompt window and navigate to the folder:
Next type the following command:
iverilog -o up_down_counter_tb.vvp up_down_counter_tb.v
The command creates an iverilog simulation file with a vvp extension from our test bench code.
Next type the command:
vvp up_down_counter_tb.vvp
You should see the following output:
A file test.vcd has been created and we can now use this to look at the results of the simulation using a piece of software called GTKWave...
Type the following command:
gtkwave test.vcd
The GTKWave program should load:
Click on the module in the SST box in the top left corner to add the signals:
Double click on each signal to display it's simulated waveform:
Click on the magnifying glass icons to expand the traces to see the output!
Our code works! We can see that while the reset is high no counting occurs. When the reset is low and up_down is low the count increases, when up_down is high the count reduces...
Simulation is a very useful tool to check that the code we have written works as intended...Lets get on with writing the top module code to complete what we set out to do in the first place. It will be quite similar to the test bench code already written.
Create a text file called top.v and save it in the same folder as the other files:
C:\msys64\src\Alex\ulx3s\Multiple Counters
Here comes the code:
module top( input clk_25mhz, // 25 MHz clock input output [3:0] led, // 4 Bit LED Output register output wifi_gpio0 // Output for Wifi enable ); //internal signals reg [24:0] counter_one_output; // Register for the first counter output reg reset_counter_one; // Register for the reset on the first counter reg up_down_counter_one=0; // Register for the up_down on the first counter reg [24:0] counter_two_output; // Register for the second counter output reg reset_counter_two; // Register for the reset on the second counter reg up_down_counter_two=0; // Register for the up_down on the second counter reg [24:0] counter_three_output; // Register for the third counter output reg reset_counter_three; // Register for the reset on the third counter reg up_down_counter_three=0; // Register for the up_down on the third counter reg [24:0] counter_four_output; // Register for the fourth counter output reg reset_counter_four; // Register for the reset on the fourth counter reg up_down_counter_four=0; // Register for the up_down on the fourth counter //first counter module instantiation up_down_counter one_sec_counter( .clk(clk_25mhz), .reset(reset_counter_one), .up_down(up_down_counter_one), .count_output(counter_one_output) ); //second counter module instantiation up_down_counter half_sec_counter( .clk(clk_25mhz), .reset(reset_counter_two), .up_down(up_down_counter_two), .count_output(counter_two_output) ); //third counter module instantiation up_down_counter quarter_sec_counter( .clk(clk_25mhz), .reset(reset_counter_three), .up_down(up_down_counter_three), .count_output(counter_three_output) ); //fourth counter module instantiation up_down_counter eighth_sec_counter( .clk(clk_25mhz), .reset(reset_counter_four), .up_down(up_down_counter_four), .count_output(counter_four_output) ); // initial settings // resets all high to start counts at same time // up_down all low to ensure we count up not down initial begin reset_counter_one = 1; reset_counter_two = 1; reset_counter_three = 1; reset_counter_four = 1; up_down_counter_one = 0; up_down_counter_two = 0; up_down_counter_three = 0; up_down_counter_four = 0; end always @(posedge clk_25mhz) // react on the positive clock edge begin //counter one set to count for one second if (counter_one_output == 25000000) // If the count register has reached 25 million begin led[0] <= ~led[0]; // toggle the LED[0] reset_counter_one = 1; // set counter one back to zero end else reset_counter_one = 0; // allow counter one to continue //counter two set to count for 0.5 seconds if (counter_two_output == 12500000) // If the count register has reached 12.5 million begin led[1] <= ~led[1]; // toggle the LED[1] reset_counter_two = 1; // set counter two back to zero end else reset_counter_two = 0; // allow counter two to continue //counter three set to count for 0.25 seconds if (counter_three_output == 6250000) // If the count register has reached 6.25 million begin led[2] <= ~led[2]; // toggle the LED[2] reset_counter_three = 1; // set counter three back to zero end else reset_counter_three = 0; // allow counter three to continue //counter four set to count for 0.125 seconds if (counter_four_output == 3125000) // If the count register has reached 3.125 million begin led[3] <= ~led[3]; // toggle the LED[0] reset_counter_four = 1; // set counter four back to zero end else reset_counter_four = 0; // allow counter four to continue end assign wifi_gpio0 = 1'b1; //set the wifi_gpio High endmodule
Copy and paste the above code into top.v and save it in the same directory as before.
Hopefully the code is fairly easy to understand...Here are the critical sections:
module top( input clk_25mhz, // 25 MHz clock input output [3:0] led, // 4 Bit LED Output register output wifi_gpio0// Output for Wifi enable );
The first part is the module statement with the inputs and the outputs - this module is called top because it is the top module and it has a clock input, an eight bit register called led and a single bit output for the wifi enable.
//internal signals reg [24:0] counter_one_output; // Register for the first counter output reg reset_counter_one; // Register for the reset on the first counter reg up_down_counter_one=0; // Register for the up_down on the first counter
The above section details the internal signals that are needed to be passed to and from the up_down counter
module:
A 24 bit counter register is needed to take and store the output from the up_down counter module
A reset register is needed to set the reset input inside the up_down counter module
An up_down_counter register is needed to set the up_down input inside the up_down counter module
This is repeated four times as there are four counter modules instantiated. The code for instantiating the module is below:
up_down_counter one_sec_counter( .clk(clk_25mhz), .reset(reset_counter_one), .up_down(up_down_counter_one), .count_output(counter_one_output) );
The above code works like this:
Make a counter from the code already written in up_down_counter.v - call it one_sec_counter
connect the clk input inside up_down_counter.v to clk_25mhz (the main clock source on the board)
connect the reset input inside up_down_counter.v to the internal register reset_counter_one
connect the up_down input inside up_down_counter.v to the internal register up_down_counter_one
connect the count_output output inside up_down_counter to the internal register counter_one_output
Because we want the reset and up_down inputs to react at the same time we set them initially:
initial BEGIN reset_counter_one = 1; reset_counter_two = 1; reset_counter_three = 1; reset_counter_four = 1; up_down_counter_one = 0; up_down_counter_two = 0; up_down_counter_three = 0; up_down_counter_four = 0; END
Finally we have the code which makes the FPGA react when the counters have reached a defined count:
always @(posedge clk_25mhz) // react on the positive clock edge begin //counter one set to count for one second if (counter_one_output == 25000000) // If the count register has reached 25 million begin led[0] <= ~led[0]; // toggle the LED[0] reset_counter_one = 1; // set counter one back to zero end else reset_counter_one = 0; // allow counter one to continue
When counter one has reached twenty-five million (one second) toggle led[0] to its alternative state, reset the count
If counter one hasn't reached twenty-five million don't reset the count...
Why twenty-five million? Well....25 MHz is the external clock frequency...that means the external clock oscillates twenty-five million times per second so if we want a count every second we need to count twenty-five million clock edges...
Lets upload the code to the board - fire up ConEmu.exe (Windows) and navigate to the folder:
C:\msys64\src\Alex\ulx3s\Multiple Counters
Remember that the board I'm working with has an ECP5 45F Lattice Semiconductor FPGA so the commands are tailored to it. If you are working with a ECP5 12F board or an ECP5 85F board you will need to change to commands appropriately:
Type the following command into the console:
apio build --board ulx3s-45f
Ignore the warnings ;)
Make sure you have the ULX3S development board connected via USB!
Now lets upload the bitstream to the ULX3S development board:
apio upload --board ulx3s-45f
Finally clean up the directory:
apio clean
If all went according to plan you should see the leds on the ULX3S board flashing!
Well...that was a lot of work! Apologies for the really long post. There was a lot to get through! Next post will be something simple and more fun hopefully!
Cheers for now - Langster!