Verilog Clock Pulse - verilog

I have 2 clocks, fast clock and slow clock. I am trying to make a clock pulse trigger by the rising edge of the slow clock, with duration of 1 fast clock cycle. I have managed to create similar as shown, but this is using an arbitrary counter, and I need to guarantee it will happen on the rising edge of the slow clock.
Ideas appreciated.
module clock_check;
reg clk18M = 1'b0;
always #1 clk18M <= ~clk18M;
wire clk6M;
wire clk_puls;
reg [4:0] clk18div = 5'b00000;
always #( posedge clk18M ) clk18div <= clk18div+5'd1;
assign clk6M = clk18div[4];
assign clk_puls = clk18div[4:0]==5'b10000;
initial
begin
#200;
$finish();
end
initial
begin
$dumpfile("dump.vcd");
$dumpvars(0);
end
endmodule

I think this will do what you need.
It has two outputs, choose which one is best suited for your need.
Output LED1 is optimised to keep the latency and jitter of the rising edge as low as possible.
The other output sacrifices latency and jitter for keeping the pulse width constant.
I don't think there is a way that can guarantee both low latency and constant pulse width.
This of course is assuming your two clock signals are not synchronised. If they are then that problem goes away.
It will cope with variations in frequency of the clocks as there is nothing like the arbitrary counter you wanted to get rid of.
With some small modifications you can change the pulse with between being equal to the period of the fast clock or half of it.
The PLL in the code is just a stand in for the clock signals you have, which I'm assuming are some external signal.
Here I deliberately made the two clocks not be exact multiples so I would have a different delay between the rising edges on each cycle to set a worst case scenario.
For that reason I set the two clocks at 25MHz and 2.4MHz respectively.
The 400MHz clock is just for the SignalTap analyzer, to give it a much higher sampling rate than the signals it is recording.
module Cyclone5FirstTest
(
input clk50MHz,
output LED1,
output LED2,
output fClock,
output sClock,
output refClock
);
reg prevState1;
reg prevState2;
reg pulseOut;
wire fastClock;
wire slowClock;
assign fClock = fastClock;
assign sClock = slowClock;
assign LED1 = ( sClock==1 && prevState1==0 );
assign LED2 = ( prevState1==1 && prevState2==0);
PLL_1 PLL_1
(
.refclk (clk50MHz),
.outclk_0 (fastClock), // 25MHz
.outclk_1 (slowClock), // 2.4MHz
.outclk_2 (refClock) // 400 MHz - clock for logic analyzer
);
always #(posedge fastClock)
begin
if ( slowClock & !prevState2 ) pulseOut <= 1;
else pulseOut <= 0;
prevState1 <= slowClock;
prevState2 <= prevState1;
end
endmodule
SignalTap trace

Related

ice40 clock delay, output timing analysis

I have an ice40 that drives the clock and data inputs of an ASIC.
The ice40 drives the ASIC's clock with the same clock that drives the ice40's internal logic. The problem is that the rising clock triggers the ice40's internal logic and changes the ice40's data outputs a few nanoseconds before the rising clock reaches the ASIC, and therefore the ASIC observes the wrong data at its rising clock.
I've solved this issue by using an inverter chain to delay the ice40's internal clock without delaying the clock driving the ASIC. That way, the rising clock reaches the ASIC before the ice40's data outputs change. But that raises a few questions:
Is my strategy -- using an inverter chain to delay the ice40 internal clock -- a good strategy?
To diagnose the problem, I used Lattice's iCEcube2 to analyze the min/max delays between the internal clock and output pins:
Notice that the asic_dataX delays are shorter than the clk_out delay, indicating the problem.
Is there a way to get this information from yosys/nextpnr?
Thank you for any insight!
Instead of tinkering with the delays I would recommend to use established techniques. For example SPI simple clocks the data on the one edge and changes them on the other: .
The logic to implement that is rather simple. Here an example implementation for an SPI slave:
module SPI_slave #(parameter WIDTH = 6'd16, parameter phase = 1'b0,
parameter polarity = 1'b0, parameter bits = 5) (
input wire rst,
input wire CS,
input wire SCLK,
input wire MOSI,
output reg MISO,
output wire data_avbl,
input wire [WIDTH-1:0] data_tx,
output reg [WIDTH-1:0] data_rx
);
reg [bits:0] bitcount;
reg [WIDTH-1:0] buf_send;
assign clk = phase ^ polarity ^ SCLK;
assign int_rst = rst | CS;
assign tx_clk = clk | CS;
assign data_avbl = bitcount == 0;
always #(negedge tx_clk or posedge rst) begin
MISO <= rst ? 1'b0 : buf_send[WIDTH-1];
end
always #(posedge clk or posedge int_rst) begin
if (int_rst) begin
bitcount <= WIDTH;
data_rx <= 0;
buf_send <= 0;
end else begin
bitcount <= (data_avbl ? WIDTH : bitcount) - 1'b1;
data_rx <= { data_rx[WIDTH-2:0], MOSI };
buf_send <= bitcount == 1 ? data_tx[WIDTH-1:0] : { buf_send[WIDTH-2:0], 1'b0};
end
end
endmodule
As one can see the data are captured at the positive edge and changed on the negative edge. If one wants to avoid the mixing of edge sensistivies a doubled clock can be used instead.

Number of transitions in a wave in verilog

How do I find the number of transitions in a square wave in one time period? Edge detection might miss out edges so the number of transitions using Verilog?
Unless I have misunderstood, it sounds like you are trying to detect a signal with a data rate that is faster than your clock. If this is the case then it is not possible. You are basically seeing a glorified version of aliasing.
If, however your clock is faster than the signal you are trying to detect edges in then something like this should work:
module Edge_Counter(
// Inputs
input Clock, // System Clock
input Reset, // System Reset
input Enable, // Enables the detection of edges
input Signal_In, // Monitored signal
// Outputs
output reg [7:0] Edge_Count // Number of edges in monitored signal while enabled
);
reg [1:0] Next_Edge_Detection, Edge_Detection;
reg [7:0] Next_Edge_Count;
always #( posedge Clock, posedge Reset ) begin
if ( Reset ) begin
Edge_Detection <= 2'd0;
Edge_Count <= 8'd0;
end else begin
Edge_Detection <= Next_Edge_Detection;
Edge_Count <= Next_Edge_Count;
end
end
always # * begin
Next_Edge_Detection = { Edge_Detection[0], Signal_In };
Next_Edge_Count = Edge_Count;
if ( Enable ) begin
if ( Edge_Detection[0] != Edge_Detection[1] )
Next_Edge_Count = Edge_Count + 1'd1;
end
end
endmodule
Also, as a side note, if you are just starting out with Verilog and your tools support use of System Verilog I would strongly recommend reading up on it and giving it a try. It will let fewer latches and other errors in your code fall through the system.

How to generate delay in verilog for synthesis?

I Want to Design a Verilog code for Interfacing 16*2 LCD. As in LCD's to give "command" or "data" we have to give LCD's Enable pin a "High to low Pulse " pulse that means
**E=1;
Delay();//Must be 450ns wide delay
E=0;**
This the place where I confuse I means in Verilog for synthesis # are not allowed so how can I give delay here I attached my code below. It must be noted that I try give delay in my code but I think delay not work so please help me to get rid of this delay problem......
///////////////////////////////////////////////////////////////////////////////////
////////////////////LCD Interfacing with Xilinx FPGA///////////////////////////////
////////////////////Important code for 16*2/1 LCDs/////////////////////////////////
//////////////////Coder-Shrikant Vaishnav(M.Tech VLSI)/////////////////////////////
///////////////////////////////////////////////////////////////////////////////////
module lcd_fpgashri(output reg [7:0]data,output reg enb,output reg rs,output reg rw ,input CLK);
reg [15:0]hold;
reg [13:0]count=0;
//Code Starts from here like C's Main......
always#(posedge CLK)
begin
count=count+1; //For Delay
//For LCD Initialization
lcd_cmd(8'b00111000);
lcd_cmd(8'b00000001);
lcd_cmd(8'b00000110);
lcd_cmd(8'b00001100);
//This is a String "SHRI" that I want to display
lcd_data(8'b01010011);//S
lcd_data(8'b01001000);//H
lcd_data(8'b01010010);//R
lcd_data(8'b01001001);//I
end
//Task For Command
task lcd_cmd(input reg [7:0]value);
begin
data=value;
rs=1'b0;
rw=1'b0;
enb=1'b1; //sending high to low pulse
hold=count[13]; //This is the place where I try to design delay
enb=1'b0;
end
endtask
//Task for Data
task lcd_data(input reg [7:0]value1);
begin
data=value1;
rs=1'b1;
rw=1'b0;
enb=1'b1; //sending high to low pulse
hold=count[13]; //This is the place where I try to design delay
enb=1'b0;
end
endtask
endmodule
You seem to be stuck in a software programming mindset based on your code, you're going to have to change things around quite a bit if you want to actually describe a controller in HDL.
Unfortunately for you there is no way to just insert an arbitrary delay into a 'routine' like you have written there.
When you write a software program, it is perfectly reasonable to write a program like
doA();
doB();
doC();
Where each line executes one at a time in a sequential fashion. HDL does not work in this way. You need to not think in terms of tasks, and start thinking in terms of clocks and state machines.
Remember that when you have an always block, the entire block executes in parallel on every clock cycle. When you have a statement like this in an always block:
lcd_cmd(8'b00111000);
lcd_cmd(8'b00000001);
lcd_cmd(8'b00000110);
lcd_cmd(8'b00001100);
This does you no good, because all four of these execute simultaneously on positive edge of the clock, and not in a sequential fashion. What you need to do is to create a state machine, such that it advances and performs one action during a clock period.
If I were to try to replicate those four lcd_cmd's in a sequential manner, it might look something like this.
always #(posedge clk)
case(state_f)
`RESET: begin
state_f <= `INIT_STEP_1;
data = 8'b00111000;
end
`INIT_STEP_1: begin
state_f <= `INIT_STEP_2;
data = 8'b00000001;
end
`INIT_STEP_2: begin
state_f <= `INIT_STEP_3;
data = 8'b00000110;
end
`INIT_STEP_3: begin
state_f <= `INIT_STEP_4;
data =8'b00111000;
end
`INIT_STEP_4: begin
state_f <= ???; //go to some new state
data = 8'b00000110;
end
endcase
end
Now with this code you are advancing through four states in four clock cycles, so you can start to see how you might handle writing a sequence of events that advances on each clock cycle.
This answer doesn't get you all of the way, as there is no 'delay' in between these as you wanted. But you could imagine having a state machine where after setting the data you move into a DELAY state, where you could set a counter which counts down enough clock cycles you need to meet your timing requirements before moving into the next state.
The best way to introduce delay is to use a counter as Tim has mentioned.
Find out how many clock cycles you need to wait to obtain the required delay (here 450ns) w.r.t your clock period.
Lets take the number of clock cycles calculated is count. In that case the following piece of code can get you the required delay. You may however need to modify the logic for your purpose.
always # (posedge clk) begin
if (N == count) begin
N <= 0;
E = ~E;
end else begin
N <= N +1;
end
end
Be sure to initialize N and E to zero.
Check the clock frequency of your FPGA board and initialize a counter accordingly. For example, if you want a delay of 1 second on an FPGA board with 50MHz clock frequency, you will have to write a code for a counter that counts from 0 to 49999999. Use the terminalCLK as clk for your design. Delayed clock input will put a delay to your design. The psuedo code for that will be:
module counter(count,terminalCLK,clk)
parameter n = 26, N = 50000000;
input clk;
output reg [n-1:0] count;
output reg terminalCLK;
always#(posedge clk)
begin
count <= count + 1;
if (count <= N/2)
terminalCLK <= ~terminalCLk;
if (count == N)
terminalCLK <= ~terminalCLk;
end

Why use this 2 DFF method every time a button press is involved?

I have been reading verilog code online and have noticed this in many of the code examples. Whenever an input is needed from a hardware source such as a button press, the input is copied to a flip flop and then AND'd with the invert of the input. I dont know if this made much sense but in code here it is:
input btn;
reg dff1, dff2;
wire db_tick;
always # (posedge clock) dff1 <= btn;
always # (posedge clock) dff2 <= dff1;
assign db_tick = ~dff1 & dff2;
And then db_tick is used as the button press.
In some cases this is also used as a rising edge detector, but cant a rising edge detector easily be implemented with always#(posedge signal)
It's called a monostable multivibrator or, specifically for digital circuits, a one-shot. The purpose of the circuit is to change an edge into a single cycle pulse.
When connected directly to a physical switch it can be a way to effect switch debouncing, but that's not really a good use for it. It's hard to say what the intent is in the code without more context.
This is providing edge detection synchronous to your clock domain. I do not see any debouncing happing here, it is quite common to also include 2 meta stability flip flops before the edge detection.
input a;
reg [2:0] a_meta;
always #(posedge clk or negedge rst_n) begin
if (~rst_n) begin
a_meta <= 3'b0 ;
end
else begin
a_meta <= {a_meta[1:0], a};
end
end
// The following signals will be 1 clk wide, Clock must be faster than event rate.
// a[2] is the oldest data,
// if new data (a[1]) is high and old data low we have just seen a rising edge.
wire a_sync_posedge = ~a_meta[2] & a_meta[1];
wire a_sync_negedge = a_meta[2] & ~a_meta[1];
wire a_sync_anyedge = a_meta[2] ^ a_meta[1]; //XOR

How to put a 2 sec counter in a for loop

I want to have a 2 sec counter in my for loop such that there is a gap of 2 seconds between every iteration.I am trying to have a shifting LEDR Display
Code:
parameter n =10;
integer i;
always#(*)
begin
for(i=0;i<n;i=i+1)
begin
LEDR[i]=1'b1;
//2 second counter here
end
end
What is your desired functionality? I assume: shifting which LED is on every 2 seconds, keeping all the other LEDs off? "Sliding LED"...
Also, I am assuming your target is an FPGA-type board.
There is no free "wait for X time" in the FPGA world. The key to what you are trying to do it counting clock cycles. You need to know the clock frequency of the clock that you are using for this block. Once you know that, then you can calculate how many clock rising edges you need to count before "an action" needs to be taken.
I recommend two processes. In one, you will watch rising edge of clock, and run a counter of sufficient size, such that it will roll over once every two seconds. Every time your counter is 0, then you set a "flag" for one clock cycle.
The other process will simply watch for the "flag" to occur. When the flag occurs, you shift which LED is turned on, and turn all other LEDs off.
I think this module implements what Josh was describing. This module will create two registers, a counter register (counter_reg) and a shift register (leds_reg). The counter register will increment once per clock cycle until it rolls over. When it rolls over, the "tick" variable will be equal to 1. When this happens, the shift register will rotate by one position to the left.
module led_rotate_2s (
input wire clk,
output wire [N-1:0] leds,
);
parameter N=10; // depends on how many LEDs are on your board
parameter WIDTH=<some integer>; // depends on your clock frequency
localparam TOP=<some integer>; // depends on your clock frequency
reg [WIDTH-1:0] counter_reg = 0, counter_next;
reg [N-1:0] leds_reg = {{N-1{1'b0}}, 1'b1}, leds_next;
wire tick = (counter_reg == 0);
assign leds = leds_reg;
always #* begin : combinational_logic
counter_next = counter_reg + 1'b1;
if (counter_next >= TOP)
counter_next = 0;
leds_next = leds_reg;
if (tick)
leds_next = {leds_reg[N-2:0], leds_reg[N-1]}; // shift register
end
always #(posedge clk) begin : sequential_logic
counter_reg <= counter_next;
leds_reg <= leds_next;
end
endmodule

Resources