Nov 29, 2016

The Future of Semiconductor


Everyone in semiconductor industry is wondering  ,where semiconductor industry will go in next 5 years or so .. what are the career opportunities and scope in future at fresher level as well as experience level ?

We heard a lot of top semiconductor companies are doing layoff , they are going in loss and shutting down their units in all over the world.... but the good news is ,there are opportunities in semiconductor market to grow up.

I think everyone in VLSI must have heard about the Moore's law , if not then you can see at
http://en.wikipedia.org/wiki/Moore's_law

From Wikipedia -

Moore's law is the observation that, over the history of computing hardware, the number of transistors on integrated circuits doubles approximately every two years.



My wild guess is , the future product will now more focus on power saving logic , and it will going to explore more on physical level. Instead of reducing the size of transistor, people will think more to save power at transistor level.

All power consumption happen at transistor level only, if you move in that area, this might be a turning point of your career. Low-Power Design will be more preferable in market.

Back to the topic , in last 50 years , semiconductor industry have been all about the manifestation of Moore's law with respect to scal of integrated circuit. but as a consumer , what are the thing we would like to see in a electronics device .... first thing we look for is the cost and then we look for the features. But now it's close to saturation and we will not see much cost difference going forward as we saw in last 20 years .. where Nokia mobile phone comes around 15K INR and now same model you can get it in 2K INR ... its a huge difference. 

The chart below, published by IBS about 3 years ago, shows the diminishing benefit of cost reduction from dimensional scaling. In fact, the chart indicates that the 20nm node might be associated with higher cost than the previous node.




The following (somewhat busy) slide from IBM summarizes things clearly saying: "Net: neither per wafer nor per gate showing historical cost reduction trends"



With increasing cost in capitals, process, R&D , design and manufacturing, it is really impossible to provide more cheap device with high features loaded.

There is one more reason the sharp increase of costs with scaling , in previous days, moving from one node (one technology like 40nm ) to other node , there were always cost associated with but as comparative , it was small.

What's coming in future ??

Think carefully and tell , what is the future of semiconductor  ??  Design guys will get the design for next 5 or 8 years and once designs are there verification guys will also get the work .. for next 5 or 8 years atleast but then what will happen ?  Will all design , verification , P&R guys sits ideal and waiting for new technology  ?

There are saturation in all places , markets cracks and start from begin. But in semiconductor , there is no start from begin , people will have to think more deep and will have to come up with innovative ideas which will help to keep semiconductor industry moving.


People who are thinking to make career in this field , should think again. In 1995 , there were not many guys working in semiconductor , but from 2006/7/8 , many guys have started working in semiconductor domain .. after 5 years there will be many guys having 10+ years of exp ... what will be the scope for freshers that time ??

So My question is still there .... What coming next ???

I think 28nm will be in market for next 3-5 years because 28nm TSMC is very good technology and full fill the designers dream to get their block working at high frequency without any timing issue .. but there are always limitation :) .

20nm,14nm, 10nm, 7nm are also an upcoming technology, one having interest can explore more on that.

If you like the blog... Put your comments here :)
Also write your views about the future of Semiconductor.

A few example of Verilog Code 


source - 
http://www.eetimes.com/author.asp?section_id=36&doc_id=1286363

VHDL operator


VHDL Operators

   Highest precedence first,
   left to right within same precedence group,
   use parenthesis to control order.
   Unary operators take an operand on the right.
   "result same" means the result is the same as the right operand.
   Binary operators take an operand on the left and right.
   "result same" means the result is the same as the left operand.

**   exponentiation,  numeric ** integer,  result numeric
abs  absolute value,  abs numeric,  result numeric
not  complement,      not logic or boolean,  result same

*    multiplication,  numeric * numeric,  result numeric
/    division,        numeric / numeric,  result numeric
mod  modulo,          integer mod integer,  result integer
rem  remainder,       integer rem integer,  result integer

+    unary plus,      + numeric,  result numeric
-    unary minus,     - numeric,  result numeric

+    addition,        numeric + numeric,  result numeric
-    subtraction,     numeric - numeric,  result numeric
&    concatenation,   array or element & array or element,
                        result array

sll  shift left logical,     logical array sll integer,  result same
srl  shift right logical,    logical array srl integer,  result same
sla  shift left arithmetic,  logical array sla integer,  result same
sra  shift right arithmetic, logical array sra integer,  result same
rol  rotate left,            logical array rol integer,  result same
ror  rotate right,           logical array ror integer,  result same

=    test for equality, result is boolean
/=   test for inequality, result is boolean
<    test for less than, result is boolean
<=   test for less than or equal, result is boolean
>    test for greater than, result is boolean
>=   test for greater than or equal, result is boolean

and  logical and,                logical array or boolean,  result is same
or   logical or,                 logical array or boolean,  result is same
nand logical complement of and,  logical array or boolean,  result is same
nor  logical complement of or,   logical array or boolean,  result is same
xor  logical exclusive or,       logical array or boolean,  result is same
xnor logical complement of exclusive or,  logical array or boolean,  result is same

Nov 26, 2016

Type of Adders with Verilog Code


Addition on 2 -bit  ->

d_out[1:0] =  a_in + b_in ;


Half Adder ->






Full Adder -->







Verilog Code ->


Half Adder -> 
module half_adder(a,b,sum,carry);
input a,b;
output sum, carry;
wire sum, carry;
assign sum = a^b; // sum bit
assign carry = (a&amp;b) ;
endmodule


Types of Adders :
  1. Ripple Carry Adder 
  2. Carry Lookahead Adder
  3. RCLA (Ripple block carry lookahead adder)
  4. BCLA (Binary carry lookahead adder)
  5. conditional sum adder 
  6. carry select adder 
  7. carry skip adder 
    8.Parallel prefix adder -
  • Ladner-Fischer adder
  • Kogge-Stone adder
  • Brent-Kung adder
  • Han-Carlson adder

Ripple Carry Adder -> 
The most straightforward implementation of a final stage adder for two n-bit operands is a ripple carry adder, which requires n full adders (FAs). The carry-out of the ith FA is connected to the carry-in of the (i+1)th FA. Figure 1 shows a ripple carry adder for n-bit operands, producing n-bit sum outputs and a carry out. 


Verilog Code for Ripple carry Adder - 

-------------------------------------------------------------------- VERILOG CODE --------------------------------
module ripple_carry_adder ( 
 input [n-1:0] A_in,
 input [n-1:0] B_in,
 output [n-1:0] Sum,
 output Cn 
);


parameter n =10;

full_adder i_full_adder_0 ( .A(A_in[0] , .B(B_in[0], .sum(sum[0]) , .cin(1'b0), .cout(carry[0]) );

genvar c;
generate
for(c=1 ; c < n ; c = c +1) begin

  full_adder i_full_adder[c] ( .A(A_in[c]),
  .B(B_in[c]),
  .sum(sum[c]),
  .cin(carry[c-1]) ,
  .cout(carry[c])
  );
end

endgenerate

endmodule
-------------------------------------------------------------------- VERILOG CODE End -------------------------

Carry Lookahead Adder

 ---- Ref ---
 http://www.aoki.ecei.tohoku.ac.jp/arith/mg/algorithm.html#fsa_pfx

Nov 25, 2016

Verilog Code for the counting number of 1's and 0's


Here is the verilog code for counting number of 1's and number of 0's in parallel data. since data is continuously changing on every clock cycle,  counting has to be done using parallel hardware.

Below is the code with testbench and simulation result :-

Does anyone know what will be the hardware synthesis tool will make ?

Is it going to be encoder , or  multiple adders or full of mux ??

---------------------------- Verilog Code ------------------

module count1n0 (
input clk,
input rstn,
input [9:0] data,
output reg [3:0] num_of_one,
output reg [3:0] num_of_zero
);

 

 always @(*) begin
      num_of_one  = 4'b0;
      num_of_zero = 4'b0;

    if(!data[0])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one + 1 ;

    if(!data[1])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[2])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[3])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[4])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[5])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[6])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[7])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[8])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

    if(!data[9])
      num_of_zero = num_of_zero + 1;
    else
      num_of_one = num_of_one +1 ;

  end

endmodule
------------------------------------------------------

------------------- Verilog Testbench ----------------

module tb;

reg clk;
reg rstn;
reg [9:0] count;
wire [3:0] one;
wire [3:0] zero;

initial begin
clk =0;
rstn =0;
count =0;
end

initial begin
#100;
rstn = 1 ;
#1000;
$finish;
end

initial $monitor("data = %b, num of zero = %d, num_of_one = %d ", count , zero, one);

always @(negedge clk) begin
count = count + 1297;
end

always #5 clk = ~clk ;

count1n0 dut (
.clk(clk),
.rstn(rstn),
.data(count),
.num_of_one(one),
.num_of_zero(zero)
);

initial begin
 $recordfile("test.trn");
 $recordvars();
end

endmodule
----------------------------------------------------

-------------------Simulation Result - -------------
data = 0000000000, num of zero = 10, num_of_one =  0 
data = 0100010001, num of zero =  7, num_of_one =  3 
data = 1000100010, num of zero =  7, num_of_one =  3 
data = 1100110011, num of zero =  4, num_of_one =  6 
data = 0001000100, num of zero =  8, num_of_one =  2 
data = 0101010101, num of zero =  5, num_of_one =  5 
data = 1001100110, num of zero =  5, num_of_one =  5 
data = 1101110111, num of zero =  2, num_of_one =  8 
data = 0010001000, num of zero =  8, num_of_one =  2 
data = 0110011001, num of zero =  5, num_of_one =  5 
data = 1010101010, num of zero =  5, num_of_one =  5 
data = 1110111011, num of zero =  2, num_of_one =  8 
data = 0011001100, num of zero =  6, num_of_one =  4 
data = 0111011101, num of zero =  3, num_of_one =  7 
data = 1011101110, num of zero =  3, num_of_one =  7 
data = 1111111111, num of zero =  0, num_of_one = 10 
data = 0100010000, num of zero =  8, num_of_one =  2 
data = 1000100001, num of zero =  7, num_of_one =  3 
data = 1100110010, num of zero =  5, num_of_one =  5 
data = 0001000011, num of zero =  7, num_of_one =  3 
data = 0101010100, num of zero =  6, num_of_one =  4 
data = 1001100101, num of zero =  5, num_of_one =  5 
data = 1101110110, num of zero =  3, num_of_one =  7 
data = 0010000111, num of zero =  6, num_of_one =  4 
data = 0110011000, num of zero =  6, num_of_one =  4 
data = 1010101001, num of zero =  5, num_of_one =  5 
data = 1110111010, num of zero =  3, num_of_one =  7 
data = 0011001011, num of zero =  5, num_of_one =  5 
data = 0111011100, num of zero =  4, num_of_one =  6 
data = 1011101101, num of zero =  3, num_of_one =  7 
data = 1111111110, num of zero =  1, num_of_one =  9 
data = 0100001111, num of zero =  5, num_of_one =  5 
data = 1000100000, num of zero =  8, num_of_one =  2 
data = 1100110001, num of zero =  5, num_of_one =  5 
data = 0001000010, num of zero =  8, num_of_one =  2 
data = 0101010011, num of zero =  5, num_of_one =  5 
data = 1001100100, num of zero =  6, num_of_one =  4 
data = 1101110101, num of zero =  3, num_of_one =  7 
data = 0010000110, num of zero =  7, num_of_one =  3 
data = 0110010111, num of zero =  4, num_of_one =  6 
data = 1010101000, num of zero =  6, num_of_one =  4 
data = 1110111001, num of zero =  3, num_of_one =  7 
data = 0011001010, num of zero =  6, num_of_one =  4 
data = 0111011011, num of zero =  3, num_of_one =  7 
data = 1011101100, num of zero =  4, num_of_one =  6 
data = 1111111101, num of zero =  1, num_of_one =  9 
data = 0100001110, num of zero =  6, num_of_one =  4 
data = 1000011111, num of zero =  4, num_of_one =  6 
data = 1100110000, num of zero =  6, num_of_one =  4 
data = 0001000001, num of zero =  8, num_of_one =  2 
data = 0101010010, num of zero =  6, num_of_one =  4 
data = 1001100011, num of zero =  5, num_of_one =  5 
data = 1101110100, num of zero =  4, num_of_one =  6 
--------------------------------------------------------------

Thanks for visiting my blog. 


Nov 24, 2016

Running Disparity


Disparity 

In order to create a DC-balanced data stream, the concept of disparity is employed to balance the number of 0s and 1s. 

The disparity of a block is calculated by the number of 1s minus the number of 0s. The value of a block that has a zero disparity is called disparity neutral. If both the 4-bit and 6-bit blocks are disparity neutral, a combined 10-bit encoded data will be disparity neutral as well. This will create a perfect DC-balanced code. 
However, this is not possible. Because only 6 out of the 16 possible values of the 4-bit block are disparity neutral, they are not enough for encoding the 8 values of the 3-bit block. 
Likewise, only 20 values of the 6-bit block are disparity neutral and they are not enough for encoding the 32 values of the 5-bit block. Because both the 4-bit and 6-bit blocks have an even number of bits, the disparity is not possible to be +1 or -1. Therefore, the values with a disparity of +2 and -2 are also used in the 8b/10b coding scheme. 

Table 1 and Table 2 are the values that are used for the 3-bit to 4-bit encoding and the 5-bit to 6-bit encoding respectively. Concatenating the 4-bit and 6-bit blocks together generates the 10-bit encoded value. Note that some of the encoded values in Table 1 and Table 2 have two possible values, one with a disparity value of +2 and the other with a disparity value of -2. The 8b/10b coding scheme was designed to combine the values of the 4-bit and 6-bit blocks perfectly so that the worst case disparity value of the 10-bit code group will be at most +2 or -2. 

For H G F E D C B A Dx.y a b c d e i f g h j MSB LSB LSB MSB LSB MSB 8b 10b or Kx.y code group 8b/10b Encoder/Decoder 3 example, the 4-bit encoded values with disparity value+2 will not be combined with the 6-bit encoded values with disparity value +2 because this will create a 10-bit value with disparity value +4.

In General , What is running disparity ?
Here is the definition -
Running disparity is the difference between the number of logic 1 bits and logic 0 bits between the start of a data sequence and a particular instant in time during its transmission. The RD for a character is the difference between the number of 1 bits and 0 bits in that character. If there are more 1 bits than 0 bits, the RD is defined as positive. If there are fewer 1 bits than 0 bits, the RD is defined as negative. If the number of 1 bits and 0 bits is the same, the RD is defined as neutral or zero.

As it is said, Running disparity is useful in DC balancing. After encoding 8-bit into 10-bits, few words still have more 1's than 0's or more 0's than 1's. DC balancing can be adjusted based on the running disparity.


So the next question is , How to calculate the running disparity ?
Answer is ,find out the number of 1's and number of 0's in the parallel data and based on the comparison , running disparity can be calculated.

Next question is , How to check the DC balance ?
Answer is , DC balancing is check the number of 1's and 0's in the data stream for a period of time , difference between number of 1's and 0's should not be large, if it is large , it means the encoding is not correctly implemented.

Please share your views or comments if you have any.
Thanks for reading my blog, have a nice day.

Nov 17, 2016

Verilog Code for FIR Filter


FIR filters are is widely used in different applications such as biomedical, communication and control due to its easily implementation, stability and best performance. Its simplicity makes it attractive for many applications where it is need to minimize computational requirements.

Below is the code for FIR Filter , Any comments/doubts are welcome.

Please contact me if you want a soft copy of the module.

Block diagram :


F is the flopped stage and C1/C2/C3/C4/C5  are the coefficient. One bug adder will required to add all the feedback.

Below is the verilog code for FIR filter with test bench.
-----------

module fir_filter (  a, b, clk, rstn) ;

input signed [31:0] a;
output signed [31:0] b;
input clk;
input rstn;


parameter avg = 20;
parameter  c1 = avg*(8'h1) ;
parameter  c2 = avg*(8'h1) ;
parameter  c3 = avg*(8'h1) ;
parameter  c4 = avg*(8'h1) ;
parameter  c5 = avg*(8'h1) ;


reg signed [31:0] f1 ;
reg signed [31:0] f2 ;
reg signed [31:0] f3 ;
reg signed [31:0] f4 ;
reg signed [31:0] f5 ;


always @(posedge clk or negedge rstn) begin
  if(!rstn)  begin
    f1 <= 32'b0;
    f2 <= 32'b0;
    f3 <= 32'b0;
    f4 <= 32'b0;
    f5 <= 32'b0;
  end
  else begin
    f1 <= a;
    f2 <= f1;
    f3 <= f2;
    f4 <= f3;
    f5 <= f4;
  end
end


assign b = (f1*c1 + f2*c2 + f3*c3 + f4*c4 + f5*c5)/(5*avg) ;


endmodule

module tb_fir;

reg [31:0] in_signal;
reg clk =0;
reg rstn =0;
reg en =0;
wire [31:0] out_signal;

always #5 clk = ~clk;

integer cnt=0;

always @(clk) cnt = cnt +1 ;

always @(*) begin
   if(en ==1 && cnt[2:0] == 3'b111) begin
   #1;
  in_signal = cnt[7:0];
  end
  end

fir_filter dut (
.a(in_signal),
.b(out_signal),
.clk(clk),
.rstn(rstn));

initial begin
  rstn =0 ;
  #100;
  rstn = 1;
  en =1;
  #10000 ;
  $finish;
end

initial
 $monitor("Input signal = %d , out_signal = %d", in_signal, out_signal);

initial begin
  $recordfile("test.trn");
  $recordvars();
  end

endmodule

------------------------- verilog code end -------------------- 

Downloads the verilog file here. 

Nov 16, 2016

Low Power Design Technique : Tutorials

To support, Click on any advertisement shown on the page.Thanks for Visiting the blog. Donate Us

Here are some low power technique used during RTL .

There are 3 main components for power calculation.
  1. Dynamic Power
  2. Static Power
  3. Short Circuit Power 
Dynamic power 
Dynamic power of a chip can be reduced by reducing the number of switching from 1's to 0's and vice versa, this is design change and will required some of the best practice to write the HDL code. Few of them are listed below.

Static power 
Static power can be controlled by below techniques.

Multi voltage in design or it is called voltage island : 
multi voltage design in vlsi :
For Multi VDD See the UPF example , how the UPF is getting define for multi voltage design. Below is one of the simple example. Any communication from voltage1 to voltage2 will have to go through the level shifter to avoid any timing issues. 


How to insert Lever shifter for Voltage cross domain -> See UPF Example
Reducing voltage will reduce the power consumption but it will also reduce the performance of the block , it means if a block is expected to run at high frequency, there could be timing issues if using low voltage. Remember with higher voltage , setup time will be less. This is effective in SoC where a block is not expected to run at higher frequency. 

Synthesis setup would be different for multi voltage design , 1st UPF should be align with the voltage island. Level shifters libraries has to include in synthesis setup.

DVFS (dynamic voltage frequency scaling)
Dynamic voltage and frequency scaling (DVFS) is a technique that aims at reducing the dynamic power consumption by dynamically adjusting voltage and frequency of a CPU. This technique exploits the fact that CPUs have discrete frequency and voltage settings as previously described.
DVFS techniques provide effective power saving by reducing the voltage on the fly based on the performance requirements , it also reduce the operating frequency. This is the only techniques which is highly effective on dynamic and static power saving. Reducing frequency will reduce the dynamic power where as reducing voltage will reduce the static power. 

DVFS Example:

Implementation of  Dynamic Voltage Frequency Scaling : 
In the implementation stage , DVFS is done by using a combination of MSV and MMMC ( multi-mode/multi-corner) techniques. 


Multi Voltage Threshold
Multi Vth  is using multi voltage threshold level in the design , they are known as LVT/SVT/HVT cells and there utilization is depends on the timing requirement. LVT is faster cell but they have more leakage hence static power consumption will be more. 
Power gating Technique
(power shut off) -> This will require UPF to implement power switches in the design. We use power switch where some part of the design is not required to be active all the time.

Physical Implementation of Power Gating :
Synthesis uses the power switches according to the definition in UPF ( power swtich must be define in UPF , it describe the control signal and other details which is required for synthesis tool to implement it.  The main task during synthesis is adding isolation cells, retention cells and always on cells define in UPF. The conneciton of power switch cells to the power control module happens during the physical implementation flow, when physical implementation information is available to the tool. 

Clock Gating Circuit 
Most of the dynamic power in design is consumed by clock , clock gating is the effective way to reduce the power consumption. There are options available in synthesis tool where you can enable the auto clock gating option , Tool will insert the clock gating at most of the places.
Visit here to see more detail information on Low Power Design Techniques.

Table of Contents


------------
multi voltage design in vlsi
------------

SPI Protocol

APTITUDE QUESTIONS


Many more yet to come, Stay Tuned.

Sample Question :


1.
Tanya is older than Eric.
Cliff is older than Tanya.
Eric is older than Cliff.
If the first two statements are true, the third statement is

A. true
B. false
C. uncertain

2.
Which cells are placed in Soft blockages?No cells
Any cells
Only sequential cells
Only Buffers and Inverters



3.
Metal layer ____ has Maximum resistance?
1
2
3
4


4.
What does chip utilization depend on?
Only on standard cells
Only on macros
Standard cells and macros both
Standard cells, macros and IO pads

5.
Leakage power is inversely proportional to _____________.

Frequency
Load Capacitance
Supply voltage
Threshold Voltage

6.
What does Prerouting mean?

Routing of clock nets
Routing of signal nets
Routing of IO nets
Routing of PG nets

7.
Utilisation of the chip after placement optimisation will _____________.

Be Constant
Decrease
Increase
None of the above

8.
What is the purpose of CTS?
Minimum Slack
Minimum Skew
Minimum EM
Minimum IR Drop

9.
Which cells would you place in the critical path for a better timing?

LVT
HVT
RVT
SVT


10.
Which of the following is a correct boolean expression ?
a) A + A = A b) A+AB = B c) AB' + B'A = A+B d) None

Ans = a


11.
How many 2:1 mux can be used to implement 3:8 decoder ?

a) 5 b) 6 c) 8 d) 7


Nov 15, 2016

VLSI Industry Updates



VLSI News Update :-

12 Dec 2016


IoT and Automotive to Drive IC Market Growth Through 2020
Ref_Link
11/14/2016 04:10 PM EST
TOKYO — Within the last 24 hours, two big players — Samsung and Siemens — announced M&A deals in the automotive field. Samsung will pay $8 billion for the U.S. car technology group Harman, while Siemens agreed to acquire Mentor Graphics, an EDA company, in $4.5 billion deal.
Ref_Link


11/14/2016 00:01 AM EST
7nm SRAMs, 10nm SoC at ISSCC
TSMC nudges out Samsung in small SRAMs
Ref_Link


Top News for the Day - Technology & Industry 1. Google buys HTC talent for $1.1 billion to spur devices push Read more at: https://lnkd.in/fmqjGD5 2. Deep learning is the money tree for IT companies Read more at: https://lnkd.in/f4Mq6Za 3. NASSCOM signs agreement with local Chinese government to push for AI Read more at: https://lnkd.in/fR2yq73 4. Companies get ready for 5G future Read more at: https://lnkd.in/fveRZSR 5. Matrimony.com makes a quiet debut; lists at par against IPO price of Rs 985 - https://lnkd.in/fZFaUpw 6. WeChat is quietly developing its own augmented reality platform - https://lnkd.in/fnK44u7

Implementation of Logical Questions


Coming soon with OOB questions and answer . stay tuned.

Please leave your comments if you want to add logical question or have any doubt.

Q1. Design a Lift controller. Below are the specification.

1. Life can move from flr-0 to flr-20.
2. There is only 1 lift.
3. Priority should be given if input given from inside of lift.

Prepare the document first, after that RTL coding in verilog.


Q2. Continue with Q1, there is one more life.  All specifications are same.
Design the controller efficiently.

Prepare the document first with analysis part. how many conditions will be there and what will be the decision.  Round robin/ Priority based arbitration can be used to resolve conflict.

Q3. Traffic light controller using verilog.
Specification -
Consider a controller for traffic light at the intersection of four roads. Consider R1, R2, R3 and R4 as four roads and PL as Pedestrian. The road has the following stages.
Green=10011, Yellow=01000,  Red=00100.

The pedestrian has following two states
Green=0000  ,Red=1111

First the road R1 is green and all other roads R2, R3 ,R4 and PL are red .After a some delay R1 is turn to yellow and then red the traffic signal on R2 is green. After a delay R2 is turn to yellow and then red the signal on R3 is green.Then R3 is changed to yellow and then red. Similarly R4 is turned green then yellow & then red. Pedestrian Light PL is green after a delay. Again R1 is turned to green & the routine will continue.

Q4.  Continuation from Q3 , with all specification in Q3,  each road having one sensor.  Sensor sense the traffic and it give output to traffic light mechanism if no vehicle cross it for a time period. Based on the input from sensor, traffic light can change the state.

Q5. Design a hardware to count the number of 1's and 0's in 40-bit data. Data is coming continuously.

Table of Contents


CDC - Real time implementation



Verilog Code for modules


Below are the modules will be available soon with documents and Verilog code , Contact me if anyone interested to do the project work.

Page will update very soon , Stay tuned.

AHB Controller
Features :

AXI Controller
Features :

AXI Interconnect
Features ;










Protocol



Here are the most used protocols in design , based on application.

List of protocol in VLSI :

Serial Protocol -
SPI Protocol
UART Protocol
I2C Protocol
Under Construction :-
I2S
I3C
Ethernet IP
PCIe
Fiber Channel
SATA
CAN
USB


Under Construction :-

Bus Protocol
AXI
AHB
AMBA
OCP
AVALON


Networking Protocol
SATA / SAS
PCIe
WIFI/WIMAX
Bluetooth
OSI Protocol
TCP Protocol
PPP - Point to Point Protocol
SFTP
HTTP
HTTPS
SSL
NTP
IMAP

Display
HDMI
Video Codec

Table of Contents

Nov 13, 2016

Verilog Binary to gray code conversion

About the Author

Welcome to my digital design blog! I share in-depth articles on RTL design, timing analysis, ASIC/FPGA concepts, and interview preparation.

Binary to Gray Code Conversion

Binary-to-Gray code conversion is commonly used in digital systems, especially in asynchronous FIFO designs, rotary encoders, and clock-domain crossing applications.

Gray code is a binary numbering system in which only one bit changes between two consecutive values. This property helps reduce errors during transitions.

Binary-to-Gray Code Conversion Formula

The most significant Gray-code bit is equal to the most significant binary bit. Each remaining Gray-code bit is obtained by XORing two adjacent binary bits.

Formula:
Gray = Binary ⊕ (Binary >> 1)

For a six-bit binary number:

G[5] = B[5]
G[4] = B[5] ⊕ B[4]
G[3] = B[4] ⊕ B[3]
G[2] = B[3] ⊕ B[2]
G[1] = B[2] ⊕ B[1]
G[0] = B[1] ⊕ B[0]

Example

Consider the six-bit binary number:

Binary = 101101

The corresponding Gray code is calculated as follows:

Gray = Binary ⊕ (Binary >> 1)

Binary     = 101101
Binary >> 1 = 010110
Gray      = 111011

Hardware for Binary-to-Gray Conversion

Verilog Code for Binary-to-Gray Conversion

The following Verilog module converts an N-bit binary input into its corresponding Gray-code output.

module binary_to_gray #(
    parameter WIDTH = 6
) (
    input  wire [WIDTH-1:0] binary_in,
    output wire [WIDTH-1:0] gray_out
);

    // Binary-to-Gray conversion
    assign gray_out = binary_in ^ (binary_in >> 1);

endmodule

Registered Binary-to-Gray Converter

If the output must be synchronized with a clock, a registered version can be used.

module binary_to_gray_registered #(
    parameter WIDTH = 6
) (
    input  wire                 clk,
    input  wire                 rst_n,
    input  wire [WIDTH-1:0]     binary_in,
    output reg  [WIDTH-1:0]     gray_out
);

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            gray_out <= {WIDTH{1'b0}};
        else
            gray_out <= binary_in ^ (binary_in >> 1);
    end

endmodule

Binary Counter with Gray-Code Output

This example generates a binary counter and continuously converts its value into Gray code.

module binary_gray_counter #(
    parameter WIDTH = 6
) (
    input  wire             clk,
    input  wire             rst_n,
    output reg  [WIDTH-1:0] binary_count,
    output wire [WIDTH-1:0] gray_count
);

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            binary_count <= {WIDTH{1'b0}};
        else
            binary_count <= binary_count + 1'b1;
    end

    assign gray_count = binary_count ^ (binary_count >> 1);

endmodule

Truth Table for a Three-Bit Converter

Decimal Binary Gray Code
0 000 000
1 001 001
2 010 011
3 011 010
4 100 110
5 101 111
6 110 101
7 111 100

Advantages of Gray Code

  • Only one bit changes between consecutive values.
  • Reduces errors during transitions.
  • Useful in asynchronous FIFO pointer synchronization.
  • Commonly used in rotary encoders.
  • Can reduce glitches in digital logic.

Conclusion

Binary-to-Gray conversion is simple to implement using XOR gates. In Verilog, the conversion can be written as:

gray_out = binary_in ^ (binary_in >> 1);

This expression works for any bus width and synthesizes into a simple XOR network.

Interview Questions and Answers

Q1. What is Gray code and why is it used?

Answer: Gray code is a binary numbering system in which two consecutive values differ by only one bit. It is used to avoid multi-bit transition errors in systems such as asynchronous FIFO pointers, rotary encoders, and analog-to-digital converters, because a single-bit change eliminates the possibility of intermediate false states during a transition.

Q2. Write the equation for binary-to-Gray conversion.

Answer: The conversion equation is:

Gray = Binary ⊕ (Binary >> 1)

The MSB of the Gray code equals the MSB of the binary value, and every other Gray bit is the XOR of two adjacent binary bits: G[i] = B[i+1] ⊕ B[i].

Q3. Write the equation for Gray-to-binary conversion.

Answer: The MSB is copied directly, and each binary bit is obtained by XORing the previous binary bit with the corresponding Gray bit:

B[MSB] = G[MSB]
B[i] = B[i+1] ⊕ G[i]   for all remaining bits

In Verilog, Gray-to-binary requires an iterative XOR-reduce (prefix XOR), for example: for (i=0; i<WIDTH-1; i=i+1) bin[i] = ^gray[WIDTH-1:i]; or a loop that accumulates: bin[i] = bin[i+1] ^ gray[i];

Q4. Why is Gray code used for FIFO pointers in asynchronous FIFOs?

Answer: When a multi-bit binary pointer crosses a clock domain through a synchronizer, multiple bits may change simultaneously and each bit may get sampled at a different time, producing a corrupted, invalid pointer value. Because a Gray-coded pointer changes only one bit at a time, even if the sample is metastable or delayed, the received value is either the old value or the new value — never an invalid intermediate value.

Q5. Is the FIFO depth required to be a power of 2 when using Gray-code pointers? Why?

Answer: Yes. Gray code wraps correctly (maintains the single-bit-change property between the last and first value) only when the counting sequence is a power of two, such as 8, 16, or 32 deep. For non-power-of-2 depths, the wrap from the last value back to zero would change multiple bits at once, breaking the CDC safety property.

Q6. What hardware is required to convert binary to Gray code?

Answer: Only a set of two-input XOR gates — one XOR gate per Gray output bit except the MSB, which is wired directly. An N-bit converter therefore needs N-1 XOR gates, and the logic depth is just one XOR gate, making the conversion very fast.

Q7. Convert binary 1011 to Gray code and Gray code 1011 back to binary.

Answer:

  • Binary 1011 → Gray: G3 = 1, G2 = 1⊕0 = 1, G1 = 0⊕1 = 1, G0 = 1⊕1 = 0 → Gray = 1110
  • Gray 1011 → Binary: B3 = 1, B2 = 1⊕0 = 1, B1 = 1⊕1 = 0, B0 = 0⊕1 = 1 → Binary = 1101

Q8. Write a synthesizable Verilog one-liner for binary-to-Gray conversion.

Answer:

assign gray = bin ^ (bin >> 1);

This works for any vector width and synthesizes to a single level of XOR gates.

Q9. Can Gray code be used for arithmetic operations directly?

Answer: No. Gray code is a reflected, non-weighted code — bit positions have no fixed weights, so addition, subtraction, and comparison cannot be performed directly. The value must be converted back to binary before arithmetic. This is why asynchronous FIFOs internally increment the binary pointer and convert to Gray only for the clock-domain-crossing stage.

Q10. What is the difference between binary code and Gray code?

Feature Binary Code Gray Code
Bit changes between consecutive values One or more bits Exactly one bit
Weighted code Yes (positional weights) No (non-weighted)
Arithmetic support Direct Not directly
Typical use General computation CDC, encoders, K-maps

Q11. Why is Gray code used in Karnaugh maps?

Answer: Karnaugh maps order their rows and columns in Gray-code sequence so that physically adjacent cells differ by exactly one input variable. This allows logically adjacent minterms to be visually identified and grouped into larger implicants for simplified Boolean expressions.

Q12. What happens if a multi-bit binary pointer is synchronized directly across clock domains?

Answer: Different bits can be sampled at different instants (due to skew and metastability), so the receiving domain may capture a value that never actually existed — for example, a transitioning pointer 0111 → 1000 could be seen as 1111, 0000, or 1100. Such a corrupted pointer can cause FIFO full/empty flags to be computed incorrectly, leading to data corruption or overflow/underflow. Gray coding eliminates this failure mode.

Q13. How would you write a Gray-code counter directly (without converting from binary)?

Answer: A Gray-code counter computes the next Gray value by finding the least significant set bit of the current Gray value, XORing it with the previous binary value, and converting back to Gray. A common approach:

// Convert Gray back to binary, increment, convert to Gray
wire [WIDTH-1:0] bin_next = bin + 1'b1;
always @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        bin  <= {WIDTH{1'b0}};
        gray <= {WIDTH{1'b0}};
    end else begin
        bin  <= bin_next;
        gray <= bin_next ^ (bin_next >> 1);
    end
end

Q14. In which other applications is Gray code used?

Answer:

  • Rotary and linear position encoders (avoids false intermediate readings).
  • Asynchronous FIFO read/write pointers.
  • Karnaugh maps for Boolean simplification.
  • Error reduction in analog-to-digital converters (e.g., shaft-angle encoders).
  • Sequential logic state encoding where adjacent states must differ by one bit to reduce glitches.
  • Genetic algorithms and Gray-coded modulation (e.g., QAM constellation labeling) for improved error performance.

Q15. Is Gray code unique? How many N-bit Gray codes exist?

Answer: No. The standard reflected binary Gray code is just one member of a family of Hamiltonian cycles on an N-dimensional hypercube. Any cycle that visits all 2N vertices exactly once, with adjacent vertices differing in one bit, is a valid N-bit Gray code. The reflected binary form is the most widely used because of its simple conversion equations.

Quick Revision Tip: Remember two one-liners — Binary→Gray: gray = bin ^ (bin >> 1)  |  Gray→Binary: bin[i] = bin[i+1] ^ gray[i] (prefix XOR). Most interview follow-ups (FIFO, CDC, power-of-2 depth) come directly from the single-bit-change property.

📚 Related Reading

Prepare for your digital design interview with our comprehensive synthesis interview guide:

🔗 Synthesis Interview Questions & Answers

Cover topics: RTL coding styles, gate-level netlist, area vs. timing trade-offs, pipeline insertion, fanout, and more.

Table of Contents

SiteMap