logo

Лічильник сірих Verilog

Код Грея – це різновид двійкової системи числення, де за раз змінюється лише один біт. Сьогодні сірий код широко використовується в цифровому світі. Це буде корисно для виправлення помилок і передачі сигналу. Лічильник Грея також корисний при проектуванні та перевірці в домені НВІС.

Лічильник сірих Verilog

Код Грея кодує цілі числа як послідовності бітів із властивістю, що представлення суміжних цілих чисел відрізняються рівно однією двійковою позицією.

Існують різні типи кодів Грея, наприклад збалансований, двійковий відбитий, максимальний розрив і антиподальний код Грея.

Основною функцією лічильників є створення заданої вихідної послідовності, і їх іноді називають генераторами шаблонів.

Дизайн

У сірому коді одночасно змінюється лише один біт. Цей код розробки має два входи, сигнали синхронізації та скидання, і один 4-бітний вихід, який генерує код Грея.

По-перше, якщо rstn сигнал високий, то на виході буде нуль, і як тільки rstn йде низько, на краю висхідного clk , дизайн генеруватиме чотирибітний код Грея та продовжуватиме генерувати на кожному передньому фронті clk сигнал.

Цей код дизайну можна оновити та ввести двійкові числа як вхідні дані, і цей дизайн працюватиме як конвертер двійкового коду в сірий.

 module gray_ctr # (parameter N = 4) ( input clk, input rstn, output reg [N-1:0] out); reg [N-1:0] q; always @ (posedge clk) begin if (!rstn) begin q <= 0; out <="0;" end else begin q + 1; `ifdef for_loop for (int i="0;" n-1; out[i] ^ q[i]; out[n-1] `else q[n-1:1] q[n-2:0]}; `endif endmodule pre> <h3>Hardware Schematic</h3> <img src="//techcodeview.com/img/verilog-tutorial/27/verilog-gray-counter-2.webp" alt="Verilog Gray Counter"> <h3>Testbench</h3> <pre> module tb; parameter N = 4; reg clk; reg rstn; wire [N-1:0] out; gray_ctr u0 ( .clk(clk), .rstn(rstn), .out(out)); always #10 clk = ~clk; initial begin {clk, rstn} <= 0; $monitor ('t="%0t" rstn="%0b" out="0x%0h&apos;," $time, rstn, out); repeat(2) @ (posedge clk); <="1;" repeat(20) $finish; end endmodule pre> <p>And it produces the following output, such as:</p> <pre> ncsim&gt; run T=0 rstn=0 out=0xx T=10 rstn=0 out=0x0 T=30 rstn=1 out=0x0 T=50 rstn=1 out=0x1 T=70 rstn=1 out=0x3 T=90 rstn=1 out=0x2 T=110 rstn=1 out=0x6 T=130 rstn=1 out=0x7 T=150 rstn=1 out=0x5 T=170 rstn=1 out=0x4 T=190 rstn=1 out=0xc T=210 rstn=1 out=0xd T=230 rstn=1 out=0xf T=250 rstn=1 out=0xe T=270 rstn=1 out=0xa T=290 rstn=1 out=0xb T=310 rstn=1 out=0x9 T=330 rstn=1 out=0x8 T=350 rstn=1 out=0x0 T=370 rstn=1 out=0x1 T=390 rstn=1 out=0x3 T=410 rstn=1 out=0x2 Simulation complete via $finish(1) at time 430 NS + 0 </pre> <h3>Balanced Gray Code</h3> <p>In balanced Gray codes, the number of changes in different coordinate positions is as close as possible.</p> <p>A Gray code is <strong> <em>uniform</em> </strong> or <strong> <em>uniformly</em> </strong> balanced if its transition counts are all equal.</p> <p>Gray codes can also be <strong> <em>exponentially</em> </strong> balanced if all of their transition counts are adjacent powers of two, and such codes exist for every power of two.</p> <p>For example, a balanced 4-bit Gray code has 16 transitions, which can be evenly distributed among all four positions (four transitions per position), making it uniformly balanced.</p> <pre> 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 </pre> <h3>n-ary Gray Code</h3> <p>There are many specialized types of Gray codes other than the binary-reflected Gray code. One such type of Gray code is the n-ary Gray code, also known as a <strong> <em>non-Boolean</em> </strong> Gray code. As the name implies, this type of Gray code uses non-Boolean values in its encodings.</p> <p>For example, a 3-ary ternary Gray code would use the values {0, 1, and 2}. The (n, k)-Gray code is the n-ary Gray code with k digits. The sequence of elements in the (3, 2)-Gray code is: {00, 01, 02, 12, 11, 10, 20, 21, and 22}.</p> <p>The (n, k)-Gray code may be constructed recursively, as the BRGC, or may be constructed iteratively.</p> <h3>Monotonic Gray Codes</h3> <p>Monotonic codes are useful in interconnection networks theory, especially for minimizing dilation for linear arrays of processors.</p> <p>If we define the weight of a binary string to be the number of 1s in the string, then although we clearly cannot have a Gray code with strictly increasing weight, we may want to approximate this by having the code run through two adjacent weights before reaching the next one.</p> <h3>Beckett-Gray Code</h3> <p>Another type of Gray code, the Beckett-Gray code, is named for Irish playwright <strong> <em>Samuel Beckett</em> </strong> , who was interested in <strong> <em>symmetry</em> </strong> . His play <strong> <em>Quad</em> </strong> features four actors and is divided into sixteen time periods. Each period ends with one of the four actors entering or leaving the stage.</p> <p>The play begins with an empty stage, and Beckett wanted each subset of actors to appear on stage exactly once. A 4-bit binary Gray code can represent the set of actors currently on stage.</p> <p>However,</p> <p>Beckett placed an additional restriction on the script: he wished the actors to enter and exit so that the actor who had been on stage the longest would always be the one to exit.</p> <p>The actors could then be represented by a first-in, first-out (FIFO) queue so that the actor being dequeued is always the one who was enqueued first.</p> <p>Beckett was unable to find a Beckett-Gray code for his play, and indeed, an exhaustive listing of all possible sequences reveals that no such code exists for n = 4. It is known today that such codes do exist for n = 2, 5, 6, 7, and 8, and do not exist for n = 3 or 4.</p> <h3>Snake-in-the-box Codes</h3> <p>Snake-in-the-box codes, or snakes, are the sequences of nodes of induced paths in an n-dimensional <strong> <em>hypercube</em> </strong> graph, and coil-in-the-box codes, or coils, are the sequences of nodes of induced cycles in a hypercube.</p> <p>Viewed as Gray codes, these sequences have the property of detecting any single-bit coding error.</p> <h3>Single-track Gray Code</h3> <p>Another kind of Gray code is the single-track Gray code (STGC) developed by <strong> <em>Norman B. Spedding</em> </strong> and refined by <strong> <em>Hiltgen, Paterson</em> </strong> and <strong> <em>Brandestini</em> </strong> in &apos;Single-track Gray codes&apos; (1996).</p> <p>The STGC is a cyclical list of P unique binary encodings of length n such that two consecutive words differ in exactly one position. When the list is examined as a P &#xD7; n matrix, each column is a cyclic shift of the first column.</p> <p>The name comes from their use with rotary encoders, where many tracks are being sensed by contacts, resulting in each in an output of 0 or 1. To reduce noise due to different contacts not switching the same moment in time, one preferably sets up the tracks so that the contacts&apos; data output is in Gray code.</p> <p>To get high angular accuracy, one needs lots of contacts; to achieve at least 1-degree accuracy, one needs at least 360 distinct positions per revolution, which requires a minimum of 9 bits of data and the same number of contacts.</p> <p>If all contacts are placed at the same angular position, then 9 tracks are needed to get a standard BRGC with at least 1-degree accuracy. However, if the manufacturer moves a contact to a different angular position but at the same distance from the center shaft, then the corresponding &apos;ring pattern&apos; needs to be rotated the same angle to give the same output.</p> <h3>Two-dimensions Gray Code</h3> <p>Two-dimensional Gray codes are used in communication to minimize the number of bit errors in quadrature amplitude modulation adjacent points in the constellation.</p> <p>In a standard encoding, the horizontal and vertical adjacent constellation points differ by a single bit, and adjacent diagonal points differ by 2 bits.</p> <hr></=></pre></=>

Збалансований код Грея

У збалансованих кодах Грея число змін у різних положеннях координат є максимально близьким.

Код Грея є уніформа або рівномірно збалансовано, якщо кількість переходів однакова.

Також можуть бути коди Грея експоненціально збалансовані, якщо всі їхні підрахунки переходів є суміжними степенями двійки, і такі коди існують для кожного ступеня двійки.

Наприклад, збалансований 4-бітовий код Грея має 16 переходів, які можна рівномірно розподілити між усіма чотирма позиціями (по чотири переходи на позицію), що робить його рівномірно збалансованим.

 0 1 1 1 1 1 1 0 0 0 0 0 0 1 1 0 0 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 1 1 1 0 0 0 0 0 1 1 0 0 0 0 0 1 1 1 1 1 1 

п-арний код Грея

Існує багато спеціалізованих типів кодів Грея, крім коду Грея з двійковим відображенням. Одним із таких типів коду Грея є n-арний код Грея, також відомий як a не булевий Код Грея. Як випливає з назви, цей тип коду Грея використовує не логічні значення у своїх кодуваннях.

Наприклад, 3-рядний потрійний код Грея використовуватиме значення {0, 1 і 2}. (n, k)-код Грея є n-рядним кодом Грея з k цифрами. Послідовність елементів у (3, 2)-коді Грея така: {00, 01, 02, 12, 11, 10, 20, 21 і 22}.

(n, k)-код Грея може бути побудований рекурсивно, як BRGC, або може бути побудований ітераційно.

Монотонні коди Грея

Монотонні коди корисні в теорії мереж взаємозв’язку, особливо для мінімізації розтягування для лінійних масивів процесорів.

Якщо ми визначаємо вагу двійкового рядка як кількість одиниць у рядку, тоді, хоча ми явно не можемо мати код Грея зі строго зростаючим вагою, ми можемо захотіти наблизити це, провівши код через дві суміжні ваги, перш ніж досягти наступний.

Код Беккета-Грея

Інший тип коду Грея, код Беккета-Грея, названий на честь ірландського драматурга Семюел Беккет , який цікавився симетрія . Його гра Quad У фільмі чотири актори і шістнадцять часових періодів. Кожен період закінчується виходом або виходом на сцену одного з чотирьох акторів.

П’єса починається з порожньої сцени, і Беккет хотів, щоб кожна підгрупа акторів з’явилася на сцені рівно один раз. 4-бітовий двійковий код Грея може представляти набір акторів, які зараз знаходяться на сцені.

однак,

Беккет поставив до сценарію додаткове обмеження: він бажав, щоб актори входили і виходили, щоб завжди виходив актор, який довше пробув на сцені.

Тоді актори можуть бути представлені чергою «першим увійшов, першим вийшов» (FIFO), щоб актор, якого вилучають із черги, завжди був тим, хто був у черзі першим.

Беккет не зміг знайти код Беккета-Ґрея для своєї п’єси, і справді, вичерпний перелік усіх можливих послідовностей показує, що такого коду не існує для n = 4. Сьогодні відомо, що такі коди існують для n = 2, 5. , 6, 7 і 8 і не існують для n = 3 або 4.

Коди «Змія в коробці».

Коди змійки в коробці, або змії, — це послідовності вузлів індукованих шляхів у n-вимірному гіперкуб граф, а коди coil-in-the-box, або котушки, — це послідовності вузлів індукованих циклів у гіперкубі.

Розглянуті як коди Грея, ці послідовності мають властивість виявляти будь-яку однобітну помилку кодування.

Одноколійний код сірого

Іншим видом коду Грея є однодоріжний код Грея (STGC), розроблений Норман Б. Спеддінг і доопрацьовано Гілтген, Патерсон і Брандестіні в «Одноколійних кодах Грея» (1996).

STGC — це циклічний список із P унікальних двійкових кодувань довжини n, у яких два послідовних слова відрізняються точно однією позицією. Коли список досліджується як матриця P × n, кожен стовпець є циклічним зсувом першого стовпця.

додавання рядка java

Назва походить від їх використання з ротаційними кодерами, де багато доріжок сприймаються контактами, в результаті чого кожен має вихідний сигнал 0 або 1. Щоб зменшити шум через те, що різні контакти не перемикаються в той самий момент часу, бажано налаштувати відстежує, щоб вихідні дані контактів були в коді Грея.

Щоб отримати високу кутову точність, потрібно багато контактів; щоб досягти принаймні 1-градусної точності, потрібно щонайменше 360 різних позицій на оберт, що вимагає мінімум 9 біт даних і стільки ж контактів.

Якщо всі контакти розташовані в однаковому кутовому положенні, то для отримання стандартного BRGC з точністю принаймні 1 градус необхідно 9 доріжок. Однак, якщо виробник переміщує контакт в інше кутове положення, але на однакову відстань від центрального валу, тоді відповідну «кільцеву модель» потрібно повернути на той самий кут, щоб отримати той самий результат.

Двовимірний код Грея

Двовимірні коди Грея використовуються в комунікації, щоб мінімізувати кількість бітових помилок у квадратурній амплітудній модуляції суміжних точок у сузір'ї.

У стандартному кодуванні горизонтальні та вертикальні суміжні точки сузір’я відрізняються на один біт, а суміжні діагональні точки відрізняються на 2 біти.