VHDL coding tips and tricks

Tuesday, April 5, 2022

Extension of Digital Clock Project with 7 segment Decoder

     In the last post I shared a Digital Clock VHDL code with you along with its testbench. Even though it was synthesizable, it would have been a bit cumbersome to test it on a FPGA board as it was. Because the timer outputs were of unsigned type, you would need to use LED's or something like that to see the time. But who would want a LED digital clock!?

    Many FPGA boards have 7 segment displays in them. And this post is to take advantage of such boards. We will take the initial steps to display the time on 7 segment displays. Of course the codes here would need some additional modifications, based on the type of 7 segment displays available on the board and if they share a common bus etc.. But as I mentioned, this is just an initial step.

    Without further ado, let me share the codes with you. I have commented the codes plus have uploaded an YouTube video explaining the code. If its useful to you in some way please like and comment on the video. As this helps me with the future direction this blog/YouTube channel will take.




Digital Clock: digital_clock.vhd

 You can get it from my last post: Digital Clock VHDL code

Binary to BCD Converter: bin2bcd.vhd

--Library declaration
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

--Binary to BCD Converter
entity bin2bcd is
port(	binary_in : in unsigned(5 downto 0);
	bcd_out : out unsigned(7 downto 0)	--8 bits(4 bits each for 2 digits)
	);
end bin2bcd;

architecture Behavioral of bin2bcd is

--actual value=0.0001100110011001101, so divide by 2^19.
constant one_by_ten : unsigned(15 downto 0) := "1100110011001101"; 
signal result_div_by_ten : unsigned(21 downto 0);
signal msb_digit : unsigned(3 downto 0);

begin

--divide the input by 10. In VHDL, division by a constant is 
--easily done by multiplication by its inverse.
result_div_by_ten <=  binary_in*one_by_ten;	
--get the decimal part of the result. Bits 18:0 are fractional part
msb_digit <= '0' & result_div_by_ten(21 downto 19);	
bcd_out(7 downto 4) <= msb_digit;	--assign it to MSB part of output 
--subtract the product, 10*msb_digit, from the input binary number to get LSB digit.
bcd_out(3 downto 0) <= to_unsigned(to_integer(binary_in) - to_integer(msb_digit)*10, 4);  

end Behavioral;

Top Module: digital_clock_topmodule.vhd

--Libraries
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

--Top module which instantiates and connect together the 3 components:
--Digital clock, Binary to BCD converter, BCD to 7 segment code converter
entity digital_clock_topmodule is
 --frequency of the clock passed as a generic parameter.
generic( 
		CLOCK_FREQ : integer := 50000000
		); 
port(	
		Clock : in std_logic;  --system clock
		reset : in std_logic;  --resets the time
		inc_secs : in std_logic;  --set a pulse here to increment the seconds by 1.
		inc_mins : in std_logic;  --set a pulse here to increment the minutes by 1.
		inc_hrs : in std_logic;  --set a pulse here to increment the hours by 1.
		secs_7seg1 :out unsigned(6 downto 0);  --seconds LSB digit
		secs_7seg10 :out unsigned(6 downto 0);  --seconds MSB digit
		mins_7seg1 :out unsigned(6 downto 0);  --minutes LSB digit
		mins_7seg10 :out unsigned(6 downto 0);  --minutes MSB digit
		hrs_7seg1 :out unsigned(6 downto 0);  --hours LSB digit
		hrs_7seg10 :out unsigned(6 downto 0)  --hours MSB digit
		);
end digital_clock_topmodule;

architecture Behavioral of digital_clock_topmodule is

	--Digital clock component
	COMPONENT digital_clock
	GENERIC( CLOCK_FREQ : integer := 50000000);
	PORT(
		Clock : IN  std_logic;
		reset : IN  std_logic;
		inc_secs : IN  std_logic;
		inc_mins : IN  std_logic;
		inc_hrs : IN  std_logic;
		seconds : OUT  unsigned(5 downto 0);
		minutes : OUT  unsigned(5 downto 0);
		hours : OUT  unsigned(4 downto 0)
		);
	END COMPONENT;
	 
	--Binary to BCD converter component
	COMPONENT bin2bcd is
	PORT(
		binary_in : in unsigned(5 downto 0);
		bcd_out : out unsigned(7 downto 0)
		);
	END COMPONENT;
	
	--Function to convert a BCD digit into a 7 segment code
	--Source: https://vhdlguru.blogspot.com/2010/03/vhdl-code-for-bcd-to-7-segment-display.html
	--The function is created by converting the code from the above link.
	function bcd2seg7(bcd_in : unsigned(3 downto 0)) return unsigned is
		variable segment7 : unsigned(6 downto 0);
	begin
		case bcd_in is
			when "0000"=> segment7 :="0000001";  -- '0'
			when "0001"=> segment7 :="1001111";  -- '1'
			when "0010"=> segment7 :="0010010";  -- '2'
			when "0011"=> segment7 :="0000110";  -- '3'
			when "0100"=> segment7 :="1001100";  -- '4'
			when "0101"=> segment7 :="0100100";  -- '5'
			when "0110"=> segment7 :="0100000";  -- '6'
			when "0111"=> segment7 :="0001111";  -- '7'
			when "1000"=> segment7 :="0000000";  -- '8'
			when "1001"=> segment7 :="0000100";  -- '9'
			 --nothing is displayed when a number more than 9 is given as input.
			when others=> segment7 :="1111111";
		end case;
		return segment7;
	end bcd2seg7;
	
	
	--Declare internal signals	
	signal seconds : unsigned(5 downto 0);
	signal minutes : unsigned(5 downto 0);
	signal hours : unsigned(4 downto 0);
	signal bcd_secs,bcd_mins,bcd_hrs : unsigned(7 downto 0);
	signal hours_extended : unsigned(5 downto 0);

	
begin

-- Instantiate the Digital Clock component
	uut: digital_clock 
		GENERIC MAP(CLOCK_FREQ => CLOCK_FREQ)
		PORT MAP (
			Clock => Clock,
			reset => reset,
			inc_secs => inc_secs,
			inc_mins => inc_mins,
			inc_hrs => inc_hrs,
			seconds => seconds,
			minutes => minutes,
			hours => hours
			);

	--convert binary to BCD for seconds
	bin2bcd_secs : bin2bcd 
		port map(
			binary_in => seconds,
			bcd_out => bcd_secs
			);

	--convert binary to BCD for minutes
	bin2bcd_mins : bin2bcd 
		port map(
			binary_in => minutes,
			bcd_out => bcd_mins
			);

	hours_extended <= '0' & hours;	--just make it the same size as seconds and minutes.
	--convert binary to BCD for hours
	bin2bcd_hrs : bin2bcd 
		port map(
			binary_in => hours_extended,
			bcd_out => bcd_hrs
			);
			
	--Call the bcd2seg7 function to convert each BCD digit into a 
  --format which can be used on the 7 segment display
	secs_7seg1 <= bcd2seg7(bcd_secs(3 downto 0));
	secs_7seg10 <= bcd2seg7(bcd_secs(7 downto 4));
	mins_7seg1 <= bcd2seg7(bcd_mins(3 downto 0));
	mins_7seg10 <= bcd2seg7(bcd_mins(7 downto 4));
	hrs_7seg1 <= bcd2seg7(bcd_hrs(3 downto 0));
	hrs_7seg10 <= bcd2seg7(bcd_hrs(7 downto 4));

end Behavioral;

Testbench for the top module: tb_digitalClock_topModule.vhd

LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
--the below library is used for finishing the simulation after we are done. 
--Otherwise it will run continously.
library std;
use std.env.finish;
 
ENTITY tb_digitalClock_topModule IS
END tb_digitalClock_topModule;
 
ARCHITECTURE behavior OF tb_digitalClock_topModule IS 
 
    -- Component Declaration for the Unit Under Test (UUT)
    COMPONENT digital_clock_topmodule is
	 --frequency of the clock passed as a generic parameter.
		generic( 
			CLOCK_FREQ : integer := 50000000
			); 
		port(	
			Clock : in std_logic;  --system clock
			reset : in std_logic;  --resets the time
			inc_secs : in std_logic;  --set a pulse here to increment the seconds by 1.
			inc_mins : in std_logic;  --set a pulse here to increment the minutes by 1.
			inc_hrs : in std_logic;  --set a pulse here to increment the hours by 1.
			secs_7seg1 :out unsigned(6 downto 0);  --seconds LSB digit
			secs_7seg10 :out unsigned(6 downto 0);  --seconds MSB digit
			mins_7seg1 :out unsigned(6 downto 0);  --minutes LSB digit
			mins_7seg10 :out unsigned(6 downto 0);  --minutes MSB digit
			hrs_7seg1 :out unsigned(6 downto 0);  --hours LSB digit
			hrs_7seg10 :out unsigned(6 downto 0)  --hours MSB digit
			);
		end COMPONENT;    

   --Inputs
   signal Clock : std_logic := '0';
   signal reset : std_logic := '0';
   signal inc_secs : std_logic := '0';
   signal inc_mins : std_logic := '0';
   signal inc_hrs : std_logic := '0';

 	--Outputs
   signal secs_7seg1,secs_7seg10 : unsigned(6 downto 0);
   signal mins_7seg1,mins_7seg10 : unsigned(6 downto 0);
   signal hrs_7seg1,hrs_7seg10 : unsigned(6 downto 0);
   -- Clock period definitions
   constant Clock_period : time := 10 ns;
	
	--Clock frequency in Hz. Use a smaller value for testbench. 
  --When testing on board it need to be set as 50 million, 100 million etc.
	constant CLOCK_FREQ : integer := 10;
 
BEGIN
 
	-- Instantiate the Unit Under Test (UUT)
   uut: digital_clock_topmodule 
		GENERIC MAP(CLOCK_FREQ => CLOCK_FREQ)
		PORT MAP (
          Clock => Clock,
          reset => reset,
          inc_secs => inc_secs,
          inc_mins => inc_mins,
          inc_hrs => inc_hrs,
          secs_7seg1 => secs_7seg1,
			 secs_7seg10 => secs_7seg10,
			 mins_7seg1 => mins_7seg1,
			 mins_7seg10 => mins_7seg10,
			 hrs_7seg1 => hrs_7seg1,
			 hrs_7seg10 => hrs_7seg10
        );

   -- Clock process definitions
   Clock_process :process
   begin
		Clock <= '0';
		wait for Clock_period/2;
		Clock <= '1';
		wait for Clock_period/2;
   end process;
 

   -- Stimulus process
   stim_proc: process
   begin		
		reset <= '1';
      -- hold reset state for 100 ns.
      wait for 100 ns;	
		reset <= '0';
      wait for Clock_period*CLOCK_FREQ*60*60*25;  --run the clock for 25 hours
		
		--increment seconds
		inc_secs <= '1';	wait for Clock_period;
		inc_secs <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing seconds once.
		
		--increment seconds 60 times
		inc_secs <= '1';	wait for Clock_period*60;
		inc_secs <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing seconds.
		
		--increment minutes
		inc_mins <= '1';	wait for Clock_period;
		inc_mins <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 mins after incrementing minutes once.
		
		--increment minutes 60 times
		inc_mins <= '1';	wait for Clock_period*60;
		inc_mins <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 mins after incrementing minutes.
		
		--increment hours
		inc_hrs <= '1';	wait for Clock_period;
		inc_hrs <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 hours after incrementing hours once.
		
		--increment hours 25 times
		inc_hrs <= '1';	wait for Clock_period*25;
		inc_hrs <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 hours after incrementing hours.
		
		--apply reset
		reset <= '1';
		
		--wait for 100 Clock cycles and then finish the simulation.
		--with the current settings it will run around 9 ms of simualtion time. 
		wait for Clock_period*100;
		finish;  
   end process;

END;

Top Level Block Diagrams:

The code was synthesized in Xilinx ISE 14.7. And the top level block diagram is shown below:




The inside view of the top module looks like this:






Sunday, April 3, 2022

Digital Clock (With ability to Set time) And Testbench in VHDL

    More than a decade back I had written a Digital Clock module in this blog, which was when I just started learning VHDL. Obviously it had its own shortcomings and through this post, I wanted to rectify these shortcomings. Plus add the ability to set time.

The codes are shared below. They are commented to help you understand the logic. For a detailed understanding watch the video. Also please make sure to like the video if it was helpful and subscribe to my YouTube channel for more such videos in the future. 




Digital Clock:

--Declare the libraries
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;  --we need this one because we are using "unsigned" data type.


entity digital_clock is
 --frequency of the clock passed as a generic parameter.
generic( CLOCK_FREQ : integer := 50000000	); 
port(	
		Clock : in std_logic;  --system clock
		reset : in std_logic;  --resets the time
		inc_secs : in std_logic;  --set a pulse here to increment the seconds by 1.
		inc_mins : in std_logic;  --set a pulse here to increment the minutes by 1.
		inc_hrs : in std_logic;  --set a pulse here to increment the hours by 1.
		seconds :out unsigned(5 downto 0);  --seconds output
		minutes :out unsigned(5 downto 0);  --minutes output
		hours :out unsigned(4 downto 0)  --hours output
		);
end digital_clock;

architecture Behavioral of digital_clock is

--temperory signals as we cant directly perform arithmetic operations on outputs
signal secs, mins, hrs : integer := 0;
--counter used for getting the 1 sec duration from the system Clock.
signal counter : integer := 0; begin process(Clock, reset) begin if(reset = '1') then --reset the time. secs <= 0; mins <= 0; hrs <= 0; counter <= 0; elsif(rising_edge(Clock)) then --increment the seconds. also increment mins and hours if needed. if(inc_secs = '1') then if(secs = 59) then secs <= 0; if(mins = 59) then mins <= 0; if(hrs = 23) then hrs <= 0; else hrs <= hrs+1; end if; else mins <= mins+1; end if; else secs <= secs + 1; end if; --increment the minutes. also increment hours if needed. elsif(inc_mins = '1') then if(mins = 59) then mins <= 0; if(hrs = 23) then hrs <= 0; else hrs <= hrs+1; end if; else mins <= mins+1; end if; --increment the hours. elsif(inc_hrs = '1') then if(hrs = 23) then hrs <= 0; else hrs <= hrs+1; end if; end if; --regular operation of the clock if(counter = CLOCK_FREQ-1) then --counting CLOCK_FREQ times takes 1 second. counter <= 0; --check and change values of secs, mins and hours if(secs = 59) then secs <= 0; if(mins = 59) then mins <= 0; if(hrs = 23) then hrs <= 0; else hrs <= hrs+1; end if; else mins <= mins+1; end if; else secs <= secs + 1; end if; else counter <= counter+1; end if; end if; end process; --The internal integer signals are converted into unsigned format. --The size of the output unsigned signal is assigned via the 2nd parameter(5 or 6 bits)
seconds <= to_unsigned(secs, 6);
minutes <= to_unsigned(mins, 6);
hours <= to_unsigned(hrs, 5);

end Behavioral;

Testbench:


LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
--the below library is used for finishing the simulation after we are done. 
--Otherwise it will run continuously.
library std;
use std.env.finish;
 
ENTITY tb_digitalClock IS
END tb_digitalClock;
 
ARCHITECTURE behavior OF tb_digitalClock IS 
 
    -- Component Declaration for the Unit Under Test (UUT)
 
    COMPONENT digital_clock
    generic( CLOCK_FREQ : integer := 50000000	); 
    PORT(
         Clock : IN  std_logic;
         reset : IN  std_logic;
         inc_secs : IN  std_logic;
         inc_mins : IN  std_logic;
         inc_hrs : IN  std_logic;
         seconds : OUT  unsigned(5 downto 0);
         minutes : OUT  unsigned(5 downto 0);
         hours : OUT  unsigned(4 downto 0)
        );
    END COMPONENT;
    

   --Inputs
   signal Clock : std_logic := '0';
   signal reset : std_logic := '0';
   signal inc_secs : std_logic := '0';
   signal inc_mins : std_logic := '0';
   signal inc_hrs : std_logic := '0';

 	--Outputs
   signal seconds : unsigned(5 downto 0);
   signal minutes : unsigned(5 downto 0);
   signal hours : unsigned(4 downto 0);

   -- Clock period definitions
   constant Clock_period : time := 10 ns;
	
	--Clock frequency in Hz. Use a smaller value for testbench. 
  --When testing on board it need to be set as 50 million, 100 million etc.
	constant CLOCK_FREQ : integer := 10;
 
BEGIN
 
	-- Instantiate the Unit Under Test (UUT)
   uut: digital_clock 
		GENERIC MAP(CLOCK_FREQ => CLOCK_FREQ)
		PORT MAP (
          Clock => Clock,
          reset => reset,
          inc_secs => inc_secs,
          inc_mins => inc_mins,
          inc_hrs => inc_hrs,
          seconds => seconds,
          minutes => minutes,
          hours => hours
        );

   -- Clock process definitions
   Clock_process :process
   begin
		Clock <= '0';
		wait for Clock_period/2;
		Clock <= '1';
		wait for Clock_period/2;
   end process;
 

   -- Stimulus process
   stim_proc: process
   begin		
		reset <= '1';
      -- hold reset state for 100 ns.
      wait for 100 ns;	
		reset <= '0';
      wait for Clock_period*CLOCK_FREQ*60*60*25;  --run the clock for 25 hours
		
		--increment seconds
		inc_secs <= '1';	wait for Clock_period;
		inc_secs <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing seconds once.
		
		--increment seconds 60 times
		inc_secs <= '1';	wait for Clock_period*60;
		inc_secs <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing seconds.
		
		--increment minutes
		inc_mins <= '1';	wait for Clock_period;
		inc_mins <= '0';	
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing minutes once.
--increment minutes 60 times inc_mins <= '1'; wait for Clock_period*60; inc_mins <= '0';
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing minutes.
--increment hours inc_hrs <= '1'; wait for Clock_period; inc_hrs <= '0';
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing hours once.
--increment hours 25 times inc_hrs <= '1'; wait for Clock_period*25; inc_hrs <= '0';
    wait for Clock_period*CLOCK_FREQ*5;	--wait for 5 secs after incrementing hours.
--apply reset reset <= '1'; --wait for 100 Clock cycles and then finish the simulation. --with the current settings it will run around 9 ms of simualtion time. wait for Clock_period*100; finish; end process; END;


So what next?

    As an extension of this project I want to show you how you can convert the time into BCD format and then connect a BCD to 7 segment converter to it. This will be useful for those who want to try this clock on a real FPGA board. Look forward to it in the next post.

So until next time...

Sunday, December 20, 2020

Image Processsing: RGB to Gray scale Converter in VHDL

    Implementing image processing algorithms in VHDL is a scary thing for many. Though I agree that its much more difficult to do it in VHDL than in a high level programming language like C, Matlab etc, it needn't be that scary.

    In this post I am going to share the code for a simple image processing algorithm - A RGB to Gray scale image converter. 

    There are many ways, from simple to complex, in which you can do this. I have done it in a way, which makes sense to me. Touching upon few topics related to this subject. For example reading the image data from a text file, storing it in RAM and accessing the data within the code and then manipulating them etc...

    I have used the standard Matlab image Lenna.bmp for this. The original image was 512*512*3 pixels in size. This takes a long time to load and run in Modelsim. So I first reduced its size to 1/8th of its original size, making it a 64*64*3 pixel image. Each pixel ranges from 0 to 255 and the dimension "3" indicates the presence of Red, Green and Blue components.

    VHDL text file operations aren't ideal for reading multiple pixels from the same row. So I converted the 3 Dimensional image data into a 1 Dimensional matrix. And then used dlmwrite Matlab command to write it to a text file named rgb.txt. This will be our input image.

    In Matlab, I manually converted the above RGB image into a gray scale image using the formula:

 Grayscale Image = ( (0.3 * R) + (0.59 * G) + (0.11 * B) ).

    The above grayscale pixels were converted to a 1-D matrix and written to a text file called gray.txt. This text file would be read by our VHDL testbench to verify that the results from our VHDL design is the same as the ideal result obtained from Matlab.

The Matlab program which I used for achieving all this is shared below:


I=imread('Lenna.bmp');  %read the image into memory

I=imresize(I,1/8);  %reduce the size by 8 times.

%convert image to 1-D array and write it to a text file.

dlmwrite('rgb.txt',reshape(I,64*64*3,1,1));

I4=double(I);   %convert it to double format

%convert rgb pixels to gray manually as per formula.

for i=1:64

    for j=1:64

        I2(i,j) = I4(i,j,1)*0.3 + I4(i,j,2)*0.59 + I4(i,j,3)*0.11;

    end

end

%the converted image is changed to 1-D and then written to a text file.

I3=reshape(I2,64*64,1);

dlmwrite('gray.txt',I3);


    The standard RGB format Lenna image, the resized version of it and the converted Grayscale image are shared below:




    Now that we have prepared the above basic data to work with, we can go and explore the VHDL designs. There are three VHDL files in this project:

1) im_ram.vhd:

    The input RGB image is internally stored in a RAM. The RAM is declared and initialized with the pixel values from the text file rgb.txt. The std.textio library is used, to do the file reading operations.


--RAM entity for storing the image.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
--the below libraries are needed for reading text file.
library std;
use std.textio.all;

entity im_ram is
    generic(
        ADDR_WIDTH : integer := 16; --Address bus size of the Image Ram.
        IM_SIZE_D1 : integer := 64; --Size along Dimension 1
        IM_SIZE_D2 : integer := 64  --Size along Dimension 2
    );
    port (
        Clk : in std_logic;
        addr_in : in unsigned(ADDR_WIDTH-1 downto 0);   --Address bus to the Image Ram.
        rgb_out : out std_logic_vector(23 downto 0) --24 bit RGB pixel output
    );
end im_ram;

architecture Behav of im_ram is

--custom array declaration.
type im_ram_type is array (0 to  IM_SIZE_D1*IM_SIZE_D2-1) of std_logic_vector(23 downto 0);

--function for reading the image pixels from text file and use
--it to initialize the RAM.
impure function im_ram_initialize return im_ram_type is
    variable line_var : line;
    file text_var : text;
    variable pixel : integer;
    variable image_pixels : im_ram_type;
begin        
    --Open the file in read mode.
    file_open(text_var,"rgb.txt",read_mode);    
    while(NOT ENDFILE(text_var)) loop   --until end of file is reached
        for k in 1 to 3 loop    --through R, G and B.
            for j in 0 to IM_SIZE_D2-1 loop
                for i in 0 to IM_SIZE_D1-1 loop
                    readline(text_var,line_var);   --read one row. Each row contains one pixel.
                    read(line_var,pixel);   --From the read line, read the integer value.
                    --save the pixel in the RAM.
                    image_pixels(i*IM_SIZE_D2+j)(k*8-1 downto k*8-8) := std_logic_vector(to_unsigned(pixel,8));
                end loop;
            end loop;
        end loop;
    end loop;
    file_close(text_var); --close the file after reading.
    return image_pixels;    
end function;

--declare and initialize the image ram.
signal ram : im_ram_type := im_ram_initialize;

begin

--read the R,G and B pixels from RAM with the addr_in input.
rgb_out <= ram(to_integer(addr_in));

end architecture;


2) rgb2gray.vhd:

    This is the top level entity which converts the image from RGB format to Grayscale. The RAM block is instantiated as a component inside this entity. 


--Convert a internally stored RGB image into gray image.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity rgb2gray is
    generic(
        ADDR_WIDTH : integer := 16; --Address bus size of the Image Ram.
        IM_SIZE_D1 : integer := 64; --Size along Dimension 1
        IM_SIZE_D2 : integer := 64  --Size along Dimension 2
    );
    port (
        Clk : in std_logic;
        reset : in std_logic;   --active high asynchronous reset
        data_valid : out  std_logic;    --High when gray_out has valid output.
        gray_out : out unsigned(7 downto 0) --8 bit gray pixel output
    );
end rgb2gray;

architecture Behav of rgb2gray is

    component im_ram is
        generic(
            ADDR_WIDTH : integer := 16; --Address bus size of the Image Ram.
            IM_SIZE_D1 : integer := 64; --Size along Dimension 1
            IM_SIZE_D2 : integer := 64  --Size along Dimension 2
        );
        port (
            Clk : in std_logic;
            addr_in : in unsigned(ADDR_WIDTH-1 downto 0);   --Address bus to the Image Ram.
            rgb_out : out std_logic_vector(23 downto 0) --24 bit RGB pixel output
        );
    end component;

    signal rgb_out : std_logic_vector(23 downto 0);
    signal addr_in : unsigned(ADDR_WIDTH-1 downto 0);

begin

    --Instantiation of Image RAM. Internally stored image.
    image_ram : im_ram generic map(ADDR_WIDTH,  IM_SIZE_D1 ,IM_SIZE_D2)
        port map(Clk, addr_in, rgb_out);

    --Process to convert RGB to Gray image.
    CONVERTER_PROC : process(Clk,reset)
        --temperary variables
        variable temp1,temp2,temp3,temp4 : unsigned(15 downto 0);
    begin
        if(reset = '1') then    --active high asynchronous reset
            addr_in <= (others => '0');
            data_valid <= '0';
        elsif rising_edge(Clk) then
            --output is ready when the last address in the ram has reached.
            if(to_integer(addr_in) = IM_SIZE_D1*IM_SIZE_D2-1) then  
                addr_in <= (others => '0');
                data_valid <= '0';
            else    --otherwise keep incrementing the address value.
                addr_in <= addr_in + 1;
                data_valid <= '1';  --indicates output is ready
            end if;
            --Gray pixel = 0.3*Red pixel + 0.59*Green pixel + 0.11*Blue pixel
            --the 24 bit value is split into R,G and B components and multiplied
            --with their respective weights and then added together.
            temp1 := "01001100" * unsigned(rgb_out(7 downto 0));        --(0.3 * R)  
            temp2 := "10010111" * unsigned(rgb_out(15 downto 8));       --(0.59 * G) 
            temp3 := "00011100" * unsigned(rgb_out(23 downto 16));  --(0.11 * B)
            temp4 := temp1 + temp2 + temp3;
            --Most significant bit of the LSB portion is added to the MSB portion. 
            --To round off the result.
            gray_out <= temp4(15 downto 8) + ("0000000" & temp4(7));
        end if;
    end process;

end architecture;


3) tb.vhd:

    This is the testbench for testing our main designs. The output image is received from the main design and compared with the actual result. Previously using Matlab, we have saved the actual result in a file called gray.txt .


--Testbench
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
--the below libraries are needed for reading text file.
library std;
use std.textio.all;

--Testbench entity is always empty.
entity tb is
end tb;

architecture sim of tb is

    --the generic parameters are declared and initialized as constants here.
    constant IM_SIZE_D1: integer := 64;
    constant IM_SIZE_D2: integer := 64; --we have a 64*64 image.
    constant ADDR_WIDTH: integer := 12; --64*64=4096 which needs 12 bits.
    
    --this array is used to store the output gray pixels.
    type image_type is array (1 to  IM_SIZE_D1, 1 to  IM_SIZE_D2) of integer;
    signal image_pixels : image_type := (others => (others => 0));

    --component declaration.
    component rgb2gray is
        generic(
            ADDR_WIDTH : integer := 16;
            IM_SIZE_D1 : integer := 64;
            IM_SIZE_D2 : integer := 64
        );
        port (
            Clk : in std_logic;
            reset : in std_logic;
            data_valid : out  std_logic;
            gray_out : out unsigned(7 downto 0)
        );
    end component;

    --temperory signal declarations.
    signal Clk,reset,data_valid : std_logic := '0';
    signal gray_out : unsigned(7 downto 0);
    constant Clk_period : time := 10 ns;    --clock period.

begin

    --generate the clock signal.
    Clk <= not Clk after Clk_period/2;

    --Instantiate the Unit under test.
    UUT : rgb2gray generic map(ADDR_WIDTH, IM_SIZE_D1, IM_SIZE_D2)
            port map(Clk, reset, data_valid, gray_out);


    --Process where we apply inputs, read outputs and verify the result.        
    STIMULUS_PROC : process
        variable i,j : integer := 1;    --loop indices.
        variable line_var : line;
        file text_var : text;
        variable pixel : integer;
        variable error : integer := 0;  --this value should be zero at the end of simulation.
        variable diff : image_type := (others => (others => 0));    
    begin
        reset <= '1';
        wait for Clk_period;
        reset <= '0';   --reset is applied for one clock cycle.
        wait until data_valid = '1';    --wait for valid data at the output port.
        while(data_valid = '1') loop
            wait until (falling_edge(Clk)); --sample outputs at the falling edge of clock
            image_pixels(i,j) <= to_integer(gray_out);  --save pixel as integer.
            --generate indices to save the pixels in the correct place.
            if(j = IM_SIZE_D2) then
                j := 1;
                if(i = IM_SIZE_D1) then
                    i := 1;
                else
                    i := i+1;
                end if;
            else
                j := j+1;
            end if; 
            wait until (rising_edge(Clk));  --pause until rising edge of the clock 
        end loop;
        --all output gray pixels are read. Activate reset again.
        reset <= '1';

        --Now check if the results are the same as in Matlab
        --Open the file in read mode. gray.txt contains pixels calculated using Matlab.
        file_open(text_var,"gray.txt",read_mode);   
        while(NOT ENDFILE(text_var)) loop   --until end of file is reached
            for j in 1 to IM_SIZE_D2 loop
                for i in 1 to IM_SIZE_D1 loop
                    readline(text_var,line_var);   --read one row. Each row contains one pixel.
                    read(line_var,pixel);
                    --calculate the difference between actual gray pixels from Matlab
                    --and pixel values from our rgb2gray VHDL design.
                    diff(i,j) := abs(image_pixels(i,j) - pixel);
                    --If the difference is 2 or more then, we take it as an error
                    --and increment the variable 'error' by 1.
                    if(diff(i,j) > 1) then
                        error := error+1;
                    end if;
                    wait for 1 ns;  --pause for 1 ns. 
                end loop;
            end loop;
        end loop;
        file_close(text_var); --close the file after reading.

        wait;   --wait eternally after finishing simulation.
    end process;

end architecture;   --End of Testbench


    Note that IM_SIZE_D1 and IM_SIZE_D2 are the number of rows and columns respectively of the image matrix. You can read it as a short form for "Image size along dimension 1 (or) 2".

     In the testbench we have a variable matrix called "diff". This matrix contains the absolute value  of difference between gray image pixels, from Matlab and VHDL. A difference of "1" is considered okay, as binary multiplications can cause some loss of least significant bits. But more than a difference of "1" is considered as an error. We can see that at the end of simulation, we didn't get any "error". 

    There is no address output from the top level entity rgb2gray. In our design, I thought it was unnecessary, because the pixel outputs were coming out in a sequential manner. So the testbench "knew" where to place each output pixel.

    I hope this post was helpful for you and gave you some ideas on how to do image processing using VHDL.

    You can Download the VHDL codes, images etc from Here.