I'm a C programmer and started learning Ada a few weeks ago. I have been puzzled by how Ada handles foreign binary data, such as when decoding a communications packet stored in a serial input buffer.
In C, I would define a packed structure to reflect the layout of the packet, and then cast the pointer-to-buffer to pointer-to-structure to access the individual elements in the communications data. What is the typical way to do such decoding in Ada?
I have tried to replicate the same method for C in Ada with the following
-- Fundamental types for fields in the packet
type Station_Addr_Type is mod 2**8;
type Func_Code_Type is (FUNC1, FUNC2);
for Func_Code_Type use
(
FUNC1 => 1,
FUNC2 => 2
);
type Packet is
record
Station_Addr : Station_Addr_Type;
Func_Code : Func_Code_Type;
end record;
-- attempts to reflect packet binary layout
for Packet use
record at mod 1;
Station_Addr at 0 range 0 .. 7;
Func_Code at 1 range 0 .. 7;
end record;
I then defined the array for the communications receive buffer that accepts foreign binary data (possibly from a different architecture):
type Communication_Data is mod 2**8;
for Communication_Data'Size use 8;
type Communication_Buffer is array (Natural range <>) of Communication_Data;
Buffer : Communication_Buffer (0 .. 20);
Then a procedure that decodes such communications
procedure Decode_Packet (Packet_Provided : in Packet);
-- non-working sample
declare
begin
-- Attempts to sanity-check packet by object casting
Decode_Packet (Packet (Buffer));
---------------^----
Error: invalid conversion, not compatible with type "Communication_Buffer"
exception
when others =>
raise Decode_Failure;
end;
However, the compiler forbids such casting with error as shown. Thanks for reading this far. My question is,
Regarding the correct way of decoding foreign binary data, am I "in the ball park", or is there a better way of doing this?
If you sure that the data has a right alignment, you can map a Packet object to space allocated by Communication_Data:
Buffer : Communication_Buffer (0 .. 20);
Pkg : Packet;
pragma Import (Ada, Pkg);
for Pkg'Address use Buffer (0)'Address;
The same with aspect syntax:
Buffer : Communication_Buffer (0 .. 20);
Pkg : Packet
with Import, Address => Buffer (0)'Address;
Another way is to use Ada.Unchecked_Conversion, but you should be sure that Buffer and Packet have the same size:
subtype Packet_Buffer is Communication_Buffer (1 .. 2);
function To_Packet is new Ada.Unchecked_Conversion
(Packet_Buffer, Packet);
Pkg : Packet := To_Packet (Buffer (0 .. 1));
PS. If you want an endianness independent code you may also need a Scalar_Storage_Order (GNAT implementation defined) aspect.
PS. I recommend also take a look at "Safe Communication" chapter of Safe and Secure Software booklet.
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:
I I I I I
I I I I
I I I
I I
I
n = 5
The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?
The closest I've come is
I I I
I I
I
n = 3
and that's using
THIS CODE NOW WORKS
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure pyramidchaser is
subtype X_Type is Integer range 0..30;
X: X_Type;
Indent : Integer := 0;
procedure Numbergrabber (X : out Integer) is
begin
Put("Enter a number: ");
Get(X);
Skip_Line;
end Numbergrabber;
procedure PrintSpaces(I : in Integer) is
begin
if I in X_Type then
Put(" ");
else
return;
end if;
PrintSpaces(I - 1);
end Printspaces;
procedure PrintPins(i, n: in Integer) is
begin
if i >= n then
return;
end if;
Put('I');
Put(' ');
PrintPins(i + 1, n);
end Printpins;
function Pins (X, Indent: in Integer) return Integer is
Printed : Integer;
begin
Printed:= 0;
if X > 0 then
PrintSpaces(Indent);
PrintPins(0, X);
New_Line;
Printed := X + Pins(X - 1, Indent + 1);
end if;
return Printed;
end Pins;
Bowlingpins : Integer;
begin
Numbergrabber(X);
Bowlingpins:= Pins(X, Indent);
end pyramidchaser;
but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.
I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.
I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.
As always, immensely thankful for anyone fighting the good fight!
Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:
THE PYRAMID PROBLEM 2
hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.
Level 1
|=|
Level 2
|===|
||=||
|===|
Level 3
|=====|
||===||
|||=|||
||===||
|=====|
it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.
To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?
Bowling pins:
Printing ----I---- is just: (I'm going to use dashes instead of spaces throughout for readability)
Put_Line (4 * "-" & "I" & 4 * "-");
And printing the whole bowling triangle could be:
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
procedure Print_Bowling_Line (Dashes : Natural; Pins : Positive) is
Middle : constant String := (if Pins = 1 then "I"
else (Pins - 1) * "I-" & "I");
begin
Put_Line (Dashes * "-" & Middle & Dashes * "-");
end Print_Bowling_Line;
begin
Print_Bowling_Line (0, 5);
Print_Bowling_Line (1, 4);
Print_Bowling_Line (2, 3);
Print_Bowling_Line (3, 2);
Print_Bowling_Line (4, 1);
end Main;
Writing the five repeated lines as a loop is quite obvious. For recursion, there are two ways.
Tail recursion
Tail recursion is the more natural 'ask questions, then shoot' approach; first check the parameter for an end-condition, if not, do some things and finally call self.
procedure Tail_Recurse (Pins : Natural) is
begin
if Pins = 0 then
return;
end if;
Print_Bowling_Line (Total_Pins - Pins, Pins);
Tail_Recurse (Pins - 1);
end Tail_Recurse;
Head recursion
Head recursion is what mathematicians love; how do you construct a proof for N? Well, assuming you already have a proof for N-1, you just apply X and you're done. Again, we need to check the end condition before we go looking for a proof for N-1, otherwise we would endlessly recurse and get a stack overflow.
procedure Head_Recurse (Pins : Natural) is
begin
if Pins < Total_Pins then
Head_Recurse (Pins + 1); -- assuming N + 1 proof here
end if;
Print_Bowling_Line (Total_Pins - Pins, Pins);
end Head_Recurse;
For the full code, expand the following snippet:
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
Total_Pins : Natural := 5;
procedure Print_Bowling_Line (Dashes : Natural; Pins : Positive) is
Middle : constant String := (if Pins = 1 then "I"
else (Pins - 1) * "I-" & "I");
begin
Put_Line (Dashes * "-" & Middle & Dashes * "-");
end Print_Bowling_Line;
procedure Tail_Recurse (Pins : Natural) is
begin
if Pins = 0 then
return;
end if;
Print_Bowling_Line (Total_Pins - Pins, Pins);
Tail_Recurse (Pins - 1);
end Tail_Recurse;
procedure Head_Recurse (Pins : Natural) is
begin
if Pins < Total_Pins then
Head_Recurse (Pins + 1); -- assuming N + 1 proof here
end if;
Print_Bowling_Line (Total_Pins - Pins, Pins);
end Head_Recurse;
begin
Total_Pins := 8;
Head_Recurse (1);
end Main;
For simplicity, I don't pass around the second number, that indicates the stopping condition, but rather set it once before running the whole.
I always find it unfortunate to try to learn a technique by applying it where it makes the code more complicated, rather than less. So I want to show you a problem where recursion really does shine. Write a program that prints a maze with exactly one path between every two points in the maze, using the following depth-first-search pseudo code:
start by 'visiting' any field (2,2 in this example)
(recursion starts with this:)
while there are any neighbours that are unvisited,
pick one at random and
connect the current field to that field and
run this procedure for the new field
As you can see in the animation below, this should meander randomly until it gets 'stuck' in the bottom left, after which it backtracks to a node that still has an unvisited neighbour. Finally, when everything is filled, all the function calls that are still active will return because for each node there will be no neighbours left to connect to.
You can use the skeleton code in the snippet below. The answer should only modify the Depth_First_Make_Maze procedure. It need be no longer than 15 lines, calling Get_Unvisited_Neighbours, Is_Empty on the result, Get_Random_Neighbour and Connect (and itself, of course).
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers; use Ada.Containers;
with Ada.Containers.Vectors;
with Ada.Numerics.Discrete_Random;
procedure Main is
N : Positive := 11; -- should be X*2 + 1 for some X >= 1
type Cell_Status is (Filled, Empty);
Maze : array (1 .. N, 1 .. N) of Cell_Status := (others => (others => Filled));
procedure Print_Maze is
begin
for Y in 1 .. N loop
for X in 1 .. N loop
declare
C : String := (case Maze (X, Y) is
--when Filled => "X", -- for legibility,
when Filled => "█", -- unicode block 0x2588 for fun
when Empty => " ");
begin
Put (C);
end;
end loop;
Put_Line ("");
end loop;
end Print_Maze;
type Cell_Address is record
X : Positive;
Y : Positive;
end record;
procedure Empty (Address : Cell_Address) is
begin
Maze (Address.X, Address.Y) := Empty;
end Empty;
procedure Connect (Address1 : Cell_Address; Address2 : Cell_Address) is
Middle_X : Positive := (Address1.X + Address2.X) / 2;
Middle_Y : Positive := (Address1.Y + Address2.Y) / 2;
begin
Empty (Address1);
Empty (Address2);
Empty ((Middle_X, Middle_Y));
end Connect;
function Cell_At (Address : Cell_Address) return Cell_Status is (Maze (Address.X, Address.Y));
function Left (Address : Cell_Address) return Cell_Address is (Address.X - 2, Address.Y);
function Right (Address : Cell_Address) return Cell_Address is (Address.X + 2, Address.Y);
function Up (Address : Cell_Address) return Cell_Address is (Address.X, Address.Y - 2);
function Down (Address : Cell_Address) return Cell_Address is (Address.X, Address.Y + 2);
type Neighbour_Count is new Integer range 0 .. 4;
package Neighbours_Package is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Cell_Address);
use Neighbours_Package;
function Get_Unvisited_Neighbours (Address : Cell_Address) return Neighbours_Package.Vector is
NeighbourList : Neighbours_Package.Vector;
begin
NeighbourList.Reserve_Capacity (4);
if Address.X >= 4 then
declare
L : Cell_Address := Left (Address);
begin
if Cell_At (L) = Filled then
NeighbourList.Append (L);
end if;
end;
end if;
if Address.Y >= 4 then
declare
U : Cell_Address := Up (Address);
begin
if Cell_At (U) = Filled then
NeighbourList.Append (U);
end if;
end;
end if;
if Address.X <= (N - 3) then
declare
R : Cell_Address := Right (Address);
begin
if Cell_At (R) = Filled then
NeighbourList.Append (R);
end if;
end;
end if;
if Address.Y <= (N - 3) then
declare
D : Cell_Address := Down (Address);
begin
if Cell_At (D) = Filled then
NeighbourList.Append (D);
end if;
end;
end if;
return NeighbourList;
end Get_Unvisited_Neighbours;
package Rnd is new Ada.Numerics.Discrete_Random (Natural);
Gen : Rnd.Generator;
function Get_Random_Neighbour (List : Neighbours_Package.Vector) return Cell_Address is
Random : Natural := Rnd.Random (Gen);
begin
if Is_Empty (List) then
raise Program_Error with "Cannot select any item from an empty list";
end if;
declare
Index : Natural := Random mod Natural (List.Length);
begin
return List (Index);
end;
end Get_Random_Neighbour;
procedure Depth_First_Make_Maze (Address : Cell_Address) is
begin
null;
end Depth_First_Make_Maze;
begin
Rnd.Reset (Gen);
Maze (1, 2) := Empty; -- entrance
Maze (N, N - 1) := Empty; -- exit
Depth_First_Make_Maze ((2, 2));
Print_Maze;
end Main;
To see the answer, expand the following snippet.
procedure Depth_First_Make_Maze (Address : Cell_Address) is
begin
loop
declare
Neighbours : Neighbours_Package.Vector := Get_Unvisited_Neighbours (Address);
begin
exit when Is_Empty (Neighbours);
declare
Next_Node : Cell_Address := Get_Random_Neighbour (Neighbours);
begin
Connect (Address, Next_Node);
Depth_First_Make_Maze (Next_Node);
end;
end;
end loop;
end Depth_First_Make_Maze;
Converting recursion to loop
Consider how a function call works; we take the actual parameters and put them on the call stack along with the function's address. When the function completes, we take those values off the stack again and put back the return value.
We can convert a recursive function by replacing the implicit callstack containing the parameters with an explicit stack. I.e. instead of:
procedure Foo (I : Integer) is
begin
Foo (I + 1);
end Foo;
We would put I onto the stack, and as long as there are values on the stack, peek at the top value and do the body of the Foo procedure using that value. When there is a call to Foo within that body, push the value you would call the procedure with instead, and restart the loop so that we immediately start processing the new value. If there is no call to self in this case, we discard the top value on the stack.
Restructuring a recursive procedure in this way will give you an insight into how it works, especially since pushing on to the stack is now separated from 'calling' that function since you explicitly take an item from the stack and do something with it.
You will need a stack implementation, here is one that is suitable:
Bounded_Stack.ads
generic
max_stack_size : Natural;
type Element_Type is private;
package Bounded_Stack is
type Stack is private;
function Create return Stack;
procedure Push (Onto : in out Stack; Item : Element_Type);
function Pop (From : in out Stack) return Element_Type;
function Top (From : in out Stack) return Element_Type;
procedure Discard (From : in out Stack);
function Is_Empty (S : in Stack) return Boolean;
Stack_Empty_Error : exception;
Stack_Full_Error : exception;
private
type Element_List is array (1 .. max_stack_size) of Element_Type;
type Stack is
record
list : Element_List;
top_index : Natural := 0;
end record;
end Bounded_Stack;
Bounded_Stack.adb
package body Bounded_Stack is
function Create return Stack is
begin
return (top_index => 0, list => <>);
end Create;
procedure Push (Onto : in out Stack; Item : Element_Type) is
begin
if Onto.top_index = max_stack_size then
raise Stack_Full_Error;
end if;
Onto.top_index := Onto.top_index + 1;
Onto.list (Onto.top_index) := Item;
end Push;
function Pop (From : in out Stack) return Element_Type is
Top_Value : Element_Type := Top (From);
begin
From.top_index := From.top_index - 1;
return Top_Value;
end Pop;
function Top (From : in out Stack) return Element_Type is
begin
if From.top_index = 0 then
raise Stack_Empty_Error;
end if;
return From.list (From.top_index);
end Top;
procedure Discard (From : in out Stack) is
begin
if From.top_index = 0 then
raise Stack_Empty_Error;
end if;
From.top_index := From.top_index - 1;
end Discard;
function Is_Empty (S : in Stack) return Boolean is (S.top_index = 0);
end Bounded_Stack;
It can be instantiated with a maximum stack size of Width*Height, since the worst case scenario is when you happen to choose a non-forking path that visits each cell once:
N_As_Cell_Size : Natural := (N - 1) / 2;
package Cell_Stack is new Bounded_Stack(max_stack_size => N_As_Cell_Size * N_As_Cell_Size, Element_Type => Cell_Address);
Take your answer to the previous assignment, and rewrite it without recursion, using the stack above instead.
To see the answer, expand the following snippet.
procedure Depth_First_Make_Maze (Address : Cell_Address) is
Stack : Cell_Stack.Stack := Cell_Stack.Create;
use Cell_Stack;
begin
Push (Stack, Address);
loop
exit when Is_Empty (Stack);
declare
-- this shadows the parameter, which we shouldn't refer to directly anyway
Address : Cell_Address := Top (Stack);
Neighbours : Neighbours_Package.Vector := Get_Unvisited_Neighbours (Address);
begin
if Is_Empty (Neighbours) then
Discard (Stack); -- equivalent to returning from the function in the recursive version
else
declare
Next_Cell : Cell_Address := Get_Random_Neighbour (Neighbours);
begin
Connect (Address, Next_Cell);
Push (Stack, Next_Cell); -- equivalent to calling self in the recursive version
end;
end if;
end;
end loop;
end Depth_First_Make_Maze;
You’re going to print as many lines as there are pins. Each line has an indentation consisting of a number of spaces and a number of pins, each printed as "I " (OK,there's an extra space at the end of the line, but no one's going to see that).
Start off with no leading spaces and the number of pins you were asked to print.
The next line needs one more leading space and one fewer pin (unless, of course, that would mean printing no pins, in which case we're done).
I don't program in Ada (it looks like a strange Pascal to me), but there is an obvious algorithmic problem in your Pins function.
Basically, if you want to print a pyramid whose base is N down to the very bottom where base is 1, you would need to do something like this (sorry for crude pascalization of the code).
procedure PrintPins(i, n: Integer)
begin
if i >= n then return;
Ada.Text_IO.Put('I'); // Print pin
Ada.Text_IO.Put(' '); // Print space
PrintPins(i + 1, n); // Next iteration
end;
function Pins(x, indent: Integer): Integer
printed: Integer;
begin
printed := 0;
if x > 0 then
PrintSpaces(indent); // Print indentation pretty much using the same artificial approach as by printing pins
PrintPins(0, x);
(*Print new line here*)
(*Now go down the next level and print another
row*)
printed := x + Pins(x - 1, indent + 1);
end;
return printed;
end
P.S. You don't need a specific function to count the number of printed pins here. It's just a Gauss sequence sum of the range 1..N, which is given by N(N + 1)/2
A variation of this program is to use both head recursion and tail recursion in the same procedure.
The output of such a program is
Enter the number of rows in the pyramid: 5
I I I I I
I I I I
I I I
I I
I
I
I I
I I I
I I I I
I I I I I
N = 5
Tail recursion produces the upper triangle and head recursion produces the lower triangle.
The way you develop a recursive algorithm is to pretend that you already have a subprogram that does what you want, except for the first bit, and you know, or can figure out, how to do the first bit. Then your algorithm is
Do the first bit
Call the subprogram to do the rest on what remains,
taking into account the effect of the first bit, if necessary
The trick is that "Call the subprogram to do the rest" is a recursive call to the subprogram you're creating.
It's always possible that the subprogram may be called when there's nothing to do, so you have to take that into account:
if Ending Condition then
Do any final actions
return [expression];
end if;
Do the first bit
Call the subprogram to do the rest
And you're done. By repreatedly doing the first bit until the ending condition is True, you end up doing the whole thing.
As an example, the function Get_Line in Ada.Text_IO may be implemented (this is not how it is usually implemented) by thinking, "I know how to get the first Character of the line. If I have a function to return the rest of the line, then I can return the first Character concatenated with the function result." So:
function Get_Line return String is
C : Character;
begin
Get (Item => C);
return C & Get_Line;
end Get_Line;
But what if we're already at the end of a line, so there's no line to get?
function Get_Line return String is
C : Character;
begin
if End_Of_Line then
Skip_Line;
return "";
end if;
Get (Item => C);
return C & Get_Line;
end Get_Line;
For your problem the first bit is printing a row with an indent and a number of pins, and the ending condition is when there are no more rows to print.
For your pyramid problem, this tail recursion scheme doesn't work. You need to do "middle recursion":
if Level = 1 then
Print the line for Level
return
end if
Print the top line for Level
Recurse for Level - 1
Print the bottom line for Level
The lines:
type some_array_type is array (0 to 4, 0 to 4) of unsigned(7 downto 0);
signal some_array : some_array_type := (others=>(others=>'0'));
cause vivado 2018.2 to throw the error:
[Synth 8-1807] character '0' is not in type unresolved_unsigned
for some reason in a VHDL 2008 file. What it the magical syntax to get Vivado to realize that I'm just trying to initialize the array to zeros? I shouldn't have to write a function to do this. I also tried unsigned((others=>(others=>'0')));
The code below can of course be ignored and isn't needed for anything at all. It is just there for the OCD people. "You have to always include a minimal working example!"
library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
entity some_entity is
port (
clk, rst: in std_logic ;
);
end some_entity ;
architecture arch of some_entity is
type some_array_type is array (0 to 4, 0 to 4) of unsigned(7 downto 0);
-- throws error
signal some_array : some_array_type := (others=>(others=>'0'));
type some_other_array_type is array (natural range <>) of std_logic_vector(7 downto 0);
-- doesn't throw error
signal some_other_array : some_other_array_type(0 to 4) := (others=>(others=>'0'));
begin
-- some made up process
process(clk, rst)
begin
if(rising_edge(clk)) then
if rst = '1' then
some_array <= (others=>(others=>'0'));
else
some_array <= (others=>(others=>'1'));
end if;
end if;
end process;
end arch;
Here is a design for 4-bit asynchronous ripple counter (using T flip flop however I didn't define a component for Tff and just coded the behavior of circuit regarding T signals).
Following are the questions:
1.) inout ports, I first defined Q as inout (since it's obviously my output and the bits are also used as clk inputs to their following flip flops). Still, when I wanted to simulate my code, the Q output was UUUU which makes sense cause I had to initialize it with the number I wanted my count to begin with. Though I didn't know how to set an inout initial value (I tried Process ... Q <= "0000"; wait; end process but it didn't work)!
2.) In order to solve the above-mentioned problem I changed my inout port to out (Q_out) and defined Q as a signal, this worked BUT...my counter only changed the Q(0) bit and not the others...thus it counts like: 0,1,0,1,0,1,...
3.) I want to debug this code. I tried another style, instead of a 4-bit output I defined 4 1-bit output signals (Q_out1 to Q_out2) in addition to 4 internal signals Q0 to Q1 and this perfectly works
I just want to know why the first style (Q as a 4_bit vector) didn't work out.
thanks in advance for your help.
Here is my code and its test bench:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity four_bit_Asynch_Counter is
Port ( T0,T1,T2,T3 : in STD_LOGIC;
clk : in STD_LOGIC;
Q_out: out STD_LOGIC_VECTOR (3 downto 0));
end four_bit_Asynch_Counter;
architecture Behavioral of four_bit_Asynch_Counter is
signal Q : STD_LOGIC_VECTOR (3 downto 0) := "0000";
begin
Process (clk,Q(0),Q(1),Q(2))
begin
if (falling_edge(clk)) then
if (T0 = '1') then
Q(0) <= not Q(0);
else
Q(0) <= Q(0);
end if;
end if;
if (falling_edge(Q(0))) then
if (T1 = '1') then
Q(1) <= not Q(1);
else
Q(1) <= Q(1);
end if;
end if;
if (falling_edge(Q(1))) then
if (T2 = '1') then
Q(2) <= not Q(2);
else
Q(2) <= Q(2);
end if;
end if;
if (falling_edge(Q(2))) then
if (T3 = '1') then
Q(3) <= not Q(3);
else
Q(3) <= Q(3);
end if;
end if;
Q_out <= Q;
end Process;
end Behavioral;
--------------- Test Bench------------
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
ENTITY tb_counter IS
END tb_counter;
ARCHITECTURE behavior OF tb_counter IS
-- Component Declaration for the Unit Under Test (UUT)
COMPONENT four_bit_Asynch_Counter
PORT(
T0 : IN std_logic;
T1 : IN std_logic;
T2 : IN std_logic;
T3 : IN std_logic;
clk : IN std_logic;
Q_out : OUT std_logic_vector(3 downto 0)
);
END COMPONENT;
--Inputs
signal T0 : std_logic := '1';
signal T1 : std_logic := '1';
signal T2 : std_logic := '1';
signal T3 : std_logic := '1';
signal clk : std_logic := '0';
--Outputs
signal Q_out : std_logic_vector(3 downto 0);
-- Clock period definitions
constant clk_period : time := 10 ns;
BEGIN
-- Instantiate the Unit Under Test (UUT)
uut: four_bit_Asynch_Counter PORT MAP (
T0 => T0,
T1 => T1,
T2 => T2,
T3 => T3,
clk => clk,
Q_out => Q_out
);
-- Clock process definitions
clk_process :process
begin
clk <= '0';
wait for clk_period/2;
clk <= '1';
wait for clk_period/2;
end process;
-- Stimulus process
stim_proc: process
begin
-- hold reset state for 100 ns.
wait for 100 ns;
wait for clk_period*10;
-- insert stimulus here
wait;
end process;
END;
The TL;DR answer is that q(3) doesn't show up in your process sensitivity list.
architecture behavioral of four_bit_asynch_counter is
signal q: std_logic_vector (3 downto 0) := "0000";
begin
process (clk, q(0), q(1), q(2))
begin
if falling_edge(clk) then
if t0 = '1' then
q(0) <= not q(0);
-- else
-- q(0) <= q(0);
end if;
end if;
if falling_edge(q(0)) then
if t1 = '1' then
q(1) <= not q(1);
-- else
-- q(1) <= q(1);
end if;
end if;
if falling_edge(q(1)) then
if t2 = '1' then
q(2) <= not q(2);
-- else
-- q(2) <= q(2);
end if;
end if;
if falling_edge(q(2)) then
if t3 = '1' then
q(3) <= not q(3);
-- else
-- q(3) <= q(3);
end if;
end if;
q_out <= q;
end process;
end architecture behavioral;
For your process sensitivity list you've discovered a feature in how the sensitivity list is constructed from the expression consisting of primaries - clk, q(0), q(1), q(2).
From IEEE Std 1076 -1993, 8.1 Wait statement:
...
The sensitivity set is initially empty. For each primary in the condition of the condition clause, if the primary is
-- A simple name that denotes a signal, add the longest static prefix of the name to the sensitivity set
-- A selected name whose prefix denotes a signal, add the longest static prefix of the name to the sensitivity set
-- An expanded name whose prefix denotes a signal, add the longest static prefix of the name to the sensitivity set
-- An indexed name whose prefix denotes a signal, add the longest static prefix of the name to the sensitivity set and apply this rule to all expressions in the indexed name
...
...
This rule is also used to construct the sensitivity sets of the wait statements in the equivalent process statements for concurrent procedure call statements( 9.3 ), concurrent assertion statements ( 9.4 ), and concurrent signal assignment statements ( 9.5 ).
If a signal name that denotes a signal of a composite type appears in a sensitivity list, the effect is as if the name of each scalar subelement of that signal appears in the list.
...
I only included elements of the rule that are of interest here, the first covers the clock the last element shown covers the std_logic_vector elements specified by selected names.
It helps to understand what is meant by the longest static prefix. This explained in -1993 6.1 Names.
The primaries (indexed names) are static names (q(0), q(1), q(2)), every expression that's part of each indexed name is static.
This means the longest static prefix is the indexed name comprising each primary.
And this leaves q(3) dangling in the breeze for the process signal assignment statement:
q_out <= q;
Without sensitivity to q(3) the value of q_out is not updated until the next event in the sensitivity list, which happens to be on clk:
There are two ways to cure this, you could move the q_out assignment outside the process statement, where it becomes a concurrent signal assignment (with an elaborated equivalent process with a sensitivity list set to q), or you can change the sensitivity list in the present process:
process (clk, q)
So that q_out is updated for an event on q(3) (noting the last quoted paragraph in 8.1 above).
This behavior hold true for later revisions of the standard as well.
With the process sensitivity list is fixed:
Your counter behaves properly.
Also note I commented out the redundant else assignments to the q(0), q(1), q(2) and q(3) a signal will hold it's value until assigned and these are sequential (clocked) statements. Also eliminated the redundant parentheses pairs.
When implementing counters in realisable hardware (either ASIC or FPGA) you should never use a ripple counter. By using the flip-flop output as a clock to the next you will have sub-optimal timing, the tools will not be able to accurately validate the setup and hold times and you are not able to take advantage of dedicated clock routing. In general asynchronous design is a bad idea for real implementations.
A true synchronous design will be much better for synthesis and is much easier to infer in the VHDL code.
Examples of Counter implementations
See the above link for both verilog and vhdl examples of counter implementation.
I have this code
--RAM module
library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.numeric_std.all;
entity RAM is
generic(
address_length, data_length : integer);
port(
addr : in std_logic_vector(address_length-1 downto 0);
dat : inout std_logic_vector(data_length-1 downto 0);
rd, wr, en : in bit);
end entity RAM;
architecture RAM_impl of RAM is
type mem is array(2**address_length-1 downto 0) of std_logic_vector(data_length-1 downto 0);
begin
process(rd, wr, en)is
variable cont : mem;
begin
if(en = '1')then
if(wr = '1' and rd = '0')then
cont(to_integer(unsigned(addr))) := dat;
end if;
if(rd = '1' and wr = '0')then
dat <= cont(to_integer(unsigned(addr)));
end if;
end if;
end process;
end architecture RAM_impl;
--Test module
library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.numeric_std.all;
entity Example4RAM is
end entity Example4RAM;
architecture Tester of Example4RAM is
signal rd, wr, en : bit;
signal str : std_logic_vector(15 downto 0);
signal ext : std_logic_vector(7 downto 0);
begin
module : entity work.RAM(RAM_impl)
generic map(
address_length => 16,
data_length => 8)
port map(str, ext, rd, wr, en);
tt : process is
begin
str <= X"0001";
ext <= "00000000";
rd <= '0'; wr <= '1';
wait for 5 ns;
en <= '1';
wait for 5 ns;
rd <= '0'; wr <= '0';
wait for 10 ns;
rd <= '1'; wr <= '0';
end process;
end architecture Tester;
When i run simulation on this RAM module str vector initializes fine but ext vector stays uninitialized. In RAM module str is in vector and ext is inout vector. Is this somehow making problem and does anyone know the solution? (I did change source since yesterday but it doesn't work still)
I added a RAM module and tinkered with the test stimulus slightly (ext is driven to all 'Z's when wr goes invalid (the behavioral model requires no hold over).
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity RAM is
generic (
constant address_length: natural := 16;
constant data_length: natural := 8
);
port (
signal str: in std_logic_vector (address_length-1 downto 0);
signal ext: inout std_logic_vector (data_length-1 downto 0);
signal rd: in BIT;
signal wr: in BIT
);
end entity;
architecture RAM_impl of RAM is
type ram_array is array (natural range address_length-1 downto 0)
of std_logic_vector (data_length-1 downto 0);
signal mem_array: ram_array;
begin
MEMORY:
process (str, ext, rd, wr)
variable addr: natural range 0 to 2**address_length -1 ;
begin
addr := TO_INTEGER(UNSIGNED(str)); -- heed the warnings
if wr = '1' then
mem_array(addr) <= ext;
end if;
if rd = '0' then
ext <= (others => 'Z');
else
ext <= mem_array(addr);
end if;
end process;
end architecture;
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
-- use IEEE.numeric_std.ALL;
entity Example4RAM is
end entity Example4RAM;
architecture Tester of Example4RAM is
signal rd,wr,clk: bit;
signal str: std_logic_vector(15 downto 0);
signal ext: std_logic_vector(7 downto 0);
begin
module:
entity work.RAM(RAM_impl)
generic map (
address_length=>16,
data_length=>8
)
port map (
str,
ext,
rd,
wr
)
;
tt:
process
begin
str<=X"0001";
ext<="00000000";
wait for 5 ns;
rd<='0';wr<='1';
wait for 5 ns;
rd<='0';wr<='0';
ext <= (others => 'Z'); -- ADDED
wait for 10 ns;
rd<='1';wr<='0';
wait for 20 ns; -- ADDED
str <=X"0002"; -- ADDED
wait for 20 ns; -- ADDED
wait;
end process;
end architecture Tester;
The change to the stimulus includes a change to the RAM address showing that reading an uninitialized location returns 'U's (uu on the waveform):
ghdl -a exampleram.vhdl
ghdl -r Example4RAM --wave=Example4RAM.ghw
../../../../libraries/ieee/numeric_std-body.v93:2098:7:#0ms:(assertion warning):
NUMERIC_STD.TO_INTEGER: metavalue detected, returning 0
open *.ghw
Essentially, the process and the RAM drive ext with all 'Z's whenever either one shouldn't be driving a value out. Writing before reading hides the 'U' values from str address X"0001". As you see, if the address is changed to a location that is not initialized, the 'U's show up. Resolution delivers the RAM read data or provides write data to the RAM array on the bidirectional data bus (ext).
(This was done on a Mac with a ghdl mcode version (direct compile, like for Windows, requiring no explicit elaboration), and displayed using GTKWave).
The assertion warning (metavalue detected) comes from the default value assigned to str (all 'U's) at time zero (#0ms).