Frequency divisor in verilog - verilog

i need a frequency divider in verilog, and i made the code below. It works, but i want to know if is the best solution, thanks!
module frquency_divider_by2 ( clk ,clk3 );
output clk3 ;
reg clk2, clk3 ;
input clk ;
wire clk ;
initial clk2 = 0;
initial clk3 = 0;
always # (posedge (clk)) begin
clk2 <= ~clk2;
end
always # (posedge (clk2)) begin
clk3 <= ~clk3;
end
endmodule
the circuit generated by quartus:

Your block divides the frequency by 4 not 2. There is actually quite a good description of this on Wikipedia Digital Dividers. Your code can be tidied up a bit but only 1 D-Type is required, which is smaller than a JK Flip-flop so is optimal.
module frquency_divider_by2(
input rst_n,
input clk_rx,
output reg clk_tx
);
always # (posedge clk_rx) begin
if (~rst_n) begin
clk_tx <= 1'b0;
end
else begin
clk_tx <= ~clk_tx;
end
end
endmodule
When chaining these types of clock dividers together be aware that there is a clk to q latency which is compounded every time you go through one of these dividers. IF this is not managed correctly by synthesis the clocks can not be considered synchronous.
Example on EDAplayground, should open the waveform when run.

Related

A simple clock divider module

I am asked to design simple clock divider circuit for different types of inputs.
I have a enabler [1:0] input and an input clock, and an output named clk_enable.
If enabler=01 then my input clock should be enabled once in 2 clock signals.If enabler=10 then my input should be divided by 4 etc.
I managed to divide my input clock for different cases with using case keyword but for enabler=00 my input clock should be equal to my output clk_enable which i could not manage to do it.
Here is what i tried. I am asking a help for the enabler=00 situation.
module project(input [1:0] enabler,
input clock,
output reg clk_enable);
reg [3:0] count,c;
initial begin
count=4'b0000;
c=4'b0000;
end
always #( posedge clock)
case(enabler)
2'b00:clk_enable<=clock;
2'b01:clk_enable<=~clk_enable;
2'b10:begin
if (count >= 4'b0100-1)
count<=4'b0000;
else begin
count<=count + 4'b0001;
clk_enable<=(count<(4'b0100 / 2));
end
end
2'b11: begin
if (count >= 4'b1000-1)
count<=4'b0000;
else begin
count<=count + 4'b0001;
clk_enable<=(count<(4'b1000 / 2));
end
end
endcase
endmodule
This will generate gated pulsed clock with posedge rate matching the div_ratio input.
div_ratio output
0 div1 clock (clk as it is)
1 div2 (pulse every 2 pulses of clk)
2 div3
3 div4
This is usually preferable when sampling at negedge of divided clock is not needed
If you need 50% duty cycle I can give you another snippet
module clk_div_gated (
input [1:0] div_ratio,
input clk,
input rst_n, // async reset - a must for clock divider
output clk_div
);
reg [1:0] cnt;
reg clk_en;
always #(posedge clk or negedge rst_n)
if (~rst_n)
cnt <= 2'h0;
else
cnt <= (cnt == div_ratio)? 2'h0 : cnt + 1'b1;
// clk_en toggled at negedge to prevent glitches on output clock
// This is ok for FPGA, synthesizeable ASIC design must use latch + AND method
always #(negedge clk)
clk_en <= (cnt == div_ratio);
assign clk_div <= clk & clk_en;
endmodule
This looks like you have a strong background in software development? :)
My suggestion is that you always make a clean cut between combinational and sequential logic. This includes some thoughts on what part of the design actually has to be sequential and what can be combinational.
For your case, the clock division clearly has to be sequential, since you want to invert the generated CLK signal (frequency f/2, case 0'b01) at each positive edge of the incoming CLK signal (frequency f, case 0'b00). Same is valid for f/4 (case 0'b10).
This part needs to be sequential, since you want to invert the previous CLK state...this would cause a cmobinational loop if realized in combinational logic. So triggering on a CLK edge is really necessary here.
However, the actual selection of the correct CLK output signal can be combinational. You just want to assign the correct CLK signal to the output CLK.
An implementation of the sequential part could look like:
// frequency division from input CLK --> frequency: f/2
always #(posedge clk or negedge rst_neg) begin
if (rst_neg = 1'b0) begin
clk_2 <= 1'b0;
end else begin
clk_2 <= ~clk_2;
end
end
// frequency division from first divided CLK --> frequency: f/4
always #(posedge clk_2 or negedge rst_neg) begin
if (rst_neg = 1'b0) begin
clk_ 4 <= 1'b0;
end else begin
clk_4 <= ~clk_4;
end
end
// frequency division from first divided CLK --> frequency: f/8
always #(posedge clk_4 or negedge rst_neg) begin
if (rst_neg = 1'b0) begin
clk_ 8 <= 1'b0;
end else begin
clk_8 <= ~clk_8;
end
end
So this plain sequential logic takes care of generating the divided CLK signals of f/2 and f/4 that you need. I also included reset signals on negative edge, which you usually need. And you spare the counter logic (increments and comparison).
Now we take care of the correct selection with plain combinational logic:
always #(*) begin
case(enabler)
2'b00: clk_enable = clk;
2'b01: clk_enable = clk_2;
2'b10: clk_enable = clk_4;
2'b11: clk_enable = clk_8;
endcase
end
This is quite close to your hardware description (clk_enable needs to be a reg here).
However, another way for the combinational part would be the following (declare clk_enable as wire):
assign clk_enable = (enabler == 2'b00) ? clk
: (enabler == 2'b01) ? clk_2
: (enabler == 2'b10) ? clk_4
: (enabler == 2'b11) ? clk_8;

Verilog, Parallel in Series out Shift Register

I am learning and practicing Verilog HDL. I wanted to design a 16 bit parallel in series out shift register.
module verilog_shift_register_test_PISO( din, clk, load, dout );
output reg dout ;
input [15:0] din ;
input clk ;
input load ;
reg [15:0]temp;
always # (clk or load) begin
if (load)
temp <= din;
else begin
dout <= temp[0];
temp <= {1'b0, temp[15:1]};
end
end
endmodule
I wrote this code and tried to simulate it.
simulation result
simulation_result
I could not understand the reason why data output (dout) signal is always LOW
It works for me.
BUT!
That code can no be turned into gates.
You must use 'posedge clk' or 'negedge clk'.
Also your load is a-synchronous which is very unusual and can
give race conditions against the clock edge.
always # (posedge clk)
begin
if (load)
temp <= din;
else
begin
dout <= temp[0];
temp <= {1'b0, temp[15:1]};
end
end
Furthermore it is usual to have a reset condition. As long as there is no 'load' signal the dout will produce X-es. This can very much upset the rest of your circuit. Also you have an extra clock delay in dout. You could, if you want, save a clock cycle there. Here its is with an a-synchronous active low reset:
always # (posedge clk or negedge reset_n)
begin
if (!reset_n)
temp <= 16'h0000;
else
if (load)
temp <= din;
else
temp <= {1'b0, temp[15:1]};
end
assign dout = temp[0];

4 bit countetr using verilog not incrementing

Sir,
I have done a 4 bit up counter using verilog. but it was not incrementing during simulation. A frequency divider circuit is used to provide necessory clock to the counter.please help me to solve this. The code is given below
module my_upcount(
input clk,
input clr,
output [3:0] y
);
reg [26:0] temp1;
wire clk_1;
always #(posedge clk or posedge clr)
begin
temp1 <= ( (clr) ? 4'b0 : temp1 + 1'b1 );
end
assign clk_1 = temp1[26];
reg [3:0] temp;
always #(posedge clk_1 or posedge clr)
begin
temp <= ( (clr) ? 4'b0 : temp + 1'b1 );
end
assign y = temp;
endmodule
Did you run your simulation for at least (2^27) / 2 + 1 iterations? If not then your clk_1 signal will never rise to 1, and your counter will never increment. Try using 4 bits for the divisor counter so you won't have to run the simulation for so long. Also, the clk_1 signal should activate when divisor counter reaches its max value, not when the MSB bit is one.
Apart from that, there are couple of other issues with your code:
Drive all registers with a single clock - Using different clocks within a single hardware module is a very bad idea as it violates the principles of synchronous design. All registers should be driven by the same clock signal otherwise you're looking for trouble.
Separate current and next register value - It is a good practice to separate current register value from the next register value. The next register value will then be assigned in a combinational portion of the circuit (not driven by the clock) and stored in the register on the beginning of the next clock cycle (check code below for example). This makes the code much more clear and understandable and minimises the probability of race conditions and unwanted inferred memory.
Define all signals at the beginning of the module - All signals should be defined at the beginning of the module. This helps to keep the module logic as clean as possible.
Here's you example rewritten according to my suggestions:
module my_counter
(
input wire clk, clr,
output [3:0] y
);
reg [3:0] dvsr_reg, counter_reg;
wire [3:0] dvsr_next, counter_next;
wire dvsr_tick;
always #(posedge clk, posedge clr)
if (clr)
begin
counter_reg <= 4'b0000;
dvsr_reg <= 4'b0000;
end
else
begin
counter_reg <= counter_next;
dvsr_reg <= dvsr_next;
end
/// Combinational next-state logic
assign dvsr_next = dvsr_reg + 4'b0001;
assign counter_next = (dvsr_reg == 4'b1111) ? counter_reg + 4'b0001 : counter_reg;
/// Set the output signals
assign y = counter_reg;
endmodule
And here's the simple testbench to verify its operation:
module my_counter_tb;
localparam
T = 20;
reg clk, clr;
wire [3:0] y;
my_counter uut(.clk(clk), .clr(clr), .y(y));
always
begin
clk = 1'b1;
#(T/2);
clk = 1'b0;
#(T/2);
end
initial
begin
clr = 1'b1;
#(negedge clk);
clr = 1'b0;
repeat(50) #(negedge clk);
$stop;
end
endmodule

Verilog code to count Number Repetition

I'm writing verilog code for an algorithm,but I have a problem with one module that receives for example:10 binary numbers (4 bits for each one)from previous module (1 input at every positive edge clk) so there are 10 clock cycles to have the 10 binary numbers.
How to Calculate the number of times each number repeats and save the frequency for each number for later use by another module using verilog hardawre language?
for example : at the end this module find 0000 twice ,0001 once,....,1111 zero. at the 10 clock cycles.
Thanks in advance...
Assuming you have a clock and active low reset:
module tracker(
input clk,
input rst_n,
input [3:0] data_rx
);
reg [7:0] count [0:15];
integer i;
always #(posedge clk, negedge rst_n) begin
if (~rst_n) begin
for(i=0; i<16, i=i+1) begin
count[i] <= 8'b0;
end
end
else begin
count[data_rx] <= count[data_rx] + 1;
end
end
endmodule
For an FPGA defaults an initial block can be used instead of the reset signal that could look like:
initial begin
for(i=0; i<16, i=i+1) begin
count[i] <= 8'b0;
end
end
always #(posedge clk) begin
count[data_rx] <= count[data_rx] + 1;
end
Note that a for loop has been used in the asynchronous reset and initial, This can be statically unrolled, there is no dynamic target so is fully synthesizable.

Circuit behaves poorly in timing simulation but alright in behavioral - new to verilog

I'm new to verilog development and am having trouble seeing where I'm going wrong on a relatively simple counter and trigger output type design.
Here's the verilog code
Note the code returns the same result whether or not the reg is declared on the output_signal without the internal_output_buffer
`timescale 1ns / 1ps
module testcounter(
input wire clk,
input wire resetn,
input wire [31:0] num_to_count,
output reg [7:0] output_signal
);
reg [31:0] counter;
initial begin
output_signal = 0;
end
always#(negedge resetn) begin
counter = 0;
end
always#(posedge clk) begin
if (counter == num_to_count) begin
counter = 0;
if (output_signal == 0) begin
output_signal = 8'hff;
end
else begin
output_signal = 8'h00;
end
end
else begin
counter = counter + 1;
end
end
assign output_signal = internal_output_buffer;
endmodule
And the code is tested by
`timescale 1ns / 1ps
module testcounter_testbench(
);
reg clk;
reg resetn;
reg [31:0] num_to_count;
wire [7:0] output_signal;
initial begin
clk = 0;
forever #1 clk = ~clk;
end
initial begin
num_to_count = 20;
end
initial begin
#7 resetn = 1;
#35 resetn = 0;
end
testcounter A1(.clk(clk),.resetn(resetn),.num_to_count(num_to_count),.output_signal(output_signal));
endmodule
Behavioral simulation looks as I expected
But the timing simulation explodes
And for good measure: the actual probed execution blows up and looks like
Any tips would be appreciated. Thanks all.
The difference between the timing and functional simulations is that a timing simulation models the actual delay of logic gates while the functional simulation just checks if values are correct.
For e.g. if you have a simple combinational adder with two inputs a and b, and output c. A functional simulation will tell you that c=a+b. and c will change in the exact microsecond that a or b changes.
However, a timing simulation for the same circuit will only show you the result (a+b) on c after some time t, where t is the delay of the adder.
What is your platform? If you are using an FPGA it is very difficult to hit 500 MHz. Your clock statement:
forever #1 clk = ~clk;
shows that you toggle the clock every 1ns, meaning that your period is 2ns and your frequency is 500MHz.
The combinational delay through FPGA resources such as lookup tables, multiplexers and wire segments is probably more than 2ns. So your circuit violates timing constraints and gives wrong behaviour.
The first thing I would try is to use a much lower clock frequency, for example 100 MHz and test the circuit again. I expect it to produce the correct results.
forever #5 clk = ~clk;
Then to know the maximum safe frequency you can run at, look at your compilation reports in your design tools by running timing analysis. It is available in any FPGA CAD tool.
Your code seems working fine using Xilinx Vivado 14.2 but there is only one error which is the following line
assign output_signal = internal_output_buffer;
You can't assign registers by using "assign" and also "internal_output_buffer" is not defined.
I also personally recommend to set all registers to some values at initial. Your variables "resetn" and "counter" are not assigned initially. Basicly change your code like this for example
reg [31:0] counter = 32'b0;
Here is my result with your code:
Your verilog code in the testcounter looks broken: (a) you're having multiple drivers, and (b) like #StrayPointer notices, you're using blocking assignments for assigning Register (Flip-Flop) values.
I'm guessing your intent was the following, which could fix a lot of simulation mismatches:
module testcounter
(
input wire clk,
input wire resetn,
input wire [31:0] num_to_count,
output reg [7:0] output_signal
);
reg [31:0] counter;
always#(posedge clk or negedge resetn) begin
if (!resetn) begin
counter <= 0;
end else begin
if (counter == num_to_count) begin
counter <= 0;
end else begin
counter <= counter + 1;
end
end
end
assign output_signal = (counter == num_to_count) ? 8'hff : 8'h00;
endmodule

Resources