I am trying to use the 8 switches on my basys2 board to control the frequency of a square wave, yet I'm having trouble with the input part of it, as I do not know how to divide the clock using the binary value of the register that I have collected the states of the switches in.
I know that I need to divide 25000000/[input value] in order to get the correct value for the counter. My question is:
how can I divide 25000000 by the register which has the switch states stored inside of it such, as input [7:0] SW?
If you can assume your input is always a power of two, you can use shifting to the right. But if you want the full 255 possible resolutions, you need to implement a divider.
Some synthesis tools just synthesize a divider when you simply write 25000000/inputValue. For some others, you may have to do it yourself.
Alternatively, if you don't want to waste time for dividing, you can pre-calculate the values beforehand and use a counter:
case (inputValue)
8'b0000_00010: counterMax = 25000000/2 ; //Where 25000000/2 can be calculated at compile time or by you
8'b0000_00011: counterMax = 25000000/3 ; //Where 25000000/3 can be calculated at compile time or by you
...
endcase
and then just count to the counterMax:
always #(posedge clock)
begin
counter <= counter + 1;
if(counter == counterMax) begin
out <= ~out;
counter <= 0;
end
end
Instead of dividing by input, can you just increment your counter by SW each clock cycle? Then if SW is for example, '15', then your period is reduced by 15x, but you avoid an expensive division circuit.
Related
I'm trying to implement a cache and index lookup memory in SystemVerilog. It's a simple CAM + circular buffer. The interface is:
input rst_n;
input clk;
input [WORD_BITS-1:0] inp;
input rd_en;
input wr_en;
output logic [DEPTH_BITS-1:0] index;
output logic index_valid;
reg [WORD_BITS-1:0] buffer[$pow(2, DEPTH_BITS)];
reg [DEPTH_BITS-1:0] next;
There's basic async reset code. There's a synchronous block that stores inp in buffer and advances next whenever wr_en is high.
Now I'm trying to come up with an efficient and readable way of finding the index of inp when rd_en is high. It seems this could be completely combinational except when clocking the result into the index output. The way I'm visualizing it in my head is to xor inp with all of the buffer locations (it will be fairly small, perhaps 64 entries) then if that is equal to 0 the entry was found. Then a block to arbitrarily choose one of the indices with a 0 value. This is where is differs from a traditional CAM, there could be multiple entries for the same value but I really only need the index of one of those and it doesn't matter which one.
Any thoughts on how to do this in System Verilog (2012)? I know I can loop through all the memory locations synchronously and save a bunch of area but I'd rather it be fast than small. I'm targeting FPGAs. (initially inexpensive Lattice and maybe Xilinx parts) I know a few of the Lattice parts actually have CAM blocks but this is for cases where that isn't available.
Following up on a suggestion from another forum, the following seems to work well.
always_comb begin
index_valid = 0;
for (int i=0; i < 64; i=i+1) begin
if (rd_en) begin
if (inp == buffer[i]) begin
index = i;
index_valid = 1'b1;
end
end
end
end
I am working with an DE2-70 board and I am trying to use some of it's buttons as inputs. The buttons are activated at 0, and I need to check if two buttons in particular are being pressend separatly, in order to increase/decrease a number.
I tried doing the following, where iKEY are the buttons and position is the number i am trying to modify:
reg [4:0] position;
position = 5'b0;
output wire enable = !(iKEY[3] && iKEY[2]);
always #(posedge enable) begin
if(iKEY[3] == 0)
position = position + 5'b00001;
if(iKEY[2] == 0)
position = position - 5'b00001;
end
I tried several differences of this implementation, such as tring to change the ifs conditions or changing the logic function when setting the enable signal, but I always get stuck in some problem.
I am new to hardware logic, so maybe I am thinking in it in the wrong way
Edit:
If both buttons are pressed at the same time I expect the hardware to neither increment nor decrement the number
Summary of the chat discussion:
Missing key background information:
iKEY is 4-bit active low input. Input source is from physical buttons,
A operation should happen on a one-cold (inverse of one-hot) iKEY,
There are clocks available, such as the 50MHz iCLK_50
Solution for operations executing unexpectedly:
Move all the all the iKEY into one always block and decode the operation with a case statement. Ex:
case(iKEY[3:0]) // one-cold, full-case
4'b1110: /* operation 0 */
4'b1101: /* operation 1 */
4'b1011: /* operation 2 */
4'b0111: /* operation 3 */
default: /* default behavior */
endcase
If using iKEY as a clocking event, then perform a bit-wise NAND operation: wire enable = ~&iKEY[3:0];
If using using the iCLK_50 clock, then add a reg to watch for button release to insure one operation per button press. Ex:
if (allow_op) begin // value from past clock event
/* case statement defined above */
end
// value for next clock event
allow_op = &iKEY[4:0]; // bit-wise AND
You probably should be looking for a CHANGE in the button press. The code below looks for a falling edge on the iKEY[3] input. Otherwise, as soon as IKEY is pushed, that counter will go NUTS and start incrementing or decrementing like crazy.
reg iKEY3_LAST;
output wire enable = !(iKEY[3] && iKEY[2]);
always #(posedge enable) begin
iKEY3_LAST = iKEY[3];
if(iKEY[3] == 0 && iKEY3_LAST == 1)
position = position + 5'b00001;
First, you have a combinational loop on signal position. When enable=1 position will change and then change again and again. Simulations will usually get stuck in this case, as for the real world, it depends on how your tools implemented it; I guess most of them will just break the loop. Look for any errors or warnings in the logs.
You want position to be a flop, so it will not be a loop, but will increment by 1 every clock cycle:
always #(posedge clock or posedge reset)
if (reset)
position <= 5'h0;
else
position <= position + iKEY[3] - iKey[2];
Now you must take into account that buttons introduce the bouncing effect. Look here for more information. You'll probably want to implement the Digital Switch Debouncing.
And as Russell wrote, you might consider changing the position only on falling edge of the buttons, otherwise the counter will overflow/underflow like crazy.
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
I'm trying to slow a 50MHz clock down to 25.175MHz for use in a VGA controller. I have a clock divider already, but am having trouble slowing the clock down whenever the resulting division of the current clock speed and the desired clock speed is not a whole number. I.E. 50000000/25175000 ~ 1.98. The clock divider compiles and runs, but outputs nothing if the division is a decimal number. Here's my code:
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
ENTITY Clockdiv IS PORT (
Clkin: IN STD_LOGIC;
Clk: OUT STD_LOGIC);
END Clockdiv;
ARCHITECTURE Behavior OF Clockdiv IS
CONSTANT max: INTEGER := 50000000/25175000;
CONSTANT half: INTEGER := max/2;
SIGNAL count: INTEGER RANGE 0 TO max;
BEGIN
PROCESS
BEGIN
WAIT UNTIL Clkin'EVENT and Clkin = '1';
IF count < max THEN
count <= count + 1;
ELSE
count <= 0;
END IF;
IF count < half THEN
Clk <= '0';
ELSE
Clk <= '1';
END IF;
END PROCESS;
END Behavior;
I searched on google, and found using the REAL data type will allow you to use decimals, but when I changed the variables I'm using to REALs, Quartus gives me the error: Error (10414): VHDL Unsupported Feature error at Clockdiv.vhd(12): cannot synthesize non-constant real objects or values.
Then, if I change "count" to a CONSTANT type, I get the error: Error (10477): VHDL error at Clockdiv.vhd(18): name "count" must represent signal.
Does anybody know how I can slow a clock down to 25.175MHz? Also, does anybody know how to slow a clock down so that the compiler is happy with the resulting division being a decimal value?
Thanks
Reals are, in general, not synthesisable, so you'll need to come up with an integer based solution.
That ratio is quite a tricky one because it's almost 2:1, but not quite. Most edge based clock divider circuits work only on one edge of the original clock, so the lowest ratio you can divide by is 2. In this case you'll have to work on both edges of the clock.
Once you've got that you need to have a counter that increments by the denominator of your ratio and is it's over the numerator then output a clock edge.
PROCESS
BEGIN
WAIT UNTIL Clkin'EVENT;
IF count < max THEN
count <= count + DENOMINATOR;
ELSE
count <= 0;
END IF;
IF count > NOMINATOR THEN
Clk <= ~Clk;
END IF;
END PROCESS;
For this ratio I think the smallest way you can represent it is 2000/1007.
The trouble with this is that you'll get a clock that's basically 25MHz, but occasionally (each 2000 / 7 iterations) you'll get an extra edge. It won't be a 25.175MHz clock. Getting 25.175MHz from 50MHz is impossible without a PLL.
I've written plenty of VGA controllers, and just using a 25 MHz clock has never been much of a problem. If you absolutely want to get closer though, your FPGA probably has a clock manager of some sort (I'm only familiar with Xilinx devices), that will allow you to synthesize an output clock by multiplying and dividing an input clock.
Also, while using derived/gated clocks (clocks where you directly set the value in a process) will probably work for you in this case, it can lead to a lot of problems that can be hard to debug. A better solution is to generate clock enables, and then run everything on the same (fast) clock.
And a last thing, although it is probably as much a question of preferred style, but I usually use clocked process statements instead of WAIT statements (shown below with rising edge trigger, synchronous reset and a clock enable). I find it clearer to read and understand, and less prone to writing unsynthesizable constructs such as wait for 10ns;, or statements with multiple WAITs.
process(clk)
begin
if(rising_edge(clk)) then
if(sync_reset = '1') then
--Reset logic
elsif(clk_enable = '1') then
--Actual functionality
end if;
end if;
end process;
I need to split a two-digit number up so that I can display them separately. The problem is that mod only works with numbers that are a power of 2. How can this be done?
From http://www.edaboard.com/thread112872.html
Many synthesis tools don't support
integer division/modulus/remainder
unless the calculation is trivial,
such as division by a power of two. If
your value isn't a power of two, then
you are probably out of luck.
Maybe you can use another approach
such as building your own math module,
or using a math core from your
software's IP library.
Or maybe you can approximate the
division by multiplying by the
fraction 1/K instead of dividing by K.
If both operands are small, you could
fetch the result from a ROM lookup
table.
If this is a simple incrementing value, you should consider Binary Coded Decimal counters. You need 4 bits per digit but it makes interfacing with 7-segment displays much easier.
//BCD counter - I did not test this
reg [3:0] digit_one, digit_two;
always #(posedge clk)
begin : led_digits
if(reset)
begin
digit_one <= 0;
digit_two <= 0;
end
else if(increment)
begin
//BCD values wrap at 9
if(digit_one == 4'd9)
digit_one <= 0;
else
digit_one <= digit_one + 1;
//Carry when previous digit wraps
if(digit_one == 4'd9)
begin
if(digit_two == 4'd9)
digit_two <= 0;
else
digit_two <= digit_two + 1;
end
end
end
If you have some arbitrary decimal value you need to display, then it gets more complicated. GuanoLoco's solution should work for a 2 digit output. A more efficient algorithm exists but the implementation is not as straightforward.
A simple brute force solution would be to use an if-else block to compare your number to multiples of 10. The largest multiple of ten that is smaller than your number is the "tens" digit, and the difference is the "ones" digit.
if (number >= 90) begin
tens <= 9;
ones <= number - 90;
end else if ...
That said, this isn't scalable, and giant if-else blocks are generally not good practice.
Rather confusinq question. When you say "display", I immediately think $display, hence modeling and simulation. There are no powers of 2 restrictions on modulo for modeling purposes.
But even if you mean synthesis, it is not true in general that modulo only works with powers of 2. However, doing this is probably not a very good idea, because it would be quite expensive in hardware.