Graycode for state machine

Source: Internet
Author: User

How & Why Use Gray Code

A gray counter is a binary counter where the one bit changes at a time.

Gray code is mostly used to send values across clock domains (the this-to-the-it has a uncertainty of only 1).

The easiest-to-create a gray counter is to first make a binary counter, and then convert the value to gray.

=======================================================================

VS2013, Simulation

-------------------------------------------

#include <stdio.h>
#include <string>

Template<int bits>
std::string GetBits (unsigned int val) {
std::string str;
for (int i = BITS-1; I >= 0; I-) {
char c = ' 0 ';
if (Val & (1 << i) c = ' 1 ';
Str.push_back (c);
    }
return str;
}

Template<int bits>
unsigned int getgraycode () {
unsigned long mask = (1<<bits)-1;
static unsigned int next = 0;
unsigned int nrtn = 0;
Nrtn = (Next >> 1) ^ (next);
next++;
if (Next > Mask) next = 0;
return NRTN;
}

void Testgraycode () {
//generate 4Bit Gray Code
const int BITS = 4;
printf ("%6s:%s \ n", "Index", "Graycode");
printf ("---------------------------------\ n");
for (int i = 0; i <; i++) {
std::string str = getbits<bits> (getgraycode<bits> ());
printf ("%06d:%s \ n", I, Str.c_str ());
    }
printf ("---------------------------------\ n");
}

void Main () {
Testgraycode ();
}

----------------------------------------------------

4Bit Graycode Result:

/////////////////////////////////////////////////////////////////////////////////////

-------------------------------Verilog-----------------------------------

module Generategraycode (CLK, Rst_n, gray_code);

parameter bits_count = 4;

input CLK, rst_n;
output [bits_count-1:0] Gray_code;

reg [bits_count-1:0]cnt = 1 ' b0;

Always @ (Posedge CLK or Negedge rst_n)
begin
if (! rst_n) CNT <= 0;
Else
begin
CNT <= cnt + 1 ' B1;
End
End

Assign Gray_code = (CNT >> 1 ' B1) ^ cnt;

Endmodule

Graycode for state machine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.