How to put a 2 sec counter in a for loop - verilog

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

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

How to find middle point between 2 pulses in Verilog in an FPGA?

I'm trying to find the mid-point between hsync pulses in a video stream. There are many "pixel clocks" in between hsync pulses. How can I get a pulse or signal exactly at the midpoint between two hsync pulses? Basically I want to be able to find the horizontal center of the screen. Here is what I have:
reg [30:0] count;
reg [30:0] counter;
wire left;
always #(posedge pixclk)
begin
if (hsync == 1'b1)
begin
count = counter;
counter = 1'b0;
end
else
begin
counter = counter + 1;
end
end
assign left = (counter < (count / 2) ? 1'b1 : 1'b0);
First, I don't know if this is conceptually the right way to do this.
Second, if hsync is held low for more than one pixclk cycle, then count will always be zero. It will only work if the width of hsync pulse is exactly one clock cycle or less.
First: You should use non-blocking assignments in a clocked section. <=
In your case you tell me that you have an hsync which is longer then your pixel clock.
One way is to count pulses when the hsync is low and store the result when it is high. That would require a small two-state Fine-State-Machine (FSM)
However I personally find making Fine-State-Machines a burden to be avoided. So here is what I would do:
Detect the edge of the hysnc (when it goes high or when it goes low) and count between the edges. Here is the core of the code:
reg hsync_one_cycle_delayed;
always #(posedge pixclk)
begin
hsync_one_cycle_delayed <= hsync;
if (hsync==1'b1 && hsync_one_cycle_delayed==1'b0)
// We have a detected a rising edge on hsync
begin
count <= counter;
counter <= 31'h0;
end
else
counter <= counter + 1;
end
Some final notes:
It assume the hsync is synchronous to the pixel clock.
This code has no reset which seems to become the norm in FPGA code, but which I personally deplore.

How to program a delay in Verilog?

I'm trying to make a morse code display using an led. I need a half second pulse of the light to represent a dot and a 1.5 second pulse to represent a dash.
I'm really stuck here. I have made a counter using an internal 50MHz clock on my FPGA. The machine I have to make will take as input a 3 bit number and translate that to a morse letter, A-H with A being 000, B being 001 and so on. I just need to figure out how to tell the FPGA to keep the led on for the specified time and then turn off for about a second (that would be the delay between a dot pulse and a dash pulse).
Any tips would be greatly appreciated.
Also, it has to be synthesizable.
Here is my code. It's not functioning yet. The error message it keeps giving me is:
Error (10028): Can't resolve multiple constant drivers for net "c3[0]"
at part4.v(149)
module part4 (SELECT, CLK, CLOCK_50, RESET, led);
input [2:0]SELECT;
input RESET, CLK, CLOCK_50;
output reg led=0;
reg [26:0] COUNT=0; //register that keeps track of count
reg [1:0] COUNT2=0; //keeps track of half seconds
reg halfsecflag=0; //goes high every time half second passes
reg dashflag=0; //goes high every time 1 and half second passes
reg [3:0] code; //1 is dot and 0 is dash. There are 4 total
reg [1:0] c3; //keeps track of the index we are on in the code.
reg [3:0] STATE; //register to keep track of states in the state machine
reg done=0; //a flag that goes up when one morse pulse is done.
reg ending=0; //another flag that goes up when a whole morse letter has flashed
reg [1:0] length; //This is the length of the morse letter. It varies from 1 to 4
wire i; // if i is 1, then the state machine goes to "dot". if 0 "dash"
assign i = code[c3];
parameter START= 4'b000, DOT= 4'b001, DASH= 4'b010, DELAY= 4'b011, IDLE=
4'b100;
parameter A= 3'b000, B=3'b001, C=3'b010, D=3'b011, E=3'b100, F=3'b101,
G=3'b110, H=3'b111;
always #(posedge CLOCK_50 or posedge RESET) //making counter
begin
if (RESET == 1)
COUNT <= 0;
else if (COUNT==8'd25000000)
begin
COUNT <= 0;
halfsecflag <= 1;
end
else
begin
COUNT <= COUNT+1;
halfsecflag <=0;
end
end
always #(posedge CLOCK_50 or posedge RESET)
begin
if (RESET == 1)
COUNT2 <= 0;
else if ((COUNT2==2)&&(halfsecflag==1))
begin
COUNT2 = 0;
dashflag=1;
end
else if (halfsecflag==1)
COUNT2= COUNT2+1;
end
always #(RESET) //asynchronous reset
begin
STATE=IDLE;
end
always#(STATE) //State machine
begin
done=0;
case(STATE)
START: begin
led = 1;
if (i) STATE = DOT;
else STATE = DASH;
end
DOT: begin
if (halfsecflag && ~ending) STATE = DELAY;
else if (ending) STATE= IDLE;
else STATE=DOT;
end
DASH: begin
if ((dashflag)&& (~ending))
STATE = DELAY;
else if (ending)
STATE = IDLE;
else STATE = DASH;
end
DELAY: begin
led = 0;
if ((halfsecflag)&&(ending))
STATE=IDLE;
else if ((halfsecflag)&&(~ending))
begin
done=1;
STATE=START;
end
else STATE = DELAY;
end
IDLE: begin
c3=0;
if (CLK) STATE=START;
else STATE=IDLE;
end
default: STATE = IDLE;
endcase
end
always #(posedge CLK)
begin
case (SELECT)
A: length=2'b01;
B: length=2'b11;
C: length=2'b11;
D: length=2'b10;
E: length=2'b00;
F: length=2'b11;
G: length=2'b10;
H: length=2'b11;
default: length=2'bxx;
endcase
end
always #(posedge CLK)
begin
case (SELECT)
A: code= 4'b0001;
B: code= 4'b1110;
C: code= 4'b1010;
D: code= 4'b0110;
E: code= 4'b0001;
F: code= 4'b1011;
G: code= 4'b0100;
H: code= 4'b1111;
default: code=4'bxxxx;
endcase
end
always #(posedge CLK)
begin
if (c3==length)
begin
c3<=0; ending=1;
end
else if (done)
c3<= c3+1;
end
endmodule
I have been reading your code and there are many issues:
The code is not formatted.
You did not provide a test-bench. Did you write one?
"Can't resolve multiple constant drivers for net" Search on stack exchange for the error message. It has been asked many times.
Use always #(*) not e.g. always #(STATE) you are missing signals like i, halfsecflag, ending. But see point 6: You want the STATE in a clocked section.
Where you use always #(posedge CLK) you must use non-blocking assignments: <=.
There are many places where you use always #(posedge CLK) where you want to use always #(*) (e.g. where you set length and code) Opposite you want to use a posedge CLK where you work with your STATE.
Use one clock and one clock only. Do not use CLK and CLOCK_50. Use either one or the other.
Take care of your vector sizes. This 8'd25000000 is wrong as you can no fit 25000000 in 8 bits.
Your usage of halfsecflag is excellent! I have see many times where people think they can use always #(halfsecflag) which is a recipe for disaster!
Below you find a small piece of your code which I have re-written.
All assignments are non-blocking <=
halfsecflag is essential to operate the code only every half a second, so I put that by itself in a separate if at the top. I would use that throughout the code.
All register are reset, both COUNT2 and dashflag.
dashflag was set to 1 but never set back to 0. I fixed that.
I specified the vector sizes. It makes the code "Lint proof".
Here is it:
always #(posedge CLOCK_50 or posedge RESET)
begin
if (RESET == 1'b1)
begin
COUNT2 <= 2'd00;
dashflag <= 1'b0;
end // reset
else if (halfsecflag) // or if (halfsecflag==1'b1)
begin
if (COUNT2==2'd2))
begin
COUNT2 <= 2'd0;
dashflag <=1'b1;
end
else
begin
COUNT2 <= COUNT2+2'd1;
dashflag <=1'b0;
end
end // clocked
end // always
Start fixing the rest of your code the same way. Write a test-bench, simulate and trace on a waveform display where things go wrong.
Normally you would build the finite state machine to produce the output. That machine would have some stages, like reading the input, mapping it to a sequence of morse code element, shifting out the elements to output buffer, waiting for conditions to move to the next morse element. You will need some timer that would produce one morse time unit intervals, and depending on the FSM stage you will wait one, three or seven time units. The FSM will spin in the waiting stage, it doesn't "magically" sleeps in some fpga-produced delay, there's no such things.
Okay a year later, I know exactly what one should do if they want to create a delay in their verilog program! Essentially, what you should do is create a timer using one of the clocks on your FPGA. For me on my Altera DE1-SoC, the timer I could use is the 50MHz clock known as CLOCK_50. What you do is make a timer module that triggers on the positive (or negative, doesn't matter) edge of the 50MHz clock. Set up a count register that holds a constant value. For example, reg [24:0] timer_limit = 25'd25000000; This is a register that can hold 25 bits. I've set this register to hold the number 25 million. The idea is to flip a bit every time the value in this register is exceeded. Here's some pseudocode to help you understand:
//Your variable declarations
reg [24:0] timer_limit = 25'd25000000; //defining our timer limit register
reg [25:0] timer_count = 0; //See note A
reg half_sec_clock;
always#(posedge of CLOCK_50) begin
if timer_count >= timer_limit then begin
reset timer_count to 0;
half_sec_clock = ~half_sec_clock; //toggle your half_sec_clock
end
Note A: Setting it to zero may or may not initialize count, it's always best to include a reset function that clears your count to zero because you don't know what the initial state is when you're dealing with hardware.
This is the basic idea of how to introduce timing into your hardware. You need to use an onboard clock on your device, trigger on the edge of that clock and create your own slower clock to measure things like seconds. The example above will give you a clock that triggers periodically every half second. For me, this allowed me to easily make a morse code light that could flash on either 1 half second count, or 3 half seconds. My best advice to you beginners is to work in a modular fashion. For example build your half second clock and then test it out to see if you can get a light on your FPGA to toggle once every half second (or whatever interval you want). :) I really hope this is the answer that helps you. I know this is what I was looking for when I originally posted this question so long ago.

How to make an LED blink in Verilog?

I have a FPGA board and I'm trying to make an led blink with a 30% timing margin of 60 seconds.
I have the clock set at 24 MHz
Here is the code I used from a tutorial website
reg [33:0] counter;
reg state;
assign ledg[0] = state;
always # (posedge clock) begin
counter <= counter + 1;
state <= counter[24]; //
end
There are 3 concerns I have about this code:
I don't understand why the counter was declared with the subscript [33:0]
I don't understand why the state is set to unblock when counter[24]
Upon using this code, my timing margin is off, i.e. when I timed the amount of blinks per 60 seconds, it was 0.73, which is off by .03 according to the requirements.
Thanks
I don't understand why the counter was declared with the subscript [33:0]
The subscript [33:0] means that your counter has 34 bits. This means it can count from 0 to 2^(34)-1, or 0 to 17179869183 in decimal.
I don't understand why the state is set to unblock when counter[24]
Upon using this code, my timing margin is off, i.e. when I timed the
amount of blinks per 60 seconds, it was 0.73, which is off by .03
according to the requirements.
state is assigned to the 24th bit of the counter. That means that whenever the 24th bit of the counter is equal to 1, the state will be '1' and the LED will turn on. Whenever the 24th bit of the counter is 0, the state will be 0 and the LED will turn off.
Note that the 24th bit of the counter toggles every 2^24 cycles, or 16,777,216 cycles. Remember that your clock is 24 MHz so that means the clock toggles 24,000,000 times per second. So if your LED state toggles every 16,777,216 cycles, that means it toggles (16,777,216/24,000,000) times per second or every 0.699 second - so it should be very close to the 0.7 that you are looking for.
//300MHz to 1Hz
module top(
input clk,
input reset,
output led
);
reg [27:0] counter;
reg led;
reg clkout;
always #(posedge clk) begin
if (counter == 0) begin
counter <= 149999999;
clkout <= ~clkout;
end else begin
counter <= counter - 1;
end
end
always #(posedge clkout) begin
if (reset == 0) begin
led <= 0;
end else begin
led <= ~led;
end
end

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

Resources