Number of transitions in a wave in verilog - 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.

Related

Verilog Clock Pulse

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

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.

1second down counter with initial value verilog code

I want to write the code of 1-second down counter that get the initial value from outside and count it down till 0. but there is a problem. How can I get the initial value. i tried some ways but ....
here is the code:
module second_counter ( input clk,
input top_num,
output reg [3:0] sec_num
);
parameter clk_frequency = 25;
reg [31:0]cnt;
wire [3:0]sec;
/// how can get the top_num and count it down.
assign sec=top_num;
always #(posedge clk)
begin
if (cnt==clk_frequency)
begin
sec <= sec -1;
cnt<=0;
end
else
cnt <=cnt+1;
end
What you basically need is a reset signal. Just like clock, reset is to be added in the sensitivity list.
After instantiation of module, you must apply a reset signal to initialize all the internal variables and registers of design.
Following code gives you initial value of cnt by reset application. This is an active low reset.
module second_counter ( input clk, input reset, input top_num, output reg [3:0] sec_num );
parameter clk_frequency = 25;
reg [31:0]cnt;
// wire [3:0]sec;
reg [3:0] sec;
///
// assign sec=top_num;
always #(posedge clk, negedge reset)
begin
if(!reset)
begin
cnt<=0; // initialize all internal variables and registers
sec<=0;
end
else
begin
if(sec == 0) // latch input when previous count is completed
sec<=top_num;
if (cnt==clk_frequency)
begin
sec <= sec -1;
cnt<=0;
end
else
cnt <=cnt+1;
end
end
Note that this is an asynchronous reset, means it does not depend on clocking signal. Synchronous reset is the one which only affects the registers at the clock pulse.
Edit:
Regarding to sec, I have modified the code. Now the design latches the inputs for one clock cycle and counts down to zero. Once the counter reaches zero, it again latches the input to re-count to zero.
Note that you cannot do like latching top_num at every clock and counting through zero (since top_num can change at every pulse). For latching at every clock pulse, you need more complex logic implementation.

verilog always #(posedge) failing in uart

I'm learning verilog and I think there is something that I must not understand about always #* and always (#posedge clk, ...)
Here is a piece of code supposed to send bits via uart. It fails at synthesization.
The error is
" The logic for does not match a known FF or Latch template. The description style you are using to describe a register or latch is not supported in the current software release."
(and 3 other errors for , and )
If I change the always #(...) by always #*, things fail in the next step ("implement design") because things are not connected.
In the book that I have, they implement an fsmd with an always (posedge clk) for the state, and always #* for the other logic, but I don't understand why this doesn't work.
On another forum, I read that the error could come from too complicated conditions. But I have simplified things too (not code the code here but basically I removed the case(state) and the ifs to have single line assignments with ? : or binary conditions, but it didn't work either)
I have seen this error before in other pieces of code that I wrote but I didn't get to the bottom of it, so if you could help me understand the general problem (with this uart thing as a support for a concrete example), I would be very happy.
Thanks
Thomas
P.S : Im using xilinx spartan 3e starter kit and xilinx ise 14.4
module UART_out #(parameter [3:0] NUM_BITS = 8)
(
input wire baud_clk,
input wire send_tick,
input wire[NUM_BITS-1:0] data_in,
output wire tx,
output wire debug_done
);
localparam
IDLE = 0,
TRANSMIT = 1;
reg[NUM_BITS:0] bits_to_send;
reg state;
reg out_bit;
reg[4:0] cnt;
always #(posedge baud_clk, posedge send_tick)
begin
case (state)
IDLE:
if (send_tick)
begin
bits_to_send <= {data_in, 0};
state <= TRANSMIT;
cnt <= 0;
end
TRANSMIT:
begin
if (cnt < NUM_BITS)
cnt <= cnt + 1;
else
state <= IDLE;
bits_to_send <= {1, bits_to_send[NUM_BITS:1]};
out_bit <= bits_to_send[0];
end
endcase
end
assign tx = (state == IDLE ? 1 : out_bit);
assign debug_done = (state == IDLE);
endmodule
The error:
The logic for does not match a known FF or Latch template. The description style you are using to describe a register or latch is not supported in the current software release.
Is referring to the fact that the synthesis tool does not have any hardware cells to use which match your description.
What hardware do you want from :
always #(posedge baud_clk, posedge send_tick)
This looks like you want a flip-flop with an enable signal. The enable signal (send_tick) should be 1 clock period wide. This is then used to select the path of logic on a clock edge. not as an alternative trigger.
I think that this is all you really need:
always #(posedge baud_clk) begin
case (state)
IDLE:
if (send_tick) begin
//...
end
//...
endcase
end
If send_tick is from another clock domain then you will need to do some clock domain crossing to turn it it to a clock wide pulse on the baud_clk.
You may be getting confused with blocks which have multiple triggers, they are normally a clk and reset. A negedge reset_n or posedge reset are often added for reset (initialisation) conditions.
If adding a reset :
always #(posedge baud_clk or negedge reset_n) begin
if (~reset_n) begin
//reset conditions
state <= IDLE;
//...
end
else begin
// Standard logic
end
end
You will notice that there is a very definite structure here, if reset else ... The synthesis tools recognise this as a flip-flop with an asynchronous reset. The data in the reset condition is also static, typically setting everything to zero.

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

Resources