Embedded HandbookApps
All sections › I. Basics
STM32C5 · level intermediate · 53 min read
Open in the interactive handbook

5д. One project twice on STM32C5: CMSIS and registers only versus HAL2 — the same project on a new series and a comparison

In sections 5в and 5г one and the same project is written twice — on registers and on HAL1 — for F103 and F405. Here the same project moves to STM32C562 (the NUCLEO-C562RE board). The first variant again has not a single line of HAL or LL: only core_cm33.h from CMSIS 6 and the device header stm32c5xx.h from the STM32CubeC5 2.1.0 package (stm32c5xx_dfp 2.1.0). The second uses HAL2 from the same package (stm32c5xx_drivers 2.1.0, BSD-3-Clause license). There is no HAL1 for C5 at all, so the pair here is "registers versus HAL2".

The module plan is the same as in 5г: the clock from a crystal at the maximum frequency, SysTick 1 ms, a button on EXTI with debouncing, UART on interrupts with a ring buffer and line reception, DMA reception until a line pause, TIM2 PWM on the LED, the ADC with the temperature sensor, I2C with bus recovery and a sensor register read. The USART2 output of both projects is the same.

Foundations: building without an IDE — section 4в; HAL2 and how it differs from HAL1 — section 5б; the C5 series — section 2з; clocking — section 6; interrupts — section 7; GPIO — section 8; DMA — section 9; timers — section 13; ADC — section 14; UART — section 16; I2C — section 17. Individual blocks are not explained again here — only what C5 does differently from F1 and F4.

Terms used in the documentation

Term Meaning
PSIREF, PSIFREQ RCC_CR2 fields: the synthesizer reference frequency and its output — both from a fixed list
WRHIGHFREQ flash write signal delay; depends on frequency, like read latency
rs a bit the program can only set; writing zero has no effect
TEACK, REACK USART acknowledgement that the transmitter and receiver are enabled
REQSEL the peripheral request number of an LPDMA channel
BNDT how many bytes of the DMA block are still left to transfer
TIMINGR the new-style I2C register: prescaler and SCL phase lengths in one word
CMSIS_NVIC_VIRTUAL CMSIS switch: NVIC functions come from your own header
direct transfer a DMA transfer as a single block, without a linked list
ADCDACSEL RCC_CCIPR2 field: which clock feeds the ADC and DAC

5д.1 The project, the bench and how C5 differs from F1 and F4 in registers

Clock tree of the project on STM32C562: a 24 MHz HSE crystal, the PSI synthesizer with a 24 MHz reference and a 144 MHz output, the SW switch set to PSIS, HCLK 144 MHz with four flash wait states named FLASH_ACR_LATENCY_3, buses PCLK1, PCLK2 and PCLK3 at 144 MHz without division, TIM2 with PSC 143, USART2 with BRR 0x4E2, I2C1 with TIMINGR 0x80B25455, the ADC from PSIS through a divider of 4 at 36 MHz and the fallback to HSIDIV3 48 MHz if the crystal does not start

Project files:

File Contents
regs/main.c the whole register project: clock, GPIO, EXTI, UART, DMA, TIM2, ADC, I2C, main
regs/regs_time.c, regs_time.h SysTick 1 ms, delay_ms, wait_bits — the only place where the project waits for time
hal/main.c the same project on HAL2
HAL2 configuration the package template stm32c5xx_hal_conf.h unchanged; the crystal — the package stm32_external_env.h
startup file and linking startup_stm32c562xx.c, stm32c562xe_flash.ld and stm32c562xe_flash.sct from stm32c5xx_dfp, unchanged

The C5 startup file is no longer assembly but C: the vector table is the __VECTOR_TABLE array, Reset_Handler sets MSPLIM and calls SystemInit and __PROGRAM_START from CMSIS 6. The same file is built by both GCC and Arm Compiler.

The bench has two parts. Build: arm-none-eabi-gcc 12.2.1 with -Wall -Wextra -Werror and Arm Compiler 6.24, both for Cortex-M33 with an FPU. PC bench: QEMU 7.2 knows no board with a C5, so both main.c files are built by an ordinary gcc for x86, and the peripherals are PC memory at the same addresses as on the chip (mmap with MAP_FIXED: 0x40000000 — the buses, 0xE0000000 — the core). The CMSIS and device headers are real; only cmsis_compiler.h (core instructions) and the NVIC functions are replaced — the latter through the standard CMSIS_NVIC_VIRTUAL switch (see 5д.7). The model host/model.c answers what the project waits for: HSE and PSI ready, the SW switch, ADC steps, an I²C exchange with device 0x68, USART2 transmission and reception, a line pause after three DMA bytes. If interrupts are enabled, the model calls the handlers itself at every step. Both firmwares run main to the end in four scenarios: all good, the crystal did not start, no sensor, SDA held low.

There is no C5 reference manual on disk. The numbers below come from the headers, the HAL2/LL sources and the package descriptions; doc5e.py collects and prints them.

How C5 differs from F103 and F405 at the register level (from stm32c562xx.h):

What F103 / F405 C562
frequency multiplication PLL: RCC_CFGR_PLLMULL9 / RCC_PLLCFGR no PLL (not a single PLL in the header); the PSI synthesizer: reference and output in RCC_CR2
clock registers RCC->CR, RCC->CFGR RCC->CR1, CR2, CFGR1 (switch), CFGR2 (dividers)
after reset HSI 8 / 16 MHz HSIDIV3 48 MHz; RCC_CR1_Rst = 0x22
flash latency FLASH_ACR_LATENCY_2 = 2 / FLASH_ACR_LATENCY_5WS = 5 FLASH_ACR_LATENCY_3 = 4 wait states; plus WRHIGHFREQ
GPIO clock APB2 / AHB1 RCC->AHB2ENR; ports on AHB2 from 0x42020000
port selection for EXTI AFIO->EXTICR / SYSCFG->EXTICR EXTI->EXTICR, 8-bit field
EXTI flags PR separate RPR1 (rising) and FPR1 (falling)
EXTI interrupts EXTI15_10_IRQn one line per input: 16 of them, EXTI13_IRQn
USART SR, DR ISR, ICR, TDR, RDR, PRESC; kernel clock — RCC->CCIPR1
DMA channels / streams with CHSEL LPDMA: a channel with CTR1, CTR2.REQSEL, CBR1; a ring only through a linked list
ADC ADON / ADC->CCR sleep DEEPPWD, regulator ADVREGEN, calibration ADCAL, ADEN and ADRDY
I2C CCR, TRISE, SR1/SR2 TIMINGR, CR2 with address and byte count, ISR/ICR
FPU — / SCB->CPACR by hand SCB_EnableFPU() right in stm32c5xx.h

5д.2 Startup and clock: PSI instead of PLL, latency named "_3"

SystemInit of the register project enables the FPU with a function from the device header — ST put SCB_EnableFPU, SCB_SetVTOR and macros like STM32_ATOMIC_SET_BIT_32 into stm32c5xx.h. There is no magic (3UL << 20) in our own code any more:

void SystemInit(void)                   /* зовёт стартовый файл пакета до main */
{
    SCB_EnableFPU();                    /* из stm32c5xx.h: CP10, CP11 в SCB->CPACR */
    __DSB();
    __ISB();
}

The clock — a pair of listings. Registers:

    RCC->CR1 |= RCC_CR1_HSEON;
    if (wait_bits(&RCC->CR1, RCC_CR1_HSERDY, RCC_CR1_HSERDY, HSE_TIMEOUT_MS) != 0) {
        RCC->CR1 &= ~RCC_CR1_HSEON;     /* кварц не завёлся — остаёмся на HSIDIV3 */
        return -1;
    }
    RCC->CR2 = (RCC->CR2 & ~(RCC_CR2_PSIREFSRC | RCC_CR2_PSIREF | RCC_CR2_PSIFREQ))
             | RCC_CR2_PSIREF_1 | RCC_CR2_PSIREF_0      /* опора 24 МГц; PSIREFSRC = 0 — от HSE */
             | RCC_CR2_PSIFREQ_0;                       /* выход 144 МГц */
    RCC->CR1 |= RCC_CR1_PSISON;
    if (wait_bits(&RCC->CR1, RCC_CR1_PSISRDY, RCC_CR1_PSISRDY, PSI_TIMEOUT_MS) != 0)
        return -2;
    RCC->CFGR2 &= ~(RCC_CFGR2_HPRE | RCC_CFGR2_PPRE1 | RCC_CFGR2_PPRE2 | RCC_CFGR2_PPRE3);   /* шины без деления */
    FLASH->ACR = (FLASH->ACR & ~FLASH_ACR_LATENCY) | FLASH_ACR_LATENCY_3 | FLASH_ACR_PRFTEN; /* _3 = 4 такта! */
    if ((FLASH->ACR & FLASH_ACR_LATENCY) != FLASH_ACR_LATENCY_3)
        return -3;                      /* задержка принята — только теперь повышать частоту */
    RCC->CFGR1 = (RCC->CFGR1 & ~RCC_CFGR1_SW) | RCC_CFGR1_SW;          /* SW = 11: PSIS */
    if (wait_bits(&RCC->CFGR1, RCC_CFGR1_SWS, RCC_CFGR1_SWS, SW_TIMEOUT_MS) != 0)
        return -4;
    FLASH->ACR = (FLASH->ACR & ~FLASH_ACR_WRHIGHFREQ) | FLASH_ACR_WRHIGHFREQ_1;   /* запись флеша: 136–170 МГц */

HAL2 — each step as a separate call:

    if (HAL_RCC_HSE_Enable(HAL_RCC_HSE_ON) != HAL_OK)
        return -1;                      /* кварц не завёлся — остаёмся на HSIDIV3 */
    hal_rcc_psi_config_t psi;
    psi.psi_source = HAL_RCC_PSI_SRC_HSE;
    psi.psi_ref = HAL_RCC_PSI_REF_24MHZ;
    psi.psi_out = HAL_RCC_PSI_OUT_144MHZ;
    if (HAL_RCC_PSI_SetConfig(&psi) != HAL_OK || HAL_RCC_PSIS_Enable() != HAL_OK)
        return -2;
    hal_rcc_bus_clk_config_t bus;
    bus.hclk_prescaler = HAL_RCC_HCLK_PRESCALER1;
    bus.pclk1_prescaler = HAL_RCC_PCLK_PRESCALER1;
    bus.pclk2_prescaler = HAL_RCC_PCLK_PRESCALER1;
    bus.pclk3_prescaler = HAL_RCC_PCLK_PRESCALER1;
    if (HAL_RCC_SetBusClockConfig(&bus) != HAL_OK)
        return -3;
    HAL_FLASH_ITF_SetLatency(HAL_FLASH, HAL_FLASH_ITF_LATENCY_4);   /* до повышения частоты */
    if (HAL_RCC_SetSYSCLKSource(HAL_RCC_SYSCLK_SRC_PSIS) != HAL_OK)
        return -4;
    HAL_FLASH_ITF_SetProgrammingDelay(HAL_FLASH, HAL_FLASH_ITF_PROGRAM_DELAY_2);
    if (HAL_UpdateCoreClock() != HAL_OK)   /* SystemCoreClock и SysTick заново */
        return -5;

The numbers. The C562 core limit is 144 MHz (Dclock of the package). The board crystal is 24 MHz (the package stm32_external_env.h), its start timeout is 100 ms. PSI has three outputs — 100, 144 and 160 MHz; a 24 MHz reference is code 011 in PSIREF, a 144 MHz output is 01 in PSIFREQ (stm32c5xx_ll_rcc.h). SW = 11 is PSIS. Latency is 4 wait states, as in the NUCLEO-C562RE template, and the write delay WRHIGHFREQ = 10 is for a flash frequency from 136 to 170 MHz (stm32c5xx_ll_flash.h).

The main trap is the latency name. In stm32c562xx.h FLASH_ACR_LATENCY_3 equals 0x4, and FLASH_ACR_LATENCY_4 is 0x5: the name is one less than the number of wait states. LL hides this: LL_FLASH_LATENCY_4WS is defined as FLASH_ACR_LATENCY_3. On F4 it was conveniently the other way — FLASH_ACR_LATENCY_5WS.

On the PC bench both projects reached 144 MHz and wrote the same into RCC and FLASH: RCC_CR1 = 0x00031122, RCC_CR2 = 0x10300000, RCC_CFGR1 = 0x1b, FLASH_ACR = 0x124 (4 wait states, WRHIGHFREQ, prefetch — HAL2 enables it in HAL_Init). Both left the HSIDIV3ON bit on. Without the crystal both stayed on HSIDIV3: the line clock: error -1, HSIDIV3 48000000 Hz, and the whole run became longer by 110 and 111 model milliseconds — that is the 100 ms HSE timeout.


5д.3 SysTick, GPIO, the button on EXTI13 and priorities

regs_time.c is the same as in 5г: SysTick_Config(core_hz / 1000u). On the bench both have SysTick_LOAD = 0x2327f = 143999 — 1 ms at 144 MHz.

Pins. Registers — the same MODER/AFR as on F4, but the bit names differ (GPIO_MODER_MODE5, not GPIO_MODER_MODER5), and the port clock is on AHB2:

    RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN | RCC_AHB2ENR_GPIOCEN;
    (void)RCC->AHB2ENR;                 /* пауза после включения такта */
    /* PA5 — TIM2_CH1 (AF1): светодиод; PA2/PA3 — USART2 TX/RX (AF7), на RX подтяжка вверх */
    GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODE2 | GPIO_MODER_MODE3 | GPIO_MODER_MODE5))
                 | GPIO_MODER_MODE2_1 | GPIO_MODER_MODE3_1 | GPIO_MODER_MODE5_1;
    GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(GPIO_AFRL_AFSEL2 | GPIO_AFRL_AFSEL3 | GPIO_AFRL_AFSEL5))
                  | (AF7_USART2 << GPIO_AFRL_AFSEL2_Pos) | (AF7_USART2 << GPIO_AFRL_AFSEL3_Pos)
                  | (AF1_TIM2 << GPIO_AFRL_AFSEL5_Pos);
    GPIOA->PUPDR = (GPIOA->PUPDR & ~GPIO_PUPDR_PUPD3) | GPIO_PUPDR_PUPD3_0;
    GPIOC->MODER &= ~GPIO_MODER_MODE13; /* PC13 — вход (кнопка на землю, резистор на плате) */
    /* выбор порта — в самом EXTI, отдельного SYSCFG для этого нет; поле 8 бит, порт C = 2 */
    EXTI->EXTICR[3] = (EXTI->EXTICR[3] & ~EXTI_EXTICR4_EXTI13) | EXTI_EXTICR4_EXTI13_1;
    EXTI->FTSR1 |= EXTI_FTSR1_FT13;     /* нажатие — спад */
    EXTI->IMR1 |= EXTI_IMR1_IM13;
    NVIC_SetPriority(EXTI13_IRQn, 6u);  /* у C5 своя линия прерывания на каждый EXTI0…15 */
    NVIC_EnableIRQ(EXTI13_IRQn);

HAL2 — a structure per pin and a separate EXTI line handle:

    hal_exti_config_t e;
    (void)HAL_EXTI_Init(&hexti13, HAL_EXTI_LINE_13);
    e.trigger = HAL_EXTI_TRIGGER_FALLING;
    e.gpio_port = HAL_EXTI_GPIOC;
    (void)HAL_EXTI_SetConfig(&hexti13, &e);
    (void)HAL_EXTI_Enable(&hexti13, HAL_EXTI_MODE_INTERRUPT);
    HAL_CORTEX_NVIC_SetPriority(EXTI13_IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_6, HAL_CORTEX_NVIC_SUB_PRIORITY_0);
    HAL_CORTEX_NVIC_EnableIRQ(EXTI13_IRQn);

The function numbers come from the package pin description (STM32C5(5-6)2R(C-E)Tx(J-_)_pinout.json): PA5 — TIM2_CH1 AF1, PA2/PA3 — USART2 AF7, PB6/PB7 — I2C1 AF4. Both have GPIOA_MODER = 0x8a0, AFRL = 0x00107700, EXTI_EXTICR4 = 0x200 (port C = 2 in an eight-bit field). The C5 GPIO reset values are not in the header, the model starts from zeros.

The register handler checks both flags — rising and falling: a software trigger through SWIER1, according to the LL description, "sets the pending bit", and the documents on disk do not say which of the two:

void EXTI13_IRQHandler(void)
{
    uint32_t pend = (EXTI->RPR1 | EXTI->FPR1) & EXTI_FPR1_FPIF13;
    if (pend != 0u) {
        EXTI->FPR1 = EXTI_FPR1_FPIF13;  /* rc_w1: сброс записью единицы, без |= */
        EXTI->RPR1 = EXTI_RPR1_RPIF13;  /* программный запуск (SWIER) может поднять и этот флаг */
        edges++;
        uint32_t now = millis();
        if ((now - last_press_ms) >= DEBOUNCE_MS) {
            last_press_ms = now;
            presses++;
            TIM2->CCR1 = (TIM2->CCR1 == PWM_DUTY_LOW) ? PWM_DUTY_HIGH : PWM_DUTY_LOW;
        }
    }
}

In HAL2 the same is done by HAL_EXTI_IRQHandler and the weak HAL_EXTI_TriggerCallback. In the model SWIER1 sets RPR1. Three edges at 0, 10 and 110 ms: both print button: 2 presses of 3 edges, ccr1 250.

IRQ priorities are the same in both: USART2 0x50, EXTI13 0x60, TIM2 0x70, SysTick 0xf0. HAL_Init also sets priority group 4 (SCB_AIRCR = 0x05fa0300, 0 for registers) — C5, like F4, has 4 priority bits, and the behaviour does not change.


5д.4 UART on interrupts and reception by LPDMA

USART2 is the board's virtual COM port. Its kernel clock is selected by USART2SEL in RCC->CCIPR1; after reset it is 0 — PCLK1. BRR = 144000000 / 115200 = 1250 = 0x4E2, at 48 MHz — 416.7 → 0x1A1. The same for both in both scenarios.

Transmission on registers — the same ring as in 5г, only the flags are in ISR, and clearing is done by a separate ICR:

    if ((isr & USART_ISR_IDLE) != 0u && (USART2->CR1 & USART_CR1_IDLEIE) != 0u) {
        USART2->ICR = USART_ICR_IDLECF; /* у USART нового образца флаги сбрасывает отдельный ICR */
        rx_dma_len = RX_DMA_SIZE - (LPDMA1_CH1->CBR1 & DMA_CBR1_BNDT);
        rx_dma_events++;
    }
    if ((isr & USART_ISR_TXE_TXFNF) != 0u && (USART2->CR1 & USART_CR1_TXEIE_TXFNFIE) != 0u) {
        if (tx_tail != tx_head) {
            USART2->TDR = tx_buf[tx_tail];
            tx_tail = (uint16_t)((tx_tail + 1u) % TX_SIZE);
        } else {
            USART2->CR1 &= ~USART_CR1_TXEIE_TXFNFIE;   /* нечего передавать — молчать */
        }
    }

HAL2, like HAL1, does not know rings — the chunk up to the end of the ring is given to HAL_UART_Transmit_IT, and the callback starts the next one:

static void tx_start(void)
{
    if (tx_len != 0u || tx_tail == tx_head)
        return;
    uint16_t end = (tx_head > tx_tail) ? tx_head : TX_SIZE;
    tx_len = (uint16_t)(end - tx_tail);
    (void)HAL_UART_Transmit_IT(&huart2, (const uint8_t *)&tx_buf[tx_tail], tx_len);
}

void HAL_UART_TxCpltCallback(hal_uart_handle_t *huart)
{
    (void)huart;
    tx_tail = (uint16_t)((tx_tail + tx_len) % TX_SIZE);
    tx_len = 0u;
    tx_start();
}

Callbacks in HAL2 are weak functions with different parameters: HAL_UART_RxCpltCallback(huart, size_byte, rx_event) receives the byte count and the reason (block end, pause, timeout, character match).

A HAL2 surprise: HAL_UART_SetConfig leaves UE = 0. The block is enabled on the first transmission or reception, and HAL2 waits for TEACK in a counting loop without a clock. On the bench this first looked like a hang: the model did not set TEACK, and HAL_UART_Receive_IT returned HAL_ERROR. Now TEACK and REACK are always 1 in the model.

DMA reception. C562 has two LPDMA blocks (8 and 4 channels); USART2_RX is request 14 (stm32c5xx_ll_dma.h; the device header has no name for the number). LPDMA has no ring without a linked list, so both projects receive one 64-byte block until a line pause. Registers:

    RCC->AHB1ENR |= RCC_AHB1ENR_LPDMA1EN;
    (void)RCC->AHB1ENR;
    LPDMA1_CH1->CCR &= ~DMA_CCR_EN;
    LPDMA1_CH1->CFCR = DMA_CFCR_TCF | DMA_CFCR_HTF | DMA_CFCR_DTEF | DMA_CFCR_ULEF | DMA_CFCR_USEF
                     | DMA_CFCR_SUSPF | DMA_CFCR_TOF;
    LPDMA1_CH1->CTR1 = DMA_CTR1_DINC;   /* байт в байт; источник — неподвижный RDR, приёмник растёт */
    LPDMA1_CH1->CTR2 = LPDMA_REQ_USART2_RX << DMA_CTR2_REQSEL_Pos;
    LPDMA1_CH1->CBR1 = RX_DMA_SIZE;     /* блок 64 байта; кольца без связного списка у LPDMA нет */
    LPDMA1_CH1->CSAR = (uint32_t)&USART2->RDR;
    LPDMA1_CH1->CDAR = (uint32_t)rx_dma_buf;
    LPDMA1_CH1->CLLR = 0u;              /* один блок, без связного списка */
    LPDMA1_CH1->CCR = DMA_CCR_PRIO_1 | DMA_CCR_EN;
    USART2->CR1 &= ~USART_CR1_RXNEIE_RXFNEIE;   /* байты теперь забирает DMA */
    USART2->CR3 |= USART_CR3_DMAR;
    USART2->ICR = USART_ICR_IDLECF;
    USART2->CR1 |= USART_CR1_IDLEIE;    /* пауза в линии — конец посылки */

HAL2 — a channel handle, a "direct transfer" setup, binding to the UART and one call:

    (void)HAL_DMA_Init(&hdma_rx, HAL_LPDMA1_CH1);
    HAL_RCC_LPDMA1_EnableClock();
    x.request = HAL_LPDMA1_REQUEST_USART2_RX;
    x.direction = HAL_DMA_DIRECTION_PERIPH_TO_MEMORY;
    x.src_inc = HAL_DMA_SRC_ADDR_FIXED;
    x.dest_inc = HAL_DMA_DEST_ADDR_INCREMENTED;
    x.src_data_width = HAL_DMA_SRC_DATA_WIDTH_BYTE;
    x.dest_data_width = HAL_DMA_DEST_DATA_WIDTH_BYTE;
    x.priority = HAL_DMA_PRIORITY_HIGH;
    (void)HAL_DMA_SetConfigPeriphDirectXfer(&hdma_rx, &x);
    HAL_CORTEX_NVIC_SetPriority(LPDMA1_CH1_IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_5, HAL_CORTEX_NVIC_SUB_PRIORITY_0);
    HAL_CORTEX_NVIC_EnableIRQ(LPDMA1_CH1_IRQn);
    (void)HAL_UART_SetRxDMA(&huart2, &hdma_rx);
    (void)HAL_UART_AbortReceive(&huart2);   /* снять побайтовый приём по прерыванию */
    rx_dma_mode = 1u;
    (void)HAL_UART_ReceiveToIdle_DMA(&huart2, rx_dma_buf, RX_DMA_SIZE);

On the bench, after the line dma: rx armed, the model puts three bytes straight into the destination memory, decreases BNDT and raises IDLE. Both print dma: 3 bytes 'abc'. The paths differ. The register handler reads 64 − BNDT and that is all. HAL2 stops the channel on the pause: it clears DMAR and IDLEIE, asks LPDMA for a suspend (SUSP) and reports the reception from the channel interrupt handler. Without an enabled LPDMA1_CH1_IRQn and a LPDMA1_CH1_IRQHandler the callback never comes — that is what happened on the bench until the model learned to call this handler. LPDMA1_CH1_CTR2 = 0xe, CBR1 = 0x3d (64 − 3), CSAR = 0x40004424 (USART2->RDR) matched in both.


5д.5 Timer, ADC and I2C

1 kHz PWM on PA5. The bus dividers are 1, so the timer is clocked directly by PCLK1 — 144 MHz, without doubling. PSC = 143, ARR = 999, CCR1 = 250; without the crystal PSC = 47. The timer code is the same as on F4:

    uint32_t tim_hz = ((RCC->CFGR2 & RCC_CFGR2_PPRE1) == 0u) ? pclk1_hz : 2u * pclk1_hz;   /* делитель APB1 > 1 → ×2 */
    TIM2->PSC = tim_hz / 1000000u - 1u;                       /* счёт 1 МГц */
    TIM2->ARR = PWM_PERIOD - 1u;
    TIM2->CCR1 = PWM_DUTY_LOW;                                /* 25 % */
    TIM2->CCMR1 = (TIM2->CCMR1 & ~(TIM_CCMR1_OC1M | TIM_CCMR1_CC1S))
                | TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1PE;   /* ШИМ, режим 1 */
    TIM2->CCER |= TIM_CCER_CC1E;
    TIM2->EGR = TIM_EGR_UG;             /* загрузить PSC сейчас; заодно поднимает UIF */
    TIM2->SR = ~TIM_SR_UIF;             /* rc_w0: сброс записью нуля, остальные биты — единицы */
    TIM2->DIER |= TIM_DIER_UIE;
    NVIC_SetPriority(TIM2_IRQn, 7u);
    NVIC_EnableIRQ(TIM2_IRQn);
    TIM2->CR1 |= TIM_CR1_ARPE | TIM_CR1_CEN;

HAL2 computes the timer frequency itself (HAL_TIM_GetClockFreq), and the channel takes three calls: the output (HAL_TIM_OC_SetConfigChannel), the compare unit (HAL_TIM_OC_SetConfigCompareUnit) and preload. Both have TIM2_CCMR1 = 0x68 and 100 updates in 100 ms; the only difference is that HAL2 does not set ARPE (TIM2_CR1 0x01 versus 0x81).

The C5 ADC is of the new type. Registers:

    RCC->AHB2ENR |= RCC_AHB2ENR_ADC12EN;
    (void)RCC->AHB2ENR;
    RCC->CCIPR2 = (RCC->CCIPR2 & ~(RCC_CCIPR2_ADCDACSEL | RCC_CCIPR2_ADCDACPRE))
                | RCC_CCIPR2_ADCDACSEL_0 | RCC_CCIPR2_ADCDACPRE_1;   /* PSIS / 4 = 36 МГц */
    ADC1->CR = (ADC1->CR & ~(ADC_CR_RS | ADC_CR_DEEPPWD)) | ADC_CR_ADVREGEN;   /* выйти из сна, стабилизатор */
    delay_ms(1u);                                             /* нужно 10 мкс */
    ADC1->CR = (ADC1->CR & ~ADC_CR_RS) | ADC_CR_ADCAL;        /* калибровка при ADEN = 0 */
    if (wait_bits(&ADC1->CR, ADC_CR_ADCAL, 0u, 2u) != 0)
        return -1;
    ADC12_COMMON->CCR |= ADCC_CCR_TSEN;                       /* датчик температуры к каналу 12 */
    ADC1->SMPR2 |= ADC_SMPR2_SMP12;                           /* 289 тактов выборки */
    ADC1->SQR1 = ADC_CH_TEMP << ADC_SQR1_SQ1_Pos;             /* L = 0: одно измерение */
    ADC1->ISR = ADC_ISR_ADRDY;                                /* rc_w1 */
    ADC1->CR = (ADC1->CR & ~ADC_CR_RS) | ADC_CR_ADEN;
    if (wait_bits(&ADC1->ISR, ADC_ISR_ADRDY, ADC_ISR_ADRDY, 2u) != 0)
        return -2;
    delay_ms(1u);                                             /* датчику — 25 мкс */
    return 0;

The order: leave sleep (DEEPPWD), enable the regulator (ADVREGEN, 10 µs per LL), calibrate with ADEN = 0, enable and wait for ADRDY, give the sensor 25 µs. The sensor is internal channel 12, the TSEN bit in the common register, 289 sampling cycles, ADC clock PSIS / 4 = 36 MHz, as in the package example. The ADCAL, ADEN, ADSTART bits are rs: |= would repeat the ones already set, so every write first clears the whole group — LL_ADC_Enable does the same. The sensor calibration addresses (0x08FFF814 and the next) are not in the device header, only in LL, — so both projects print raw counts. HAL2 — HAL_ADC_Start (regulator, enable, sensor wait), HAL_ADC_Calibrate (disable — calibrate — enable) and HAL_ADC_REG_StartConv. The ADC registers after the run matched completely: ADC12_CCR = 0x800000, SMPR2 = 0x1c0, SQR1 = 0x300, CFGR1 = 0x3000. The count 1000 is a model number, not a measurement.

I2C1 on PB6/PB7. HAL2 does not compute the TIMINGR value itself — the package has the STM32_UTILS_I2C_ComputeTimingBasic utility for that. The register project writes the same fields it produces, with position names: at 144 MHz 0x80B25455 (PRESC 8, SCLDEL 11, SDADEL 2, SCLH 84, SCLL 85), at 48 MHz 0x20B14B4C. Reading a register — the address, the register number without AUTOEND, a repeated start for reading with AUTOEND:

    I2C1->CR2 = ((uint32_t)dev << 1 << I2C_CR2_SADD_Pos) | (1u << I2C_CR2_NBYTES_Pos) | I2C_CR2_START;
    int r = i2c_wait(I2C_ISR_TXIS);
    if (r != 0)
        return i2c_fail(r);
    I2C1->TXDR = reg;
    r = i2c_wait(I2C_ISR_TC);
    if (r != 0)
        return i2c_fail(r);
    /* повторный старт, адрес + чтение, n байт, стоп и NACK на последнем — аппаратно (AUTOEND) */
    I2C1->CR2 = ((uint32_t)dev << 1 << I2C_CR2_SADD_Pos) | I2C_CR2_RD_WRN | (n << I2C_CR2_NBYTES_Pos)
              | I2C_CR2_AUTOEND | I2C_CR2_START;
    for (uint32_t i = 0; i < n; i++) {
        r = i2c_wait(I2C_ISR_RXNE);
        if (r != 0)
            return i2c_fail(r);
        buf[i] = (uint8_t)I2C1->RXDR;
    }
    r = i2c_wait(I2C_ISR_STOPF);
    I2C1->ICR = I2C_ICR_STOPCF;

In HAL2 this is one HAL_I2C_MASTER_MemRead. On the bench the model of device 0x68 answered register 0x75 with byte 0x68 to both; without the device both printed i2c: error nack, and HAL2 told a NACK from a timeout by the return code: on a NACK it is not HAL_TIMEOUT. Bus recovery: with SDA released — 0 pulses, with SDA held — 9 and i2c: recovery -1. HAL_I2C_SetConfig with own_address1 = 0 enables the own address (I2C1_OAR1 = 0x8000, OA1EN) — a slave address 0 alongside the master.


5д.6 Comparison

The output of both firmwares on the PC bench; HAL2 has the first line project: hal2, the other 14 matched in all four scenarios:

project: regs
clock: PSI 144000000 Hz
uart: BRR 0x4e2
fpu: 1.5 * 1.5 * 1000 = 2250
tim2: psc 143 arr 999 ccr1 250
tim2: 100 updates in 100 ms
button: 2 presses of 3 edges, ccr1 250
adc: raw 1000 then 1000
adc: continuous, DR 1000
i2c: recovery 0
i2c: id 0x68
rx: type a line
rx: 'hello'
dma: rx armed
dma: 3 bytes 'abc'
done
What registers HAL2
GCC 12.2.1 -Os: text / data / bss 4944 / 112 / 2104 24016 / 112 / 5000
of which .bss without heap and stack 568 3464
Arm Compiler 6.24 -Os: Code / RO / RW / ZI 3586 / 722 / 8 / 1932 22446 / 1162 / 12 / 4840
HAL_ functions in the firmware 0 91
instructions in the USART2 handler (disassembly) 87 4 + HAL_UART_IRQHandler 290 + UART_TxISR_8BIT 33
USART2 handler calls per bench run 655 982
of 60 registers after the run matched 54 54
largest functions, bytes main 640, clock_init 216, USART2_IRQHandler 200 HAL_UART_IRQHandler 792, __udivmoddi4 746, main 728
warnings 0 0 (HAL2 — with -Wall)

Flash (text + data) — 5056 versus 24128 bytes, 4.8 times. Own code is almost equal: 455 non-empty lines in regs/main.c versus 490 in hal/main.c. __udivmoddi4 is the 64-bit division from the compiler library, pulled in by HAL2; the register project does not have it.

Register differences — 6 of 60: SCB_AIRCR (priority group), USART2_CR1 and USART2_CR3 (after the pause HAL2 clears IDLEIE and DMAR), LPDMA1_CH1_CCR (HAL2 resets the channel, the register project leaves it enabled), TIM2_CR1 (ARPE), I2C1_OAR1 (OA1EN).

registers HAL2
what is written to a register visible in the line you have to read HAL2 and LL
name traps FLASH_ACR_LATENCY_3 = 4 wait states HAL_FLASH_ITF_LATENCY_4 = 4 wait states
configuration own arithmetic and fields one step — one call, check the return code
I2C you must know the TIMINGR fields TIMINGR from the package utility
hidden work none UE is enabled on the first transfer; on a DMA pause — channel stop through an interrupt
porting from F4 rewrite almost everything also almost everything: HAL2 is a different API (section 5б)

5д.7 Pitfalls

Flash "is too slow" with the right number. FLASH_ACR_LATENCY_4 in stm32c562xx.h is 5 wait states; 4 wait states is FLASH_ACR_LATENCY_3. Set it before switching SW and read it back.

The PLL cannot be found. C5 has none: the PSI synthesizer takes the reference and the output only from lists. Foreign code with RCC_PLLCFGR does not build at all — better than building and silently running at 48 MHz.

A block register reads zero. The clock is not enabled. On C5 the GPIO ports are on AHB2 (RCC->AHB2ENR), USART2, TIM2 and I2C1 — in RCC->APB1LENR, LPDMA — in RCC->AHB1ENR. After writing to ENR the project reads the register back.

The wrong EXTI flag got cleared. RPR1 and FPR1 are rc_w1; |= clears all set flags. Write one mask.

The ADC "does not turn on". The ADCAL, ADEN, ADSTART bits in ADC_CR are rs: clear the group before writing, like LL_ADC_Enable.

The UART is silent after SetConfig. HAL2 does not set UE in HAL_UART_SetConfig — the block is enabled on the first Transmit/Receive. Whoever writes to TDR bypassing HAL2 gets silence.

DMA reception until a pause never arrives. In HAL2 single-block mode the pause is reported through the LPDMA channel interrupt — it must be enabled in the NVIC and LPDMA1_CH1_IRQHandler must exist.

The model lies differently from the board. In PC memory, writing zero to NVIC->ISER erases neighbouring lines, while on the chip it does not: the first run "lost" the USART2 interrupt when TIM2 enabled its own. The standard CMSIS_NVIC_VIRTUAL switch helped — NVIC functions from our own header. In the same way the model keeps the ADC rs bits and the TEACK/REACK flags. Matching output of the two projects on a model is not proof that they work on a board.


5д.8 Summary

Full sources

regs/main.c — the whole register project.

/* Раздел 5д: проект на STM32C562 без HAL2 и LL — только CMSIS (core_cm33.h) и заголовок устройства stm32c5xx.h.
 * Такт 144 МГц от кварца 24 МГц через синтезатор PSI, SysTick 1 мс, кнопка на EXTI13, USART2 по прерываниям
 * с кольцевым буфером, приём по LPDMA1 до паузы, ШИМ TIM2 на светодиод, АЦП с датчиком температуры,
 * I2C1 с восстановлением шины. Тот же проект на HAL2 — hal/main.c; вывод в USART2 у обоих одинаковый. */
#include <stdarg.h>
#include <stdint.h>
#include "stm32c5xx.h"
#include "regs_time.h"

/* ── константы платы и проекта ── */
#define HSE_HZ          24000000u    /* кварц NUCLEO-C562RE */
#define PSI_HZ          144000000u   /* выход PSI: 100, 144 или 160 МГц; ядру — не выше 144 */
#define HSIDIV3_HZ      48000000u    /* такт после сброса: HSI 144 МГц / 3 */
#define HSE_TIMEOUT_MS  100u
#define PSI_TIMEOUT_MS  2u
#define SW_TIMEOUT_MS   5u
#define AF1_TIM2        1u           /* номера альтернативных функций — описание выводов пакета */
#define AF4_I2C1        4u
#define AF7_USART2      7u
#define LPDMA_REQ_USART2_RX 14u      /* номер запроса — в stm32c5xx_ll_dma.h; в заголовке устройства имени нет */
#define UART_BAUD       115200u
#define TX_SIZE         256u
#define LINE_SIZE       32u
#define RX_DMA_SIZE     64u
#define ADC_CH_TEMP     12u          /* ADC1, внутренний канал 12 — датчик температуры */
#define PWM_PERIOD      1000u        /* 1 МГц / 1000 = 1 кГц */
#define PWM_DUTY_LOW    250u
#define PWM_DUTY_HIGH   750u
#define DEBOUNCE_MS     50u
#define I2C_DEV         0x68u        /* семибитный адрес датчика, как в разделе 17 */
#define I2C_REG_ID      0x75u
#define I2C_TIMEOUT_MS  10u
#define I2C_ERR_TIMEOUT (-1)
#define I2C_ERR_NACK    (-2)
/* поля TIMINGR для 100 кГц — те же, что считает STM32_UTILS_I2C_ComputeTimingBasic пакета */
#define I2C_T144        ((8u << I2C_TIMINGR_PRESC_Pos) | (11u << I2C_TIMINGR_SCLDEL_Pos) \
                         | (2u << I2C_TIMINGR_SDADEL_Pos) | (84u << I2C_TIMINGR_SCLH_Pos) | (85u << I2C_TIMINGR_SCLL_Pos))
#define I2C_T48         ((2u << I2C_TIMINGR_PRESC_Pos) | (11u << I2C_TIMINGR_SCLDEL_Pos) \
                         | (1u << I2C_TIMINGR_SDADEL_Pos) | (75u << I2C_TIMINGR_SCLH_Pos) | (76u << I2C_TIMINGR_SCLL_Pos))
#define ADC_CR_RS       (ADC_CR_ADCAL | ADC_CR_JADSTP | ADC_CR_ADSTP | ADC_CR_JADSTART | ADC_CR_ADSTART \
                         | ADC_CR_ADDIS | ADC_CR_ADEN)   /* биты «rs»: запись 0 не действует, |= их повторит */

uint32_t SystemCoreClock = HSIDIV3_HZ;
uint32_t pclk1_hz = HSIDIV3_HZ;

/* ── 1. запуск: FPU и тактирование ── */
void SystemInit(void)                   /* зовёт стартовый файл пакета до main */
{
    SCB_EnableFPU();                    /* из stm32c5xx.h: CP10, CP11 в SCB->CPACR */
    __DSB();
    __ISB();
}

int clock_init(void)
{
    RCC->CR1 |= RCC_CR1_HSEON;
    if (wait_bits(&RCC->CR1, RCC_CR1_HSERDY, RCC_CR1_HSERDY, HSE_TIMEOUT_MS) != 0) {
        RCC->CR1 &= ~RCC_CR1_HSEON;     /* кварц не завёлся — остаёмся на HSIDIV3 */
        return -1;
    }
    RCC->CR2 = (RCC->CR2 & ~(RCC_CR2_PSIREFSRC | RCC_CR2_PSIREF | RCC_CR2_PSIFREQ))
             | RCC_CR2_PSIREF_1 | RCC_CR2_PSIREF_0      /* опора 24 МГц; PSIREFSRC = 0 — от HSE */
             | RCC_CR2_PSIFREQ_0;                       /* выход 144 МГц */
    RCC->CR1 |= RCC_CR1_PSISON;
    if (wait_bits(&RCC->CR1, RCC_CR1_PSISRDY, RCC_CR1_PSISRDY, PSI_TIMEOUT_MS) != 0)
        return -2;
    RCC->CFGR2 &= ~(RCC_CFGR2_HPRE | RCC_CFGR2_PPRE1 | RCC_CFGR2_PPRE2 | RCC_CFGR2_PPRE3);   /* шины без деления */
    FLASH->ACR = (FLASH->ACR & ~FLASH_ACR_LATENCY) | FLASH_ACR_LATENCY_3 | FLASH_ACR_PRFTEN; /* _3 = 4 такта! */
    if ((FLASH->ACR & FLASH_ACR_LATENCY) != FLASH_ACR_LATENCY_3)
        return -3;                      /* задержка принята — только теперь повышать частоту */
    RCC->CFGR1 = (RCC->CFGR1 & ~RCC_CFGR1_SW) | RCC_CFGR1_SW;          /* SW = 11: PSIS */
    if (wait_bits(&RCC->CFGR1, RCC_CFGR1_SWS, RCC_CFGR1_SWS, SW_TIMEOUT_MS) != 0)
        return -4;
    FLASH->ACR = (FLASH->ACR & ~FLASH_ACR_WRHIGHFREQ) | FLASH_ACR_WRHIGHFREQ_1;   /* запись флеша: 136–170 МГц */
    SystemCoreClock = PSI_HZ;
    pclk1_hz = PSI_HZ;
    return 0;
}

/* ── 2. вывод: кольцевой буфер передачи и мини-форматер ── */
static volatile uint8_t tx_buf[TX_SIZE];
static volatile uint16_t tx_head, tx_tail;
static volatile char line[LINE_SIZE];
static volatile uint32_t line_len, line_ready;
static uint8_t rx_dma_buf[RX_DMA_SIZE + 1u];
static volatile uint32_t rx_dma_len, rx_dma_events;

void uart_putc(char c)
{
    uint16_t next = (uint16_t)((tx_head + 1u) % TX_SIZE);
    uint32_t t0 = millis();
    while (next == tx_tail) {           /* буфер полон — ждём, пока прерывание освободит место */
        if ((millis() - t0) > 100u)
            return;                     /* передатчик встал — байт теряется, но программа не виснет */
    }
    tx_buf[tx_head] = (uint8_t)c;
    tx_head = next;
    USART2->CR1 |= USART_CR1_TXEIE_TXFNFIE;   /* передатчик пуст → прерывание заберёт байт */
}

static void out_u32(uint32_t v, uint32_t base)
{
    char d[10];
    int n = 0;
    do {
        d[n++] = "0123456789abcdef"[v % base];
        v /= base;
    } while (v != 0u);
    while (n > 0)
        uart_putc(d[--n]);
}

void print(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    for (; *fmt != '\0'; fmt++) {
        if (*fmt != '%') {
            uart_putc(*fmt);
            continue;
        }
        fmt++;
        if (*fmt == 's') {
            for (const char *s = va_arg(ap, const char *); *s != '\0'; s++)
                uart_putc(*s);
        } else if (*fmt == 'u') {
            out_u32(va_arg(ap, uint32_t), 10u);
        } else if (*fmt == 'x') {
            out_u32(va_arg(ap, uint32_t), 16u);
        } else if (*fmt == 'd') {
            int32_t v = va_arg(ap, int32_t);
            if (v < 0) {
                uart_putc('-');
                v = -v;
            }
            out_u32((uint32_t)v, 10u);
        }
    }
    va_end(ap);
}

void uart_flush(void)
{
    uint32_t t0 = millis();
    while ((tx_tail != tx_head || (USART2->ISR & USART_ISR_TC) == 0u) && (millis() - t0) < 100u) {
    }
}

/* ── 3. GPIO: светодиод на ШИМ, USART2, кнопка PC13 на EXTI13 ── */
void gpio_init(void)
{
    RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN | RCC_AHB2ENR_GPIOCEN;
    (void)RCC->AHB2ENR;                 /* пауза после включения такта */
    /* PA5 — TIM2_CH1 (AF1): светодиод; PA2/PA3 — USART2 TX/RX (AF7), на RX подтяжка вверх */
    GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODE2 | GPIO_MODER_MODE3 | GPIO_MODER_MODE5))
                 | GPIO_MODER_MODE2_1 | GPIO_MODER_MODE3_1 | GPIO_MODER_MODE5_1;
    GPIOA->AFR[0] = (GPIOA->AFR[0] & ~(GPIO_AFRL_AFSEL2 | GPIO_AFRL_AFSEL3 | GPIO_AFRL_AFSEL5))
                  | (AF7_USART2 << GPIO_AFRL_AFSEL2_Pos) | (AF7_USART2 << GPIO_AFRL_AFSEL3_Pos)
                  | (AF1_TIM2 << GPIO_AFRL_AFSEL5_Pos);
    GPIOA->PUPDR = (GPIOA->PUPDR & ~GPIO_PUPDR_PUPD3) | GPIO_PUPDR_PUPD3_0;
    GPIOC->MODER &= ~GPIO_MODER_MODE13; /* PC13 — вход (кнопка на землю, резистор на плате) */
    /* выбор порта — в самом EXTI, отдельного SYSCFG для этого нет; поле 8 бит, порт C = 2 */
    EXTI->EXTICR[3] = (EXTI->EXTICR[3] & ~EXTI_EXTICR4_EXTI13) | EXTI_EXTICR4_EXTI13_1;
    EXTI->FTSR1 |= EXTI_FTSR1_FT13;     /* нажатие — спад */
    EXTI->IMR1 |= EXTI_IMR1_IM13;
    NVIC_SetPriority(EXTI13_IRQn, 6u);  /* у C5 своя линия прерывания на каждый EXTI0…15 */
    NVIC_EnableIRQ(EXTI13_IRQn);
}

static volatile uint32_t presses, edges, last_press_ms;

void EXTI13_IRQHandler(void)
{
    uint32_t pend = (EXTI->RPR1 | EXTI->FPR1) & EXTI_FPR1_FPIF13;
    if (pend != 0u) {
        EXTI->FPR1 = EXTI_FPR1_FPIF13;  /* rc_w1: сброс записью единицы, без |= */
        EXTI->RPR1 = EXTI_RPR1_RPIF13;  /* программный запуск (SWIER) может поднять и этот флаг */
        edges++;
        uint32_t now = millis();
        if ((now - last_press_ms) >= DEBOUNCE_MS) {
            last_press_ms = now;
            presses++;
            TIM2->CCR1 = (TIM2->CCR1 == PWM_DUTY_LOW) ? PWM_DUTY_HIGH : PWM_DUTY_LOW;
        }
    }
}

/* ── 4. UART: скорость, прерывания, приём строки ── */
void uart_init(void)
{
    RCC->APB1LENR |= RCC_APB1LENR_USART2EN;
    (void)RCC->APB1LENR;
    /* такт ядра USART2 — PCLK1: поле USART2SEL в RCC->CCIPR1 после сброса = 0 */
    USART2->BRR = (pclk1_hz + UART_BAUD / 2u) / UART_BAUD;    /* OVER8 = 0, PRESC = 0: BRR = f / бод */
    USART2->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_RXNEIE_RXFNEIE;
    NVIC_SetPriority(USART2_IRQn, 5u);
    NVIC_EnableIRQ(USART2_IRQn);
}

void USART2_IRQHandler(void)
{
    uint32_t isr = USART2->ISR;
    if ((isr & USART_ISR_RXNE_RXFNE) != 0u) {
        char c = (char)USART2->RDR;     /* чтение RDR сбрасывает RXNE */
        if (c == '\r' || c == '\n') {
            if (line_len != 0u)
                line_ready = 1u;
        } else if (line_len < LINE_SIZE - 1u && line_ready == 0u) {
            line[line_len++] = c;
        }
    }
    if ((isr & USART_ISR_IDLE) != 0u && (USART2->CR1 & USART_CR1_IDLEIE) != 0u) {
        USART2->ICR = USART_ICR_IDLECF; /* у USART нового образца флаги сбрасывает отдельный ICR */
        rx_dma_len = RX_DMA_SIZE - (LPDMA1_CH1->CBR1 & DMA_CBR1_BNDT);
        rx_dma_events++;
    }
    if ((isr & USART_ISR_TXE_TXFNF) != 0u && (USART2->CR1 & USART_CR1_TXEIE_TXFNFIE) != 0u) {
        if (tx_tail != tx_head) {
            USART2->TDR = tx_buf[tx_tail];
            tx_tail = (uint16_t)((tx_tail + 1u) % TX_SIZE);
        } else {
            USART2->CR1 &= ~USART_CR1_TXEIE_TXFNFIE;   /* нечего передавать — молчать */
        }
    }
}

/* ── 5. DMA: приём USART2 — LPDMA1, канал 1, запрос 14 ── */
void uart_rx_dma_start(void)
{
    RCC->AHB1ENR |= RCC_AHB1ENR_LPDMA1EN;
    (void)RCC->AHB1ENR;
    LPDMA1_CH1->CCR &= ~DMA_CCR_EN;
    LPDMA1_CH1->CFCR = DMA_CFCR_TCF | DMA_CFCR_HTF | DMA_CFCR_DTEF | DMA_CFCR_ULEF | DMA_CFCR_USEF
                     | DMA_CFCR_SUSPF | DMA_CFCR_TOF;
    LPDMA1_CH1->CTR1 = DMA_CTR1_DINC;   /* байт в байт; источник — неподвижный RDR, приёмник растёт */
    LPDMA1_CH1->CTR2 = LPDMA_REQ_USART2_RX << DMA_CTR2_REQSEL_Pos;
    LPDMA1_CH1->CBR1 = RX_DMA_SIZE;     /* блок 64 байта; кольца без связного списка у LPDMA нет */
    LPDMA1_CH1->CSAR = (uint32_t)&USART2->RDR;
    LPDMA1_CH1->CDAR = (uint32_t)rx_dma_buf;
    LPDMA1_CH1->CLLR = 0u;              /* один блок, без связного списка */
    LPDMA1_CH1->CCR = DMA_CCR_PRIO_1 | DMA_CCR_EN;
    USART2->CR1 &= ~USART_CR1_RXNEIE_RXFNEIE;   /* байты теперь забирает DMA */
    USART2->CR3 |= USART_CR3_DMAR;
    USART2->ICR = USART_ICR_IDLECF;
    USART2->CR1 |= USART_CR1_IDLEIE;    /* пауза в линии — конец посылки */
}

/* ── 6. Таймер: ШИМ 1 кГц на PA5 и прерывание по переполнению ── */
static volatile uint32_t tim_updates;

void pwm_init(void)
{
    RCC->APB1LENR |= RCC_APB1LENR_TIM2EN;
    (void)RCC->APB1LENR;
    uint32_t tim_hz = ((RCC->CFGR2 & RCC_CFGR2_PPRE1) == 0u) ? pclk1_hz : 2u * pclk1_hz;   /* делитель APB1 > 1 → ×2 */
    TIM2->PSC = tim_hz / 1000000u - 1u;                       /* счёт 1 МГц */
    TIM2->ARR = PWM_PERIOD - 1u;
    TIM2->CCR1 = PWM_DUTY_LOW;                                /* 25 % */
    TIM2->CCMR1 = (TIM2->CCMR1 & ~(TIM_CCMR1_OC1M | TIM_CCMR1_CC1S))
                | TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1PE;   /* ШИМ, режим 1 */
    TIM2->CCER |= TIM_CCER_CC1E;
    TIM2->EGR = TIM_EGR_UG;             /* загрузить PSC сейчас; заодно поднимает UIF */
    TIM2->SR = ~TIM_SR_UIF;             /* rc_w0: сброс записью нуля, остальные биты — единицы */
    TIM2->DIER |= TIM_DIER_UIE;
    NVIC_SetPriority(TIM2_IRQn, 7u);
    NVIC_EnableIRQ(TIM2_IRQn);
    TIM2->CR1 |= TIM_CR1_ARPE | TIM_CR1_CEN;
}

void TIM2_IRQHandler(void)
{
    if ((TIM2->SR & TIM_SR_UIF) != 0u) {
        TIM2->SR = ~TIM_SR_UIF;
        tim_updates++;
    }
}

/* ── 7. АЦП: датчик температуры — однократно и непрерывно ── */
int adc_init(void)
{
    RCC->AHB2ENR |= RCC_AHB2ENR_ADC12EN;
    (void)RCC->AHB2ENR;
    RCC->CCIPR2 = (RCC->CCIPR2 & ~(RCC_CCIPR2_ADCDACSEL | RCC_CCIPR2_ADCDACPRE))
                | RCC_CCIPR2_ADCDACSEL_0 | RCC_CCIPR2_ADCDACPRE_1;   /* PSIS / 4 = 36 МГц */
    ADC1->CR = (ADC1->CR & ~(ADC_CR_RS | ADC_CR_DEEPPWD)) | ADC_CR_ADVREGEN;   /* выйти из сна, стабилизатор */
    delay_ms(1u);                                             /* нужно 10 мкс */
    ADC1->CR = (ADC1->CR & ~ADC_CR_RS) | ADC_CR_ADCAL;        /* калибровка при ADEN = 0 */
    if (wait_bits(&ADC1->CR, ADC_CR_ADCAL, 0u, 2u) != 0)
        return -1;
    ADC12_COMMON->CCR |= ADCC_CCR_TSEN;                       /* датчик температуры к каналу 12 */
    ADC1->SMPR2 |= ADC_SMPR2_SMP12;                           /* 289 тактов выборки */
    ADC1->SQR1 = ADC_CH_TEMP << ADC_SQR1_SQ1_Pos;             /* L = 0: одно измерение */
    ADC1->ISR = ADC_ISR_ADRDY;                                /* rc_w1 */
    ADC1->CR = (ADC1->CR & ~ADC_CR_RS) | ADC_CR_ADEN;
    if (wait_bits(&ADC1->ISR, ADC_ISR_ADRDY, ADC_ISR_ADRDY, 2u) != 0)
        return -2;
    delay_ms(1u);                                             /* датчику — 25 мкс */
    return 0;
}

uint32_t adc_read_once(void)
{
    ADC1->CR = (ADC1->CR & ~ADC_CR_RS) | ADC_CR_ADSTART;
    if (wait_bits(&ADC1->ISR, ADC_ISR_EOC, ADC_ISR_EOC, 2u) != 0)
        return 0xFFFFu;
    return ADC1->DR;                    /* чтение DR сбрасывает EOC */
}

void adc_continuous_start(void)
{
    ADC1->CFGR1 |= ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD;         /* без остановки; старое значение затирается */
    ADC1->CR = (ADC1->CR & ~ADC_CR_RS) | ADC_CR_ADSTART;
}

/* ── 8. I2C1: восстановление шины, настройка, чтение регистра с повторным стартом ── */
static void half_bit_delay(void)
{
    for (volatile uint32_t i = SystemCoreClock / 1000000u; i != 0u; i--) {
    }
}

int i2c_bus_recover(void)
{
    /* PB6 = SCL, PB7 = SDA: открытый сток, обычные выходы, обе линии отпущены */
    GPIOB->OTYPER |= GPIO_OTYPER_OT6 | GPIO_OTYPER_OT7;
    GPIOB->BSRR = GPIO_BSRR_BS6 | GPIO_BSRR_BS7;
    GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODE6 | GPIO_MODER_MODE7)) | GPIO_MODER_MODE6_0 | GPIO_MODER_MODE7_0;
    int pulses = 0;
    while ((GPIOB->IDR & GPIO_IDR_ID7) == 0u && pulses < 9) {   /* ведомый держит SDA */
        GPIOB->BSRR = GPIO_BSRR_BR6;
        half_bit_delay();
        GPIOB->BSRR = GPIO_BSRR_BS6;
        half_bit_delay();
        pulses++;
    }
    GPIOB->BSRR = GPIO_BSRR_BR7;        /* старт и стоп: SDA вниз и вверх при высоком SCL */
    half_bit_delay();
    GPIOB->BSRR = GPIO_BSRR_BS7;
    half_bit_delay();
    return ((GPIOB->IDR & GPIO_IDR_ID7) != 0u) ? pulses : -1;
}

void i2c_init(void)
{
    RCC->APB1LENR |= RCC_APB1LENR_I2C1EN;
    (void)RCC->APB1LENR;
    GPIOB->OTYPER |= GPIO_OTYPER_OT6 | GPIO_OTYPER_OT7;      /* I2C — только открытый сток */
    GPIOB->PUPDR = (GPIOB->PUPDR & ~(GPIO_PUPDR_PUPD6 | GPIO_PUPDR_PUPD7)) | GPIO_PUPDR_PUPD6_0 | GPIO_PUPDR_PUPD7_0;
    GPIOB->AFR[0] = (GPIOB->AFR[0] & ~(GPIO_AFRL_AFSEL6 | GPIO_AFRL_AFSEL7))
                  | (AF4_I2C1 << GPIO_AFRL_AFSEL6_Pos) | (AF4_I2C1 << GPIO_AFRL_AFSEL7_Pos);
    GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODE6 | GPIO_MODER_MODE7)) | GPIO_MODER_MODE6_1 | GPIO_MODER_MODE7_1;
    I2C1->CR1 &= ~I2C_CR1_PE;           /* TIMINGR пишется только при выключенном блоке; PE = 0 ещё и сброс */
    I2C1->TIMINGR = (pclk1_hz == PSI_HZ) ? I2C_T144 : I2C_T48;
    I2C1->CR1 |= I2C_CR1_PE;
}

static int i2c_wait(uint32_t flag)      /* ждать флаг; NACK и тайм-аут — ошибки */
{
    uint32_t t0 = millis();
    while ((I2C1->ISR & flag) == 0u) {
        if ((I2C1->ISR & I2C_ISR_NACKF) != 0u)
            return I2C_ERR_NACK;
        if ((millis() - t0) > I2C_TIMEOUT_MS)
            return I2C_ERR_TIMEOUT;
    }
    return 0;
}

static int i2c_fail(int err)
{
    if ((I2C1->CR2 & I2C_CR2_AUTOEND) == 0u)
        I2C1->CR2 |= I2C_CR2_STOP;      /* без AUTOEND стоп после NACK ставим сами */
    (void)i2c_wait(I2C_ISR_STOPF);
    I2C1->ICR = I2C_ICR_NACKCF | I2C_ICR_STOPCF;
    I2C1->CR2 = 0u;
    return err;
}

int i2c_read(uint8_t dev, uint8_t reg, uint8_t *buf, uint32_t n)
{
    /* старт, адрес + запись, 1 байт без AUTOEND — потом повторный старт */
    I2C1->CR2 = ((uint32_t)dev << 1 << I2C_CR2_SADD_Pos) | (1u << I2C_CR2_NBYTES_Pos) | I2C_CR2_START;
    int r = i2c_wait(I2C_ISR_TXIS);
    if (r != 0)
        return i2c_fail(r);
    I2C1->TXDR = reg;
    r = i2c_wait(I2C_ISR_TC);
    if (r != 0)
        return i2c_fail(r);
    /* повторный старт, адрес + чтение, n байт, стоп и NACK на последнем — аппаратно (AUTOEND) */
    I2C1->CR2 = ((uint32_t)dev << 1 << I2C_CR2_SADD_Pos) | I2C_CR2_RD_WRN | (n << I2C_CR2_NBYTES_Pos)
              | I2C_CR2_AUTOEND | I2C_CR2_START;
    for (uint32_t i = 0; i < n; i++) {
        r = i2c_wait(I2C_ISR_RXNE);
        if (r != 0)
            return i2c_fail(r);
        buf[i] = (uint8_t)I2C1->RXDR;
    }
    r = i2c_wait(I2C_ISR_STOPF);
    I2C1->ICR = I2C_ICR_STOPCF;
    I2C1->CR2 = 0u;
    return r;
}

/* ── проект целиком: тот же порядок и тот же вывод, что в hal/main.c ── */
int main(void)
{
    tick_init(SystemCoreClock);         /* 1 мс от HSIDIV3 — нужен для тайм-аутов clock_init */
    int clk = clock_init();
    tick_init(SystemCoreClock);         /* 1 мс от нового такта */
    gpio_init();
    uart_init();
    print("project: regs\n");
    if (clk == 0)
        print("clock: PSI %u Hz\n", SystemCoreClock);
    else
        print("clock: error %d, HSIDIV3 %u Hz\n", clk, SystemCoreClock);
    print("uart: BRR 0x%x\n", USART2->BRR);
    volatile float k = 1.5f;
    print("fpu: 1.5 * 1.5 * 1000 = %u\n", (uint32_t)(k * k * 1000.0f));
    pwm_init();
    print("tim2: psc %u arr %u ccr1 %u\n", TIM2->PSC, TIM2->ARR, TIM2->CCR1);
    uint32_t t0 = millis(), n0 = tim_updates;
    while ((millis() - t0) < 100u) {
    }
    print("tim2: %u updates in 100 ms\n", tim_updates - n0);
    EXTI->SWIER1 = EXTI_SWIER1_SWI13;   /* «нажатие» программой: то же прерывание, что от PC13 */
    delay_ms(10u);
    EXTI->SWIER1 = EXTI_SWIER1_SWI13;   /* дребезг через 10 мс */
    delay_ms(100u);
    EXTI->SWIER1 = EXTI_SWIER1_SWI13;   /* второе нажатие */
    delay_ms(10u);
    print("button: %u presses of %u edges, ccr1 %u\n", presses, edges, TIM2->CCR1);
    if (adc_init() != 0) {
        print("adc: init error\n");
    } else {
        uint32_t a1 = adc_read_once();
        uint32_t a2 = adc_read_once();
        if (a2 == 0xFFFFu) {
            print("adc: EOC timeout\n");
        } else {
            print("adc: raw %u then %u\n", a1, a2);
            adc_continuous_start();
            delay_ms(10u);
            print("adc: continuous, DR %u\n", ADC1->DR);
        }
    }
    int rec = i2c_bus_recover();
    print("i2c: recovery %d\n", rec);
    i2c_init();
    uint8_t id = 0;
    int r = i2c_read(I2C_DEV, I2C_REG_ID, &id, 1u);
    if (r == 0)
        print("i2c: id 0x%x\n", id);
    else
        print("i2c: error %s\n", (r == I2C_ERR_NACK) ? "nack" : "timeout");
    print("rx: type a line\n");
    t0 = millis();
    while (line_ready == 0u && (millis() - t0) < 3000u) {
    }
    if (line_ready != 0u) {
        line[line_len] = '\0';
        print("rx: '%s'\n", (const char *)line);
    } else {
        print("rx: timeout\n");
    }
    uart_rx_dma_start();
    print("dma: rx armed\n");
    t0 = millis();
    while (rx_dma_events == 0u && (millis() - t0) < 1000u) {
    }
    if (rx_dma_events != 0u) {
        rx_dma_buf[rx_dma_len] = 0u;
        print("dma: %u bytes '%s'\n", rx_dma_len, (const char *)rx_dma_buf);
    } else {
        print("dma: timeout\n");
    }
    print("done\n");
    uart_flush();
    for (;;) {
        __WFI();
    }
}

regs/regs_time.h — register project time: declarations.

/* Раздел 5д: время проекта на регистрах — SysTick 1 мс, задержка и ожидание флага с тайм-аутом. */
#ifndef REGS_TIME_H
#define REGS_TIME_H
#include <stdint.h>

void tick_init(uint32_t core_hz);
uint32_t millis(void);
void delay_ms(uint32_t ms);
int wait_bits(volatile uint32_t *reg, uint32_t mask, uint32_t want, uint32_t timeout_ms);

#endif

regs/regs_time.c — SysTick, delay and flag wait.

/* Раздел 5д: SysTick 1 мс, delay_ms и wait_bits — единственное место, где проект ждёт время.
 * На стенде ПК этот файл подменяется моделью (host/model.c), остальной код не меняется. */
#include "stm32c5xx.h"
#include "regs_time.h"

static volatile uint32_t ticks;                 /* миллисекунды с запуска */

void SysTick_Handler(void)
{
    ticks++;
}

void tick_init(uint32_t core_hz)
{
    SysTick_Config(core_hz / 1000u);            /* CMSIS: LOAD, VAL, приоритет 15, такт ядра, прерывание */
}

uint32_t millis(void)
{
    return ticks;
}

void delay_ms(uint32_t ms)
{
    uint32_t t0 = ticks;
    while ((ticks - t0) < ms) {
        __WFI();                                /* спать до следующего прерывания */
    }
}

int wait_bits(volatile uint32_t *reg, uint32_t mask, uint32_t want, uint32_t timeout_ms)
{
    uint32_t t0 = ticks;
    while ((*reg & mask) != want) {
        if ((ticks - t0) > timeout_ms)
            return -1;                          /* флаг так и не пришёл */
    }
    return 0;
}

hal/main.c — the same project on HAL2.

/* Раздел 5д: тот же проект, что regs/main.c, — на HAL2 из пакета STM32CubeC5 (stm32c5xx_drivers).
 * Конфигурация — шаблон пакета stm32c5xx_hal_conf.h без правок; частота кварца — stm32_external_env.h
 * пакета (USE_EXTERNAL_ENV, 24 МГц). Порядок модулей, константы и вывод в USART2 — как у проекта на регистрах. */
#include <stdarg.h>
#include <stdint.h>
#include "stm32_hal.h"
#include "stm32_utils_i2c.h"

#define UART_BAUD       115200u
#define TX_SIZE         256u
#define LINE_SIZE       32u
#define RX_DMA_SIZE     64u
#define PWM_PERIOD      1000u
#define PWM_DUTY_LOW    250u
#define PWM_DUTY_HIGH   750u
#define DEBOUNCE_MS     50u
#define I2C_SPEED_HZ    100000u
#define I2C_DEV         0x68u
#define I2C_REG_ID      0x75u
#define I2C_TIMEOUT_MS  10u
#define I2C_ERR_TIMEOUT (-1)
#define I2C_ERR_NACK    (-2)

static hal_uart_handle_t huart2;
static hal_dma_handle_t hdma_rx;
static hal_tim_handle_t htim2;
static hal_exti_handle_t hexti13;
static hal_adc_handle_t hadc1;
static hal_i2c_handle_t hi2c1;
uint32_t pclk1_hz;

/* ── 1. запуск и такт ── */
void SysTick_Handler(void)
{
    HAL_IncTick();
}

int clock_init(void)
{
    if (HAL_RCC_HSE_Enable(HAL_RCC_HSE_ON) != HAL_OK)
        return -1;                      /* кварц не завёлся — остаёмся на HSIDIV3 */
    hal_rcc_psi_config_t psi;
    psi.psi_source = HAL_RCC_PSI_SRC_HSE;
    psi.psi_ref = HAL_RCC_PSI_REF_24MHZ;
    psi.psi_out = HAL_RCC_PSI_OUT_144MHZ;
    if (HAL_RCC_PSI_SetConfig(&psi) != HAL_OK || HAL_RCC_PSIS_Enable() != HAL_OK)
        return -2;
    hal_rcc_bus_clk_config_t bus;
    bus.hclk_prescaler = HAL_RCC_HCLK_PRESCALER1;
    bus.pclk1_prescaler = HAL_RCC_PCLK_PRESCALER1;
    bus.pclk2_prescaler = HAL_RCC_PCLK_PRESCALER1;
    bus.pclk3_prescaler = HAL_RCC_PCLK_PRESCALER1;
    if (HAL_RCC_SetBusClockConfig(&bus) != HAL_OK)
        return -3;
    HAL_FLASH_ITF_SetLatency(HAL_FLASH, HAL_FLASH_ITF_LATENCY_4);   /* до повышения частоты */
    if (HAL_RCC_SetSYSCLKSource(HAL_RCC_SYSCLK_SRC_PSIS) != HAL_OK)
        return -4;
    HAL_FLASH_ITF_SetProgrammingDelay(HAL_FLASH, HAL_FLASH_ITF_PROGRAM_DELAY_2);
    if (HAL_UpdateCoreClock() != HAL_OK)   /* SystemCoreClock и SysTick заново */
        return -5;
    return 0;
}

/* ── 2. вывод: то же кольцо; кусок до конца кольца отдаётся HAL_UART_Transmit_IT ── */
static volatile uint8_t tx_buf[TX_SIZE];
static volatile uint16_t tx_head, tx_tail, tx_len;
static volatile char line[LINE_SIZE];
static volatile uint32_t line_len, line_ready, rx_dma_mode;
static uint8_t rx_byte;
static uint8_t rx_dma_buf[RX_DMA_SIZE + 1u];
static volatile uint32_t rx_dma_len, rx_dma_events;

static void tx_start(void)
{
    if (tx_len != 0u || tx_tail == tx_head)
        return;
    uint16_t end = (tx_head > tx_tail) ? tx_head : TX_SIZE;
    tx_len = (uint16_t)(end - tx_tail);
    (void)HAL_UART_Transmit_IT(&huart2, (const uint8_t *)&tx_buf[tx_tail], tx_len);
}

void HAL_UART_TxCpltCallback(hal_uart_handle_t *huart)
{
    (void)huart;
    tx_tail = (uint16_t)((tx_tail + tx_len) % TX_SIZE);
    tx_len = 0u;
    tx_start();
}

void uart_putc(char c)
{
    uint16_t next = (uint16_t)((tx_head + 1u) % TX_SIZE);
    uint32_t t0 = HAL_GetTick();
    while (next == tx_tail) {
        if ((HAL_GetTick() - t0) > 100u)
            return;
    }
    tx_buf[tx_head] = (uint8_t)c;
    tx_head = next;
    uint32_t pm = __get_PRIMASK();      /* кусок запускает и прерывание — не пересечься с ним */
    __disable_irq();
    tx_start();
    __set_PRIMASK(pm);
}

static void out_u32(uint32_t v, uint32_t base)
{
    char d[10];
    int n = 0;
    do {
        d[n++] = "0123456789abcdef"[v % base];
        v /= base;
    } while (v != 0u);
    while (n > 0)
        uart_putc(d[--n]);
}

void print(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    for (; *fmt != '\0'; fmt++) {
        if (*fmt != '%') {
            uart_putc(*fmt);
            continue;
        }
        fmt++;
        if (*fmt == 's') {
            for (const char *s = va_arg(ap, const char *); *s != '\0'; s++)
                uart_putc(*s);
        } else if (*fmt == 'u') {
            out_u32(va_arg(ap, uint32_t), 10u);
        } else if (*fmt == 'x') {
            out_u32(va_arg(ap, uint32_t), 16u);
        } else if (*fmt == 'd') {
            int32_t v = va_arg(ap, int32_t);
            if (v < 0) {
                uart_putc('-');
                v = -v;
            }
            out_u32((uint32_t)v, 10u);
        }
    }
    va_end(ap);
}

void uart_flush(void)
{
    uint32_t t0 = HAL_GetTick();
    while ((tx_tail != tx_head || HAL_UART_GetTxState(&huart2) != HAL_UART_TX_STATE_IDLE)
           && (HAL_GetTick() - t0) < 100u) {
    }
}

/* ── 3. GPIO и кнопка PC13 на EXTI13 ── */
void gpio_init(void)
{
    hal_gpio_config_t g;
    HAL_RCC_GPIOA_EnableClock();
    HAL_RCC_GPIOB_EnableClock();
    HAL_RCC_GPIOC_EnableClock();
    g.mode = HAL_GPIO_MODE_ALTERNATE;
    g.output_type = HAL_GPIO_OUTPUT_PUSHPULL;
    g.pull = HAL_GPIO_PULL_NO;
    g.speed = HAL_GPIO_SPEED_FREQ_LOW;
    g.alternate = HAL_GPIO_AF_1;
    g.init_state = HAL_GPIO_PIN_RESET;
    (void)HAL_GPIO_Init(HAL_GPIOA, HAL_GPIO_PIN_5, &g);
    g.alternate = HAL_GPIO_AF_7;
    (void)HAL_GPIO_Init(HAL_GPIOA, HAL_GPIO_PIN_2, &g);
    g.pull = HAL_GPIO_PULL_UP;
    (void)HAL_GPIO_Init(HAL_GPIOA, HAL_GPIO_PIN_3, &g);
    g.mode = HAL_GPIO_MODE_INPUT;
    g.pull = HAL_GPIO_PULL_NO;
    (void)HAL_GPIO_Init(HAL_GPIOC, HAL_GPIO_PIN_13, &g);
    hal_exti_config_t e;
    (void)HAL_EXTI_Init(&hexti13, HAL_EXTI_LINE_13);
    e.trigger = HAL_EXTI_TRIGGER_FALLING;
    e.gpio_port = HAL_EXTI_GPIOC;
    (void)HAL_EXTI_SetConfig(&hexti13, &e);
    (void)HAL_EXTI_Enable(&hexti13, HAL_EXTI_MODE_INTERRUPT);
    HAL_CORTEX_NVIC_SetPriority(EXTI13_IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_6, HAL_CORTEX_NVIC_SUB_PRIORITY_0);
    HAL_CORTEX_NVIC_EnableIRQ(EXTI13_IRQn);
}

static volatile uint32_t presses, edges, last_press_ms;

void EXTI13_IRQHandler(void)
{
    HAL_EXTI_IRQHandler(&hexti13);
}

void HAL_EXTI_TriggerCallback(hal_exti_handle_t *hexti, hal_exti_trigger_t trigger)
{
    (void)hexti;
    (void)trigger;
    edges++;
    uint32_t now = HAL_GetTick();
    if ((now - last_press_ms) >= DEBOUNCE_MS) {
        last_press_ms = now;
        presses++;
        uint32_t ccr = HAL_TIM_OC_GetCompareUnitPulse(&htim2, HAL_TIM_OC_COMPARE_UNIT_1);
        (void)HAL_TIM_OC_SetCompareUnitPulse(&htim2, HAL_TIM_OC_COMPARE_UNIT_1,
                                             (ccr == PWM_DUTY_LOW) ? PWM_DUTY_HIGH : PWM_DUTY_LOW);
    }
}

/* ── 4. UART: дескриптор, такт, настройка, приём по байту ── */
void uart_init(void)
{
    hal_uart_config_t u;
    (void)HAL_UART_Init(&huart2, HAL_UART2);
    HAL_RCC_USART2_EnableClock();
    (void)HAL_RCC_USART2_SetKernelClkSource(HAL_RCC_USART2_CLK_SRC_PCLK1);
    u.baud_rate = UART_BAUD;
    u.clock_prescaler = HAL_UART_PRESCALER_DIV1;
    u.word_length = HAL_UART_WORD_LENGTH_8_BIT;
    u.stop_bits = HAL_UART_STOP_BIT_1;
    u.parity = HAL_UART_PARITY_NONE;
    u.direction = HAL_UART_DIRECTION_TX_RX;
    u.hw_flow_ctl = HAL_UART_HW_CONTROL_NONE;
    u.oversampling = HAL_UART_OVERSAMPLING_16;
    u.one_bit_sampling = HAL_UART_ONE_BIT_SAMPLE_DISABLE;
    (void)HAL_UART_SetConfig(&huart2, &u);
    HAL_CORTEX_NVIC_SetPriority(USART2_IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_5, HAL_CORTEX_NVIC_SUB_PRIORITY_0);
    HAL_CORTEX_NVIC_EnableIRQ(USART2_IRQn);
    (void)HAL_UART_Receive_IT(&huart2, &rx_byte, 1u);
}

void USART2_IRQHandler(void)
{
    HAL_UART_IRQHandler(&huart2);
}

void LPDMA1_CH1_IRQHandler(void)
{
    HAL_DMA_IRQHandler(&hdma_rx);
}

void HAL_UART_RxCpltCallback(hal_uart_handle_t *huart, uint32_t size_byte, hal_uart_rx_event_types_t rx_event)
{
    (void)rx_event;
    if (rx_dma_mode != 0u) {            /* приём по DMA закончился паузой в линии */
        rx_dma_len = size_byte;
        rx_dma_events++;
        return;
    }
    char c = (char)rx_byte;
    if (c == '\r' || c == '\n') {
        if (line_len != 0u)
            line_ready = 1u;
    } else if (line_len < LINE_SIZE - 1u && line_ready == 0u) {
        line[line_len++] = c;
    }
    (void)HAL_UART_Receive_IT(huart, &rx_byte, 1u);
}

/* ── 5. DMA: приём USART2 — LPDMA1, канал 1 ── */
void uart_rx_dma_start(void)
{
    hal_dma_direct_xfer_config_t x;
    (void)HAL_DMA_Init(&hdma_rx, HAL_LPDMA1_CH1);
    HAL_RCC_LPDMA1_EnableClock();
    x.request = HAL_LPDMA1_REQUEST_USART2_RX;
    x.direction = HAL_DMA_DIRECTION_PERIPH_TO_MEMORY;
    x.src_inc = HAL_DMA_SRC_ADDR_FIXED;
    x.dest_inc = HAL_DMA_DEST_ADDR_INCREMENTED;
    x.src_data_width = HAL_DMA_SRC_DATA_WIDTH_BYTE;
    x.dest_data_width = HAL_DMA_DEST_DATA_WIDTH_BYTE;
    x.priority = HAL_DMA_PRIORITY_HIGH;
    (void)HAL_DMA_SetConfigPeriphDirectXfer(&hdma_rx, &x);
    HAL_CORTEX_NVIC_SetPriority(LPDMA1_CH1_IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_5, HAL_CORTEX_NVIC_SUB_PRIORITY_0);
    HAL_CORTEX_NVIC_EnableIRQ(LPDMA1_CH1_IRQn);
    (void)HAL_UART_SetRxDMA(&huart2, &hdma_rx);
    (void)HAL_UART_AbortReceive(&huart2);   /* снять побайтовый приём по прерыванию */
    rx_dma_mode = 1u;
    (void)HAL_UART_ReceiveToIdle_DMA(&huart2, rx_dma_buf, RX_DMA_SIZE);
}

/* ── 6. Таймер: ШИМ 1 кГц на PA5 и прерывание по переполнению ── */
static volatile uint32_t tim_updates;

void pwm_init(void)
{
    hal_tim_config_t t;
    hal_tim_oc_channel_config_t oc;
    hal_tim_oc_compare_unit_config_t cu;
    (void)HAL_TIM_Init(&htim2, HAL_TIM2);
    HAL_RCC_TIM2_EnableClock();
    t.prescaler = HAL_TIM_GetClockFreq(&htim2) / 1000000u - 1u;   /* счёт 1 МГц */
    t.counter_mode = HAL_TIM_COUNTER_UP;
    t.period = PWM_PERIOD - 1u;
    t.repetition_counter = 0u;
    t.clock_sel.clock_source = HAL_TIM_CLK_INTERNAL;
    (void)HAL_TIM_SetConfig(&htim2, &t);
    oc.polarity = HAL_TIM_OC_HIGH;
    oc.idle_state = HAL_TIM_OC_IDLE_STATE_RESET;
    oc.override_state = HAL_TIM_OC_OVERRIDE_RESET;
    oc.break_mode = HAL_TIM_OC_BREAKMODE_IMMEDIATE;
    (void)HAL_TIM_OC_SetConfigChannel(&htim2, HAL_TIM_CHANNEL_1, &oc);
    cu.mode = HAL_TIM_OC_PWM1;
    cu.pulse = PWM_DUTY_LOW;
    (void)HAL_TIM_OC_SetConfigCompareUnit(&htim2, HAL_TIM_OC_COMPARE_UNIT_1, &cu);
    (void)HAL_TIM_OC_EnableComparePreload(&htim2, HAL_TIM_OC_COMPARE_UNIT_1);
    HAL_CORTEX_NVIC_SetPriority(TIM2_IRQn, HAL_CORTEX_NVIC_PREEMP_PRIORITY_7, HAL_CORTEX_NVIC_SUB_PRIORITY_0);
    HAL_CORTEX_NVIC_EnableIRQ(TIM2_IRQn);
    (void)HAL_TIM_OC_StartChannel(&htim2, HAL_TIM_CHANNEL_1);
    (void)HAL_TIM_Start_IT(&htim2);
}

void TIM2_IRQHandler(void)
{
    HAL_TIM_IRQHandler(&htim2);
}

void HAL_TIM_UpdateCallback(hal_tim_handle_t *htim)
{
    (void)htim;
    tim_updates++;
}

/* ── 7. АЦП: датчик температуры — однократно и непрерывно ── */
static hal_adc_reg_config_t adc_reg;

int adc_init(void)
{
    hal_adc_config_t a;
    hal_adc_channel_config_t ch;
    (void)HAL_ADC_Init(&hadc1, HAL_ADC1);
    HAL_RCC_ADC12_EnableClock();
    (void)HAL_RCC_ADCDAC_SetKernelClkSource(HAL_RCC_ADCDAC_CLK_SRC_PSIS);
    (void)HAL_RCC_ADCDAC_SetKernelClkPrescaler(HAL_RCC_ADCDAC_PRESCALER4);   /* 144 / 4 = 36 МГц */
    a.resolution = HAL_ADC_RESOLUTION_12_BIT;
    a.sampling_mode = HAL_ADC_SAMPLING_MODE_NORMAL;
    (void)HAL_ADC_SetConfig(&hadc1, &a);
    adc_reg.trigger_src = HAL_ADC_REG_TRIG_SOFTWARE;
    adc_reg.sequencer_length = 1;
    adc_reg.sequencer_discont = HAL_ADC_REG_SEQ_DISCONT_DISABLE;
    adc_reg.continuous = HAL_ADC_REG_CONV_SINGLE;
    adc_reg.overrun = HAL_ADC_REG_OVR_DATA_OVERWRITTEN;
    (void)HAL_ADC_REG_SetConfig(&hadc1, &adc_reg);
    ch.group = HAL_ADC_GROUP_REGULAR;
    ch.sequencer_rank = 1;
    ch.sampling_time = HAL_ADC_SAMPLING_TIME_289CYCLES;
    ch.input_mode = HAL_ADC_IN_SINGLE_ENDED;
    (void)HAL_ADC_SetConfigChannel(&hadc1, HAL_ADC_CHANNEL_TEMPSENSOR, &ch);
    if (HAL_ADC_Start(&hadc1) != HAL_OK)        /* стабилизатор, включение, ожидание датчика */
        return -1;
    if (HAL_ADC_Calibrate(&hadc1) != HAL_OK)    /* выключает, калибрует, включает снова */
        return -2;
    return 0;
}

uint32_t adc_read_once(void)
{
    (void)HAL_ADC_REG_StartConv(&hadc1);
    if (HAL_ADC_REG_PollForConv(&hadc1, 2u) != HAL_OK)
        return 0xFFFFu;
    return (uint32_t)HAL_ADC_REG_ReadConversionData(&hadc1);
}

void adc_continuous_start(void)
{
    adc_reg.continuous = HAL_ADC_REG_CONV_CONTINUOUS;
    (void)HAL_ADC_REG_SetConfig(&hadc1, &adc_reg);
    (void)HAL_ADC_REG_StartConv(&hadc1);
}

/* ── 8. I2C1: восстановление шины, настройка, чтение регистра ── */
static void half_bit_delay(void)
{
    for (volatile uint32_t i = SystemCoreClock / 1000000u; i != 0u; i--) {
    }
}

int i2c_bus_recover(void)
{
    hal_gpio_config_t g;
    g.mode = HAL_GPIO_MODE_OUTPUT;
    g.output_type = HAL_GPIO_OUTPUT_OPENDRAIN;
    g.pull = HAL_GPIO_PULL_NO;
    g.speed = HAL_GPIO_SPEED_FREQ_LOW;
    g.alternate = HAL_GPIO_AF_0;
    g.init_state = HAL_GPIO_PIN_SET;
    (void)HAL_GPIO_Init(HAL_GPIOB, HAL_GPIO_PIN_6 | HAL_GPIO_PIN_7, &g);
    int pulses = 0;
    while (HAL_GPIO_ReadPin(HAL_GPIOB, HAL_GPIO_PIN_7) == HAL_GPIO_PIN_RESET && pulses < 9) {
        HAL_GPIO_WritePin(HAL_GPIOB, HAL_GPIO_PIN_6, HAL_GPIO_PIN_RESET);
        half_bit_delay();
        HAL_GPIO_WritePin(HAL_GPIOB, HAL_GPIO_PIN_6, HAL_GPIO_PIN_SET);
        half_bit_delay();
        pulses++;
    }
    HAL_GPIO_WritePin(HAL_GPIOB, HAL_GPIO_PIN_7, HAL_GPIO_PIN_RESET);
    half_bit_delay();
    HAL_GPIO_WritePin(HAL_GPIOB, HAL_GPIO_PIN_7, HAL_GPIO_PIN_SET);
    half_bit_delay();
    return (HAL_GPIO_ReadPin(HAL_GPIOB, HAL_GPIO_PIN_7) == HAL_GPIO_PIN_SET) ? pulses : -1;
}

void i2c_init(void)
{
    hal_gpio_config_t g;
    hal_i2c_config_t c;
    stm32_utils_i2c_timing_basic_config_t tc;
    uint32_t timing = 0u;
    (void)HAL_I2C_Init(&hi2c1, HAL_I2C1);
    HAL_RCC_I2C1_EnableClock();
    (void)HAL_RCC_I2C1_SetKernelClkSource(HAL_RCC_I2C1_CLK_SRC_PCLK1);
    g.mode = HAL_GPIO_MODE_ALTERNATE;
    g.output_type = HAL_GPIO_OUTPUT_OPENDRAIN;
    g.pull = HAL_GPIO_PULL_UP;
    g.speed = HAL_GPIO_SPEED_FREQ_LOW;
    g.alternate = HAL_GPIO_AF_4;
    g.init_state = HAL_GPIO_PIN_RESET;
    (void)HAL_GPIO_Init(HAL_GPIOB, HAL_GPIO_PIN_6 | HAL_GPIO_PIN_7, &g);
    tc.clock_src_freq_hz = HAL_I2C_GetClockFreq(&hi2c1);
    tc.i2c_freq_hz = I2C_SPEED_HZ;
    (void)STM32_UTILS_I2C_ComputeTimingBasic(&tc, &timing);   /* HAL2 сам TIMINGR не считает */
    c.timing = timing;
    c.addressing_mode = HAL_I2C_ADDRESSING_7BIT;
    c.own_address1 = 0u;
    (void)HAL_I2C_SetConfig(&hi2c1, &c);
}

int i2c_read(uint8_t dev, uint8_t reg, uint8_t *buf, uint32_t n)
{
    hal_status_t s = HAL_I2C_MASTER_MemRead(&hi2c1, (uint32_t)dev << 1, reg, HAL_I2C_MEM_ADDR_8BIT, buf, n,
                                            I2C_TIMEOUT_MS);
    if (s == HAL_OK)
        return 0;
    return (s == HAL_TIMEOUT) ? I2C_ERR_TIMEOUT : I2C_ERR_NACK;
}

/* ── проект целиком: тот же порядок и тот же вывод, что в regs/main.c ── */
int main(void)
{
    (void)HAL_Init();                   /* предвыборка флеша, группа приоритетов 4, SysTick 1 мс */
    int clk = clock_init();
    pclk1_hz = HAL_RCC_GetPCLK1Freq();
    gpio_init();
    uart_init();
    print("project: hal2\n");
    if (clk == 0)
        print("clock: PSI %u Hz\n", SystemCoreClock);
    else
        print("clock: error %d, HSIDIV3 %u Hz\n", clk, SystemCoreClock);
    print("uart: BRR 0x%x\n", USART2->BRR);
    volatile float k = 1.5f;
    print("fpu: 1.5 * 1.5 * 1000 = %u\n", (uint32_t)(k * k * 1000.0f));
    pwm_init();
    print("tim2: psc %u arr %u ccr1 %u\n", HAL_TIM_GetPrescaler(&htim2), HAL_TIM_GetPeriod(&htim2),
          HAL_TIM_OC_GetCompareUnitPulse(&htim2, HAL_TIM_OC_COMPARE_UNIT_1));
    uint32_t t0 = HAL_GetTick(), n0 = tim_updates;
    while ((HAL_GetTick() - t0) < 100u) {
    }
    print("tim2: %u updates in 100 ms\n", tim_updates - n0);
    (void)HAL_EXTI_GenerateSWI(&hexti13);
    t0 = HAL_GetTick();
    while ((HAL_GetTick() - t0) < 10u) {
    }
    (void)HAL_EXTI_GenerateSWI(&hexti13);
    t0 = HAL_GetTick();
    while ((HAL_GetTick() - t0) < 100u) {
    }
    (void)HAL_EXTI_GenerateSWI(&hexti13);
    t0 = HAL_GetTick();
    while ((HAL_GetTick() - t0) < 10u) {
    }
    print("button: %u presses of %u edges, ccr1 %u\n", presses, edges,
          HAL_TIM_OC_GetCompareUnitPulse(&htim2, HAL_TIM_OC_COMPARE_UNIT_1));
    if (adc_init() != 0) {
        print("adc: init error\n");
    } else {
        uint32_t a1 = adc_read_once();
        uint32_t a2 = adc_read_once();
        if (a2 == 0xFFFFu) {
            print("adc: EOC timeout\n");
        } else {
            print("adc: raw %u then %u\n", a1, a2);
            adc_continuous_start();
            t0 = HAL_GetTick();
            while ((HAL_GetTick() - t0) < 10u) {
            }
            print("adc: continuous, DR %u\n", (uint32_t)HAL_ADC_REG_ReadConversionData(&hadc1));
        }
    }
    int rec = i2c_bus_recover();
    print("i2c: recovery %d\n", rec);
    i2c_init();
    uint8_t id = 0;
    int r = i2c_read(I2C_DEV, I2C_REG_ID, &id, 1u);
    if (r == 0)
        print("i2c: id 0x%x\n", id);
    else
        print("i2c: error %s\n", (r == I2C_ERR_NACK) ? "nack" : "timeout");
    print("rx: type a line\n");
    t0 = HAL_GetTick();
    while (line_ready == 0u && (HAL_GetTick() - t0) < 3000u) {
    }
    if (line_ready != 0u) {
        line[line_len] = '\0';
        print("rx: '%s'\n", (const char *)line);
    } else {
        print("rx: timeout\n");
    }
    uart_rx_dma_start();
    print("dma: rx armed\n");
    t0 = HAL_GetTick();
    while (rx_dma_events == 0u && (HAL_GetTick() - t0) < 1000u) {
    }
    if (rx_dma_events != 0u) {
        rx_dma_buf[rx_dma_len] = 0u;
        print("dma: %u bytes '%s'\n", rx_dma_len, (const char *)rx_dma_buf);
    } else {
        print("dma: timeout\n");
    }
    print("done\n");
    uart_flush();
    for (;;) {
        __WFI();
    }
}

Next: section 6 "Clocking (RCC)" — the clock tree, the PLL, manual setup for 72 MHz and why a wrong HSE_VALUE breaks all delays.

Open in the interactive handbook