How do I add 1 to a 4 bit wire in Verilog - verilog

This seems like it would be simple, but I can't find out how to do this anywhere... All I want to do is add 1 to a 4 bit wire.
Overall, I want to count the number of 1's in a 8 bit variable. Let's call this input inA. The output will be outA. Both are defined as wires; inA is 8 bits where outA is 4 bits.
wire[0:7] inA;
wire[0:3] outA;
I can do a for loop to go through the array:
for (i = 0; i <= 7; i = i + 1) begin
if (inA[i] == 1) begin
outA <= outA + 1;
end
end
But this isn't working.
Can someone please help? I am extremely new to Verilog (and VHDL), so I really have no clue what I am doing wrong.

There are a few ways to do this, here is one option:
reg [0:3] ones;
integer i;
always # (inA) begin
ones = 0;
for (i = 0; i < 8; i = i + 1) begin
ones = ones + inA[i];
end
end
assign outA = ones;
Since you haven't provided your full source code (e.g. the context of the for loop), we can only guess what the problem with that is.
Remember though that non-blocking assignments like outA <= outA + 1 will be scheduled to be executed at the end of the always block, such that the last assignment will override all previous ones.
Since outA (which by the way will have to be a reg if your for loop is embedded in an always block), is only updated after the always block has finished "executing", only inA[7] can cause an increment to outA.
Have a look at my answer here for further information on how always blocks are executed.

Related

Bits Not Shifting

I want to be able to create a shift from right to left everytime I press a button, but my simulation says my bits is not shifting.
this is the code I wrote:
module Sipo(KEY0, qIN, qOUT, LEDsipo);
input KEY0;
output reg [5:0] qIN;
output reg [5:0] qOUT;
output [6:0] LEDsipo;
assign LEDsipo[0] = qIN[0];
assign LEDsipo[1] = qIN[1];
assign LEDsipo[2] = qIN[2];
assign LEDsipo[3] = qIN[3];
assign LEDsipo[4] = qIN[4];
assign LEDsipo[5] = qIN[5];
assign LEDsipo[6] = KEY0;
always #(KEY0) begin
if (KEY0 == 1)
qIN = 6'b000000;
qOUT[0] <= KEY0;
qOUT[1] <= qOUT[0];
qOUT[2] <= qOUT[1];
qOUT[3] <= qOUT[2];
qOUT[4] <= qOUT[3];
qOUT[5] <= qOUT[4];
if (qOUT == 7'b111111)
qOUT[0] = 0;
qOUT[1] = 0;
qOUT[2] = 0;
qOUT[3] = 0;
qOUT[4] = 0;
qOUT[5] = 0;
qIN = qOUT;
end
endmodule
The result I got in the simulation is that LEDsipo[0] was responding to KEY0, but the rest of the LEDsipo was not. I don't see why my bits are not shifting.
It is dificult to test your code without a testbench, which you have not provided, but I thik that you rissue is an extra exposure to python.
Verilog does not understand indentation as scope indicators and requires begin/end to indicats scopes. So, my guess is that you have at least several issues:
missing begin/end: if (KEY0 == 1) begin...end
incorrect mix of non-blocing/non-blocking assignments mix
Incorrect coding of your latch
bad use of veriog syntax
so, though it is corret, you can avoid using separate bits:
assign LEDsipo[6:0] = {KEY0, qIN[5:0]};
do not use sensititivity lists in the latch, it will not synthesize correctly in your case. Use always #* instead. Well, and begin/end.
I do not know why you need qIn, but it makes no sense to initialize it to 0 in the first place. Also, it is not a part of the latch and should be moved out of the always block.
always #* begin
if (KEY0 == 1) begin // need begin/end for multiple statements
// qIN <= 6'b000000; -- why do you need it?
qOut[5:0] <= {qOut[4:0], KEY0};
if (qOUT == 7'b111111) // can omit begin/end for a single statement
qOut <= 6'b0;
end
end
assign qIn = qOut;
Since you have not provide any testbench, I did not test the code.

How to use two events in an "always" block in verilog

I have two push buttons (using Basys2 rev C board) and I want to increment a register (counter) when I push one of them. I used this:
always #( posedge pb1 or posedge pb2 )
begin
if(count2==9) count2=0;
else count2= count2+1;
end
but when I implemented it (using ISE 9.2), an error appeared:
The logic for does not match a known FF or Latch template.
However when I tried it using just one event (posedge pb1), it worked.
So why did that happen?
The error message means that the target technology (I am guessing in your case is an FPGA or CPLD) doesn't have the physical circuit required to implement the functionality you described with this behavioural code.
One of the important things to consider when writing synthesizable RTL (verilog or VHDL) is you are describing an electronic circuit. You should understand what real world logic you are trying implement (combinatorial logic, registers) before you start coding. In this case, you are describing a register with two separate clocks--something that doesn't exist in any FPGA or ASIC library I've seen. If you can't figure out what you're trying to implement, the chances are the synthesizer can't either.
In other words, not everything you can describe in Verilog can be translated into an actual circuit.
The solution depends on what you want to do - if you require that the counter increments on both pb1 and pb2 rising edges, irrespective of the other pbs state, I would look into solutions which use another (independent) clock (clk in the code below) - something like this:
reg old_pb1, old_pb2;
always # (posedge clk) begin
if (old_pb1 == 0 && pb1 == 1)
if(count2==9) count2 = 0;
else count2 <= count2 + 1;
if (old_pb2 == 0 && pb2 == 1)
if(count2==9) count2 = 0;
else count2 <= count2 + 1;
old_pb1 <= pb1;
old_pb2 <= pb2;
end
If you have no other clock, you could also combine both input signals like in this example:
wire pbs = pb1 | pb2;
always # (pbs) begin
if(count2==9) count2 <= 0;
else count2 <= count2 + 1;
end
Another option would be to use independent counters for the inputs:
always # (posedge pb1)
begin
if(count_pb1==9) count_pb1 <= 0;
else count_pb1 <= count_pb1 + 1;
end
always # (posedge pb2)
begin
if(count_pb2==9) count_pb2 <= 0;
else count_pb2 <= count_pb2 + 1;
end
wire [4:0] count2 = count_pb1 + count_pb2;
All options have their own restrictions, limitations and drawbacks, therefore it depends heavily on what you want to do. Corner cases matter.
Note that I put these example codes together without testing them - please let me know in a comment if you are having trouble with any of them and I look into it.

Verilog generate statement with always#(*) block

I have this generate block below which I think should work, but I am seeing issues with the always #(*) part under the else block. When using VCS, temp_in[i+1][j] is assigned 'x' always. I expect it to be set to '0'. If I instantiate a module/gate instead of always block, like I did for the if part, then it works correctly. Googling for the right syntax for using foreach, generate, always and if within a single block does not yield any useful results. I know the fix is a minor change but I am not that familiar with all the language constructs, so I will appreciate any help.
ceil() is a function which returns an integer. It uses only parameters which are fixed at compile time, so I expect the loop unrolling to happen correctly.
genvar i, j, k;
generate
for (i = 0; i < NUM_STAGES; i = i + 1) begin:gen_stage
for (j = 0; j < (TOTAL_LENGTH/(2**(i+1))); j = j + 1) begin:gen_or
if(j < ceil(i)) begin
for (k = 0; k < CPU_DATA_WIDTH; k = k + 1) begin:gen_bit
msw_mem_out_mux_bit_or U_msw_mem_out_mux_bit_or (
.in_1 (temp_in[i][2*j][k]),
.in_2 (temp_in[i][(2*j)+1][k]),
.out (temp_in[i+1][j][k])
);
end
end else begin
always #(*) begin
temp_in[i+1][j] = {CPU_DATA_WIDTH{1'b0}};
end
end
end
end
endgenerate
An always #* waits until a change occurs on a signal in the inferred sensitivity list. i and j are constants (from the perspective of simulation time when always #* is evaluating), so the your always block has no signals in the sensitivity list.
If using SystemVerilog, change always #* to always_comb which will run at time 0. For Verilog, add an initial block.
Reference: IEEE Std 1800-2012 ยง 9.2.2.2.2 always_comb compared to always #*

Verilog Register to output

I am working with an Altera DE2 development board and I want to read an input in on the switches. This is stored in registers. Based on a counter these registers are incremented. The registers are then supposed to be output to the Seven Segment Displays thought a B2D converter. But I can not pass a register to a function.
wire [26:0] Q,Q2,Q3,Q4;
wire [3:0] one,two,three,four;
reg SecInc,MinInc,HrInc;
reg [3:0] M1,M2,H1,H2;
assign one = SW[3:0];
assign two = SW[7:4];
assign three = SW[11:8];
assign four = SW[15:12];
always begin
M1 = SW[3:0];
M2 = SW[7:4];
H1 = SW[11:8];
H2 = SW[15:12];
end
This is how I get and store the inputs. They come from the switches which we use as a binary representation on Hours and Minutes.
Based on a counter we increment a minute or an hour register.
//increment seconds from 0 to 60
counter seconds (SecInc,KEY[0],Q2);
defparam seconds.n = 8;
defparam seconds.mod = 60;
always # (negedge CLOCK_50) begin
if (Q2 >= 60) begin
MinInc = 1;
M1 <= M1 + 1'b1;
if(M1 >= 9) begin
M1 <= 0;
M2 <= M2 + 1'b1;
end
end else begin
MinInc = 0;
end
end
We want to display the result on the SSD's.
hex(M1,HEX4);
hex(M2,HEX5);
hex(H1,HEX6);
hex(H2,HEX7);
Here in lies the problem. This is not allowed in verilog. I need a way to send my registers to a function which displays numbers from 0 to 9 using some B2D conversion.
I will say I have never had a formal intro to verilog before and I have tried all I can think to do. I even tried to make a new module in which I would pass one,two,three,four and have the module increment them, like it does with Q2 for the counter I have shown. Any suggestions or help is greatly appreciated!
As requested here is the hex module:
module hex(BIN, SSD);
input [15:0] BIN;
output reg [0:6] SSD;
always begin
case(BIN)
0:SSD=7'b0000001;
1:SSD=7'b1001111;
2:SSD=7'b0010010;
3:SSD=7'b0000110;
4:SSD=7'b1001100;
5:SSD=7'b0100100;
6:SSD=7'b0100000;
7:SSD=7'b0001111;
8:SSD=7'b0000000;
9:SSD=7'b0001100;
endcase
end
endmodule
Thank you in advance!
Your hex module is not a function, it is a module and therefore must be instantiated with an instance name like this:
hex digit0(.BIN(M1), .SSD(HEX4));
hex digit1(.BIN(M2), .SSD(HEX5));
hex digit2(.BIN(H1), .SSD(HEX6));
hex digit3(.BIN(H2), .SSD(HEX7));
In addition to nguthrie being correct, that you need to instantiate your hex converter as a module, you drive M1 from a race condition in your always block. Non-blocking assignments will evaluate simultaneously within a block (or essentially simultaneously). This is not a program, where things happen in order. What might work better is:
always # (negedge CLOCK_50) begin
if (Q2 >= 60) begin
MinInc = 1;
if (M1 < 9) begin
M1 <= M1 + 1'b1;
end else begin
M1 <= 0;
M2 <= M2 + 1'b1;
end
end else begin
MinInc = 0;
end
end
You will also potentially get unexpected results from your blocking assignments to MinInc, but since I don't see where this is read it's hard to know what will happen.
Read up on blocking (=) vs non-blocking (<=) assignments in Verilog. It's one of the trickiest concepts of the language, and misuse of the two operations is the cause of 90% of the most dastardly bugs I've ever seen.
EDIT: In re-reading your question, it seems that you're trying to drive M1-4 from at least three places. You really can't have a continuous always begin block and a clocked (always # (negedge clock) begin) driving the same register. This will send your compiler into a tantrum.

Verilog Synthesis fails on if statement containing two variables

I encountered a problem with synthesis where if I had two variables in an if statement, Synthesis will fail (with a very misleading and unhelpful error message).
Given the code snippet below
case(state)
//other states here
GET_PAYLOAD_DATA:
begin
if (packet_size < payload_length) begin
packet_size <= packet_size + 1;
//Code to place byte into ram that only triggers with a toggle flag
next_state = GET_PAYLOAD_DATA;
end else begin
next_state = GET_CHKSUM2;
end
end
I get an error in Xilinx ISE during synthesis:
ERROR:Xst:2001 - Width mismatch detected on comparator next_state_cmp_lt0000/ALB. Operand A and B do not have the same size.
The error claims that next_state isn't correct, but if I take out payload_length and assign a static value to it, it works perfectly fine. As both packet_size and payload_length are of type integer, they are the same size and that is not the problem. Therefore I assume its a similar problem to for loops not being implementable in hardware unless it is a static loop with a defined end. But If statements should work as it is just a comparator between 2 binary values.
What I was trying to do here is that when a byte is received by my module, it will be added into RAM until the the size of the entire payload (which I get from earlier packet data) is reached, then change to a different state to handle the checksum. As the data only comes in 1 byte at a time, I recall this state multiple times until the counter reaches the limit, then I set the next state to something else.
My question is then, how do I achieve the same results of calling my state and repeat until the counter has reached the length of the payload without the error showing up?
EDIT:
Snippets of how packet_size and payload_length are declared, as requested in comments
integer payload_length, packet_size;
initial begin
//other stuff
packet_size <= 0;
end
always # (posedge clk) begin
//case statements with various states
GET_PAYLOAD_LEN:
begin
if (rx_toggle == 1) begin
packet_size <= packet_size + 1;
addr <= 3;
din <= rx_byte_buffer;
payload_length <= rx_byte_buffer;
next_state = GET_PAYLOAD_DATA;
end else begin
next_state = GET_PAYLOAD_LEN;
end
end
rx_byte_buffer is a register of the input data my module receives as 8 bits wide, while packet_size increments in various other states of the machine prior to the one you see above.
I have gotten around the error by switching the if statement conditionals around, but still want to understand why that would change anything.
There are some errors that stick out right away about the code, while they may not fix this problem, they will need to be corrected because it will cause a difference in simulation and hardware tests.
The nextstate logic needs to be in a different always block that does not change based on the posedge of clock. The sensitivity list needs to include things like "state" and/or "*". And if you wanted the nextstate logic to be registered like it is now (which you don't) you should use a nonblocking assignment, this is described in great deal in the cummings paper, provided below.
http://www.sunburst-design.com/papers/CummingsSNUG2000SJ_NBA_rev1_2.pdf
the code should look something like this:
always # (*) begin
//case statements with various states
GET_PAYLOAD_LEN:
begin
if (rx_toggle == 1) begin
packet_size_en = 1'b1;
//these will need to be changed in a similar manner
addr <= 3;
din <= rx_byte_buffer;
payload_length <= rx_byte_buffer;
/////////////////////////////////////////////////////
next_state = GET_PAYLOAD_DATA;
end else begin
next_state = GET_PAYLOAD_LEN;
end
end
always#(posedge clk) begin
if(pcket_size_en)
packet_size <= packet_size +1 ;
end
Also, the first thing I would try is to make these a defined length, by making them of type reg (I assume that you wont be needing a signed number so it should have no difference on simulation), outside of generate blocks, you should try to not let synthesis play around with integers.

Resources