[HTML-версия](index_ru.html)

[← Упражнения на макетной плате](../index_ru.md) · [English](index.md)

BB-FSM-01B · CMOS → RTL → FPGA → ASIC

# Юрий: зелёный 4 → жёлтый 2 → красный 4

Три реализации циклического автомата светофора. В этом уроке — одна полная сборка.

- [1. Цель и подготовка](#s01)
- [2. Поведение, символы и наблюдения](#s02)
- [3. Необходимые компоненты](#s03)
- [4. Функции, выводы и полярность микросхем](#s04)
- [5. Схема 1 · Общая логика](#s05)
- [6. Схема 2 · Соединения микросхем](#s06)
- [7. Схема 3 · Макетная плата и сборка](#s07)
- [8. Общий синтезируемый SystemVerilog](#s08)
- [9. Модели микросхем CMOS](#s09)
- [10. SystemVerilog с соединениями выводов](#s10)
- [11. Тестбенчи и скрипты симуляторов](#s11)
- [12. Подключение к BGM lab\_top](#s12)
- [13. Подключение к BGM hackathon\_top](#s13)
- [14. Подключение к Tiny Tapeout project.v](#s14)
- [15. Задания, поиск ошибок и источники](#s15)

<a id="s01"></a>

## 1. Цель и подготовка

Конечный автомат хранит текущий шаг и выбирает выходы по состоянию. Этот циклический автомат Мура делает один переход на фронт такта; сигнал лампы получается дешифрацией состояния. Соберите его на CMOS и сравните общий RTL с моделью соединений микросхем.

| № | Вариант | G / Y / R | CMOS |
| --- | --- | --- | --- |
| 1 | [Тимофей: зелёный 3 → жёлтый 1 → красный 3](../traffic_light_timofei/index_ru.md) | 3 / 1 / 3 | 4017 + 4075 |
| 2 | [Юрий: зелёный 4 → жёлтый 2 → красный 4](../traffic_light/index_ru.md) | 4 / 2 / 4 | 4017 + 4072 + 4071 |
| 3 | [COUT: зелёный 5 → жёлтый 1 → красный 4](../traffic_light_carry/index_ru.md) | 5 / 1 / 4 | 4017 + 4072 |

Это десятисостоянийный вариант Юрия с исправленной последовательностью зелёный → жёлтый → красный. Прежнее приписывание схемы 4/2/4 Тимофею было ошибочным. Сохраняется каталог traffic\_light, чтобы прежние ссылки продолжали работать.

Подготовка: контакты макетки, полярность, базовые ИЛИ/НЕ и положительный фронт такта. Используйте стабилизированные 5 В, готовый генератор и проверенный кнопочный модуль с активной единицей из списка. Три индикатора должны быть указанными типами на 5 В с ограничением тока. Это учебная схема, а не контроллер дорожного светофора.

[Правила стиля SystemVerilog](../systemverilog_style_ru.md)

<a id="s02"></a>

## 2. Поведение, символы и наблюдения

После сброса: S0, горит зелёный. Каждый положительный фронт переводит автомат в следующее устойчивое состояние. Зелёный длится 4 тактов, жёлтый 2, красный 4, затем цикл повторяется. При 1 Гц эти числа равны секундам; при f Гц делите их на f. Ручной сброс сразу включает зелёный, прерывая текущую фазу.

```
green = Q0 | Q1 | Q2 | Q3
yellow = Q4 | Q5
red = Q6 | Q7 | Q8 | Q9
RESET = rst
```

[![Граф переходов](images/fsm_ru.png)](images/fsm_ru.svg)

Граф переходов · [SVG](images/fsm_ru.svg) · [PNG](images/fsm_ru.png)

[![Граф кодирования состояний](images/fsm_encoding_ru.png)](images/fsm_encoding_ru.svg)

Граф кодирования состояний · [SVG](images/fsm_encoding_ru.svg) · [PNG](images/fsm_encoding_ru.png)

| S | state\[9:0\] | R | Y | G | Следующий ↑clk |
| --- | --- | --- | --- | --- | --- |
| S0 | `0000000001` | 0 | 0 | 1 | S1 |
| S1 | `0000000010` | 0 | 0 | 1 | S2 |
| S2 | `0000000100` | 0 | 0 | 1 | S3 |
| S3 | `0000001000` | 0 | 0 | 1 | S4 |
| S4 | `0000010000` | 0 | 1 | 0 | S5 |
| S5 | `0000100000` | 0 | 1 | 0 | S6 |
| S6 | `0001000000` | 1 | 0 | 0 | S7 |
| S7 | `0010000000` | 1 | 0 | 0 | S8 |
| S8 | `0100000000` | 1 | 0 | 0 | S9 |
| S9 | `1000000000` | 1 | 0 | 0 | S0 |

[![Временная диаграмма](images/timing_ru.png)](images/timing_ru.svg)

Временная диаграмма · [SVG](images/timing_ru.svg) · [PNG](images/timing_ru.png)

Кнопки симуляции доступны в HTML-версии. [Открыть интерактивную модель в HTML](index_ru.html#s02).

<a id="s03"></a>

## 3. Необходимые компоненты

| Компонент | Количество | Строка LSSK | Назначение |
| --- | --- | --- | --- |
| CD4017BE | 1 | [37](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Логика CMOS |
| CD4072BE | 1 | [21](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Логика CMOS |
| CD4071BE | 1 | [20](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Логика CMOS |
| Макетная плата на 830 контактов | 1 | [45](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Макетная плата |
| Модуль стабилизированного питания 5 В | 1 | [56](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Питание всей логики 5 В |
| Кабель USB → 9 В | 1 | [57](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Только на вход совместимого стабилизатора |
| Кнопочный модуль с активной единицей | 1 | [65](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Ручной сброс; встроенная подтяжка к земле |
| Готовый тактовый модуль 555 | 1 | [54](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Такт, около 1 Гц |
| LED на 5 В с ограничением тока · красный | 1 | [46](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Один сигнал |
| LED на 5 В с ограничением тока · зелёный | 1 | [47](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Один сигнал |
| LED на 5 В с ограничением тока · жёлтый | 1 | [48](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Один сигнал |
| Перемычка M–M | 29 | [70](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Соединения на плате, включая шины |
| Провод M–F | 14 | [71](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit) | Провода модулей/LED; окончания по реальным разъёмам |

[CSV](parts.csv) · 43 проводов, включая выводы модулей и перемычки шин; без запаса. Окончания подберите по реальным модулям. Компоненты отменённой схемы буфера наблюдения от 14 октября не включены.

<a id="s04"></a>

## 4. Функции, выводы и полярность микросхем

[![Цоколёвка](images/pinouts_ru.png)](images/pinouts_ru.svg)

Цоколёвка · [SVG](images/pinouts_ru.svg) · [PNG](images/pinouts_ru.png)

Вид сверху: на цоколёвке выемка вверху; на горизонтальной макетке — слева, вывод 1 под канавкой. CD4017: 16 = +5 В, 8 = GND, 14 = такт, 13 = запрет счёта (ноль), 15 = асинхронный сброс активной единицей. Сброс выбирает Q0 и поднимает COUT. Все неиспользуемые логические входы заземлены; неиспользуемые выходы и настоящие NC свободны.

### U1 · CD4017B

| Вывод | Функция | Тип | Цепь |
| --- | --- | --- | --- |
| 1 | Q5 | выход | state\[5\] |
| 2 | Q1 | выход | state\[1\] |
| 3 | Q0 | выход | state\[0\] |
| 4 | Q2 | выход | state\[2\] |
| 5 | Q6 | выход | state\[6\] |
| 6 | Q7 | выход | state\[7\] |
| 7 | Q3 | выход | state\[3\] |
| 8 | VSS | питание | GND |
| 9 | Q8 | выход | state\[8\] |
| 10 | Q4 | выход | state\[4\] |
| 11 | Q9 | выход | state\[9\] |
| 12 | CARRY | выход | NC |
| 13 | INHIBIT | вход | GND |
| 14 | CLOCK | вход | clk |
| 15 | RESET | вход | rst |
| 16 | VDD | питание | +5V |

### U2 · CD4072B

ИЛИ, группы выводов: 2/3/4/5 → 1; 9/10/11/12 → 13. Питание: 14 = +5 В, 7 = GND.

| Вывод | Функция | Тип | Цепь |
| --- | --- | --- | --- |
| 1 | J | выход | green |
| 2 | A | вход | state\[0\] |
| 3 | B | вход | state\[1\] |
| 4 | C | вход | state\[2\] |
| 5 | D | вход | state\[3\] |
| 6 | NC | NC | NC |
| 7 | VSS | питание | GND |
| 8 | NC | NC | NC |
| 9 | E | вход | state\[6\] |
| 10 | F | вход | state\[7\] |
| 11 | G | вход | state\[8\] |
| 12 | H | вход | state\[9\] |
| 13 | K | выход | red |
| 14 | VDD | питание | +5V |

### U3 · CD4071B

ИЛИ, группы выводов: 1/2 → 3; 5/6 → 4; 8/9 → 10; 12/13 → 11. Питание: 14 = +5 В, 7 = GND.

| Вывод | Функция | Тип | Цепь |
| --- | --- | --- | --- |
| 1 | A | вход | state\[4\] |
| 2 | B | вход | state\[5\] |
| 3 | J | выход | yellow |
| 4 | K | выход | NC |
| 5 | C | вход | GND |
| 6 | D | вход | GND |
| 7 | VSS | питание | GND |
| 8 | E | вход | GND |
| 9 | F | вход | GND |
| 10 | L | выход | NC |
| 11 | M | выход | NC |
| 12 | G | вход | GND |
| 13 | H | вход | GND |
| 14 | VDD | питание | +5V |

<a id="s05"></a>

## 5. Схема 1 · Общая логика

[![Общая логика](images/logic_ru.png)](images/logic_ru.svg)

Общая логика · [SVG](images/logic_ru.svg) · [PNG](images/logic_ru.png)

ИЛИ означает «хотя бы один вход равен единице». Состояние хранит счётчик. Для дешифрации ламп дополнительные периоды такта не нужны.

<a id="s06"></a>

## 6. Схема 2 · Соединения микросхем

[![Соединения микросхем](images/connections_ru.png)](images/connections_ru.svg)

Соединения микросхем · [SVG](images/connections_ru.svg) · [PNG](images/connections_ru.png)

Одинаковые имена цепей обозначают соединение. Таблицы выводов включают питание, постоянные уровни и свободные выводы. Аноды A индикаторов подключаются к сигналам ламп, катоды K — к GND. Метки контактов модулей обозначают функции, а не универсальную распиновку разъёма.

[Полная база выводов и цепей](netlist.json)

<a id="s07"></a>

## 7. Схема 3 · Макетная плата и сборка

[![Монтаж на макетке](images/breadboard_ru.png)](images/breadboard_ru.svg)

Монтаж на макетке · [SVG](images/breadboard_ru.svg) · [PNG](images/breadboard_ru.png)

B1.a…e с одинаковым номером — один контакт; B1.f…j — другой. TP/BP — положительные шины, TG/BG — земля. Соедините показанные разрывы шин 25–26, затем верхние и нижние шины. Если устройство вашей макетки отличается, проверьте связность прозвонкой. Пересечения без точек не являются соединениями.

1. При отключённом питании поставьте DIP поперёк канавки, выемкой ВЛЕВО. Следуйте координатам ниже: ножка занимает e или f, провод — другое отверстие того же контакта.
2. Сначала подключите GND, +5 В, перемычки шин и постоянные входы. Установите выход стабилизатора 5 В до подключения логики; кабель 9 В не подключается прямо к шинам логики.
3. Добавьте OUT генератора и OUT кнопки, затем сигналы и провода LED по jumpers.csv. Внешние модули расположите рядом с макеткой и следуйте маркировке контактов.
4. Проверьте ориентацию, питание и неиспользуемые входы. Включите питание, нажмите и отпустите сброс. Первым должен загореться зелёный. Настройте готовый генератор примерно на 1 Гц и отсчитайте полный цикл.

| IC | Вывод 1 | Последний вывод |
| --- | --- | --- |
| U1 | B1.f8 | B1.e8 |
| U2 | B1.f26 | B1.e26 |
| U3 | B1.f42 | B1.e42 |

[Полный CSV соединений](jumpers.csv) · [Проверки связности](research/wiring_validation.json)

| ID | Цепь | Откуда | Куда |
| --- | --- | --- | --- |
| W001 | +5V | B1.TP25 | B1.TP26 |
| W002 | GND | B1.TG25 | B1.TG26 |
| W003 | +5V | B1.BP25 | B1.BP26 |
| W004 | GND | B1.BG25 | B1.BG26 |
| W005 | +5V | B1.TP1 | B1.BP1 |
| W006 | GND | B1.TG1 | B1.BG1 |
| W007 | state\[5\] | B1.j8 | B1.j43 |
| W008 | state\[1\] | B1.j9 | B1.j28 |
| W009 | state\[0\] | B1.j10 | B1.j27 |
| W010 | state\[2\] | B1.j11 | B1.j29 |
| W011 | state\[6\] | B1.j12 | B1.a31 |
| W012 | state\[7\] | B1.j13 | B1.a30 |
| W013 | state\[3\] | B1.j14 | B1.j30 |
| W014 | GND | B1.j15 | B1.BG2 |
| W015 | GND | B1.a11 | B1.TG2 |
| W016 | GND | B1.j32 | B1.BG3 |
| W017 | GND | B1.j46 | B1.BG4 |
| W018 | GND | B1.j47 | B1.BG5 |
| W019 | GND | B1.j48 | B1.BG6 |
| W020 | GND | B1.a48 | B1.TG3 |
| W021 | GND | B1.a47 | B1.TG4 |
| W022 | GND | B1.a44 | B1.TG5 |
| W023 | GND | B1.a43 | B1.TG6 |
| W024 | GND | S1.GND | B1.BG7 |
| W025 | GND | CLK.GND | B1.BG8 |
| W026 | GND | PWR.GND | B1.BG9 |
| W027 | GND | L1.K | B1.BG10 |
| W028 | GND | L2.K | B1.BG11 |
| W029 | GND | L3.K | B1.BG12 |
| W030 | state\[8\] | B1.a15 | B1.a29 |
| W031 | state\[4\] | B1.a14 | B1.j42 |
| W032 | state\[9\] | B1.a13 | B1.a28 |
| W033 | clk | B1.a10 | CLK.OUT |
| W034 | rst | B1.a9 | S1.OUT |
| W035 | +5V | B1.a8 | B1.TP2 |
| W036 | +5V | B1.a26 | B1.TP3 |
| W037 | +5V | B1.a42 | B1.TP4 |
| W038 | +5V | S1.VCC | B1.BP2 |
| W039 | +5V | CLK.VCC | B1.BP3 |
| W040 | +5V | PWR.+5V | B1.BP4 |
| W041 | green | B1.j26 | L3.A |
| W042 | red | B1.a27 | L1.A |
| W043 | yellow | B1.j44 | L2.A |

<a id="s08"></a>

## 8. Общий синтезируемый SystemVerilog

One-hot-регистр хранит устойчивое состояние. Сброс явно устанавливает бит 0; нельзя полагаться на запуск неинициализированной схемы в S0. Интерфейс одинаков у обоих описаний. В RTL нет timeunit, timeprecision и timescale; используются четыре пробела и обычные input/output для сетевых портов.

### rtl/traffic\_light.sv

[Скачать исходник](rtl/traffic_light.sv)

```systemverilog
// Synthesizable one-hot FSM: green, then yellow, then red.

module traffic_light
(
    input              clk,
    input              rst,

    output             red,
    output             yellow,
    output             green,
    output logic [9:0] state
);

    wire [9:0] next_state = { state [8:0], state [9] };

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            state <= 10'b00_0000_0001;
        else
            state <= next_state;

    assign red    = | state [9:6];
    assign yellow = | state [5:4];
    assign green  = | state [3:0];

endmodule
```

<a id="s09"></a>

## 9. Модели микросхем CMOS

Модели описывают булево поведение и синтезируются. Питание, нагрузочная способность и задержки исключены. CD4017 использует счёт по модулю 10, дешифрированные выходы и COUT = count \< 5. В этих сборках inhibit заземлён. Тест микросхем дополнительно проверяет запрет счёта и асинхронный сброс.

### models/cd4017b.sv

[Скачать исходник](models/cd4017b.sv)

```systemverilog
// Synthesizable, zero-delay functional model of a powered CD4017B.
// Physical supply pins: 16 = VDD, 8 = VSS; they are not HDL ports.
// Binary encoding abstracts the chip's five-stage Johnson counter.
// Reset is required. Illegal Johnson-state recovery and electrical effects
// (current, setup/hold, pulse width and propagation delay) are not modeled.

module cd4017b
(
    input   p14_clock,
    input   p13_inhibit,
    input   p15_reset,

    output  p3_q0,
    output  p2_q1,
    output  p4_q2,
    output  p7_q3,
    output  p10_q4,
    output  p1_q5,
    output  p5_q6,
    output  p6_q7,
    output  p9_q8,
    output  p11_q9,
    output  p12_carry
);

    // Falling INHIBIT while CLOCK is high is also a count event.
    // INHIBIT is tied low in this exercise, so synthesis removes the gate.
    // This models the chip; it is not a recommendation to gate FPGA clocks.

    wire effective_clock = p14_clock & ~ p13_inhibit;

    logic [3:0] count;

    always_ff @ (posedge effective_clock or posedge p15_reset)
        if (p15_reset)
            count <= '0;
        else if (count == 4'd9)
            count <= '0;
        else
            count <= count + 1'b1;

    assign p3_q0     = (count == 4'd0);
    assign p2_q1     = (count == 4'd1);
    assign p4_q2     = (count == 4'd2);
    assign p7_q3     = (count == 4'd3);
    assign p10_q4    = (count == 4'd4);
    assign p1_q5     = (count == 4'd5);
    assign p5_q6     = (count == 4'd6);
    assign p6_q7     = (count == 4'd7);
    assign p9_q8     = (count == 4'd8);
    assign p11_q9    = (count == 4'd9);
    assign p12_carry = (count <  4'd5);

endmodule
```

### models/cd4071b.sv

[Скачать исходник](models/cd4071b.sv)

```systemverilog
// Synthesizable ideal gate model. Power pins and propagation delay omitted.

module cd4071b
(
    input              p1_a,
    input              p2_b,
    input              p5_c,
    input              p6_d,
    input              p8_e,
    input              p9_f,
    input              p12_g,
    input              p13_h,
    output             p3_j,
    output             p4_k,
    output             p10_l,
    output             p11_m
);

    assign p3_j  = p1_a | p2_b;
    assign p4_k  = p5_c | p6_d;
    assign p10_l = p8_e | p9_f;
    assign p11_m = p12_g | p13_h;

endmodule
```

### models/cd4072b.sv

[Скачать исходник](models/cd4072b.sv)

```systemverilog
// Synthesizable ideal gate model. Power pins and propagation delay omitted.

module cd4072b
(
    input              p2_a,
    input              p3_b,
    input              p4_c,
    input              p5_d,
    input              p9_e,
    input              p10_f,
    input              p11_g,
    input              p12_h,
    output             p1_j,
    output             p13_k
);

    assign p1_j  = p2_a | p3_b | p4_c | p5_d;
    assign p13_k = p9_e | p10_f | p11_g | p12_h;

endmodule
```

<a id="s10"></a>

## 10. SystemVerilog с соединениями выводов

Имена портов включают номера физических выводов. state\[9:0\] позволяет видеть все выходы счётчика в симуляции; десять дополнительных LED или проводов на макетке не требуются. Сравнивайте выходы после установления комбинационной логики.

### rtl/traffic\_light\_chips.sv

[Скачать исходник](rtl/traffic_light_chips.sv)

```systemverilog
// Pin-connected model. state observes the counter outputs without adding hardware.

module traffic_light_chips
(
    input              clk,
    input              rst,

    output             red,
    output             yellow,
    output             green,
    output       [9:0] state
);

    cd4017b u1
    (
        .p1_q5        (state [5]),
        .p2_q1        (state [1]),
        .p3_q0        (state [0]),
        .p4_q2        (state [2]),
        .p5_q6        (state [6]),
        .p6_q7        (state [7]),
        .p7_q3        (state [3]),
        .p9_q8        (state [8]),
        .p10_q4       (state [4]),
        .p11_q9       (state [9]),
        .p12_carry    (),
        .p13_inhibit  (1'b0),
        .p14_clock    (clk),
        .p15_reset    (rst)
    );

    cd4072b u2
    (
        .p1_j         (green),
        .p2_a         (state [0]),
        .p3_b         (state [1]),
        .p4_c         (state [2]),
        .p5_d         (state [3]),
        .p9_e         (state [6]),
        .p10_f        (state [7]),
        .p11_g        (state [8]),
        .p12_h        (state [9]),
        .p13_k        (red)
    );

    cd4071b u3
    (
        .p1_a         (state [4]),
        .p2_b         (state [5]),
        .p3_j         (yellow),
        .p4_k         (),
        .p5_c         (1'b0),
        .p6_d         (1'b0),
        .p8_e         (1'b0),
        .p9_f         (1'b0),
        .p10_l        (),
        .p11_m        (),
        .p12_g        (1'b0),
        .p13_h        (1'b0)
    );

endmodule
```

<a id="s11"></a>

## 11. Тестбенчи и скрипты симуляторов

Запускайте из каталога этого урока. Три самопроверяющихся теста перебирают входы вентилей, проверяют счётчик/COUT, двенадцать полных циклов ламп, сброс из каждого устойчивого состояния при высоком и низком такте, а также оба ядра во всех трёх оболочках. Тестбенчи начинаются с \`timescale 1ns / 1ps; в RTL объявлений времени нет. Сторожевые тайм-ауты считают такты.

```bash
bash scripts/run_icarus.sh
bash scripts/run_verilator.sh
bash scripts/run_questa.sh
python3 scripts/check_synthesis.py
```

Скрипты принимают переменные IVERILOG/VVP, VERILATOR и VLIB/VMAP/VLOG/VSIM. Questa на этом компьютере: /home/verilog/altera\_lite/25.1std/questa\_fse/bin. Лицензия расположена в /home/verilog/flexlm. Результаты и ограничения приведены ниже; успешная компиляция не означает успешную симуляцию.

| Проверка | Результат |
| --- | --- |
| icarus14 | PASS |
| synthesis | PASS |
| verilator | PASS |
| questa\_compile | PASS |
| icarus12 | PASS |
| questa\_runtime | См. лог / ограничение |

[Результаты с датой и хешами исходников](research/tool_validation_20261028.json)

Запуск Questa внутри песочницы агента недоступен: не удаётся определить лицензируемый host ID, хотя установка и лицензия существуют. Это не означает, что Questa не работает из обычного терминала пользователя. Здесь использованы Icarus 12 и 14; версия 13 не установлена.

### tb/tb\_cmos.sv

[Скачать исходник](tb/tb_cmos.sv)

```systemverilog
// Simulation only. Chip pin truth tables and 4017 clock semantics.

`timescale 1ns / 1ps

module tb_cmos;

    localparam period         = 20;
    localparam timeout_cycles = 1000;

    logic clk     = 1'b0;
    logic inhibit = 1'b0;
    logic rst     = 1'b0;
    logic [7:0] a = '0;

    always # (period / 2) clk = ~ clk;

    logic [9:0] q;
    logic carry;

    int expected = 0;

    logic [1:0] y_cd4072b;

    cd4072b gates_cd4072b
    (
        .p2_a         (a [0]),
        .p3_b         (a [1]),
        .p4_c         (a [2]),
        .p5_d         (a [3]),
        .p1_j         (y_cd4072b [0]),
        .p9_e         (a [4]),
        .p10_f        (a [5]),
        .p11_g        (a [6]),
        .p12_h        (a [7]),
        .p13_k        (y_cd4072b [1])
    );

    logic [3:0] y_cd4071b;

    cd4071b gates_cd4071b
    (
        .p1_a         (a [0]),
        .p2_b         (a [1]),
        .p3_j         (y_cd4071b [0]),
        .p5_c         (a [2]),
        .p6_d         (a [3]),
        .p4_k         (y_cd4071b [1]),
        .p8_e         (a [4]),
        .p9_f         (a [5]),
        .p10_l        (y_cd4071b [2]),
        .p12_g        (a [6]),
        .p13_h        (a [7]),
        .p11_m        (y_cd4071b [3])
    );

    cd4017b counter
    (
        .p14_clock    (clk),
        .p13_inhibit  (inhibit),
        .p15_reset    (rst),
        .p3_q0        (q [0]),
        .p2_q1        (q [1]),
        .p4_q2        (q [2]),
        .p7_q3        (q [3]),
        .p10_q4       (q [4]),
        .p1_q5        (q [5]),
        .p5_q6        (q [6]),
        .p6_q7        (q [7]),
        .p9_q8        (q [8]),
        .p11_q9       (q [9]),
        .p12_carry    (carry)
    );

    task check_counter;
        if (q !== (10'b1 << expected) || carry !== (expected < 5))
            $fatal (1, "4017 state/carry mismatch: expected=%0d q=%b carry=%b",
                expected, q, carry);
    endtask

    task tick;
        @ (posedge clk);
        expected = rst ? 0 : inhibit ? expected : (expected + 1) % 10;
        # 1;  // Counter register and decoded output settling.
        check_counter ();
    endtask

    initial
    begin
        @ (posedge clk);
        # 1;  // Assert reset after the clock event, without a stimulus/DUT race.
        rst      = 1'b1;
        expected = 0;
        # 1;  // Check asynchronous reset before the next clock edge.
        check_counter ();

        // Inputs are changed after sampling, safely before the next clock edge.
        for (int i = 0; i < 256; i ++)
        begin
            a = 8' (i);
            tick ();

            if (y_cd4072b !== { (| a [7:4]), (| a [3:0]) }
                || y_cd4071b !== { (| a [7:6]), (| a [5:4]), (| a [3:2]), (| a [1:0]) })
                $fatal (1, "Gate pin truth-table mismatch input=%h", a);
        end

        rst = 1'b0;

        repeat (30)
            tick ();

        inhibit = 1'b1;
        # 1;  // Raising inhibit while CLOCK is high must not count.
        check_counter ();

        repeat (4)
            tick ();

        // Necessary exception: falling INHIBIT with CLOCK low must not count.
        // Posedge-only stimulus cannot test this half of the chip's truth table.
        @ (negedge clk);
        inhibit = 1'b0;
        # 1;  // Settle the effective clock and output decode before checking.
        check_counter ();

        tick ();

        inhibit = 1'b1;
        # 1;  // Raising inhibit with CLOCK high must not count.
        check_counter ();

        inhibit  = 1'b0;
        expected = (expected + 1) % 10;
        # 1;  // Falling inhibit with CLOCK high IS a count event.
        check_counter ();

        rst      = 1'b1;
        expected = 0;
        # 1;  // Reset must act without waiting for the next clock edge.
        check_counter ();

        inhibit = 1'b1;
        tick ();
        inhibit = 1'b0;
        # 1;  // Reset also dominates the falling-INHIBIT count event.
        check_counter ();

        repeat (2)
            tick ();

        $display ("PASS CMOS: 256 gate input combinations; 30 count edges; carry, inhibit and asynchronous reset");
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout after %0d clock cycles", timeout_cycles);
    end

endmodule
```

### tb/tb\_traffic\_light.sv

[Скачать исходник](tb/tb_traffic_light.sv)

```systemverilog
// Simulation only. Portable procedural checks; no classes, DPI or UVM.

`timescale 1ns / 1ps

module tb_traffic_light;

    localparam period         = 20;
    localparam timeout_cycles = 500;

    logic clk = 1'b0;
    logic rst = 1'b0;

    always # (period / 2) clk = ~ clk;

    logic red_generic, yellow_generic, green_generic;
    logic red_chips, yellow_chips, green_chips;
    logic [9:0] state_generic, state_chips;

    int expected     = 0;
    int checks       = 0;
    int red_slots    = 0;
    int yellow_slots = 0;
    int green_slots  = 0;
    int visits [0:9];

    traffic_light generic_dut
    (
        .clk          (clk),
        .rst          (rst),
        .red          (red_generic),
        .yellow       (yellow_generic),
        .green        (green_generic),
        .state        (state_generic)
    );

    traffic_light_chips chip_dut
    (
        .clk          (clk),
        .rst          (rst),
        .red          (red_chips),
        .yellow       (yellow_chips),
        .green        (green_chips),
        .state        (state_chips)
    );

    task check_state;
        logic [9:0] wanted;
        logic [2:0] lamps;

        wanted = 10'b1 << expected;
        lamps  = expected < 4 ? 3'b001 : expected < 6 ? 3'b010 : 3'b100;

        if (   state_generic !== wanted
            || state_chips   !== wanted
            || { red_generic, yellow_generic, green_generic } !== lamps
            || { red_chips,   yellow_chips,   green_chips   } !== lamps)
        begin
            $fatal (1, "state=%0d generic=%b/%b chips=%b/%b",
                expected,
                state_generic, { red_generic, yellow_generic, green_generic },
                state_chips,   { red_chips,   yellow_chips,   green_chips   });
        end

        checks = checks + 1;
    endtask

    task tick;
        @ (posedge clk);
        expected = rst ? 0 : (expected + 1) % 10;
        # 1;  // Let register updates and lamp decoding settle before sampling.
        check_state ();
    endtask

    // Called between rising edges, after tick or the focused low-phase check.
    // Checking before the next clock edge distinguishes asynchronous reset.
    task reset_now;
        rst      = 1'b1;
        expected = 0;
        # 1;  // Asynchronous register update and combinational output settling.
        check_state ();
        rst = 1'b0;
    endtask

    initial
    begin
        $dumpfile ("traffic_light.vcd");
        $dumpvars (0, tb_traffic_light);

        for (int i = 0; i < 10; i ++)
            visits [i] = 0;

        @ (posedge clk);
        # 1;  // Place the initial reset after the clock event, without a race.
        reset_now ();

        for (int round = 0; round < 12; round ++)
            for (int i = 0; i < 10; i ++)
            begin
                visits [expected] = visits [expected] + 1;

                if (red_generic)
                    red_slots = red_slots + 1;

                if (yellow_generic)
                    yellow_slots = yellow_slots + 1;

                if (green_generic)
                    green_slots = green_slots + 1;

                tick ();
            end

        if (red_slots != 48 || yellow_slots != 24 || green_slots != 48)
            $fatal (1, "4/2/4 green/yellow/red duration mismatch");

        for (int i = 0; i < 10; i ++)
            if (visits [i] != 12)
                $fatal (1, "Missing state %0d", i);

        // Reset from every state while CLOCK is high, then while it is low.
        for (int low_phase = 0; low_phase < 2; low_phase ++)
            for (int i = 0; i < 10; i ++)
            begin
                tick ();
                reset_now ();

                repeat (i)
                    tick ();

                if (low_phase != 0)
                begin
                    // Necessary exception: exercise reset with CLOCK low and
                    // verify that a falling clock edge does not advance state.
                    @ (negedge clk);
                    # 1;  // Observe any erroneous falling-edge state update.
                    check_state ();
                end

                reset_now ();
            end

        rst      = 1'b1;
        expected = 0;

        repeat (3)
            tick ();  // Reset dominates the clock.

        rst = 1'b0;
        tick ();

        $display ("PASS traffic_light: %0d checks; 12 full cycles; green/yellow/red=48/24/48; reset and wrap",
            checks);
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout after %0d clock cycles", timeout_cycles);
    end

endmodule
```

### tb/tb\_integrations.sv

[Скачать исходник](tb/tb_integrations.sv)

```systemverilog
// Simulation only. Both core versions in all three integration wrappers.

`timescale 1ns / 1ps

module tb_integrations;

    localparam period         = 20;
    localparam timeout_cycles = 200;

    logic clk = 1'b0;
    logic rst = 1'b0;
    logic ena = 1'b1;

    always # (period / 2) clk = ~ clk;

    logic [7:0] ui  = '0;
    logic [7:0] key = '0;

    logic [7:0] lab_led  [0:1];
    logic [7:0] hack_led [0:1];
    logic [7:0] tt_out   [0:1];
    logic [7:0] tt_io    [0:1];
    logic [7:0] tt_oe    [0:1];

    int n_bgm = 0;
    int n_tt  = 0;
    logic [7:0] seven [0:9];

    generate
        genvar k;

        for (k = 0; k < 2; k ++)
        begin : versions
            lab_top # (.CHIP_MODEL (k)) lab
            (
                .clk          (clk),
                .slow_clk     (clk),
                .rst          (rst),
                .key          (key [3:0]),
                .sw           (8'b0),
                .led          (lab_led [k]),
                .abcdefgh     (),
                .digit        (),
                .x            (10'b0),
                .y            (9'b0),
                .red          (),
                .green        (),
                .blue         (),
                .mic          (24'b0),
                .sound        (),
                .uart_rx      (1'b0),
                .uart_tx      (),
                .gpio         ()
            );

            hackathon_top # (.CHIP_MODEL (k)) hack
            (
                .clock        (clk),
                .slow_clock   (clk),
                .reset        (rst),
                .key          (key),
                .led          (hack_led [k]),
                .abcdefgh     (),
                .digit        (),
                .x            (9'b0),
                .y            (9'b0),
                .red          (),
                .green        (),
                .blue         (),
                .gpio         ()
            );

            tt_um_yuri_traffic_light # (.USE_CHIP_MODEL (k)) tt
            (
                .ui_in        (ui),
                .uo_out       (tt_out [k]),
                .uio_in       (8'b0),
                .uio_out      (tt_io [k]),
                .uio_oe       (tt_oe [k]),
                .ena          (ena),
                .clk          (clk),
                .rst_n        (~ rst)
            );
        end
    endgenerate

    task check_all;
        logic [2:0] bgm_lamps;
        logic [2:0] tt_lamps;
        logic [7:0] segments;

        bgm_lamps = n_bgm < 4 ? 3'b100 : n_bgm < 6 ? 3'b010 : 3'b001;
        tt_lamps  = n_tt  < 4 ? 3'b100 : n_tt  < 6 ? 3'b010 : 3'b001;
        segments  = ui [0] ? seven [n_tt] : n_tt < 4 ? 8'h08 : n_tt < 6 ? 8'h40 : 8'h01;

        for (int j = 0; j < 2; j ++)
        begin
            if (   lab_led  [j] !== { 5'b0, bgm_lamps }
                || hack_led [j] !== { 5'b0, bgm_lamps })
                $fatal (1, "BGM output mismatch state=%0d model=%0d", n_bgm, j);

            if (   tt_out [j] !== (ena ? segments : 8'b0)
                || tt_io  [j] !== (ena ? { 5'b0, tt_lamps } : 8'b0)
                || tt_oe  [j] !== (ena ? 8'h07 : 8'b0))
                $fatal (1, "Tiny Tapeout output mismatch state=%0d model=%0d", n_tt, j);
        end
    endtask

    task tick;
        @ (posedge clk);
        n_bgm = rst || key [0] ? 0 : (n_bgm + 1) % 10;
        n_tt  = rst           ? 0 : (n_tt  + 1) % 10;
        # 1;  // Register updates and wrapper output decoding must settle.
        check_all ();
    endtask

    initial
    begin
        seven [0] = 8'h3f;
        seven [1] = 8'h06;
        seven [2] = 8'h5b;
        seven [3] = 8'h4f;
        seven [4] = 8'h66;
        seven [5] = 8'h6d;
        seven [6] = 8'h7d;
        seven [7] = 8'h07;
        seven [8] = 8'h7f;
        seven [9] = 8'h6f;

        @ (posedge clk);
        # 1;  // Drive reset after the clock event, without a stimulus/DUT race.
        rst   = 1'b1;
        n_bgm = 0;
        n_tt  = 0;
        # 1;  // Asynchronous reset must be observable before the next clock.
        check_all ();
        rst = 1'b0;

        // Each display mode sees all stable states; stimulus changes after sampling.
        for (int i = 0; i < 30; i ++)
        begin
            ui = 8' ((i / 10) % 2);
            tick ();
        end

        // ena blanks TT outputs but must not stop the internal state sequence.
        ena = 1'b0;

        repeat (3)
            tick ();

        ena = 1'b1;
        # 1;  // Combinational output-enable and display settling.
        check_all ();

        // Check the BGM reset button independently of the dedicated TT reset.
        key   = 8'd1;
        n_bgm = 0;
        # 1;  // Asynchronous button reset; TT must retain its own state.
        check_all ();

        repeat (2)
            tick ();

        key = '0;
        tick ();

        rst   = 1'b1;
        n_bgm = 0;
        n_tt  = 0;
        # 1;  // Asynchronous dedicated reset in all wrappers.
        check_all ();

        repeat (2)
            tick ();

        rst = 1'b0;
        tick ();

        $display ("PASS integrations: both implementations in BGM lab/hackathon and Tiny Tapeout; 30 steps, both display modes, 3 disabled cycles, independent button and dedicated resets");
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout after %0d clock cycles", timeout_cycles);
    end

endmodule
```

### scripts/run.sh

[Скачать исходник](scripts/run.sh)

```bash
#!/usr/bin/env bash
set -euo pipefail
exercise_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
simulator=${1:-icarus}
case "$simulator" in icarus|questa|verilator) ;; *) echo "Usage: $0 {icarus|questa|verilator}" >&2; exit 2;; esac
build_dir="$exercise_dir/build/$simulator"
mkdir -p "$build_dir"
cd "$build_dir"
core=("$exercise_dir"/rtl/*.sv "$exercise_dir"/models/*.sv)
wrappers=("$exercise_dir/integration/bgm_lab/lab_top.sv" "$exercise_dir/integration/bgm_hackathon/hackathon_top.sv" "$exercise_dir/integration/tinytapeout/project.v")
for top in ${TEST_TOP:-tb_cmos tb_traffic_light tb_integrations}; do
    case "$top" in tb_cmos|tb_traffic_light|tb_integrations) ;; *) echo "Unknown test: $top" >&2; exit 2;; esac
    sources=("${core[@]}" "$exercise_dir/tb/$top.sv")
    if [[ "$top" == tb_integrations ]]; then sources+=("${wrappers[@]}"); fi
    case "$simulator" in
        icarus)
            "${IVERILOG:-iverilog}" -g2012 -Wall -s "$top" -o "$top.vvp" "${sources[@]}" 2>&1 | tee "$top.compile.log"
            "${VVP:-vvp}" "$top.vvp" 2>&1 | tee "$top.log"
            ;;
        questa)
            [[ -f modelsim.ini ]] || "${VMAP:-vmap}" -c > /dev/null
            [[ -d work ]] || "${VLIB:-vlib}" work
            # The RTL has no time declarations; set a simulation-only default.
            "${VLOG:-vlog}" -sv -timescale 1ns/1ps -work work "${sources[@]}" 2>&1 | tee "$top.compile.log"
            # $fatal/onbreak returns failure; normal $finish exits successfully.
            "${VSIM:-vsim}" "${QUESTA_MODE:--batch}" -onfinish exit "work.$top" -do "onerror {quit -code 1}; onbreak {quit -code 1}; run -all; quit -code 0" 2>&1 | tee "$top.log"
            ;;
        verilator)
            "${VERILATOR:-verilator}" --binary --timing --trace --timescale 1ns/1ps --top-module "$top" --Mdir "obj_$top" \
                -Wno-PINCONNECTEMPTY -Wno-DECLFILENAME -j 2 "${sources[@]}" > "$top.compile.log" 2>&1 || { cat "$top.compile.log"; exit 1; }
            "./obj_$top/V$top" 2>&1 | tee "$top.log"
            ;;
    esac
    grep -q 'PASS ' "$top.log" || { echo "Missing PASS from $top" >&2; exit 1; }
done
```

### scripts/run\_icarus.sh

[Скачать исходник](scripts/run_icarus.sh)

```bash
#!/usr/bin/env bash
set -euo pipefail
exec "$(dirname -- "${BASH_SOURCE[0]}")/run.sh" icarus
```

### scripts/run\_questa.sh

[Скачать исходник](scripts/run_questa.sh)

```bash
#!/usr/bin/env bash
set -euo pipefail

# Preserve explicit tool choices; otherwise find a local Quartus installation.
questa_bin=${QUESTA_BIN:-}
if [[ -z "$questa_bin" ]]; then
    if command -v "${VSIM:-vsim}" > /dev/null 2>&1; then
        questa_bin=$(dirname -- "$(command -v "${VSIM:-vsim}")")
    else
        for candidate in "$HOME"/altera_lite/*/questa_fse/bin \
                         "$HOME"/intelFPGA_lite/*/questa_fse/bin \
                         /opt/altera_lite/*/questa_fse/bin \
                         /opt/intelFPGA_lite/*/questa_fse/bin; do
            if [[ -x "$candidate/vsim" ]]; then
                questa_bin=$candidate
                break
            fi
        done
    fi
fi
if [[ -n "$questa_bin" ]]; then
    export VLIB=${VLIB:-$questa_bin/vlib}
    export VMAP=${VMAP:-$questa_bin/vmap}
    export VLOG=${VLOG:-$questa_bin/vlog}
    export VSIM=${VSIM:-$questa_bin/vsim}
fi

# Read the user's existing license; never copy it into the project or archive.
if [[ -z "${SALT_LICENSE_SERVER:-}" && -f "$HOME/flexlm/license.dat" ]]; then
    export SALT_LICENSE_SERVER="$HOME/flexlm/license.dat"
fi

exec "$(dirname -- "${BASH_SOURCE[0]}")/run.sh" questa
```

### scripts/run\_verilator.sh

[Скачать исходник](scripts/run_verilator.sh)

```bash
#!/usr/bin/env bash
set -euo pipefail
exec "$(dirname -- "${BASH_SOURCE[0]}")/run.sh" verilator
```

### scripts/check\_synthesis.py

[Скачать исходник](scripts/check_synthesis.py)

```python
#!/usr/bin/env python3
"""Check both cores using the built-in Yosys reader, or optionally Slang."""
import argparse
import os
from pathlib import Path
import subprocess


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--frontend', choices=['verilog', 'slang'], default='verilog')
    args = parser.parse_args()
    exercise = Path(__file__).resolve().parents[1]
    build = exercise / 'build/synthesis'
    build.mkdir(parents=True, exist_ok=True)
    sources = sorted((exercise / 'rtl').glob('*.sv'))
    sources += sorted((exercise / 'models').glob('*.sv'))
    # Fixed relative source names also work when the exercise directory has spaces.
    filenames = ' '.join(p.relative_to(exercise).as_posix() for p in sources)
    yosys = os.environ.get('YOSYS', 'yosys')

    for top in ['traffic_light', 'traffic_light_chips']:
        read = (f'read_slang --top {top}' if args.frontend == 'slang'
                else 'read_verilog -sv')
        commands = (f'{read} {filenames}; '
                    f'synth -top {top} -flatten; check -assert; stat')
        log = build / f'{top}.log'
        with log.open('w') as output:
            plugin = ['-m', 'slang'] if args.frontend == 'slang' else []
            result = subprocess.run([yosys, '-Q'] + plugin + ['-p', commands],
                                    cwd=exercise, stdout=output, stderr=subprocess.STDOUT)
        if result.returncode:
            print(log.read_text())
            raise SystemExit(result.returncode)
        print(f'PASS synthesis: {top} (Yosys, {args.frontend} frontend); {log}')


if __name__ == '__main__':
    main()
```

<a id="s12"></a>

## 12. Подключение к BGM lab\_top

CHIP\_MODEL=0 выбирает общий RTL; 1 — модель соединений. Подайте медленный такт 1 Гц. Отдельный reset ИЛИ key\[0\] сбрасывает автомат на зелёный. led\[2:0\] = {green,yellow,red}; остальные биты нулевые. Экран залит цветом текущей лампы; семисегментный выход погашен.

lab\_top использует clk, slow\_clk и rst интерфейса лабораторных BGM. Быстрый такт не является тактом состояний урока.

```bash
python3 scripts/stage_integration.py lab /tmp/traffic_light_lab
```

Выберите новый каталог назначения. Скопируйте набор файлов в новое упражнение BGM, замените top и добавьте файлы sources.f в проект платы. Назначения выводов и полярность конкретной платы задаёт платформа. Компилируйте набор только одного варианта за раз: имена ядер намеренно одинаковы.

### integration/bgm\_lab/lab\_top.sv

[Скачать исходник](integration/bgm_lab/lab_top.sv)

```systemverilog
// Full BGM lab interface. Requires w_key >= 1 and w_led >= 3.

module lab_top
# (
    parameter CHIP_MODEL    = 0,
    parameter clk_mhz       = 50,
    parameter w_key         = 4,
    parameter w_sw          = 8,
    parameter w_led         = 8,
    parameter w_digit       = 8,
    parameter w_gpio        = 100,

    parameter screen_width  = 640,
    parameter screen_height = 480,

    parameter w_red         = 4,
    parameter w_green       = 4,
    parameter w_blue        = 4,

    parameter w_x           = $clog2 (screen_width),
    parameter 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 [w_led   - 1:0] led,

    // A dynamic seven-segment display

    output [          7:0] abcdefgh,
    output [w_digit - 1:0] digit,

    // Graphics

    input  [w_x     - 1:0] x,
    input  [w_y     - 1:0] y,

    output [w_red   - 1:0] red,
    output [w_green - 1:0] green,
    output [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
);

    logic lamp_red, lamp_yellow, lamp_green;
    logic [9:0] state;

    wire exercise_reset = rst | key [0];

    generate
        if (CHIP_MODEL == 0)
        begin : generic_version
            traffic_light dut
            (
                .clk          (slow_clk),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
        else
        begin : chip_version
            traffic_light_chips dut
            (
                .clk          (slow_clk),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
    endgenerate

    // Infrastructure LEDs and graphics use active-high logical signals.

    assign led      = w_led' ({ 5'b0, lamp_green, lamp_yellow, lamp_red });
    assign red      = { w_red   { lamp_red   | lamp_yellow } };
    assign green    = { w_green { lamp_green | lamp_yellow } };
    assign blue     = '0;
    assign abcdefgh = '0;
    assign digit    = '0;
    assign sound    = '0;
    assign uart_tx  = 1'b1;
    assign gpio     = 'z;

    wire unused_inputs = & { 1'b0, clk, sw, key, x, y, mic, uart_rx, state };

endmodule
```

<a id="s13"></a>

## 13. Подключение к BGM hackathon\_top

CHIP\_MODEL=0 выбирает общий RTL; 1 — модель соединений. Подайте медленный такт 1 Гц. Отдельный reset ИЛИ key\[0\] сбрасывает автомат на зелёный. led\[2:0\] = {green,yellow,red}; остальные биты нулевые. Экран залит цветом текущей лампы; семисегментный выход погашен.

Имя модуля — hackathon\_top (с h). Здесь сохранён интерфейс примера 480×272: x\[8:0\], y\[8:0\], clock, slow\_clock, reset. Для конфигурации BGM 800×480 измените x на \[9:0\] в соответствии с ней. gpio находится в высокоимпедансном состоянии.

```bash
python3 scripts/stage_integration.py hackathon /tmp/traffic_light_hackathon
```

Выберите новый каталог назначения. Скопируйте набор файлов в новое упражнение BGM, замените top и добавьте файлы sources.f в проект платы. Назначения выводов и полярность конкретной платы задаёт платформа. Компилируйте набор только одного варианта за раз: имена ядер намеренно одинаковы.

### integration/bgm\_hackathon/hackathon\_top.sv

[Скачать исходник](integration/bgm_hackathon/hackathon_top.sv)

```systemverilog
// The BGM module is spelled hackathon_top, with "h".

module hackathon_top
# (
    parameter CHIP_MODEL = 0
)
(
    input        clock,
    input        slow_clock,
    input        reset,

    input  [7:0] key,
    output [7:0] led,

    // A dynamic seven-segment display

    output [7:0] abcdefgh,
    output [7:0] digit,

    // LCD screen interface

    input  [8:0] x,
    input  [8:0] y,

    output [4:0] red,
    output [5:0] green,
    output [4:0] blue,

    inout  [3:0] gpio
);

    logic lamp_red, lamp_yellow, lamp_green;
    logic [9:0] state;

    wire exercise_reset = reset | key [0];

    generate
        if (CHIP_MODEL == 0)
        begin : generic_version
            traffic_light dut
            (
                .clk          (slow_clock),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
        else
        begin : chip_version
            traffic_light_chips dut
            (
                .clk          (slow_clock),
                .rst          (exercise_reset),
                .red          (lamp_red),
                .yellow       (lamp_yellow),
                .green        (lamp_green),
                .state        (state)
            );
        end
    endgenerate

    assign led      = { 5'b0, lamp_green, lamp_yellow, lamp_red };
    assign red      = { 5 { lamp_red   | lamp_yellow } };
    assign green    = { 6 { lamp_green | lamp_yellow } };
    assign blue     = '0;
    assign abcdefgh = '0;
    assign digit    = '0;
    assign gpio     = 'z;

    wire unused_inputs = & { 1'b0, clock, key, x, y, state };

endmodule
```

<a id="s14"></a>

## 14. Подключение к Tiny Tapeout project.v

Верхний модуль: `tt_um_yuri_traffic_light`. Компилируйте project.v как SystemVerilog со всеми подготовленными зависимостями. Подайте внешний clk 1 Гц. rst\_n активен нулём и инвертируется внутри. USE\_CHIP\_MODEL выбирает реализацию; по умолчанию 0.

| Сигнал | Назначение |
| --- | --- |
| ui\_in\[0\] | 0: красный/жёлтый/зелёный как верхняя/средняя/нижняя полосы; 1: номер устойчивого состояния |
| uo\_out\[7:0\] | {dp,g,f,e,d,c,b,a} · активная единица |
| uio\_out\[2:0\] | {green,yellow,red} |
| uio\_oe | 00000111 при ena=1, иначе 0 |
| ena=0 | Значения выходов и разрешения равны нулю; состояние продолжает меняться |

Номер состояния — не число оставшихся секунд. Оболочка реализует схему внутри FPGA/ASIC; выходы макетки на 5 В не подключаются к выводам этих платформ. Объедините info\_fragment.yaml с метаданными шаблона Tiny Tapeout. Список для src/ использует имена без подкаталогов.

```bash
python3 scripts/stage_integration.py tinytapeout /tmp/traffic_light_tt
```

### integration/tinytapeout/project.v

[Скачать исходник](integration/tinytapeout/project.v)

```systemverilog
// Synthesizable Tiny Tapeout top; compile as SystemVerilog.
// Set the external project clock to 1 Hz.
// Set USE_CHIP_MODEL to 1 to synthesize the pin-connected version.

module tt_um_yuri_traffic_light
# (
    parameter USE_CHIP_MODEL = 0
)
(
    input  [7:0] ui_in,
    output [7:0] uo_out,
    input  [7:0] uio_in,
    output [7:0] uio_out,
    output [7:0] uio_oe,
    input        ena,
    input        clk,
    input        rst_n
);

    logic red, yellow, green;
    logic [9:0] state;

    generate
        if (USE_CHIP_MODEL == 0)
        begin : generic_version
            traffic_light dut
            (
                .clk          (clk),
                .rst          (~ rst_n),
                .red          (red),
                .yellow       (yellow),
                .green        (green),
                .state        (state)
            );
        end
        else
        begin : chip_version
            traffic_light_chips dut
            (
                .clk          (clk),
                .rst          (~ rst_n),
                .red          (red),
                .yellow       (yellow),
                .green        (green),
                .state        (state)
            );
        end
    endgenerate

    // TT output order [7:0] = { dp, g, f, e, d, c, b, a }; active high.
    // DIP 0 = 0: top/middle/bottom bar represents red/yellow/green.
    // DIP 0 = 1: show state number 0..9, not seconds remaining.

    logic [7:0] decimal_segments;

    always_comb
    begin
        decimal_segments = '0;

        case (state)
        10'b00_0000_0001: decimal_segments = 8'h3f;
        10'b00_0000_0010: decimal_segments = 8'h06;
        10'b00_0000_0100: decimal_segments = 8'h5b;
        10'b00_0000_1000: decimal_segments = 8'h4f;
        10'b00_0001_0000: decimal_segments = 8'h66;
        10'b00_0010_0000: decimal_segments = 8'h6d;
        10'b00_0100_0000: decimal_segments = 8'h7d;
        10'b00_1000_0000: decimal_segments = 8'h07;
        10'b01_0000_0000: decimal_segments = 8'h7f;
        10'b10_0000_0000: decimal_segments = 8'h6f;
        default:          decimal_segments = '0;
        endcase
    end

    wire [7:0] bars = { 1'b0, yellow, 2'b00, green, 2'b00, red };

    assign uo_out  = ena ? (ui_in [0] ? decimal_segments : bars) : '0;
    assign uio_out = ena ? { 5'b0, green, yellow, red } : '0;
    assign uio_oe  = ena ? 8'b0000_0111 : '0;

    wire unused_inputs = & { 1'b0, ui_in [7:1], uio_in };

endmodule
```

### integration/tinytapeout/info\_fragment.yaml

[Скачать исходник](integration/tinytapeout/info_fragment.yaml)

```
project:
  top_module: "tt_um_yuri_traffic_light"
  clock_hz: 1
  source_files:
    - "project.v"
    - "traffic_light.sv"
    - "traffic_light_chips.sv"
    - "cd4017b.sv"
    - "cd4072b.sv"
    - "cd4071b.sv"
# Flat names for the staged src/ directory; merge the template metadata.
```

### scripts/stage\_integration.py

[Скачать исходник](scripts/stage_integration.py)

```python
#!/usr/bin/env python3
"""Stage one platform and all local HDL dependencies in a new directory."""
from pathlib import Path
import argparse,shutil
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('target',choices=['lab','hackathon','tinytapeout'])
p.add_argument('destination',type=Path)
a=p.parse_args();root=Path(__file__).resolve().parents[1]
if a.destination.exists():p.error('Destination already exists; choose a new directory.')
folder={'lab':'bgm_lab','hackathon':'bgm_hackathon','tinytapeout':'tinytapeout'}[a.target]
files=list((root/'rtl').glob('*.sv'))+list((root/'models').glob('*.sv'))
files+=list((root/'integration'/folder).glob('*.sv'))+list((root/'integration'/folder).glob('*.v'))
a.destination.mkdir(parents=True)
for f in files:shutil.copy2(f,a.destination/f.name)
(a.destination/'sources.f').write_text(''.join(f.name+'\n' for f in files))
if a.target=='tinytapeout':shutil.copy2(root/'integration/tinytapeout/info_fragment.yaml',a.destination/'info_fragment.yaml')
print('Staged',len(files),'HDL files in',a.destination)
```

<a id="s15"></a>

## 15. Задания, поиск ошибок и источники

Предскажите лампу после каждого фронта до запуска модели. Измерьте полный цикл. Измените частоту и объясните, какие величины изменились. Сравните число микросхем, вентилей и поведение сброса трёх вариантов. Измените дешифрацию выходов при прежнем цикле состояний, затем обновите таблицу ожиданий и тестбенч.

| Признак | Проверьте сначала |
| --- | --- |
| Нет последовательности | Питание, землю, OUT такта, inhibit=0, RESET не удерживается единицей |
| Неверная длительность/цвет | Вариант, нумерацию Q с Q0, полярность LED и таблицу выводов |
| Сброс не включает зелёный | Кнопку с активной единицей, подтяжку к земле, цепь сброса и ориентацию ИС |

Проверены идеальное поведение HDL и статическая связность проводов. Физическая сборка, нагрузка/яркость LED, уровни генератора, полная трассировка FPGA и выпуск ASIC не выполнялись. Проверьте реальные модули и временные требования производителя на оборудовании.

- [Исходный список упражнений](https://verilog-meetup.com/2026/07/31/an-improved-way-of-teaching-school-kids-digital-electronics-using-venerable-small-scale-integration-ics/)
- [Список LSSK](https://docs.google.com/spreadsheets/d/1ULTF4ocT2YyJowGakEOEVTsIUBTxLMkqXyvZM56vlU8/edit)
- [Исходная статья; описание светофора уточнено 27 октября](https://habr.com/en/articles/1071736/)
- [Basics-Graphics-Music](https://github.com/yuri-panchul/basics-graphics-music)
- [SystemVerilog Homework](https://github.com/yuri-panchul/systemverilog-homework)
- [CD4017B · документация производителя](https://www.ti.com/lit/ds/symlink/cd4017b.pdf)
- [CD4071B · документация производителя](https://www.ti.com/lit/ds/symlink/cd4075b.pdf)
- [CD4072B · документация производителя](https://www.ti.com/lit/ds/symlink/cd4075b.pdf)

Пересборка трёх вариантов: `python3 breadboard/tools/build_traffic.py --png`. Есть версия каждой страницы в [Markdown](index_ru.md).

[Скачать все девять уроков и исходники (ZIP)](traffic_light.zip)

LSSK · Yuri Panchul / Verilog Meetup · 2026-10-28 · [English](index.md)
