Verilog Hex to Seven Segment Display


We will be moving on to write slightly more complex example, this time a hex to seven segment encoder. Basically LED number is displayed with 7 segments.


The hexadecimal to 7 segment encoder has 4 bit input and 7 output. Depending upon the input number, some of the 7 segments are displayed. The seven segments are represented as a,b,c,d,e,f,g. A high on one of these segements make it display. For example to write 1 we need to display segments b and C.

The 7 segment display also has a decimal point dp.


The figure below explains this Let write this example making use of the verilog case statement
  1. // www.referencedesigner.com
  2. // Verilog Tutorial
  3. // Hex to 7 Segment Example
  4.  
  5. module hexto7segment(
  6. input [3:0]x,
  7. output reg [6:0]z
  8. );
  9. always @*
  10. case (x)
  11. 4'b0000 : //Hexadecimal 0
  12. z = 7'b1111110;
  13. 4'b0001 : //Hexadecimal 1
  14. z = 7'b0110000 ;
  15. 4'b0010 : // Hexadecimal 2
  16. z = 7'b1101101 ;
  17. 4'b0011 : // Hexadecimal 3
  18. z = 7'b1111001 ;
  19. 4'b0100 : // Hexadecimal 4
  20. z = 7'b0110011 ;
  21. 4'b0101 : // Hexadecimal 5
  22. z = 7'b1011011 ;
  23. 4'b0110 : // Hexadecimal 6
  24. z = 7'b1011111 ;
  25. 4'b0111 : // Hexadecimal 7
  26. z = 7'b1110000;
  27. 4'b1000 : //Hexadecimal 8
  28. z = 7'b1111111;
  29. 4'b1001 : //Hexadecimal 9
  30. z = 7'b1111011 ;
  31. 4'b1010 : // Hexadecimal A
  32. z = 7'b1110111 ;
  33. 4'b1011 : // Hexadecimal B
  34. z = 7'b0011111;
  35. 4'b1100 : // Hexadecimal C
  36. z = 7'b1001110 ;
  37. 4'b1101 : // Hexadecimal D
  38. z = 7'b0111101 ;
  39. 4'b1110 : // Hexadecimal E
  40. z = 7'b1001111 ;
  41. 4'b1111 : // Hexadecimal F
  42. z = 7'b1000111 ;
  43. endcase
  44.  
  45. endmodule


Note that we had to assign out as a register in

reg out;




In our case, it was not required because we had only one statement. We now suggest that you write a test bench for this code and verify that it works. If you have sifficulty, you can check it with following test bench

  1. `timescale 1ns / 1ps
  2. module stimulus;
  3. // Inputs
  4. reg [3:0] x;
  5. // Outputs
  6. wire [6:0] z;
  7. // Instantiate the Unit Under Test (UUT)
  8. hexto7segment uut (
  9. .x(x),
  10. .z(z)
  11. );
  12.  
  13. initial begin
  14. // Initialize Inputs
  15. x = 0;
  16.  
  17. #20 x = 1;
  18. #20 x = 2;
  19. #20 x = 3;
  20. #20 x = 4;
  21. #20 x = 5;
  22. #20 x = 6;
  23. #20 x = 7;
  24. #20 x = 8;
  25. #20 x = 9;
  26. #20 x = 10;
  27. #20 x = 11;
  28. #20 x = 12;
  29. #20 x = 13;
  30. #20 x = 14;
  31. #20 x = 15;
  32. #40;
  33. end
  34.  
  35. initial begin
  36. $monitor("x=%h,z=%7b",x,z);
  37. end
  38.  
  39. endmodule





Exercise

1. Change the above hex to BCD verilog code so that it take negative logic. A segment is on when it gets 0. A segment is off when it gets logic 1.