If condition with externally selected value - counter

I'm new to Verilog and it is maybe a dumb question but what is the preferred codeflow in Verilog to solve this problem:
Simple counter, counting external clk (INP) up to a particular value. If the counter matches the value it rises an output wire (DRDY) for one clk period then lowers it to 0. There is an external input (SR) where I'd like to set the comparison value, so if SR = 0, then the counting is up to 500000, if SR = 1 then up to 1000000. I can do it with one value, but I'd like to expand the functionality of my module.
Thank you in advance.
My code so far with one value comparison:
module ec(INP, RST, SR, DRDY, DRDY2);
input INP, RST, SR;
output reg DRDY, DRDY2;
reg [23:0] Q;
always #(posedge INP or negedge RST)
begin
if(!RST)
begin
Q <= 24'd0;
DRDY <= 1'b0;
end
else if( Q == 24'd1000000)
begin
Q <= 24'd0;
DRDY <= 1'b1;
DRDY2 <=~DRDY2;
end
else
begin
Q <= Q + 1;
DRDY <= 1'b0;
end
end
endmodule

An easy way to handle 2 options would be an expand the if statement:
always #(posedge INP or negedge RST) begin
if(!RST) begin
Q <= 24'd0;
DRDY <= 1'b0;
end
else if(
( (SR ==1'b0) && (Q == 24'd1000000) ||
(SR ==1'b1) && (Q == 24'd500000)
) begin
//...
end
else begin
//..
end
This can look quite messy in the code so could be separated out into a count target logic, if more options are to be supported then switch to a case statement instead of if.
reg [23:0] cnt_target ;
always #* begin
if (SR == 1'b1) begin
cnt_target = 24'd1000000 ;
else begin
cnt_target = 24'd500000 ;
end
end
always #(posedge INP or negedge RST) begin
if(!RST) begin
Q <= 24'd0;
DRDY <= 1'b0;
end
else if( Q == cnt_target) begin
//...
end
else begin
//..
end
NB: You might want to consider using Q >= cnt_target that way if SR changed on the fly you do not have to wait for Q to overflow. Plus >= for me tends to synthesis smaller than ==.

Related

verilog with out control variables cnt

module count(clk,rst,cnt);
want to wrire the verilog code which counts upto 7 and then down to
0 and repeats forever as follows. 0,1,2,3,4,5,6,7,6,5,4,4,3,2,1
endmodule
Blockquote
Repeat state 4 for two times while counting down:
module count(
input clk,
input rst,
output cnt
);
reg [2:0] counter;
assign cnt = counter;
// Count up if flag is 1'b0, count down if flag is 1'b1
wire flag;
assign flag = (counter == 3'b1) ? 1'b1 : (counter == 3'b0) ? 1'b0;
// Repeat counter once if special_flag is 2'b01
reg [1:0] special_flag;
always #(posedge clk)
begin
if (flag == 1'b0)
begin
counter = counter + 1;
end
else if (counter == 3'b100 && special_flag == 2'b01)
begin
// Do not decrease counter, reset special_flag back to 2'b0
special_flag = 2'b0;
end else
begin
counter = counter - 1;
end
// Set special_flag to be 2'b01 when counter is 3'b1
if (counter == 3'b1)
begin
special_flag = 2'b01;
end
end
endmodule
module count(
input clk,
input rst,
output cnt
);
reg [2:0] counter;
assign cnt = counter;
// Count up if flag is 1'b0, count down if flag is 1'b1
wire flag;
assign flag = (counter == 3'b1) ? 1'b1 : (counter == 3'b0) ? 1'b0;
always #(posedge clk)
begin
if (flag == 1'b0)
begin
counter = counter + 1;
end
if (flag == 1'b1)
begin
counter = counter - 1;
end
end
endmodule

SystemVerilog error: "already exists; must not be redefined as a named block"

I'm creating a state machine with implicit datapath and am getting three errors that I haven't been able to resolve.
For the endcase error, I've made sure that all the begins have a corresponding end in the always block.
For the Finish error, the state has only been defined once so I'm not sure about that.
For the ; error, I have no idea why it doesn't want me to include countx and county statements.
Any help would be appreciated!
module fillscreen(input logic clk, input logic rst_n, input logic [2:0] colour,
input logic start, output logic done,
output logic [7:0] vga_x, output logic [6:0] vga_y,
output logic [2:0] vga_colour, output logic vga_plot);
enum logic [1:0] {Load = 2'b00, Increment = 2'b01, Out = 2'b10, Finish = 2'b11} state, next_state;
logic [7:0] countx, county;
always # (posedge clk) begin
case(state)
Load:
if(rst_n == 0)
next_state <= Load;
else if (start == 1)
next_state <= Increment;
else begin
next_state <= Load; end
//initialize counter
countx <= 0;
county <= 0;
Increment:
if(rst_n == 0)
next_state <= Load;
else if (county < 119 && countx < 159) begin
county <= county+1;
next_state <= Increment; end
else if (countx < 159) begin
countx <= countx +1;
next_state <= Increment; end
else
next_state <= Finish;
//output
vga_y <= county;
vga_x <= countx;
vga_colour <= countx % 8;
vga_plot <= 1;
Finish:
done <= 1;
if(rst_n == 0)
next_state <= Load;
else begin
next_state = Finish; end
Default:
vga_y <= county;
vga_x <= countx;
done <= 0;
vga_plot <= 0;
endcase
end
endmodule
Here are the errors I'm getting:
** Error: fillscreen.sv(22): near ";": syntax error, unexpected ';', expecting ':'
** Error: fillscreen.sv(54): near "endcase": syntax error, unexpected endcase
** Error: fillscreen.sv(25): 'Increment' already exists; must not be redefined as a named block
** Error fillscreen.sv(43): 'Finish' already exists; must not be redefined as a named block
For any case, you need to include begin..end if the code block for that case has multiple lines, just like if-statements or always blocks (see comments inline, there more than just missing begin..end):
case(state) // <- Note, you never assign state, only next_state, might want to review your code for correctness
Load: begin // <- This case has multiple lines
if (rst_n == 0) begin // <- I do begin..end for EVERYTHING as I inevitably come back and add lines in the body which can lead to bugs if there is no begin..end, like {..} in C
next_state <= Load;
end
else if (start == 1) begin
next_state <= Increment;
end
else begin
next_state <= Load;
end
//initialize counter
countx <= 0;
county <= 0;
end
Increment: begin
if (rst_n == 0) begin
next_state <= Load;
end
else if (county < 119 && countx < 159) begin
county <= county+1;
next_state <= Increment;
end
else if (countx < 159) begin
countx <= countx +1;
next_state <= Increment;
end
else begin
next_state <= Finish;
end
//output
vga_y <= county;
vga_x <= countx;
vga_colour <= countx % 8;
vga_plot <= 1;
end
Finish: begin
done <= 1;
if (rst_n == 0) begin
next_state <= Load;
end
else begin
next_state <= Finish; // Should be non-blocking
end
end
default: begin // <- Should be lower-case "default"
vga_y <= county;
vga_x <= countx;
done <= 0;
vga_plot <= 0;
end
endcase

ONE clock period pulse based on trigger signal

i am making a midi interface. UART works fine, it sends the 8 bit message along with a flag to a control unit. When the flag goes high, the unit will store the message in a register and make a clr_flag high in order to set the flag of UART low again. The problem is that i can not make this clr_flag one period long. I need it to be ONE period long, because this signal also controls a state machine that indicates what kind of message is being stored (note_on -> key_note -> velocity, for example).
My question here is, how can a signal (flag in this case) trigger a pulse just for one clk period? what i have now makes almost a pulse during a clock period, but i does it twice, because the flag has not become 0 yet. ive tried many ways and now i have this:
get_data:process(clk, flag)
begin
if reset = '1' then
midi <= (others => '0');
clr_flag <= '0';
control_flag <= '0';
elsif ((clk'event and clk='1') and flag = '1') then
midi <= data_in;
clr_flag <= '1';
control_flag <= '1';
elsif((clk'event and clk='0') and control_flag = '1') then
control_flag <= '0';
elsif((clk'event and clk='1') and control_flag = '0') then
clr_flag <= '0';
end if;
end process;
the problem with this double pulse or longer than one period pulse(before this, i had something that made clr_flag a two period clk pulse), is that the system will go though two states instead of one per flag.
so in short: when one signal goes high (independent of when it goes low), a pulse during one clock period should be generated.
thanks for your help.
The trick to making a single cycle pulse is realising that having made the pulse, you have to wait as long as the trigger input is high before getting back to the start. Essentially you are building a very simple state machine, but with only 2 states you can use a simple boolean to tell them apart.
Morten is correct about the need to adopt one of the standard patterns for a clocked process; I have chosen a different one that works equally well.
get_data:process(clk, reset)
variable idle : boolean;
begin
if reset = '1' then
idle := true;
elsif rising_edge(clk) then
clr_flag <= '0'; -- default action
if idle then
if flag = '1' then
clr_flag <= '1'; -- overrides default FOR THIS CYCLE ONLY
idle <= false;
end if;
else
if flag = '0' then
idle := true;
end if;
end if;
end if;
end process;
There are several issues to address in order to make the design for a one cycle
pulse using flip flops (registers).
First, the use of flip flops in hardware through VHDL constructions typically
follows a structure like:
process (clk, reset) is
begin
-- Clock
if rising_edge(clk) then
-- ... Flip flops to update at rising edge
end if;
-- Reset
if reset = '1' then
-- Flip flops to update at reset, which need not be all
end if;
end process;
So the get_data process should be updated accordingly, thus:
Sensitivity list should contain only clock (clk) and reset
The nested structure with if on event should be as above
Only rising edge of clk should be used, thus no check on clk = '0'
Making a one cycle pulse on clr_flag when flag goes high can be made with a
synchronous '0' to '1' detector on flag, using a version of flag that is
delayed a single cycle, called flag_ff below, and then checking for (flag =
''1) and (flag_ff = '0').
The resulting code may then look like:
get_data : process (clk, reset) is
begin
-- Clock
if rising_edge(clk) then
flag_ff <= flag; -- One cycle delayed version
clr_flag <= '0'; -- Default value with no clear
if (flag = '1') and (flag_ff = '0') then -- Detected flag going from '0' to '1'
midi <= data_in;
clr_flag <= '1'; -- Override default value making clr_flag asserted signle cycle
end if;
end if;
-- Reset
if reset = '1' then
midi <= (others => '0');
clr_flag <= '0';
-- No need to reset flag_ff, since that is updated during reset anyway
end if;
end process;
Synchronisation and Edge Detection for FSM
The Rise, Edge and Fall outputs will strobe for one cycle when those events are detected. Inputs and outputs are synchronised for use with a Finite State Machine.
entity SynchroniserBit is
generic
(
REG_SIZE: natural := 3 -- Default number of bits in sync register.
);
port
(
clock: in std_logic;
reset: in std_logic;
async_in: in std_logic := '0';
sync_out: out std_logic := '0';
rise_out: out std_logic := '0';
fall_out: out std_logic := '0';
edge_out: out std_logic := '0'
);
end;
architecture V1 of SynchroniserBit is
constant MSB: natural := REG_SIZE - 1;
signal sync_reg: std_logic_vector(MSB downto 0) := (others => '0');
alias sync_in: std_logic is sync_reg(MSB);
signal rise, fall, edge, previous_sync_in: std_logic := '0';
begin
assert(REG_SIZE >= 2) report "REG_SIZE should be >= 2." severity error;
process (clock, reset)
begin
if reset then
sync_reg <= (others => '0');
previous_sync_in <= '0';
rise_out <= '0';
fall_out <= '0';
edge_out <= '0';
sync_out <= '0';
elsif rising_edge(clock) then
sync_reg <= sync_reg(MSB - 1 downto 0) & async_in;
previous_sync_in <= sync_in;
rise_out <= rise;
fall_out <= fall;
edge_out <= edge;
sync_out <= sync_in;
end if;
end process;
rise <= not previous_sync_in and sync_in;
fall <= previous_sync_in and not sync_in;
edge <= previous_sync_in xor sync_in;
end;
Below is a way of creating a signal (flag2) that lasts exactly one clock period from a signal (flag1) that lasts at least one clock period.
I don't program in VHDL~ here is what I usually do for the same propose in Verilog:
always #(posedge clk or negedge rst) begin
if(~rst) flgD <= 1'b0;
else flgD <= flg;
end
assign trg = (flg^flgD)&flgD;
I am new to verilog and this is the sample code, which I used for triggering. Hope this serves your purpose. You can try same logic in VHDL.
module main(clk,busy,rd);
input clk,busy; // busy input condition
output rd; // trigger signal
reg rd,en;
always #(posedge clk)
begin
if(busy == 1)
begin
rd <= 0;
en <= 0;
end
else
begin
if (en == 0 )
begin
rd <= 1;
en <= 1;
end
else
rd <= 0;
end
end
endmodule
The below verilog code shall hold the value for the signals for one clock cycle exactly.
module PulseGen #(
parameter integer BUS_WIDTH = 32
)
(
input [BUS_WIDTH-1:0] i,
input clk,
output [BUS_WIDTH-1:0] o
);
reg [BUS_WIDTH-1:0] id_1 = 0 ;
reg [BUS_WIDTH-1:0] id_2 = 0 ;
always #(posedge clk)begin
id_1 <= i;
id_2 <= id_1;
end
assign o = (id_1 & ~id_2);
The way to achieve this is to create a debounce circuit. If you need a D flip-flop to change from 0 to 1, only for the first clock, just add an AND gate before its input like the image below:
So here you can see a D flip-flop and its debounce circuit.
P.S. Circuit created using this.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--input of minimum 1 clock pulse will give output of wanted length.
--load number 5 to PL input and you will get a 5 clock pulse no matter how long input is.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
library ieee ;
use ieee.std_logic_1164.all ;
use ieee.std_logic_unsigned.all ;
entity fifth is
port (clk , resetN : in std_logic;
pdata : in integer range 0 to 5; --parallel data in. to choose how many clock the out pulse would be.
din : in std_logic;
dout : out std_logic
) ;
end fifth ;
architecture arc_fifth of fifth is
signal count : integer range 0 to 5;
signal pl : std_logic; --trigger detect output.
signal sample1 : std_logic;
signal sample2 : std_logic;
--trigger sync proccess.
begin
process(clk , resetN)
begin
if resetN = '0' then
sample1<='0';
sample2<='0';
elsif rising_edge(clk) then
sample1<=din;
sample2<=sample1;
end if;
end process;
pl <= sample1 and (not sample2); --trigger detect output. activate the counter.
--counter proccess.
process ( clk , resetN )
begin
if resetN = '0' then
count <= 0 ;
elsif rising_edge(clk) then
if pl='1' then
count<=pdata;
else
if count=0 then
count<=count;
else
count<=count-1;
end if;
end if;
end if ;
end process ;
dout<='1' when count>0 else '0';--output - get the wanted lenght pulse no matter how long is input
end arc_fifth ;

Design for assingning output with the counted value of clock on some condition in VHDL

I'm new to VHDL and confused with this design
when Acknwledgement= '1' and clk='1' then
count should be count+1;
and when Acknwledgement= '0' my total counted value of clocks should be assigned to the 'output' and after that resetting count='0' and output='0'.
can anyone help with this.
Thanks in advance.
EDIT:
Code from comment pasted in:
library IEEE;
use IEEE.STD_LOGIC_1164.all;
entity acknw is
port (acknw : in std_logic;
clk : in std_logic;
output : out integer range 0 to 15);
end acknw;
architecture Behavioral of acknw is
begin
process(clk, acknw) variable c : integer range 0 to 15;
begin
if(clk'event and clk = '1') then
if(acknw = '1') then
c := c+1;
output <= c;
else
c := 0;
output <= c;
end if;
end if;
end process;
end Behavioral;
from your comment it sounds like you want an asynchronous acknw, try something like this:
library IEEE;
use IEEE.STD_LOGIC_1164.all;
entity acknw is
port (acknw : in std_logic;
clk : in std_logic;
output : out integer range 0 to 15);
end acknw;
architecture Behavioral of acknw is
begin
process(clk, acknw)
begin
if (acknw = '0') then
output <= 0;
elsif rising_edge(clk) then
-- rollover
if (output /= 15) then
output <= output + 1;
else
output <= 0;
end if;
end if;
end process;
end Behavioral;

Is there a better way to re-write a BCD_counter in VHDL code with less "if-statement"?

I am just beginning to learn VHDL in modelsim, so i apologize in advance if what I'm doing seems really noob.
Basically what i am trying to create is a synthesizable VHDL code for a one-digit up/down BCD counter. The counter will count when "Enable" is '1', or else it stays the same. When input "Init" is initialized, the counter is set to 0 or 9 depending on the value of "Direction" input. (When "Direction" is '1', it is an up counter).
I'm just wondering if there are better tools to use for this to work other than using 100 if and else in a row.
Here is my code, I am writing a test bench for it right now, so I am not yet sure if this will even work. So if you happen to also spot some mistake please point it out for me.
Thanks a lot in advance, and here is my code
entity BCD_counter is
port(clk, direction, init, enable: in bit;
q_out: out integer);
end entity BCD_counter;
architecture behaviour of BCD_counter is
signal q: integer;
begin
process(clk)
begin
if(Clk'event and Clk = '1') then
if(direction = '1') then -- counting up
if(init = '1')then --initialize
q<=0; -- reset to 0
else
if(enable = '1')then -- counting
if (q<9) then
q<=q+1;
else
q<=0;
end if;
else
q<=q;
end if;
end if;
elsif(direction = '0') then --counting down
if(init = '1') then --initialize
q<=9; --reset to 9
else
if(enable = '1') then --counting
if (q>0) then
q<=q-1;
else
q<=9;
end if;
else
q<=q;
end if;
end if;
end if;
end if;
end process;
q_out <= q;
end architecture behaviour;
Slightly different style, but this is how I would write it
architecture behaviour of BCD_counter is
signal next_q : integer;
signal q : integer;
begin
pReg : process
begin -- process pReg
wait until clk'event and clk = '1';
if init = '1' then
q <= 0;
else
q <= next_q;
end if;
end process pReg;
pCount : process (direction, enable, q)
begin -- process pCount
next_q <= q;
if enable = '1' then
if direction = '1' then
next_q <= q + 1;
if q = 9 then
next_q <= 0;
end if;
else
next_q <= q - 1;
if q = 0 then
next_q <= 9;
end if;
end if;
end if;
end process pCount;
q_out <= q;
end architecture behaviour;
Points to note:
The register behaviour is in a separate process from the logic. I find this style is clean. Others have different opinions which normally come down to not liking having next_blah signals.
init is your reset signal, so it overrides everything else, and I put reset signals in the register process.
The first line of the counter process is what I want to happen by default. In this case it says have the next state of q be the current state.
I have the outer if be the check of enable. If we're not enabled we don't do anything, so why check direction first?
Inside each half of the direction condition the code structure is the same. Set-up what I want the normal case to be, and then check for the exception to the rule. For example: if we're going up, I set the next state to be q+1, but if q is 9 I override it with q <= 0.
I'm not using >, < in any comparisons. These are more expensive than =, and = is just fine.
Alternatively you could take the enable into the register process. It's slightly shorter, and possibly clearer. It also makes it obvious that you're expecting to use the enable pin of a register for this function.
pReg : process
begin -- process pReg
wait until clk'event and clk = '1';
if init = '1' then
q <= 0;
else
if enable = '1' then
q <= next_q;
end if;
end if;
end process pReg;
pCount : process (direction, q)
begin -- process pCount
if direction = '1' then
next_q <= q + 1;
if q = 9 then
next_q <= 0;
end if;
else
next_q <= q - 1;
if q = 0 then
next_q <= 9;
end if;
end if;
end process pCount;
The only thing that comes to my mind is that you could ommit the two
else
q<=q;
statements because this is implicitly done if none of the other conditions check out.
I do a lot of this - I created a function called modulo_increment which takes an input integer, and "modulus" integer and returns the wrapped around value.
so you can then do
q <= modulo_increment(q, 10);