Упражнение BB4d · строительные блоки · мультиплексор
Элемент выбора И/ИЛИ 4019
Два 4-битных слова, заданных проводами, две управляющие кнопки и четыре выхода: 4019 пропускает слово A, слово B, оба через ИЛИ или ничего. Это мультиплексор из логических элементов, а не из ключей.
- BB4a: 4051, 8 каналов
- BB4b: 4052, 2 × 4 канала
- BB4c: 4053, 3 × 2 канала
- BB4d: 4019, выбор И/ИЛИ
1Что это и зачем
Что делает. Каждый из четырёх выходов D1–D4 — это D = (A И Ka) ИЛИ (B И Kb). Нажмите Ka, и выходы покажут слово A, нажмите Kb — слово B. Обе нажаты — A ИЛИ B; ни одна — все нули. Здесь A1–A4 и B1–B4 — провода к шинам; линейка показывает Ka, Kb и D1–D4.
Как работает. Внутри четыре элемента И-ИЛИ с общими управляющими входами: Ka идёт на элементы И входов A, Kb — на элементы входов B. В отличие от аналоговых ключей 4051–4053, выходы всегда управляются; висящего состояния нет.
Где применяется. Мультиплексор выбирает, какой из нескольких сигналов пойдёт дальше: регистр, который
читает процессор, источник для шины, вход АЛУ. В ПЛИС каждая таблица поиска — это мультиплексор, входы данных которого
— биты памяти конфигурации. 4019 — та форма на уровне элементов, в которую синтез превращает каждый if и ?: в проекте.
Зачем это изучать.
- Выбор между данными под управлением нескольких битов — сердце любого тракта данных.
- Мультиплексор с постоянными значениями на входах данных — это таблица поиска: он вычисляет любую функцию своих входов выбора.
- Он показывает разницу между мультиплексором из элементов, выход которого всегда управляется, и аналоговыми ключами BB4a–c.
2Главные элементы: выбор, данные, выход
| Ka | Kb | D4 … D1 |
|---|---|---|
| 0 | 0 | 0000 |
| 0 | 1 | B |
| 1 | 0 | A |
| 1 | 1 | A ИЛИ B |
Временные диаграммы
tb.sv в Icarus Verilog: первые 16 шагов, провода данных как на макетной
плате. · SVG · PNG3Детали
| Деталь | В этой схеме | Кол-во | Цена | Поставщик |
|---|---|---|---|---|
| CD4019 | четыре элемента выбора И/ИЛИ | 1 | $0.40 | Elexp (elexp.com) |
| Модули кнопок | Ka, Kb; 2 из набора из пяти | 2 | $0.66 / набор | aliexpress.us |
| Линейка из 8 светодиодов | показывает выбор и выходы | 1 | $0.38 | aliexpress.us |
| Макетная плата на 830 точек | 1 | $3.00 | amazon.com | |
| Блок питания для макетной платы | 5 В на шинах | 1 | $1.00 | aliexpress.us |
| Кабель USB-DC на 9 В | питание блока от USB-зарядки | 1 | $1.17 | aliexpress.us |
| Нарезанные перемычки | 12 проводов на плате (или перемычки Dupont папа-папа) | 12 | $11.95 / набор | jameco.com |
| Перемычки Dupont папа-мама | 13 проводов к кнопкам и линейке | 13 | $1.30 / набор | aliexpress.us |
Цены из таблицы компонентов LSSK; 4019 есть в наборе «Полный».
4Микросхема, ножка за ножкой
Микросхемы — КМОП серии 4000B: работают от 3 до 18 В, здесь от 5 В блока питания. Каждый вход должен быть куда-то подключён: висящий вход КМОП ловит наводки и может переключаться сам по себе. Микросхемы нарисованы сверху выемкой влево, как в даташите: ножка 1 внизу слева, нумерация против часовой стрелки. Синие стрелки — входы, оранжевые — выходы.
4019: четыре элемента выбора И/ИЛИ
A1–A4 — ножки 6, 4, 2 и 15, B1–B4 — ножки 7, 5, 3 и 1. Ka — ножка 9, Kb — ножка 14, а D1–D4 — ножки 10–13, рядом в верхнем ряду.
| Ножка | Имя | Направление | Функция | В этой схеме |
|---|---|---|---|---|
| 1 | B4 | вход | B4 | B4 (GND) |
| 2 | A3 | вход | A3 | A3 (+5V) |
| 3 | B3 | вход | B3 | B3 (GND) |
| 4 | A2 | вход | A2 | A2 (GND) |
| 5 | B2 | вход | B2 | B2 (+5V) |
| 6 | A1 | вход | A1 | A1 (+5V) |
| 7 | B1 | вход | B1 | B1 (+5V) |
| 8 | VSS | питание | земля, 0 В | GND |
| 9 | Ka | вход | Ka: 1 пропускает входы A | Ka |
| 10 | D1 | выход | D1 = A1·Ka + B1·Kb | D1 |
| 11 | D2 | выход | D2 = A2·Ka + B2·Kb | D2 |
| 12 | D3 | выход | D3 = A3·Ka + B3·Kb | D3 |
| 13 | D4 | выход | D4 = A4·Ka + B4·Kb | D4 |
| 14 | Kb | вход | Kb: 1 пропускает входы B | Kb |
| 15 | A4 | вход | A4 | A4 (GND) |
| 16 | VDD | питание | питание, +5 В (допустимо от 3 до 18 В) | +5V |
5Схема 1: мультиплексор как блок
and_or_select.sv. Пустые кружки —
провода к шинам, задающие данные. · SVG · PNG6Схема 2: соединения
| Цепь | Откуда | Куда | Провод |
|---|---|---|---|
| Ka | кнопка Ka, OUT | 4019 9 (Ka), линейка светодиодов, светодиод 1 | M-F, M-M |
| Kb | кнопка Kb, OUT | 4019 14 (Kb), линейка светодиодов, светодиод 2 | M-F, M-M |
| A1 | провод A1: +5V | 4019 6 (A1) | M-M |
| A2 | провод A2: GND | 4019 4 (A2) | M-M |
| A3 | провод A3: +5V | 4019 2 (A3) | M-M |
| A4 | провод A4: GND | 4019 15 (A4) | M-M |
| B1 | провод B1: +5V | 4019 7 (B1) | M-M |
| B2 | провод B2: +5V | 4019 5 (B2) | M-M |
| B3 | провод B3: GND | 4019 3 (B3) | M-M |
| B4 | провод B4: GND | 4019 1 (B4) | M-M |
| D1 | 4019 10 (D1) | линейка светодиодов, светодиод 3 | M-F |
| D2 | 4019 11 (D2) | линейка светодиодов, светодиод 4 | M-F |
| D3 | 4019 12 (D3) | линейка светодиодов, светодиод 5 | M-F |
| D4 | 4019 13 (D4) | линейка светодиодов, светодиод 6 | M-F |
| +5V | +5V | 4019 16 (VDD) | |
| GND | GND | 4019 8 (VSS) |
7Схема 3: макетная плата
Сборка шаг за шагом
- Сначала пройдите первые шаги: как макетная плата соединена внутри, блок питания с обеими перемычками на 5 В, как микросхема встаёт поперёк канавки.
- Вставьте микросхемы поперёк канавки: 4019 развёрнутой, выемкой вправо, ножкой 1 в отверстие 15e. Читайте надписи на микросхемах: многие выглядят одинаково. У развёрнутой микросхемы ножка 1 вверху справа: так нужные этой схеме ножки оказываются рядом с соседями.
- Питание: для каждой микросхемы красный провод от вывода VDD (14, или 16 у 16-выводной) к шине + и чёрный от вывода VSS (7 или 8) к шине −, каждый к шине со своей стороны канавки. У развёрнутой микросхемы VDD в нижнем ряду, а VSS — в верхнем. Проследите, чтобы ни один провод не касался + и − одновременно.
- Провода данных, каждый от своей ножки к шине, в положениях из списка.
- Сигнальные провода из списка, которые переносят ножки в ту половину платы, куда приходят перемычки модулей.
- При выключенном питании — кнопки над платой и линейку под ней.
- Включите питание.
Список проводов
| # | Цепь | Откуда | Куда | |
|---|---|---|---|---|
| Питание (красные к +, чёрные к −) · 2 провода | ||||
| 1 | +5V | 15j (4019, ножка 16, VDD) | нижняя шина +, столбик 15 | |
| 2 | GND | 8a (4019, ножка 8, VSS) | верхняя шина −, столбик 8 | |
| Провода режима: переставляйте их между + и −, чтобы сменить режим · 8 проводов | ||||
| 3 | A1 | 10a (4019, ножка 6, A1) | верхняя шина +, столбик 10 | |
| 4 | A2 | 12a (4019, ножка 4, A2) | верхняя шина −, столбик 12 | |
| 5 | A3 | 14a (4019, ножка 2, A3) | верхняя шина +, столбик 14 | |
| 6 | A4 | 14j (4019, ножка 15, A4) | нижняя шина −, столбик 14 | |
| 7 | B1 | 9a (4019, ножка 7, B1) | верхняя шина +, столбик 9 | |
| 8 | B2 | 11a (4019, ножка 5, B2) | верхняя шина +, столбик 11 | |
| 9 | B3 | 13a (4019, ножка 3, B3) | верхняя шина −, столбик 13 | |
| 10 | B4 | 15a (4019, ножка 1, B4) | верхняя шина −, столбик 15 | |
| Сигнальные провода · 2 провода | ||||
| 11 | Ka | 8g (4019, ножка 9, Ka) | 7e | |
| 12 | Kb | 13g (4019, ножка 14, Kb) | 16e | |
| Модули на перемычках папа-мама · 13 проводов | ||||
| 13 | +5V | кнопка Ka, + | верхняя шина +, столбик 7 | |
| 14 | Ka | кнопка Ka, OUT | 7a | |
| 15 | GND | кнопка Ka, − | верхняя шина −, столбик 9 | |
| 16 | +5V | кнопка Kb, + | верхняя шина +, столбик 13 | |
| 17 | Kb | кнопка Kb, OUT | 16a | |
| 18 | GND | кнопка Kb, − | верхняя шина −, столбик 16 | |
| 19 | GND | линейка светодиодов, G | нижняя шина −, столбик 22 | |
| 20 | Ka | линейка светодиодов, светодиод 1 | 8j (4019, ножка 9, Ka) | |
| 21 | Kb | линейка светодиодов, светодиод 2 | 13j (4019, ножка 14, Kb) | |
| 22 | D1 | линейка светодиодов, светодиод 3 | 9j (4019, ножка 10, D1) | |
| 23 | D2 | линейка светодиодов, светодиод 4 | 10j (4019, ножка 11, D2) | |
| 24 | D3 | линейка светодиодов, светодиод 5 | 11j (4019, ножка 12, D3) | |
| 25 | D4 | линейка светодиодов, светодиод 6 | 12j (4019, ножка 13, D4) | |
Проверка
- Ни одна кнопка не нажата: D1–D4 погашены.
- Нажмите Ka: светодиоды показывают A4…A1. Вместо неё Kb: B4…B1.
- Нажмите обе: горит каждый светодиод, где у A или у B единица.
Если не работает: если выход показывает не тот канал, проверьте перемычки выбора: перепутанная пара даёт другой, но устойчивый порядок. Если один канал никогда не появляется, проверьте его провод данных. Если выход не горит, проверьте Ka и Kb.
8SystemVerilog: общая схема
and_or_select.sv описывает схему 1 в нескольких строках. Код синтезируемый.
// Exercise BB4d: a quad AND/OR select gate, like the 4019. // // Generic version that matches schematic 1, not tied to any chip: each // output is D = A AND Ka OR B AND Kb. With exactly one of Ka and Kb at 1 // it is a 2:1 multiplexer of the 4-bit words A and B; with both at 1 it // ORs them, with both at 0 it gives 0. Synthesizable. module and_or_select ( input logic [3:0] a, // a [0] is A1 input logic [3:0] b, // b [0] is B1 input logic ka, input logic kb, output logic [3:0] d // d [0] is D1 ); assign d = a & { 4 { ka } } | b & { 4 { kb } }; endmodule
9Модель микросхемы на SystemVerilog
По модулю на микросхему, порты названы как в даташите, номер ножки каждого порта — в комментарии. Выводов питания в моделях нет: в SystemVerilog у провода просто есть значение 0 или 1.
// CD4019B: quad AND/OR select gate. // // Ports in pin order, named as in the datasheet. The power pins, VSS (8) // and VDD (16), are left out. Synthesizable. // // Each output is Dn = An & Ka | Bn & Kb: Ka passes the A word, Kb the B word, // both pass A OR B, neither gives 0. module cd4019 ( input logic b4, // Pin 1 input logic a3, // Pin 2 input logic b3, // Pin 3 input logic a2, // Pin 4 input logic b2, // Pin 5 input logic a1, // Pin 6 input logic b1, // Pin 7 // Pin 8: VSS input logic ka, // Pin 9 output logic d1, // Pin 10 output logic d2, // Pin 11 output logic d3, // Pin 12 output logic d4, // Pin 13 input logic kb, // Pin 14 input logic a4 // Pin 15 // Pin 16: VDD ); assign d1 = a1 & ka | b1 & kb; assign d2 = a2 & ka | b2 & kb; assign d3 = a3 & ka | b3 & kb; assign d4 = a4 & ka | b4 & kb; endmodule
10SystemVerilog: схема из микросхемы
and_or_select_chips.sv соединяет модели микросхем точно так же, как соединены микросхемы на схеме 2 и
на макетной плате, и у него те же порты, что у and_or_select.sv. Неиспользуемые входы подключены к
vdd или gnd, как на плате, а неиспользуемые выходы — к проводам с именами
unused_…. Файл генерируется из списка проводов макетной платы после проверки этого списка на уровне
ножек, поэтому код, рисунки и список проводов не могут разойтись.
// Exercise BB4d, chip-level version: the chips and wires of schematic 2 and // of the breadboard. Same ports as and_or_select.sv. // // Generated by tools/bb_lib.py from the checked breadboard wire list; // change the layout in tools/bb_bb4.py, not this file. Synthesizable. module and_or_select_chips ( input logic [3:0] a, input logic [3:0] b, input logic ka, input logic kb, output logic [3:0] d ); //------------------------------------------------------------------------ // U1: CD4019 quad AND/OR select gate, pin 1 in column 8 cd4019 i_u1 ( .b4 ( b [3] ), // Pin 1 <- B4 wire, at GND on the breadboard .a3 ( a [2] ), // Pin 2 <- A3 wire, at +5V on the breadboard .b3 ( b [2] ), // Pin 3 <- B3 wire, at GND on the breadboard .a2 ( a [1] ), // Pin 4 <- A2 wire, at GND on the breadboard .b2 ( b [1] ), // Pin 5 <- B2 wire, at +5V on the breadboard .a1 ( a [0] ), // Pin 6 <- A1 wire, at +5V on the breadboard .b1 ( b [0] ), // Pin 7 <- B1 wire, at +5V on the breadboard .ka ( ka ), // Pin 9 <- button Ka .d1 ( d [0] ), // Pin 10 -> D1 .d2 ( d [1] ), // Pin 11 -> D2 .d3 ( d [2] ), // Pin 12 -> D3 .d4 ( d [3] ), // Pin 13 -> D4 .kb ( kb ), // Pin 14 <- button Kb .a4 ( a [3] ) // Pin 15 <- A4 wire, at GND on the breadboard ); endmodule
11Тестбенч и скрипты симуляции
tb.sv запускает обе схемы рядом и сравнивает их с эталонной моделью. У схемы нет такта, но у
тестбенча он есть, как в тестбенчах Basics-Graphics-Music: он задаёт входы сразу после растущего фронта и проверяет
выходы на следующем. Он перебирает все сочетания данных, выбора дважды, по возрастанию начиная с проводов как на
макетной плате и в порядке кода Грея, и печатает строки с данными как на плате и каждую строку с ошибкой. Вывод ниже
сокращён.
tb.sv173 lines · показать кодфайл
// Testbench for exercise BB4d. // // Runs the generic design (and_or_select.sv) and the chip-level design // (and_or_select_chips.sv) side by side and compares both with // A where Ka is 1, ORed with B where Kb is 1. Works with Icarus Verilog, Verilator (--binary) // and Questa. // // The circuit has no clock, but like the testbenches of Basics-Graphics-Music // this one drives and checks signals only at rising edges of its own clock: // it changes the inputs after one edge and checks the outputs at the next. // It tries all 1024 input combinations twice: counting up, and then in // Gray code order, where one input changes at a time, as when a student // presses or releases one button. // Time units. The design files have none: Yosys does not accept timeunit // and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps // in its own testbench. This line sets the same units here and for the // design files compiled after it, so tb.sv comes first in the file list. `timescale 1ns / 1ps module tb; logic clk; logic [3:0] a; logic [3:0] b; logic ka; logic kb; wire [3:0] d, d_chips; and_or_select i_generic ( .a ( a ), .b ( b ), .ka ( ka ), .kb ( kb ), .d ( d ) ); and_or_select_chips i_chips ( .a ( a ), .b ( b ), .ka ( ka ), .kb ( kb ), .d ( d_chips ) ); //------------------------------------------------------------------------ // Clock with a period of 10 ns initial begin clk = '0; forever # 5 clk = ~ clk; end //------------------------------------------------------------------------ // Reference model: A where Ka is 1, ORed with B where Kb is 1. // Bits, from the left: d. function automatic logic [3:0] expected ( input logic [3:0] in_a, input logic [3:0] in_b, input logic in_ka, input logic in_kb ); logic [3:0] y; y = '0; if (in_ka) y = y | in_a; if (in_kb) y = y | in_b; return y; endfunction wire [3:0] out = { d }; wire [3:0] out_chips = { d_chips }; wire [3:0] out_model = expected (a, b, ka, kb); //------------------------------------------------------------------------ // Checking at every rising clock edge: the inputs still hold the values the // stimulus set at the previous edge, and the outputs have settled. // Initial values are fine in a testbench // verilator lint_off PROCASSINIT logic checking = 1'b0; // Set by the stimulus after the first inputs logic done = 1'b0; // Set by the stimulus before $finish int cycle = 0; int n_checks = 0; int n_errors = 0; logic [1023:0] rows_seen = '0; // Which input combinations were checked always @ (posedge clk) if (checking & ~ done) begin cycle <= cycle + 1; n_checks <= n_checks + 2; n_errors <= n_errors + (out === out_model ? 0 : 1) + (out_chips === out_model ? 0 : 1); rows_seen <= rows_seen | 1024'b1 << { a, b, ka, kb }; // Print the rows with the data wires as on the breadboard, and every error if (a == 4'b0101 & b == 4'b0011 | out !== out_model | out_chips !== out_model) $display ("%5d %b %b %b %b %b %s %s", cycle + 1, a, b, ka, kb, d, out === out_model ? "ok " : "WRONG ", out_chips === out_model ? "ok " : "WRONG"); end //------------------------------------------------------------------------ // Driving the inputs: all combinations, counting up from the data wires as on the // breadboard, then in Gray code order initial begin $dumpfile ("tb.vcd"); `ifdef __ICARUS__ $dumpvars (0, tb); // Without a scope Icarus also tries to dump $unit `else $dumpvars; `endif $display ("cycle A4..A1 B4..B1 Ka Kb D4..D1 generic chips"); checking <= '1; for (int i = 0; i < 1024; i ++) begin { a, b, ka, kb } <= 10' (i) ^ 10'h14c; @ (posedge clk); end for (int i = 0; i < 1024; i ++) begin { a, b, ka, kb } <= 10' (i ^ (i >> 1)) ^ 10'h14c; @ (posedge clk); end // Stop checking one clock edge before $finish, so that every // simulator reports the same number of checks done <= '1; @ (posedge clk); $finish; end //------------------------------------------------------------------------ final begin if (n_errors == 0 && & rows_seen) $display ("PASS: %0d checks, no errors", n_checks); else $display ("FAIL: %0d errors in %0d checks, %0d of %0d input combinations seen", n_errors, n_checks, $countones (rows_seen), 1024); end endmodule
Каждый скрипт компилирует файлы, запускает симуляцию, пишет журнал и временную диаграмму
tb.vcd и завершается с ошибкой, если тест не прошёл. Запускать можно из любого каталога:
./run_icarus.bash, ./run_verilator.bash или ./run_questa.bash;
./clean.bash удаляет то, что они создают. Диаграмму открывают в GTKWave или Surfer.
run_icarus.bash22 lines · показать кодфайл
#!/usr/bin/env bash # Exercise BB4d: run the testbench with Icarus Verilog 12 or later. # The output goes to icarus.log and the waveform to tb.vcd, # for GTKWave or Surfer. set -Eeuo pipefail cd "$(dirname "$0")" files=(tb.sv and_or_select.sv and_or_select_chips.sv cd4019.sv) if ! command -v iverilog > /dev/null then printf '%s\n' "$0: iverilog not found, install Icarus Verilog 12 or later" >&2 exit 1 fi iverilog -g2012 -o tb.vvp "${files[@]}" vvp -n tb.vvp | tee icarus.log grep -q '^PASS' icarus.log
run_verilator.bash29 lines · показать кодфайл
#!/usr/bin/env bash # Exercise BB4d: run the testbench with Verilator 5. --binary builds # a simulator with the testbench's delays; it needs a C++20 compiler. # The output goes to verilator.log and the waveform to tb.vcd. set -Eeuo pipefail cd "$(dirname "$0")" files=(tb.sv and_or_select.sv and_or_select_chips.sv cd4019.sv) # OSS CAD Suite unpacked in the home directory has Verilator too if ! command -v verilator > /dev/null && [ -x "$HOME/oss-cad-suite/bin/verilator" ] then PATH="$HOME/oss-cad-suite/bin:$PATH" fi if ! command -v verilator > /dev/null then printf '%s\n' "$0: verilator not found, install Verilator 5" >&2 exit 1 fi verilator --binary -Wall --trace --top-module tb -o tb "${files[@]}" obj_dir/tb | tee verilator.log grep -q '^PASS' verilator.log
run_questa.bash64 lines · показать кодфайл
#!/usr/bin/env bash # Exercise BB4d: run the testbench with Questa, for example the free # Questa Starter Edition that comes with Quartus Prime Lite. # The output goes to questa.log and the waveform to tb.vcd. set -Eeuo pipefail cd "$(dirname "$0")" files=(tb.sv and_or_select.sv and_or_select_chips.sv cd4019.sv) # When vsim is not in PATH, look for it where Quartus installs it if ! command -v vsim > /dev/null then for dir in "$HOME"/intelFPGA_lite/*/questa_fse/bin \ "$HOME"/altera_lite/*/questa_fse/bin \ /opt/intelFPGA_lite/*/questa_fse/bin \ /opt/altera_lite/*/questa_fse/bin do if [ -x "$dir/vsim" ] then PATH="$dir:$PATH" break fi done fi if ! command -v vsim > /dev/null then printf '%s\n' "$0: vsim not found, install Questa or add it to PATH" >&2 exit 1 fi # The Starter Edition needs a free license file from the Intel # licensing site; Quartus keeps it in ~/flexlm/license.dat license="$HOME/flexlm/license.dat" # ${SALT_LICENSE_SERVER-} is empty when the variable is not set, # where a plain $SALT_LICENSE_SERVER would stop the script (set -u) salt_license="${SALT_LICENSE_SERVER-}" if [ -z "$salt_license" ] && [ -f "$license" ] then export SALT_LICENSE_SERVER="$license" fi # Older Questa versions read LM_LICENSE_FILE; ${LM_LICENSE_FILE-} # is empty when the variable is not set lm_license="${LM_LICENSE_FILE-}" if [ -z "$lm_license" ] && [ -f "$license" ] then export LM_LICENSE_FILE="$license" fi rm -rf work vlib work > /dev/null vlog -sv -lint "${files[@]}" vsim -c tb -do "run -all; quit -f" | tee questa.log grep -q 'PASS' questa.log
Проверено в Icarus Verilog 12.0 и 14.0 (разрабатываемая версия), в Verilator 5.053 с
-Wall без предупреждений и в Questa Altera Starter FPGA Edition 2025.2 из Quartus Prime Lite 25.1. Код
использует только то, что поддерживает Icarus Verilog 13. Вот вывод Icarus Verilog:
VCD info: dumpfile tb.vcd opened for output.
cycle A4..A1 B4..B1 Ka Kb D4..D1 generic chips
1 0101 0011 0 0 0000 ok ok
2 0101 0011 0 1 0011 ok ok
3 0101 0011 1 0 0101 ok ok
4 0101 0011 1 1 0111 ok ok
1025 0101 0011 0 0 0000 ok ok
1026 0101 0011 0 1 0011 ok ok
1027 0101 0011 1 1 0111 ok ok
1028 0101 0011 1 0 0101 ok ok
tb.sv:159: $finish called at 20485000 (1ps)
PASS: 4096 checks, no errors
Чтобы убедиться, что тестбенч ловит ошибки, сломайте что-нибудь и запустите снова: замените | b & { 4 { kb } } на ^ b & { 4 { kb } } в and_or_select.sv или поменяйте местами Ka и Kb в and_or_select_chips.sv. Скрипт
сообщит FAIL, а в распечатке появятся строки с WRONG.
12На плате ПЛИС: lab_top в BGM
Репозиторий Basics-Graphics-Music (BGM) запускает одни и те же
лабораторные работы на десятках плат ПЛИС. В каждой работе есть модуль lab_top с одинаковыми на всех
платах портами: такт, медленный такт slow_clk на 1 Гц, сброс, кнопки, светодиоды, семисегментный
индикатор.
- Скопируйте
labs/1_basics/1_02_muxв новый каталог. - Замените в нём
lab_top.svнаbgm_lab/lab_top.svиз этого упражнения и добавьтеand_or_select.sv. Скрипты BGM компилируют все файлы.svкаталога, кромеtb.sv. - Запустите
./03_synthesize_for_fpga.bashи./04_configure_fpga.bash; при первом запуске скрипт спросит, какая у вас плата.
Переключатели 0 и 1 — это Ka и Kb, переключатели 5–2 — A4…A1; B4…B1 задан в lab_top.sv постоянным, как провода на плате. Светодиоды 3–0 показывают D4…D1. Чтобы запустить схему из микросхемы, добавьте and_or_select_chips.sv и cd4019.sv и поменяйте имя модуля в экземпляре.
bgm_lab/lab_top.sv98 lines · показать кодфайл
// Exercise BB4d on an FPGA board with the Basics-Graphics-Music (BGM) labs: // https://github.com/yuri-panchul/basics-graphics-music // // Copy labs/1_basics/1_02_mux to a new directory, replace its lab_top.sv with // this file and add and_or_select.sv. For the chip-level design add // and_or_select_chips.sv and cd4019.sv instead, and change the module name // below. // // Switches: sw [0] ka, sw [1] kb, sw [5:2] a. The LEDs: led [3:0] d. A board // with fewer LEDs shows the first ones. // // B4-B1 is fixed at 0011, as the wires on the breadboard. `include "config.svh" module lab_top # ( parameter clk_mhz = 50, w_key = 4, w_sw = 8, w_led = 8, w_digit = 8, w_gpio = 100, screen_width = 640, screen_height = 480, w_red = 4, w_green = 4, w_blue = 4, w_x = $clog2 ( screen_width ), w_y = $clog2 ( screen_height ) ) ( input clk, input slow_clk, input rst, // Keys, switches, LEDs input [w_key - 1:0] key, input [w_sw - 1:0] sw, output logic [w_led - 1:0] led, // A dynamic seven-segment display output logic [ 7:0] abcdefgh, output logic [w_digit - 1:0] digit, // Graphics input [w_x - 1:0] x, input [w_y - 1:0] y, output logic [w_red - 1:0] red, output logic [w_green - 1:0] green, output logic [w_blue - 1:0] blue, // Microphone, sound output and UART input [ 23:0] mic, output [ 15:0] sound, input uart_rx, output uart_tx, // General-purpose Input/Output inout [w_gpio - 1:0] gpio ); //------------------------------------------------------------------------ assign abcdefgh = '0; assign digit = '0; assign red = '0; assign green = '0; assign blue = '0; assign sound = '0; assign uart_tx = '1; //------------------------------------------------------------------------ logic [3:0] d; and_or_select i_and_or_select ( .ka ( sw [0] ), .kb ( sw [1] ), .a ( sw [5:2] ), .b ( 4'b0011 ), .d ( d ) ); assign led = w_led' ({ d }); endmodule
13На плате ПЛИС: hackathon_top в BGM
В варианте BGM для хакатонов используется Tang Nano 9K с экраном 480×272 и платой TM1638 с
кнопками, светодиодами и индикатором. У верхнего модуля hackathon_top порты проще, а первая строка
файла называет плату, так что скрипты ничего не спрашивают.
- Скопируйте
hackathon/problems/1_gates_and_muxes. - Замените в нём
hackathon_top.svнаbgm_hackathon/hackathon_top.svи добавьтеand_or_select.sv. - Запустите
./03_synthesize_for_fpga.bashи./04_configure_fpga.bash.
Кнопки 0 и 1 — это Ka и Kb, кнопки 5–2 — A4…A1, B задан постоянным; экран показывает входы синими, а D зелёными.
bgm_hackathon/hackathon_top.sv85 lines · показать кодфайл
// Board configuration: tang_nano_9k_lcd_480_272_tm1638_hackathon // This module uses few parameterization and relaxed typing rules // Exercise BB4d in the hackathon setup of Basics-Graphics-Music (BGM): // https://github.com/yuri-panchul/basics-graphics-music // // Copy a directory such as hackathon/problems/1_gates_and_muxes, replace its // hackathon_top.sv with this file and add and_or_select.sv. // // Keys: key [0] ka, key [1] kb, key [5:2] a. The LEDs: led [3:0] d. The // screen shows 10 lamps in a row: Ka, Kb, A1, A2, A3, A4, D1, D2, D3, D4; // inputs in blue, outputs in green. // // B4-B1 is fixed at 0011, as the wires on the breadboard. module hackathon_top ( input logic clock, input logic slow_clock, input logic reset, input logic [7:0] key, output logic [7:0] led, // A dynamic seven-segment display output logic [7:0] abcdefgh, output logic [7:0] digit, // LCD screen interface input logic [8:0] x, input logic [8:0] y, output logic [4:0] red, output logic [5:0] green, output logic [4:0] blue, inout logic [3:0] gpio ); //------------------------------------------------------------------------ wire ka = key [0]; wire kb = key [1]; wire [3:0] a = key [5:2]; logic [3:0] d; and_or_select i_and_or_select ( .ka ( ka ), .kb ( kb ), .a ( a ), .b ( 4'b0011 ), .d ( d ) ); assign led = { 4'b0, d }; assign abcdefgh = '0; assign digit = '0; //------------------------------------------------------------------------ // 10 square lamps on the 480 x 272 screen, 34 pixels wide, 46 apart: // the inputs in blue, the outputs in green. Bright when 1, dim when 0. wire [9:0] lamp = { d, a, kb, ka }; always_comb begin red = 0; green = 0; blue = 0; for (int i = 0; i < 10; i ++) if (x >= 9' (16 + i * 46) & x < 9' (50 + i * 46) & y >= 119 & y < 153) begin if (i < 6) blue = lamp [i] ? 31 : 6; else green = lamp [i] ? 63 : 12; end end endmodule
14На кристалле: Tiny Tapeout
Tiny Tapeout выпускает настоящие микросхемы из проектов
учащихся. Каждый проект — модуль с портами, как ниже; на демонстрационной плате ui_in идёт от
DIP-переключателей, а uo_out управляет семисегментным индикатором.
У этой схемы нет ни такта, ни состояния: project.v подаёт DIP-переключатели на её входы,
а её выходы — на индикатор. Такт и сброс от платы проект всё равно получает; они остаются неиспользованными.
Переключатели 0 и 1 — это Ka и Kb, переключатели 5–2 — A4…A1; B задан в project.v. Сегменты a–d показывают D1–D4.
tiny_tapeout/project.v51 lines · показать кодфайл
/* * Exercise BB4d on Tiny Tapeout: the AND/OR select gate, with the DIP switches as * inputs and the 7-segment display of the demo board as lamps. * * Add and_or_select.sv to source_files in info.yaml next to project.v. * Rename the module to tt_um_<your GitHub name>_<project name> and use the * same name as top_module in info.yaml. */ `default_nettype none module tt_um_example ( input wire [7:0] ui_in, // DIP switches, INPUT Pmod, RP2350 GPIO17-24 output wire [7:0] uo_out, // 7-segment display, OUTPUT Pmod, RP2350 GPIO33-40 input wire [7:0] uio_in, // BIDIR Pmod, RP2350 GPIO25-32 output wire [7:0] uio_out, // (same pins) output wire [7:0] uio_oe, // 1 = your design drives the pin input wire ena, // set by the on-chip project mux, not a board pin input wire clk, // RP2350 GPIO16 input wire rst_n // RP2350 GPIO14 ); // Switch 0 is ka, switch 1 is kb, switches 5-2 are a // B4-B1 is fixed at 0011, as the wires on the breadboard. wire [3:0] d; and_or_select i_and_or_select ( .ka ( ui_in [0] ), .kb ( ui_in [1] ), .a ( ui_in [5:2] ), .b ( 4'b0011 ), .d ( d ) ); // 7-segment display: uo_out [0] is segment a, ..., uo_out [6] is g, // uo_out [7] is the dot. Each output lights one segment: // a (top) d [0], b (top right) d [1], c (bottom right) d [2], d (bottom) // d [3]. assign uo_out = { 4'b0, d }; assign uio_out = 8'b0; assign uio_oe = 8'b0; // The circuit needs no clock or reset. // List all unused inputs to prevent warnings wire _unused = & { ena, clk, rst_n, ui_in [7:6], uio_in, 1'b0 }; endmodule
В info.yaml перечислите файлы и укажите имя модуля как верхний модуль:
project:
top_module: "tt_um_example" # переименуйте в tt_um_<ваш логин на GitHub>_and_or_select
source_files:
- "project.v"
- "and_or_select.sv"
15Что дальше
Задания для учеников
- Настоящий мультиплексор 2:1. Подайте Kb через инвертор 4069 на Ka, чтобы ровно один из них всегда был 1. Теперь одна кнопка выбирает A или B.
- Слияние по маске. Упражнение M9 строит ту же функцию из двух 4081 и 4071 и сравнивает их на линейке.
- На SystemVerilog: напишите мультиплексор 2:1 условным оператором,
s ? b : a, и сравните, что делает из него синтез, с этой формой И-ИЛИ.
Файлы упражнения
- and_or_select.sv: общая схема (раздел 8)
- cd4019.sv: модели микросхем (раздел 9)
- and_or_select_chips.sv: схема из микросхем (раздел 10)
- tb.sv, run_icarus.bash, run_verilator.bash, run_questa.bash, clean.bash (раздел 11)
- bgm_lab/lab_top.sv, bgm_hackathon/hackathon_top.sv, tiny_tapeout/project.v (разделы 12–14)
- Рисунки в SVG и PNG в каталоге images/: схемы, цоколёвки и временные диаграммы; русские версии с окончанием
_ru
Источники
Мультиплексоры 4051, 4052, 4053 и 4019 есть в списке строительных блоков статьи «An improved way of teaching school kids digital electronics» и в занятии 1.6 из статьи на Хабре о курсе электроники. 4019 описана в даташите Texas Instruments на CD4019B.