I’m developing a boolean data logger on a ZYNQ 7000 SoC. The logger takes a boolean input from GPIO and logs the input’s value and the time it takes to flip.
I use a 32-bit register as a log entry, the MSB bit is the boolean value. The 30:0 bits is an unsigned integer which records the time between last 2 flips. The logger should work like the following picture.
Here's my implementation of the logger in Verilog. To read the logged data from the processor, I use an AXI slave interface generated by vivado and inline my logger in the AXI module.
module BoolLogger_AXI #(
parameter BufferDepth = 512
)(
input wire data_in, // boolean input
input wire S_AXI_ACLK, // clock
input wire S_AXI_ARESETN, // reset_n
// other AXI signals
);
wire slv_reg_wren; // write enable of AXI interface
reg[31:0] buff[0:BufferDepth-1];
reg[15:0] idx;
reg[31:0] count;
reg last_data;
always #(posedge S_AXI_ACLK) begin
if((!S_AXI_ARESETN) || slv_reg_wren) begin
idx <= 0;
count <= 1;
last_data <= data_in;
end else begin
if(last_data!=data_in) begin // add an entry only when input flips
last_data <= data_in;
if(idx < BufferDepth) begin // stop logging if buffer is full
buff[idx] <= count | (data_in << 31);
idx <= idx + 1;
end
count <= 1;
end else begin
count <= count + 1;
end
end
end
//other AXI stuff
endmodule
In the AXI module, the 512*32bit logged data is mapped to addresses from 0x43c20000 to 0x43c20800.
In the Verilog code, the logger adds a new entry only when the boolean input flips. In simulation, the module works as expected. But in the FPGA, sometimes the logged data is not valid. There are successive 2 data and their MSB bit is the same, which means the entry is added even when the boolean input stays the same.
The invalid data appear from time to time. I've tried reading from the address programmatically (*(u32*)(0x43c20000+4*idx)), and there are still invalid data. I watch idx in a ILA module and idx is 512, which means the logging finishes when I read the data.
The FPGA clock is 10 MHz. The input signal is 10 Hz. So the typical period is 10e6/10/2=0x7A120, which most of the data is close to, except the invalid data.
I think if the Verilog code is implemented well, there should be no such invalid data. What may be the problem? Is this an issue about timing?
The code
First off, are you absolutely sure you are not issuing an accidental write on the AXI bus, resetting the registers?
If so, have you tried inserting a so-called double-flop on data_in (two flip-flops, delaying the signal two clock ticks)? I suppose that your data_in is not synchronous to the FPGA clock, which will lead to metastability and you having bad days if not accounted for. Have a look here for information by NANDLAND.
Citing the linked source:
If you have ever tried to sample some input to your FPGA, such as a button press, or if you have had to cross clock domains, you have had to deal with Metastability. A metastable state is one in which the output of a Flip-Flop inside of your FPGA is unknown, or non-deterministic. When a metastable condition occurs, there is no way to tell if the output of your Flip-Flop is going to be a 1 or a 0. A metastable condition occurs when setup or hold times are violated.
Metastability is bad. It can cause your FPGA to exhibit very strange behavior.
In that source there is also a link to a white paper from Altera about the topic of metastability, linked here for reference.
Citing from that paper:
When a metastable signal does not resolve in the allotted time, a logic failure can result if the destination logic observes inconsistent logic states, that is, different destination registers capture different values for the metastable signal.
and
To minimize the failures due to metastability in asynchronous signal transfers, circuit designers typically use a sequence of registers (a synchronization register chain or synchronizer) in the destination clock domain to resynchronize the signal to the new clock domain. These registers allow additional time for a potentially metastable signal to resolve to a known value before the signal is used in the rest of the design.
Basically having the asynchronous signal routed to two flip-flops might for example lead to one FF reading a 1 and one FF reading a 0. This in turn could lead to the data point being saved, but the counter not being reset to 0 (hence doubling the measured time) and the bit being saved as 0.
Finally, it seems to me, that you are using the Vivado-generated example AXI core. Dan Gisselquist simply calls it "broken". This might not be the problem here, but you might want to have a look at his posts and his AXI core design.
Related
I am having trouble initializing the contents of an inferred ram in Verilog. The code for the ram is as below:
module ram(
input clock, // System clock
input we, // When high RAM sets data in input lines to given address
input [13:0] data_in, // Data lines to write to memory
input [10:0] addr_in, // Address lines for saving data to memory
input [10:0] addr_out, // Address for reading from ram
output reg data_out // Data out
);
reg [13:0] ram[2047:0];
// Initialize RAM from file
// WHAT SHOULD GO HERE?
always #(posedge clock) begin
// Save data to RAM
if (we) begin
ram[addr_in] <= data_in;
end
// Place data from RAM
data_out <= ram[addr_out];
end
endmodule
I have run into the command $readmemh. However, documentation for it seems sparse. How should I format the file that contains the data? Also, how can I pass the file as argument when instantiating this module so that I can have different instances of this module load from different files?
I want the initialized content to be available for both simulation and actual implementation. So that the FPGA already boots with this content in RAM.
I am using Vivado 2015.4 to program a Kintex xc7k70 FPGA.
You are correct that you should use $readmemh inside an initial block. In order to make it so different instances of the module can have different initialization files, you should use a parameter like so:
parameter MEM_INIT_FILE = "";
...
initial begin
if (MEM_INIT_FILE != "") begin
$readmemh(MEM_INIT_FILE, ram);
end
end
The format is described in Section 21.4 of the IEEE1800-2012 specification; typically the file is just a bunch of lines containing hex numbers of the correct bit-length, like so:
0001
1234
3FFF
1B34
...
Note that there is no "0x" prefix and each line represents an adjacent address (or any separating whitespace). In the example above, $readmemh would put 14'h0001 into ram[0], 14'h1234 into ram[1], 14'h3FFF into ram[2] and so on. You can also include comments in the hex file using // or /* */. Finally, you can use the # symbol to designate an address for the following numbers to be located at, like so:
#0002
0101
0A0A
...
In the above file, ram[0] and ram[1] would be uninitialized and ram[2] would get 14'h0101. Those are all the major constructs of the hex file format, though you can also use _, x and z as you would in other Verilog numbers and theres a few more rules you can read in the section sited above.
Apart from #Unn's excellent ans, I want to add that, If you just want to initialize your memory with either all bits to 1'b1 or 1'b0, then you can just put following code,
integer j;
initial
for(j = 0; j < DEPTH; j = j+1)
ram[j] = {WIDTH{MEM_INIT_VAL}};
For your case, WIDTH=14, and MEM_INIT_VAL may be 1'b1 or 1'b0.
Since your question cited the #xilinx and #vivado tags, I wanted to suggest that you can also use the xpm_memory family of primitives to instantiate a parameterized memory. The advantages of this approach:
Exports exactly the hardware capabilities of the memory resources on the FPGA (ie, makes you think clearly about limitations such as memory ports).
Guarantees correct identical behavior in simulation and benchtop for memory primitives.
You can allow Vivado to choose the most efficient memory implementation (BRAM, UltraRAM, distributed RAM, flops) at synthesis time, according to your design constraints.
Easy to fine tune (enable or disable internal pipeline stages, etc.).
With that said, purely inferred memories are often easier to code. But, it's still worth getting familiar with the Xilinx-provided memory primitives so that you'll have a clearer idea of what Vivado can easily synthesize, and what it can't.
For more information, see UG573, the Vivado Memory Resources User Guide:
https://www.xilinx.com/support/documentation/user_guides/ug573-ultrascale-memory-resources.pdf
integer j;
initial
for(j = 0; j < DEPTH; j = j+1)
ram[j] = j;
This might be easy in case of debug, where the value of a location is its location number.
Also, I would suggest you to not initialize the RAMs. It will help you in catching bugs, if any, in simulation as the data driven will be 'x if RAM is un-intialized and can be caught easily.
I am trying to create a memory shift operation in verilog and was wondering the best way to do it. An example code is:
reg [MSB:0] a [0:NO_OF_LOCATIONS];
// after some processing
for(i =0; i <= NO_OF_LOCATIONS; i= i+1)
a[i] = a[i+1]
If I use a ROM in Xilinx it can only do synchronize writes and I need to do all the shifts within one clock cycle. If I do use a memory as above I am not sure if on board implementation will result in metastability or don't care propagation.
Also what would be the best way to do it instead of a for loop?
I am assuming this is part of a clocked synchronous block, i.e. something like the following (it would not make much sense otherwise and you wrote "I need to do all the shifts within one clock cycle", which implies that this is part of a synchronous design):
reg [MSB:0] a [0:NO_OF_LOCATIONS];
always #(posedge clk)
if (...) begin
for(i =0; i < NO_OF_LOCATIONS; i= i+1)
a[i] <= a[i+1];
a[NO_OF_LOCATIONS] <= ...;
end
// also use a[] somewhere
assign a0 = a[0];
Btw: a[] has NO_OF_LOCATIONS+1 locations in it. I'm not sure if this is intended but I just left it that way. Usually the range of a[] would be written as [0:NO_OF_LOCATIONS-1] for NO_OF_LOCATIONS memory locations.
Notice that I have changed the assignment = to <=. When assigning something in a clocked always-block and the thing you assign to is read anywhere outside that always-block then you must assign non-blocking (i.e. with <=) in order to avoid race conditions in simulation that can lead to simulation-synthesis mismatches.
Also notice that I have factored out the assignment to a[NO_OF_LOCATIONS], as it would have got its value from a[NO_OF_LOCATIONS+1], which is out-of-bounds and thus would always be undef. Without that change the synthesis tool would be right to assume that all elements of a[] are constant undef and would simply replace all reads on that array with constant 'bx.
This is perfectly fine code. I'm not sure why you brought up metastability but as long as the ... expressions are synchronous to clk there is no metastability in this circuit. But it does not really model a memory. Well, it does, but one with NO_OF_LOCATIONS write ports and NO_OF_LOCATIONS read ports (only counting the read ports inferred by that for-loop). Even if you had such a memory: it would be very inefficient to use it like that because the expensive thing about a memory port is its capability to address any memory location, but all the ports in this example have a constant memory address (i is constant after unrolling the for-loop). So this huge number of read and write ports will force the synthesis tool to implement that memory as a pile of individual registers. However, if your target architecture has dedicated shift register resources (such as many fpgas do), then this might be transformed to a shift register.
For large values of NO_OF_LOCATIONS you might consider implementing a fifo using cursor(s) into the memory instead of shifting the content of the entire memory from one element to the next. This would only infer one write port and no read port from inside the for-loop. For example:
reg [MSB:0] a [0:NO_OF_LOCATIONS];
parameter CURSOR_WIDTH = $clog2(NO_OF_LOCATIONS+1);
reg [CURSOR_WIDTH-1:0] cursor = 0;
always #(posedge clk)
if (...) begin
a[cursor] <= ...;
cursor <= cursor == NO_OF_LOCATIONS ? 0 : cursor+1;
end
assign a0 = a[cursor];
I am planning to make a snake game using the Altera DE2-115 and display it on LED Matrix
Something similar to this in the video http://www.youtube.com/watch?v=niQmNYPiPw0
but still i don't know how to start,any help?
You'll have choose between 2 implementation routes:
Using a soft processor (NIOS II)
Writing the game logic in a hardware description language ([System]Verilog or VHDL)
The former will likely be the fastest route to achieving the completed game assuming you have some software background already, however if your intention is to learn to use FPGAs then option 2 may be more beneficial. If you use a NIOS or other soft processor core you'll still need to create an FPGA image and interface to external peripherals.
To get started you'll want to look at some of the example designs that come with your board. You also need to fully understand the underlying physical interface to the LED Matrix display to determine how to drive it. You then want to start partitioning your design into sensible blocks - a block to drive the display, a block to handle user input, storage of state, the game logic itself etc. Try and break them down sufficiently to decide what the interfaces to communicate between the blocks are going to look like.
In terms of implementation, for option 1 you will probably make use of Altera's SoC development environment called Qsys. Again working from an existing example design as a starting point is probably the easiest way to get up-and-running quickly. With option 2 you need to pick a hardware description language ([System]Verilog or VHDL or MyHDL) and code away in your favourite editor.
When you start writing RTL code you'll need a mechanism to simulate it. I'd suggest writing block-level simulations for each of the blocks you write (ideally writing the tests based on your definitions of the interfaces before writing the RTL). Assuming you're on a budget you don't have many options: Altera bundles a free version of Modelsim with their Quartus tool, there's the open source options of the Icarus simulator if using verilog or GHDL for VHDL.
When each block largely works run it through the synthesis tool to check FPGA resource utilisation and timing closure (the maximum frequency the design can be clocked at). You probably don't care too much about the frequency implementing a game like snake but it's still good practice to be aware of how what you write translates into an FPGA implementation and the impact on timing.
You'll need to create a Quartus project to generate an FPGA bitfile - again working from an existing example design is the way to go. This will provide pin locations and clock input frequencies etc. You may need to write timing constraints to define the timing to your LED Matrix display depending on the interface.
Then all you have to do is figure out why it works in simulation but not on the FPGA ;)
Let's say you have a LED matrix like this:
To answer not your question, but your comment about " if u can at least show me how to make the blinking LED i will be grateful :)", we can do as this:
module blink (input wire clk, /* assuming a 50MHz clock in your trainer */
output wire anode, /* to be connected to RC7 */
output wire cathode); /* to be connected to RB7 */
reg [24:0] freqdiv = 25'h0000000;
always #(posedge clk)
freqdiv <= freqdiv + 1;
assign cathode = 1'b0;
assign anode = freqdiv[24];
endmodule
This will make the top left LED to blink at a rate of 1,4 blinks per second aproximately.
This other example will show a running dot across the matrix, left to right, top to down:
module runningdot (input wire clk, /* assuming a 50MHz clock in your trainer */
output wire [7:0] anodes, /* to be connected to RC0-7 */
output wire [7:0] cathodes); /* to be connected to RB0-7 */
reg [23:0] freqdiv = 24'h0000000;
always #(posedge clk)
freqdiv <= freqdiv + 1;
wire clkled = freqdiv[23];
reg [7:0] r_anodes = 8'b10000000;
reg [7:0] r_cathodes = 8'b01111111;
assign anodes = r_anodes;
assign cathodes = r_cathodes;
always #(posedge clkled) begin
r_anodes <= {r_anodes[0], r_anodes[7:1]}; /* shifts LED left to right */
if (r_anodes == 8'b00000001) /* when the last LED in a row is selected... */
r_cathodes <= {r_cathodes[0], r_cathodes[7:1]}; /* ...go to the next row */
end
endmodule
Your snake game, if using logic and not an embedded processor, is way much complicated than these examples, but it will use the same logic principles to drive the matrix.
I am trying to reconstruct a packet that was sent via UART RS232 connections, but am not sure how to reconstruct the packet in its entirety such that the packet can be taken apart and stuff can be done using it.
The issue is that when I receive 1 byte at a time, I store that byte into a register 8 bits wide, and when I receive the next byte, I want to be able to shift the first byte by 8 bits, then add the new byte to the end. This becomes an issue as the register is now too small (8 bits vs 16 bits to hold the next byte). In addition, I cannot see a way to change the size of the register during runtime to grow and shrink depending on the size of the packet, as all registers must be static, and I also must know the exact size of the packet in order to process it.
There is the possibility of setting up an insanely large register to hold the packet, and counting how many valid bytes were copied into the register, but I am sure there is a better way to do this that I am not seeing.
All this is done using Xilinx ISE.
Verilog is static to mimic physical design. You will need to know the maximum number of bytes that can be supported. To know the size of the input, simply incompetent a counter as the data bytes shift. The only way to have a dynamic size is if this is for non-synthesizable behavior modeling then you can use C code to link into your design (PLI/VPI/DPI) or SystemVerilog Queues (IEEE Std 1800-2012 section 7.10). Read-up about SystemVerilog if you are interested.
The follow is a Verilog example of a large shift register:
parameter SIZE = 2**10;
reg [SIZE*8-1:0] store;
always #(posedge clk or negedge rst_n) begin
if ( !rst_n ) begin
counter <= 0;
store <= {(SIZE*8){1'b0}};
end
else if ( push_in ) begin
counter <= first_byte ? 0 : (counter+1);
store <= {store[SIZE*8-1-8:0], data_in[7:0]};
end
end
With an "insanely large register" you may need to break up the store into chunks so the simulator can handle it; some simulators cannot handle reg [2**32-1:0] store;. Sudo code example:
// ...
storeN <= {store3[SIZE*8-1-8:0], storeM[7:0]};
// ...
store1 <= {store1[SIZE*8-1-8:0], store0[7:0]};
store0 <= {store0[SIZE*8-1-8:0], data_in[7:0]};
// ...
I found the following piece of code in the internet , while searching for good FIFO design. From the linkSVN Code FIFO -Author Clifford E. Cummings . I did some research , I was not able to figure out why there are three pointers in the design ?I can read the code but what am I missing ?
module sync_r2w #(parameter ADDRSIZE = 4)
(output reg [ADDRSIZE:0] wq2_rptr,
input [ADDRSIZE:0] rptr,
input wclk, wrst_n);
reg [ADDRSIZE:0] wq1_rptr;
always #(posedge wclk or negedge wrst_n)
if (!wrst_n) {wq2_rptr,wq1_rptr} <= 0;
else {wq2_rptr,wq1_rptr} <= {wq1_rptr,rptr};
endmodule
module sync_w2r #(parameter ADDRSIZE = 4)
(output reg [ADDRSIZE:0] rq2_wptr,
input [ADDRSIZE:0] wptr,
input rclk, rrst_n);
reg [ADDRSIZE:0] rq1_wptr;
always #(posedge rclk or negedge rrst_n)
if (!rrst_n) {rq2_wptr,rq1_wptr} <= 0;
else {rq2_wptr,rq1_wptr} <= {rq1_wptr,wptr};
endmodule
What you are looking at here is what's called a dual rank synchronizer. As you mentioned this is an asynchronous FIFO. This means that the read and write sides of the FIFO are not on the same clock domain.
As you know flip-flops need to have setup and hold timing requirements met in order to function properly. When you drive a signal from one clock domain to the other there is no way to guarantee this requirements in the general case.
When you violate these requirements FFs go into what is called a 'meta-stable' state where there are indeterminate for a small time and then (more or less) randomly go to 1 or 0. They do this though (and this is important) in much less than one clock cycle.
That's why the two layers of flops here. The first has a chance of going meta-stable but should resolve in time to be captured cleanly by the 2nd set of flops.
This on it's own is not enough to pass a multi-bit value (the address pointer) across clock domains. If more than one bit is changing at the same time then you can't be sure that the transition will be clean on the other side. So what you'll see often in these situations is that the FIFO pointers will by gray coded. This means that each increment of the counter changes at most one bit at a time.
e.g. Rather than 00 -> 01 -> 10 -> 11 -> 00 ... it will be 00 -> 01 -> 11 -> 10 -> 00 ...
Clock domain crossing is a deep and subtle subject. Even experienced designers very often mess them up without careful thought.
BTW ordinary Verilog simulations will not show anything about what I just described in a zero-delay sim. You need to do back annotated SDF simulations with real timing models.
In this example, the address is passed through the shift register in order for it to be delayed by one clock cycle. There could have been more “pointers” in order to delay the output even more.
Generally, it is easier to understand what is going on and why if you simulate the design and look at the waveform.
Also, here are some good FIFO implementations you can look at:
Xilinx FIFO Generator IP Core
Altera's single/double-clock FIFOs
OpenCores Generic FIFOs
Hope it helps. Good Luck!