Embedded HandbookApps
All sections › I. Basics
STM32F103 · level basic · 47 min read
Open in the interactive handbook

5в. One project twice on STM32F103: CMSIS and registers only versus HAL — 72 MHz clock, SysTick, GPIO and EXTI, UART with a ring, DMA, PWM, ADC, I2C and comparison

Sections 5 and 5а showed HAL from the inside; sections 6, 7, 8, 9, 13, 16 and 17 covered each F103 block on its own. Here everything is put together into one project for the BluePill board, and this project is written twice. The first uses only CMSIS and the device header stm32f103xb.h: register and bit names, not a single magic number. The second uses HAL. Their behaviour and UART output are the same; the common part without registers lives in a separate file. Every module is shown as a pair of listings: registers first, then HAL.

The project does little but touches almost everything: 72 MHz from the crystal, SysTick at 1 ms, the PC13 LED blinking from the TIM2 interrupt, a PA0 button on EXTI with debouncing, USART1 at 115200 baud with a transmit ring and DMA reception up to a pause on the line, 1 kHz PWM on PB0, the temperature sensor and the reference voltage through the ADC, a BMP280 sensor on I2C1 with recovery of a stuck bus. Commands over UART: pwm N, adc, btn.

Sources: RM0008 (DocID13902 Rev 17) and the STM32F103x8/B datasheet (DocID13587 Rev 17) from the Keil STM32F1xx_DFP 2.4.1 pack — with page numbers; CMSIS headers, the startup file, the linker script and HAL 1.1.10 — from the STM32CubeF1 1.8.7 package. The Keil pack for F1 contains only the old SPL library and no HAL, so HAL is taken from STM32CubeF1.

Terms used in the documentation

Original Meaning
rc_w1 the bit is cleared by writing one, zero has no effect
stabilization time (tSTAB) ADC settling time after power-on
bus recovery, clocking out bus recovery: clock SCL until the slave releases SDA
exclusive store (STREX) a store that succeeds only if nobody touched the word
model of the peripheral a program that answers like a block of the chip
access watchpoint a stop on any read or write of an address

In plain words. The same device is assembled twice: the first time every part is screwed in by hand, the second time with a ready-made tool kit. Both work the same. The section shows how much room the kit took, how many extra moves it makes and in which small details the results still differ.


5в.1 The project, the common part and the test bench

One project twice: on the left the register and HAL projects above the common part app5c.c with flash and RAM sizes, on the right the bench — firmware in QEMU netduino2, F103 registers moved to RAM, a Python model answers for them through gdbserver; at the bottom the run result

Project files:

File Contents Registers
app5c.h, app5c.c ring, own mini-printf, command line assembly, command parsing, temperature calculation none
regs/main.c eight modules on registers RCC->CR, USART1->BRR etc.
hal/main.c, hal/stm32f1xx_hal_conf.h the same eight modules on HAL only through HAL

The common part calls three project functions: board_putc, board_pwm and board_adc. Both projects use the same startup file startup_stm32f103xb.s, the same system_stm32f1xx.c and the same linker script STM32F103XB_FLASH.ld from STM32CubeF1 without changes (how they work — section 4в). Both build with arm-none-eabi-gcc 12.2.1 with -Os -Wall -Wextra -Werror without a single warning — HAL sources included.

QEMU 7.2.22 cannot emulate BluePill. The stm32vldiscovery machine (STM32F100) exists, but only its USART and SPI are real: RCC, GPIO, EXTI, DMA, timers, ADC and I2C are empty stubs that read as zero. So the bench works differently. The Cortex-M3 core with NVIC and SysTick is real, from the netduino2 machine. The firmware is built from the same sources, only with -include stand5c.h: this header moves the F103 peripheral addresses into free RAM. Every register has two watchpoints — on read and on write. After each firmware access QEMU stops, and the model5c.py model answers like the chip per RM0008: raises HSERDY after HSEON, clears IDLE by reading SR, then DR, puts UART bytes into memory by DMA, counts timers, answers for the I2C sensor, pends interrupts in the core NVIC. The run includes a button press with bounce and seven lines over UART.

The output of both projects matched line by line, except one:

clk 72000000
tick 100            ← у HAL: tick 101
i2c bus freed 5
i2c id rc=0 0x58
i2c cal rc=0 70 6b 43 67 18 fc
i2c 0x77 rc=-1
adc t=1748 v=1489 vdda=3300 mV temp=30.1 C
ready
btn 1
pwm 25%
adc t=1748 v=1489 vdda=3300 mV temp=30.1 C
btn 1
? hello
pwm 100%
? xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
pwm 50%

The tick line is not a bench error but a property of HAL_Delay: see 5в.2.


5в.2 Startup, 72 MHz and SysTick

An 8 MHz crystal, PLL × 9 = 72 MHz. The order per RM0008: enable HSE and wait for HSERDY, set the flash wait states, set the dividers and the PLL, enable the PLL and wait for PLLRDY, switch SW and wait until SWS shows the PLL. Two wait states are needed for 48 MHz < SYSCLK ≤ 72 MHz (RM0008, p. 59), the PLL output must not exceed 72 MHz (p. 101), APB1 must not exceed 36 MHz (p. 102), hence its divider of 2. Every wait has a limit: the crystal may not start.

Registers:

static int clock_72mhz(void)
{
    uint32_t t = HSE_TIMEOUT;
    RCC->CR |= RCC_CR_HSEON;
    while (!(RCC->CR & RCC_CR_HSERDY))
        if (--t == 0u)
            return -1;                    /* кварц не завёлся: остаёмся на HSI 8 МГц */

    FLASH->ACR = FLASH_ACR_PRFTBE | FLASH_ACR_LATENCY_1;   /* 2 такта ожидания — ДО разгона */
    RCC->CFGR = RCC_CFGR_HPRE_DIV1 | RCC_CFGR_PPRE1_DIV2   /* APB1 = 36 МГц, предел */
              | RCC_CFGR_PPRE2_DIV1 | RCC_CFGR_ADCPRE_DIV6 /* АЦП = 12 МГц */
              | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL9;       /* PLL = HSE × 9 */
    RCC->CR |= RCC_CR_PLLON;
    for (t = HSE_TIMEOUT; !(RCC->CR & RCC_CR_PLLRDY);)
        if (--t == 0u)
            return -2;
    RCC->CFGR |= RCC_CFGR_SW_PLL;
    for (t = HSE_TIMEOUT; (RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL;)
        if (--t == 0u)
            return -3;
    return 0;
}

HAL:

static int clock_72mhz(void)
{
    RCC_OscInitTypeDef osc = {0};
    RCC_ClkInitTypeDef clk = {0};
    RCC_PeriphCLKInitTypeDef per = {0};
    osc.OscillatorType = RCC_OSCILLATORTYPE_HSE;
    osc.HSEState = RCC_HSE_ON;
    osc.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    osc.PLL.PLLState = RCC_PLL_ON;
    osc.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    osc.PLL.PLLMUL = RCC_PLL_MUL9;
    if (HAL_RCC_OscConfig(&osc) != HAL_OK)
        return -1;
    clk.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    clk.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    clk.AHBCLKDivider = RCC_SYSCLK_DIV1;
    clk.APB1CLKDivider = RCC_HCLK_DIV2;
    clk.APB2CLKDivider = RCC_HCLK_DIV1;
    if (HAL_RCC_ClockConfig(&clk, FLASH_LATENCY_2) != HAL_OK)  /* сама ставит такты ожидания */
        return -3;
    per.PeriphClockSelection = RCC_PERIPHCLK_ADC;
    per.AdcClockSelection = RCC_ADCPCLK2_DIV6;
    HAL_RCCEx_PeriphCLKConfig(&per);
    return 0;
}

HAL does the same, but also checks the parameters, turns the PLL off and on again, re-reads the frequencies and reconfigures SysTick for the new frequency by itself. On the bench the setup took 32 instructions on registers and 487 instructions with HAL — even though the model raises the ready flags at once.

Here is the first trap of the header. FLASH_ACR_LATENCY_1 is the value 2, that is two wait states. FLASH_ACR_LATENCY_2 is bit 2, value 4, and F1 has no such code (p. 59: 000, 001 and 010 are allowed). In HAL the same confusion is hidden: FLASH_LATENCY_2 is defined as FLASH_ACR_LATENCY_1.

SysTick on registers is one CMSIS function:

void SysTick_Handler(void)
{
    ms++;
}
static void delay_ms(uint32_t n)
{
    uint32_t t0 = ms;
    while (ms - t0 < n) {
    }
}
    SystemCoreClockUpdate();              /* SystemCoreClock — по регистрам RCC */
    NVIC_SetPriorityGrouping(3u);         /* 4 бита — вытесняющий приоритет, как у HAL */
    SysTick_Config(SystemCoreClock / 1000u);
    NVIC_SetPriority(SysTick_IRQn, 0u);   /* SysTick_Config ставит 15 — самый низкий */

SysTick_Config gives SysTick the lowest priority 15 — it has to be raised separately, otherwise a delay inside an interrupt hangs. With HAL HAL_Init does it using TICK_INT_PRIORITY from stm32f1xx_hal_conf.h; the template has 0x0F, our project uses 0.

Now the tick line. The register project waits 100 ms as while (ms - t0 < n) and measures exactly 100 ticks. HAL_Delay(100) measures 101: in stm32f1xx_hal.c one tick is added to the delay so that the wait is never shorter than requested:

  /* Add a freq to guarantee minimum wait */
  if (wait < HAL_MAX_DELAY)

5в.3 GPIO and a button on EXTI

The PA0 button shorts to ground: an input with pull-up, interrupt on the falling edge. The contact bounces, so the handler masks the line, and the main loop checks after 20 ms whether the button is still pressed.

Registers:

static void gpio_init(void)
{
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN
                  | RCC_APB2ENR_AFIOEN;
    (void)RCC->APB2ENR;                   /* дождаться такта, прежде чем писать в порт */

    GPIOC->BSRR = GPIO_BSRR_BS13;         /* светодиод погашен (горит нулём) */
    GPIOC->CRH = (GPIOC->CRH & ~(GPIO_CRH_MODE13 | GPIO_CRH_CNF13)) | GPIO_CRH_MODE13_1;  /* выход 2 МГц */

    GPIOA->CRL = (GPIOA->CRL & ~(GPIO_CRL_MODE0 | GPIO_CRL_CNF0)) | GPIO_CRL_CNF0_1;     /* вход с подтяжкой */
    GPIOA->BSRR = GPIO_BSRR_BS0;          /* подтяжка вверх */
    AFIO->EXTICR[0] = (AFIO->EXTICR[0] & ~AFIO_EXTICR1_EXTI0) | AFIO_EXTICR1_EXTI0_PA;
    EXTI->FTSR |= EXTI_FTSR_TR0;          /* нажатие — спад */
    EXTI->PR = EXTI_PR_PR0;               /* сброс записью единицы, не через |= */
    EXTI->IMR |= EXTI_IMR_MR0;
    NVIC_SetPriority(EXTI0_IRQn, 3u);
    NVIC_EnableIRQ(EXTI0_IRQn);
}
void EXTI0_IRQHandler(void)
{
    EXTI->PR = EXTI_PR_PR0;
    EXTI->IMR &= ~EXTI_IMR_MR0;           /* дребезг: линию глушим на 20 мс */
    btn_t0 = ms;
    btn_wait = 1u;
}

HAL:

static void gpio_init(void)
{
    GPIO_InitTypeDef g = {0};
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_AFIO_CLK_ENABLE();

    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
    g.Pin = GPIO_PIN_13;
    g.Mode = GPIO_MODE_OUTPUT_PP;
    g.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOC, &g);

    g.Pin = GPIO_PIN_0;
    g.Mode = GPIO_MODE_IT_FALLING;        /* EXTI, AFIO и фронт — одним вызовом */
    g.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(GPIOA, &g);
    HAL_NVIC_SetPriority(EXTI0_IRQn, 3u, 0u);
    HAL_NVIC_EnableIRQ(EXTI0_IRQn);
}
void HAL_GPIO_EXTI_Callback(uint16_t pin)
{
    if (pin == GPIO_PIN_0) {
        HAL_NVIC_DisableIRQ(EXTI0_IRQn);  /* у HAL нет вызова «заглушить линию» */
        btn_t0 = HAL_GetTick();
        btn_wait = 1u;
    }
}

HAL_GPIO_Init with GPIO_MODE_IT_FALLING sets the AFIO line, the falling edge and the EXTI mask by itself. HAL has no call to "mask one EXTI line", so the HAL project disables the interrupt in NVIC and, before enabling it again, clears both the EXTI flag and the NVIC pending bit. In the model the button produced five edges within 4 ms; both projects counted one press: btn 1. The EXTI0 handler took 13 instructions on registers and 38 with HAL.

EXTI->PR = EXTI_PR_PR0 is a write, not |=: the PR bit is cleared by writing one (rc_w1). With |= every raised flag of the register would be read and cleared, not only our own.


5в.4 UART: a transmit ring, DMA reception up to a pause

USART1 at 115200 baud: BRR = 72000000 / 115200 = 625 (0x271). In RM0008 USARTDIV = DIV_Mantissa + DIV_Fraction / 16 (p. 790), here 39 + 1/16 = 39.0625, and the model obtained exactly 115200 baud from BRR and the APB2 frequency.

Transmission goes from a 128-byte ring. The main code puts a byte and enables the TXE interrupt, the handler takes one byte at a time. On registers:

void board_putc(char c)
{
    while (!ring_put(&tx, (uint8_t)c)) {
    }                                     /* кольцо полно: ждём, прерывание освобождает */
    uint32_t pm = __get_PRIMASK();
    __disable_irq();                      /* CR1 правят и здесь, и в прерывании */
    USART1->CR1 |= USART_CR1_TXEIE;
    __set_PRIMASK(pm);
}
void USART1_IRQHandler(void)
{
    uint32_t sr = USART1->SR;
    if (sr & USART_SR_IDLE) {
        (void)USART1->DR;                 /* IDLE снимается чтением SR, затем DR */
        rx_drain();
    }
    if ((USART1->CR1 & USART_CR1_TXEIE) && (sr & USART_SR_TXE)) {
        uint8_t b;
        if (ring_get(&tx, &b))
            USART1->DR = b;
        else
            USART1->CR1 &= ~USART_CR1_TXEIE;  /* нечего слать — молчим */
    }
}

CR1 is changed both by the main code and by the interrupt, so setting TXEIE is guarded by disabling interrupts: otherwise an interrupt between the read and the write of CR1 clears TXEIE, and the main code writes the old value back.

HAL cannot send "byte by byte from a ring". It sends a buffer chunk by interrupts and calls HAL_UART_TxCpltCallback at the end. So the ring hands HAL a contiguous chunk, and the callback starts the next one:

static void tx_kick(void)                 /* вызывать с запрещёнными прерываниями */
{
    const uint8_t *p;
    if (huart1.gState != HAL_UART_STATE_READY)
        return;
    tx_n = ring_chunk(&tx, &p);
    if (tx_n != 0u)
        HAL_UART_Transmit_IT(&huart1, (uint8_t *)p, tx_n);
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *h)
{
    (void)h;
    ring_skip(&tx, tx_n);
    tx_kick();
}

Reception uses DMA1 channel 5 (per table 78 of RM0008, p. 281, this is USART1_RX), circular over a 64-byte buffer. The end of a line is caught by the IDLE flag: the line is silent for a whole frame. It is cleared by reading SR, then DR (p. 820). On registers:

static void rx_dma_init(void)
{
    RCC->AHBENR |= RCC_AHBENR_DMA1EN;
    DMA1_Channel5->CPAR = (uint32_t)&USART1->DR;
    DMA1_Channel5->CMAR = (uint32_t)rx_dma;
    DMA1_Channel5->CNDTR = RX_SIZE;
    DMA1_Channel5->CCR = DMA_CCR_MINC | DMA_CCR_CIRC | DMA_CCR_EN;  /* периферия → память, байты */
}
static void rx_drain(void)                /* всё, что DMA успел положить с прошлого раза */
{
    uint32_t end = RX_SIZE - DMA1_Channel5->CNDTR;
    while (rx_pos != end) {
        app_rx_byte(rx_dma[rx_pos]);
        rx_pos = (rx_pos + 1u) % RX_SIZE;
    }
}

With HAL it is HAL_UARTEx_ReceiveToIdle_DMA: the callback receives how many bytes of the buffer are already filled and comes three times — on a pause, at the half and at the end of the buffer:

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *h, uint16_t end)
{
    (void)h;                              /* end — сколько байт буфера занято: пауза, половина, конец */
    while (rx_pos != end % RX_SIZE) {
        app_rx_byte(rx_dma[rx_pos]);
        rx_pos = (rx_pos + 1u) % RX_SIZE;
    }
}

A line of 40 x characters went through the end of the buffer (64 bytes) — both projects assembled it and cut it to 31 characters, as intended in app5c.c.

One transmit interrupt (the twentieth) took 36 instructions on registers and 81 with HAL.


5в.5 Timers, ADC and I2C

PWM and period. Timers on APB1 are clocked at twice the bus frequency if its divider is not 1: 36 × 2 = 72 MHz. TIM3_CH3 on PB0: PSC = 71 → 1 MHz, ARR = 999 → 1 kHz, CCR3 = percent × 10. TIM2: PSC = 7199, ARR = 999 → 10 Hz, PC13 toggles in its interrupt.

static void tim_init(void)
{
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN;
    GPIOB->CRL = (GPIOB->CRL & ~(GPIO_CRL_MODE0 | GPIO_CRL_CNF0)) | GPIO_CRL_MODE0_1 | GPIO_CRL_CNF0_1;

    TIM3->PSC = TIM_CLK / 1000000u - 1u;  /* 1 МГц */
    TIM3->ARR = 1000u - 1u;               /* 1 кГц */
    TIM3->CCR3 = 0u;
    TIM3->CCMR2 = TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1 | TIM_CCMR2_OC3PE;  /* ШИМ, режим 1 */
    TIM3->CCER = TIM_CCER_CC3E;
    TIM3->CR1 = TIM_CR1_ARPE;
    TIM3->EGR = TIM_EGR_UG;               /* загрузить PSC и теневые регистры */
    TIM3->CR1 |= TIM_CR1_CEN;

    TIM2->PSC = TIM_CLK / 10000u - 1u;    /* 10 кГц */
    TIM2->ARR = 1000u - 1u;               /* 10 Гц */
    TIM2->EGR = TIM_EGR_UG;
    TIM2->SR = ~TIM_SR_UIF;               /* UG поднял UIF — иначе прерывание сразу */
    TIM2->DIER = TIM_DIER_UIE;
    TIM2->CR1 = TIM_CR1_CEN;
    NVIC_SetPriority(TIM2_IRQn, 4u);
    NVIC_EnableIRQ(TIM2_IRQn);
}

TIM_EGR_UG loads the prescaler at once, but also raises UIF — without clearing it the interrupt would come immediately. HAL 1.1.10 does the same by itself: TIM_Base_SetConfig checks and clears UIF after UG. From the registers of both projects the model obtained the same: TIM3 — 1000 Hz, after pwm 50 a 50 % duty; TIM2 — 10 Hz. The TIM2 handler took 14 instructions on registers and 44 with HAL.

ADC. The ADC clock must not exceed 14 MHz (RM0008, p. 214), so 72 / 6 = 12 MHz. The temperature sensor is channel 16, the reference is channel 17, bit TSVREFE. The sensor sampling time must be at least 17.1 µs (datasheet, p. 79), so 239.5 cycles: at 12 MHz this is 19.96 µs.

static void adc_init(void)
{
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
    ADC1->SMPR1 = ADC_SMPR1_SMP16 | ADC_SMPR1_SMP17;   /* 239,5 такта: 20 мкс при 12 МГц */
    ADC1->CR2 = ADC_CR2_ADON;                          /* включить */
    spin(2u);                                          /* tSTAB — 1 мкс */
    ADC1->CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_EXTSEL | ADC_CR2_EXTTRIG;
    ADC1->CR2 |= ADC_CR2_RSTCAL;
    while (ADC1->CR2 & ADC_CR2_RSTCAL) {
    }
    ADC1->CR2 |= ADC_CR2_CAL;
    while (ADC1->CR2 & ADC_CR2_CAL) {
    }
}
uint32_t board_adc(uint32_t ch)
{
    ADC1->SQR3 = ch;                      /* один канал в очереди */
    ADC1->CR2 |= ADC_CR2_SWSTART;
    for (uint32_t t = I2C_TIMEOUT; !(ADC1->SR & ADC_SR_EOC);)
        if (--t == 0u)
            return 0u;
    return ADC1->DR;                      /* чтение DR снимает EOC */
}

F103 has a quirk: a conversion is started by writing ADON = 1 again (p. 217), but not when another bit changes in the same write (p. 242). So power-on and setup are two separate writes, and the start goes through SWSTART with EXTSEL = 111. Calibration is allowed only with the ADC on (p. 222). HAL does the same inside HAL_ADCEx_Calibration_Start and HAL_ADC_ConfigChannel:

uint32_t board_adc(uint32_t ch)
{
    ADC_ChannelConfTypeDef c = {0};
    c.Channel = ch;                       /* ADC_CHANNEL_16 == 16 */
    c.Rank = ADC_REGULAR_RANK_1;
    c.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
    HAL_ADC_ConfigChannel(&hadc1, &c);    /* для 16 и 17 сама ставит TSVREFE */
    HAL_ADC_Start(&hadc1);
    if (HAL_ADC_PollForConversion(&hadc1, 10u) != HAL_OK)
        return 0u;
    return HAL_ADC_GetValue(&hadc1);
}

F103 has no factory calibration of the sensor. app5c.c takes the typical V25 = 1.43 V and slope 4.3 mV/°C (p. 79) and VREFINT = 1.20 V (p. 41). The model returns 1748 for the sensor and 1489 for the reference; both projects computed VDDA = 3300 mV and 30.1 °C. The first measurement took 12 instructions on registers and 5235 with HAL. Almost all of it is the 10 µs pause in HAL_ADC_ConfigChannel after enabling the sensor, done by a counting loop.

I2C. If a reset came in the middle of a byte, the slave holds SDA, and the master cannot start. The cure: before enabling I2C, clock SCL as a plain open-drain pin until SDA is released (at most 9 times), then send STOP:

static uint32_t i2c_unstick(void)
{
    uint32_t n = 0;
    GPIOB->BSRR = GPIO_BSRR_BS6 | GPIO_BSRR_BS7;
    GPIOB->CRL = (GPIOB->CRL & ~(GPIO_CRL_MODE6 | GPIO_CRL_CNF6 | GPIO_CRL_MODE7 | GPIO_CRL_CNF7))
               | GPIO_CRL_MODE6_1 | GPIO_CRL_CNF6_0 | GPIO_CRL_MODE7_1 | GPIO_CRL_CNF7_0;  /* открытый сток */
    while (!(GPIOB->IDR & GPIO_IDR_IDR7) && n < 9u) {  /* ведомый держит SDA: тактуем SCL */
        GPIOB->BSRR = GPIO_BSRR_BR6;
        spin(5u);
        GPIOB->BSRR = GPIO_BSRR_BS6;
        spin(5u);
        n++;
    }
    GPIOB->BSRR = GPIO_BSRR_BR7;          /* STOP: SDA вверх при высоком SCL */
    spin(5u);
    GPIOB->BSRR = GPIO_BSRR_BS7;
    return n;
}

In the model the slave releases SDA on the fifth clock — both projects printed i2c bus freed 5. I2C1 at 100 kHz is set up as in section 17: with APB1 = 36 MHz CCR = 180, TRISE = 37. Reading registers: write the register number, repeated start, read N bytes. One byte and the last three are read in a special order (RM0008, p. 764): clear ACK before clearing ADDR, set STOP on time.

static int i2c_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint32_t n)
{
    int rc;
    for (uint32_t t = I2C_TIMEOUT; I2C1->SR2 & I2C_SR2_BUSY;)
        if (--t == 0u)
            return I2C_TMO;
    I2C1->CR1 |= I2C_CR1_ACK | I2C_CR1_START;
    if ((rc = i2c_wait(I2C_SR1_SB)) != 0)
        return rc;
    I2C1->DR = (uint32_t)addr << 1;       /* запись: номер регистра */
    if ((rc = i2c_wait(I2C_SR1_ADDR)) != 0)
        return rc;
    (void)I2C1->SR2;                      /* ADDR снимается чтением SR1, затем SR2 */
    I2C1->DR = reg;
    if ((rc = i2c_wait(I2C_SR1_BTF)) != 0)
        return rc;
    I2C1->CR1 |= I2C_CR1_START;           /* повторный старт */
    if ((rc = i2c_wait(I2C_SR1_SB)) != 0)
        return rc;
    I2C1->DR = ((uint32_t)addr << 1) | 1u;
    if ((rc = i2c_wait(I2C_SR1_ADDR)) != 0)
        return rc;
    if (n == 1u) {                        /* RM0008: ACK снять до сброса ADDR */
        I2C1->CR1 &= ~I2C_CR1_ACK;
        __disable_irq();
        (void)I2C1->SR2;
        I2C1->CR1 |= I2C_CR1_STOP;
        __enable_irq();
        if ((rc = i2c_wait(I2C_SR1_RXNE)) != 0)
            return rc;
        buf[0] = (uint8_t)I2C1->DR;
        return 0;
    }
    (void)I2C1->SR2;
    while (n > 3u) {                      /* байты с ACK, пока не останется три */
        if ((rc = i2c_wait(I2C_SR1_RXNE)) != 0)
            return rc;
        *buf++ = (uint8_t)I2C1->DR;
        n--;
    }
    if ((rc = i2c_wait(I2C_SR1_BTF)) != 0)  /* N-2 в DR, N-1 в сдвиговом */
        return rc;
    I2C1->CR1 &= ~I2C_CR1_ACK;            /* последний байт — с NACK */
    *buf++ = (uint8_t)I2C1->DR;
    if ((rc = i2c_wait(I2C_SR1_BTF)) != 0)
        return rc;
    I2C1->CR1 |= I2C_CR1_STOP;
    *buf++ = (uint8_t)I2C1->DR;
    *buf = (uint8_t)I2C1->DR;
    return 0;
}

HAL is one call to HAL_I2C_Mem_Read with the same order inside. Its error code is different (HAL_ERROR and HAL_I2C_ERROR_AF), so i2c_read in the HAL project translates it into the same −1 on NACK:

static int i2c_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint32_t n)
{
    HAL_StatusTypeDef st = HAL_I2C_Mem_Read(&hi2c1, (uint16_t)(addr << 1), reg,
                                            I2C_MEMADD_SIZE_8BIT, buf, (uint16_t)n, 10u);
    if (st == HAL_OK)
        return 0;
    return (hi2c1.ErrorCode & HAL_I2C_ERROR_AF) ? -1 : -2;   /* как у проекта на регистрах */
}

Reading six bytes took 169 instructions on registers and 482 with HAL. Address 0x77 does not answer in the model: both projects returned −1.


5в.6 Comparison: memory, instructions, registers

Sizes from arm-none-eabi-size (-Os build, BluePill). Flash: vectors, code, constants and the initial values of .data; RAM: .data and .bss, without the heap and stack reserve of the linker script (1536 bytes for registers, 1540 for HAL):

Registers HAL
flash, bytes 3476 13460
RAM, bytes 320 748
functions in the image 24 99
armclang 6.24: Code + RO + RW, bytes 4180 14168

The number of instructions from entering a function to leaving it, stepped in QEMU. The model answers at once, there are no crystal or bus waits, so this is the pure cost of the code. Clock cycles were not measured: QEMU does not count them.

What Registers HAL
from reset to main 379 811
clock setup 32 487
USART1 setup 43 721
reading 6 bytes over I2C 169 482
first ADC measurement 12 5235
UART transmit interrupt 36 81
EXTI0 interrupt 13 38
TIM2 interrupt 14 44

From reset to main HAL is longer only because of zeroing .bss: 736 bytes versus 316, the startup code is the same.

At the end of the run the model dumped all registers. RCC, FLASH, the timers, the ADC (except flags), USART1 (except CR3) and GPIOA/GPIOC matched to the bit. Five places differ, and each has a reason:

Register Registers HAL Why
I2C1_OAR1 0x0000 0x4000 bit 14 "keep at 1" (RM0008, p. 777); HAL writes it through I2C_ADDRESSINGMODE_7BIT, the device header has no name for the bit
GPIOB_CRL (PB6, PB7) 0xE 0xF HAL selects 50 MHz speed, the register project 2 MHz
USART1_CR3 0x40 0x41 HAL enables the reception error interrupt EIE
DMA1_CCR5, DMA1_ISR 0xA1, flags set 0xAF, flags cleared HAL enables DMA half, complete and error interrupts and clears the flags in the handler
ADC1_SR STRT set 0 HAL clears STRT together with EOC

Convenience and risks:

Registers HAL
amount of own code more lines per module fewer, but more settings in structures
what is written to the hardware all visible only through the debugger or HAL sources
header traps (LATENCY_2, rc_w1) yours covered by HAL macros
shared resource (CR1 from two places) protect it yourself HAL uses LDREX/STREX
moving to another series rewrite mostly change the header and the package
time in an interrupt 2–3 times less more

5в.7 Pitfalls

A register reads as zero, a write is lost. The block clock is not enabled in RCC->APBxENR. Order: enable the clock, read the enable register back (in gpio_init this is (void)RCC->APB2ENR), only then configure.

The frequency is raised, the program crashes. The flash wait states were set after switching to the PLL. First FLASH->ACR, then SW.

FLASH_ACR_LATENCY_2 instead of two wait states. In the header it is bit 2, value 4 — F1 has no such code (RM0008, p. 59). Two wait states are FLASH_ACR_LATENCY_1.

Clearing a flag with |=. EXTI->PR |= EXTI_PR_PR0 clears all raised flags of the register (rc_w1). rc_w0 flags (TIMx->SR, I2C1->SR1) are cleared by writing "all ones except the one": TIM2->SR = ~TIM_SR_UIF.

An interrupt right after starting a timer. TIM_EGR_UG raises UIF. Clear the flag before DIER = TIM_DIER_UIE.

SysTick_Config means the lowest priority. A SysTick delay inside another interrupt waits forever. Raise the SysTick priority explicitly.

The ADC does not start or starts by itself. Writing ADON = 1 again is a start, but only if nothing else in CR2 changes (p. 217 and 242).

volatile and disabling interrupts. Without volatile the compiler reads the ms counter and the button flags once. The shared CR1 register is changed by both the main code and the interrupt: guard the change with __disable_irq and restore the previous PRIMASK.

The model does not see STREX. This is a bench pitfall, not a chip one: HAL sets CR1 and CR3 bits through LDREX/STREX (ATOMIC_SET_BIT), and a QEMU watchpoint does not fire on such a store. The model compares all registers on every SysTick tick and on every read — so the write is not lost.


5в.8 Summary


Full sources

app5c.h — common header of both projects

/* app5c.h — общая часть обоих проектов раздела 5в: кольцо, вывод, команды.
 * Ни одного регистра: железо — в main.c проекта (регистры или HAL). */
#ifndef APP5C_H
#define APP5C_H
#include <stdint.h>

#define RING_SIZE 128u                    /* кольцо передачи UART */

typedef struct {
    volatile uint16_t head;               /* пишет основной код */
    volatile uint16_t tail;               /* читает прерывание */
    uint8_t buf[RING_SIZE];
} ring_t;

int ring_put(ring_t *r, uint8_t b);       /* 0 — кольцо полно */
int ring_get(ring_t *r, uint8_t *b);      /* 0 — кольцо пусто */
uint16_t ring_chunk(const ring_t *r, const uint8_t **p); /* сплошной кусок от tail */
void ring_skip(ring_t *r, uint16_t n);

void out_printf(const char *fmt, ...);    /* %u %d %x %s %c, ширина с нулём: %02x */
void app_rx_byte(uint8_t c);              /* из прерывания: очередной принятый байт */
int app_take_line(char *out, uint32_t size); /* из основного цикла: 1 — есть строка */
void app_command(const char *s);
void app_adc_report(void);
void app_button(void);

/* это пишет каждый проект сам */
void board_putc(char c);
void board_pwm(uint32_t pct);
uint32_t board_adc(uint32_t ch);

#endif

app5c.c — common part: ring, output, commands

/* app5c.c — общая часть обоих проектов раздела 5в. Без регистров и без HAL. */
#include <stdarg.h>
#include "app5c.h"

int ring_put(ring_t *r, uint8_t b)
{
    uint16_t h = r->head;
    uint16_t n = (uint16_t)((h + 1u) % RING_SIZE);
    if (n == r->tail)
        return 0;                         /* одна ячейка всегда пустая: так «полно» ≠ «пусто» */
    r->buf[h] = b;
    r->head = n;                          /* индекс — после данных */
    return 1;
}

int ring_get(ring_t *r, uint8_t *b)
{
    uint16_t t = r->tail;
    if (t == r->head)
        return 0;
    *b = r->buf[t];
    r->tail = (uint16_t)((t + 1u) % RING_SIZE);
    return 1;
}

uint16_t ring_chunk(const ring_t *r, const uint8_t **p)
{
    uint16_t h = r->head, t = r->tail;
    *p = &r->buf[t];
    return (uint16_t)(h >= t ? (uint32_t)h - t : RING_SIZE - t);
}

void ring_skip(ring_t *r, uint16_t n)
{
    r->tail = (uint16_t)((r->tail + n) % RING_SIZE);
}

static void out_num(uint32_t v, uint32_t base, uint32_t width, char pad)
{
    char tmp[11];
    uint32_t n = 0;
    do {
        uint32_t d = v % base;
        tmp[n++] = (char)(d < 10u ? '0' + d : 'a' + d - 10u);
        v /= base;
    } while (v != 0u);
    while (n < width--)
        board_putc(pad);
    while (n != 0u)
        board_putc(tmp[--n]);
}

void out_printf(const char *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    for (; *fmt != '\0'; fmt++) {
        if (*fmt != '%') {
            if (*fmt == '\n')
                board_putc('\r');
            board_putc(*fmt);
            continue;
        }
        char pad = ' ';
        uint32_t width = 0;
        if (*++fmt == '0')
            pad = *fmt++;
        while (*fmt >= '0' && *fmt <= '9')
            width = width * 10u + (uint32_t)(*fmt++ - '0');
        switch (*fmt) {
        case 'u': out_num(va_arg(ap, uint32_t), 10u, width, pad); break;
        case 'x': out_num(va_arg(ap, uint32_t), 16u, width, pad); break;
        case 'd': {
            int32_t v = va_arg(ap, int32_t);
            if (v < 0) {
                board_putc('-');
                v = -v;
            }
            out_num((uint32_t)v, 10u, width, pad);
            break;
        }
        case 's':
            for (const char *s = va_arg(ap, const char *); *s != '\0'; s++)
                board_putc(*s);
            break;
        case 'c': board_putc((char)va_arg(ap, int)); break;
        default: board_putc(*fmt); break;
        }
    }
    va_end(ap);
}

/* ── строка команды: собирается в прерывании, разбирается в основном цикле ── */
static char rx_line[32];
static uint32_t rx_len;
static char ready_line[32];
static volatile uint32_t line_ready;

void app_rx_byte(uint8_t c)
{
    if (c == '\r' || c == '\n') {
        if (rx_len != 0u && !line_ready) {
            for (uint32_t i = 0; i <= rx_len; i++)
                ready_line[i] = i < rx_len ? rx_line[i] : '\0';
            line_ready = 1u;
        }
        rx_len = 0;
    } else if (rx_len < sizeof rx_line - 1u) {
        rx_line[rx_len++] = (char)c;
    }
}

int app_take_line(char *out, uint32_t size)
{
    if (!line_ready)
        return 0;
    uint32_t i = 0;
    for (; i + 1u < size && ready_line[i] != '\0'; i++)
        out[i] = ready_line[i];
    out[i] = '\0';
    line_ready = 0u;
    return 1;
}

static volatile uint32_t btn_count;

void app_button(void)
{
    btn_count++;
    out_printf("btn %u\n", btn_count);
}

/* Датчик температуры F103 калибровки не имеет: берём типовые V25 = 1,43 В
 * и наклон 4,3 мВ/°C из описания микросхемы, VDDA — через опорное 1,20 В. */
void app_adc_report(void)
{
    uint32_t t = board_adc(16u);
    uint32_t v = board_adc(17u);
    if (v == 0u) {
        out_printf("adc error\n");
        return;
    }
    uint32_t vdda = 1200u * 4095u / v;              /* мВ */
    uint32_t vs = t * vdda / 4095u;                 /* мВ на датчике */
    int32_t t10 = ((int32_t)1430 - (int32_t)vs) * 100 / 43 + 250;  /* десятые °C */
    out_printf("adc t=%u v=%u vdda=%u mV temp=%d.%u C\n", t, v, vdda,
               t10 / 10, (uint32_t)(t10 < 0 ? -t10 : t10) % 10u);
}

void app_command(const char *s)
{
    if (s[0] == 'p' && s[1] == 'w' && s[2] == 'm' && s[3] == ' ') {
        uint32_t pct = 0;
        for (s += 4; *s >= '0' && *s <= '9'; s++)
            pct = pct * 10u + (uint32_t)(*s - '0');
        if (pct > 100u)
            pct = 100u;
        board_pwm(pct);
        out_printf("pwm %u%%\n", pct);
    } else if (s[0] == 'a' && s[1] == 'd' && s[2] == 'c' && s[3] == '\0') {
        app_adc_report();
    } else if (s[0] == 'b' && s[1] == 't' && s[2] == 'n' && s[3] == '\0') {
        out_printf("btn %u\n", btn_count);
    } else {
        out_printf("? %s\n", s);
    }
}

regs/main.c — the project on CMSIS and registers

/* main.c — раздел 5в, проект на регистрах: только CMSIS (core_cm3.h) и заголовок
 * устройства stm32f103xb.h. Плата BluePill: кварц 8 МГц, светодиод PC13,
 * кнопка PA0 на землю, USART1 PA9/PA10, ШИМ TIM3_CH3 на PB0, I2C1 PB6/PB7. */
#include "stm32f1xx.h"
#include "app5c.h"

#define HSE_TIMEOUT   50000u              /* опросов флага готовности */
#define I2C_TIMEOUT   20000u
#define BTN_DEBOUNCE  20u                 /* мс */
#define BMP280        0x76u               /* адрес датчика на I2C1 */

/* ── 1. Тактирование: HSE 8 МГц × 9 = 72 МГц ──────────────────────────── */
static int clock_72mhz(void)
{
    uint32_t t = HSE_TIMEOUT;
    RCC->CR |= RCC_CR_HSEON;
    while (!(RCC->CR & RCC_CR_HSERDY))
        if (--t == 0u)
            return -1;                    /* кварц не завёлся: остаёмся на HSI 8 МГц */

    FLASH->ACR = FLASH_ACR_PRFTBE | FLASH_ACR_LATENCY_1;   /* 2 такта ожидания — ДО разгона */
    RCC->CFGR = RCC_CFGR_HPRE_DIV1 | RCC_CFGR_PPRE1_DIV2   /* APB1 = 36 МГц, предел */
              | RCC_CFGR_PPRE2_DIV1 | RCC_CFGR_ADCPRE_DIV6 /* АЦП = 12 МГц */
              | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL9;       /* PLL = HSE × 9 */
    RCC->CR |= RCC_CR_PLLON;
    for (t = HSE_TIMEOUT; !(RCC->CR & RCC_CR_PLLRDY);)
        if (--t == 0u)
            return -2;
    RCC->CFGR |= RCC_CFGR_SW_PLL;
    for (t = HSE_TIMEOUT; (RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL;)
        if (--t == 0u)
            return -3;
    return 0;
}

/* ── 2. SysTick: 1 мс ─────────────────────────────────────────────────── */
static volatile uint32_t ms;

void SysTick_Handler(void)
{
    ms++;
}

static void delay_ms(uint32_t n)
{
    uint32_t t0 = ms;
    while (ms - t0 < n) {
    }
}

static void spin(uint32_t n)              /* короткая пауза для ног I2C, ~n мкс */
{
    for (volatile uint32_t i = 0; i < n * (SystemCoreClock / 4000000u); i++) {
    }
}

/* ── 3. GPIO, кнопка на EXTI0 с антидребезгом ─────────────────────────── */
static volatile uint32_t btn_t0, btn_wait;

static void gpio_init(void)
{
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN
                  | RCC_APB2ENR_AFIOEN;
    (void)RCC->APB2ENR;                   /* дождаться такта, прежде чем писать в порт */

    GPIOC->BSRR = GPIO_BSRR_BS13;         /* светодиод погашен (горит нулём) */
    GPIOC->CRH = (GPIOC->CRH & ~(GPIO_CRH_MODE13 | GPIO_CRH_CNF13)) | GPIO_CRH_MODE13_1;  /* выход 2 МГц */

    GPIOA->CRL = (GPIOA->CRL & ~(GPIO_CRL_MODE0 | GPIO_CRL_CNF0)) | GPIO_CRL_CNF0_1;     /* вход с подтяжкой */
    GPIOA->BSRR = GPIO_BSRR_BS0;          /* подтяжка вверх */
    AFIO->EXTICR[0] = (AFIO->EXTICR[0] & ~AFIO_EXTICR1_EXTI0) | AFIO_EXTICR1_EXTI0_PA;
    EXTI->FTSR |= EXTI_FTSR_TR0;          /* нажатие — спад */
    EXTI->PR = EXTI_PR_PR0;               /* сброс записью единицы, не через |= */
    EXTI->IMR |= EXTI_IMR_MR0;
    NVIC_SetPriority(EXTI0_IRQn, 3u);
    NVIC_EnableIRQ(EXTI0_IRQn);
}

void EXTI0_IRQHandler(void)
{
    EXTI->PR = EXTI_PR_PR0;
    EXTI->IMR &= ~EXTI_IMR_MR0;           /* дребезг: линию глушим на 20 мс */
    btn_t0 = ms;
    btn_wait = 1u;
}

static void button_poll(void)
{
    if (btn_wait && ms - btn_t0 >= BTN_DEBOUNCE) {
        btn_wait = 0u;
        if (!(GPIOA->IDR & GPIO_IDR_IDR0))
            app_button();                 /* через 20 мс всё ещё нажата */
        EXTI->PR = EXTI_PR_PR0;           /* фронты дребезга не в счёт */
        EXTI->IMR |= EXTI_IMR_MR0;
    }
}

/* ── 4. USART1 115 200: передача по прерыванию из кольца ──────────────── */
#define BAUD 115200u
static ring_t tx;

static void uart_init(uint32_t pclk2)
{
    RCC->APB2ENR |= RCC_APB2ENR_USART1EN;
    GPIOA->CRH = (GPIOA->CRH & ~(GPIO_CRH_MODE9 | GPIO_CRH_CNF9 | GPIO_CRH_MODE10 | GPIO_CRH_CNF10))
               | GPIO_CRH_MODE9 | GPIO_CRH_CNF9_1      /* PA9: альтернативная функция, 50 МГц */
               | GPIO_CRH_CNF10_0;                     /* PA10: вход без подтяжки */
    USART1->BRR = (pclk2 + BAUD / 2u) / BAUD;          /* 72 МГц: 625 = 39 + 1/16 */
    USART1->CR3 = USART_CR3_DMAR;                      /* приём — через DMA */
    USART1->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE | USART_CR1_IDLEIE;
    NVIC_SetPriority(USART1_IRQn, 1u);
    NVIC_EnableIRQ(USART1_IRQn);
}

void board_putc(char c)
{
    while (!ring_put(&tx, (uint8_t)c)) {
    }                                     /* кольцо полно: ждём, прерывание освобождает */
    uint32_t pm = __get_PRIMASK();
    __disable_irq();                      /* CR1 правят и здесь, и в прерывании */
    USART1->CR1 |= USART_CR1_TXEIE;
    __set_PRIMASK(pm);
}

/* ── 5. Приём по DMA1, канал 5 (USART1_RX), кольцом; конец посылки — IDLE ── */
#define RX_SIZE 64u
static uint8_t rx_dma[RX_SIZE];
static uint32_t rx_pos;

static void rx_dma_init(void)
{
    RCC->AHBENR |= RCC_AHBENR_DMA1EN;
    DMA1_Channel5->CPAR = (uint32_t)&USART1->DR;
    DMA1_Channel5->CMAR = (uint32_t)rx_dma;
    DMA1_Channel5->CNDTR = RX_SIZE;
    DMA1_Channel5->CCR = DMA_CCR_MINC | DMA_CCR_CIRC | DMA_CCR_EN;  /* периферия → память, байты */
}

static void rx_drain(void)                /* всё, что DMA успел положить с прошлого раза */
{
    uint32_t end = RX_SIZE - DMA1_Channel5->CNDTR;
    while (rx_pos != end) {
        app_rx_byte(rx_dma[rx_pos]);
        rx_pos = (rx_pos + 1u) % RX_SIZE;
    }
}

void USART1_IRQHandler(void)
{
    uint32_t sr = USART1->SR;
    if (sr & USART_SR_IDLE) {
        (void)USART1->DR;                 /* IDLE снимается чтением SR, затем DR */
        rx_drain();
    }
    if ((USART1->CR1 & USART_CR1_TXEIE) && (sr & USART_SR_TXE)) {
        uint8_t b;
        if (ring_get(&tx, &b))
            USART1->DR = b;
        else
            USART1->CR1 &= ~USART_CR1_TXEIE;  /* нечего слать — молчим */
    }
}

/* ── 6. Таймеры: TIM3_CH3 — ШИМ 1 кГц на PB0, TIM2 — прерывание 10 Гц ── */
#define TIM_CLK 72000000u                 /* APB1 = 36 МГц, при делителе ≠ 1 таймеру ×2 */

static void tim_init(void)
{
    RCC->APB1ENR |= RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN;
    GPIOB->CRL = (GPIOB->CRL & ~(GPIO_CRL_MODE0 | GPIO_CRL_CNF0)) | GPIO_CRL_MODE0_1 | GPIO_CRL_CNF0_1;

    TIM3->PSC = TIM_CLK / 1000000u - 1u;  /* 1 МГц */
    TIM3->ARR = 1000u - 1u;               /* 1 кГц */
    TIM3->CCR3 = 0u;
    TIM3->CCMR2 = TIM_CCMR2_OC3M_2 | TIM_CCMR2_OC3M_1 | TIM_CCMR2_OC3PE;  /* ШИМ, режим 1 */
    TIM3->CCER = TIM_CCER_CC3E;
    TIM3->CR1 = TIM_CR1_ARPE;
    TIM3->EGR = TIM_EGR_UG;               /* загрузить PSC и теневые регистры */
    TIM3->CR1 |= TIM_CR1_CEN;

    TIM2->PSC = TIM_CLK / 10000u - 1u;    /* 10 кГц */
    TIM2->ARR = 1000u - 1u;               /* 10 Гц */
    TIM2->EGR = TIM_EGR_UG;
    TIM2->SR = ~TIM_SR_UIF;               /* UG поднял UIF — иначе прерывание сразу */
    TIM2->DIER = TIM_DIER_UIE;
    TIM2->CR1 = TIM_CR1_CEN;
    NVIC_SetPriority(TIM2_IRQn, 4u);
    NVIC_EnableIRQ(TIM2_IRQn);
}

void board_pwm(uint32_t pct)
{
    TIM3->CCR3 = pct * (TIM3->ARR + 1u) / 100u;
}

void TIM2_IRQHandler(void)
{
    if (TIM2->SR & TIM_SR_UIF) {
        TIM2->SR = ~TIM_SR_UIF;
        GPIOC->BSRR = (GPIOC->ODR & GPIO_ODR_ODR13) ? GPIO_BSRR_BR13 : GPIO_BSRR_BS13;
    }
}

/* ── 7. АЦП1: датчик температуры (16) и опорное (17), однократно ─────── */
static void adc_init(void)
{
    RCC->APB2ENR |= RCC_APB2ENR_ADC1EN;
    ADC1->SMPR1 = ADC_SMPR1_SMP16 | ADC_SMPR1_SMP17;   /* 239,5 такта: 20 мкс при 12 МГц */
    ADC1->CR2 = ADC_CR2_ADON;                          /* включить */
    spin(2u);                                          /* tSTAB — 1 мкс */
    ADC1->CR2 = ADC_CR2_ADON | ADC_CR2_TSVREFE | ADC_CR2_EXTSEL | ADC_CR2_EXTTRIG;
    ADC1->CR2 |= ADC_CR2_RSTCAL;
    while (ADC1->CR2 & ADC_CR2_RSTCAL) {
    }
    ADC1->CR2 |= ADC_CR2_CAL;
    while (ADC1->CR2 & ADC_CR2_CAL) {
    }
}

uint32_t board_adc(uint32_t ch)
{
    ADC1->SQR3 = ch;                      /* один канал в очереди */
    ADC1->CR2 |= ADC_CR2_SWSTART;
    for (uint32_t t = I2C_TIMEOUT; !(ADC1->SR & ADC_SR_EOC);)
        if (--t == 0u)
            return 0u;
    return ADC1->DR;                      /* чтение DR снимает EOC */
}

/* ── 8. I2C1 100 кГц: снять зависание шины, чтение регистров ─────────── */
static uint32_t i2c_unstick(void)
{
    uint32_t n = 0;
    GPIOB->BSRR = GPIO_BSRR_BS6 | GPIO_BSRR_BS7;
    GPIOB->CRL = (GPIOB->CRL & ~(GPIO_CRL_MODE6 | GPIO_CRL_CNF6 | GPIO_CRL_MODE7 | GPIO_CRL_CNF7))
               | GPIO_CRL_MODE6_1 | GPIO_CRL_CNF6_0 | GPIO_CRL_MODE7_1 | GPIO_CRL_CNF7_0;  /* открытый сток */
    while (!(GPIOB->IDR & GPIO_IDR_IDR7) && n < 9u) {  /* ведомый держит SDA: тактуем SCL */
        GPIOB->BSRR = GPIO_BSRR_BR6;
        spin(5u);
        GPIOB->BSRR = GPIO_BSRR_BS6;
        spin(5u);
        n++;
    }
    GPIOB->BSRR = GPIO_BSRR_BR7;          /* STOP: SDA вверх при высоком SCL */
    spin(5u);
    GPIOB->BSRR = GPIO_BSRR_BS7;
    return n;
}

static void i2c_init(uint32_t pclk1)
{
    RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
    GPIOB->CRL |= GPIO_CRL_CNF6 | GPIO_CRL_CNF7;       /* альтернативная функция, открытый сток */
    I2C1->CR1 = I2C_CR1_SWRST;            /* сброс блока после возни с ногами */
    I2C1->CR1 = 0u;
    I2C1->CR2 = pclk1 / 1000000u;         /* частота APB1 в МГц: 36 */
    I2C1->CCR = pclk1 / (2u * 100000u);   /* стандартный режим: 180 */
    I2C1->TRISE = pclk1 / 1000000u + 1u;  /* 1000 нс × 36 МГц + 1 = 37 */
    I2C1->CR1 = I2C_CR1_PE;
}

#define I2C_NACK (-1)
#define I2C_TMO  (-2)

static int i2c_wait(uint32_t flag)
{
    for (uint32_t t = I2C_TIMEOUT; !(I2C1->SR1 & flag);) {
        if (I2C1->SR1 & I2C_SR1_AF) {     /* ведомый не ответил */
            I2C1->CR1 |= I2C_CR1_STOP;
            I2C1->SR1 = ~I2C_SR1_AF;      /* rc_w0: ноль сбрасывает, единицы не трогают */
            return I2C_NACK;
        }
        if (--t == 0u)
            return I2C_TMO;
    }
    return 0;
}

static int i2c_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint32_t n)
{
    int rc;
    for (uint32_t t = I2C_TIMEOUT; I2C1->SR2 & I2C_SR2_BUSY;)
        if (--t == 0u)
            return I2C_TMO;
    I2C1->CR1 |= I2C_CR1_ACK | I2C_CR1_START;
    if ((rc = i2c_wait(I2C_SR1_SB)) != 0)
        return rc;
    I2C1->DR = (uint32_t)addr << 1;       /* запись: номер регистра */
    if ((rc = i2c_wait(I2C_SR1_ADDR)) != 0)
        return rc;
    (void)I2C1->SR2;                      /* ADDR снимается чтением SR1, затем SR2 */
    I2C1->DR = reg;
    if ((rc = i2c_wait(I2C_SR1_BTF)) != 0)
        return rc;
    I2C1->CR1 |= I2C_CR1_START;           /* повторный старт */
    if ((rc = i2c_wait(I2C_SR1_SB)) != 0)
        return rc;
    I2C1->DR = ((uint32_t)addr << 1) | 1u;
    if ((rc = i2c_wait(I2C_SR1_ADDR)) != 0)
        return rc;
    if (n == 1u) {                        /* RM0008: ACK снять до сброса ADDR */
        I2C1->CR1 &= ~I2C_CR1_ACK;
        __disable_irq();
        (void)I2C1->SR2;
        I2C1->CR1 |= I2C_CR1_STOP;
        __enable_irq();
        if ((rc = i2c_wait(I2C_SR1_RXNE)) != 0)
            return rc;
        buf[0] = (uint8_t)I2C1->DR;
        return 0;
    }
    (void)I2C1->SR2;
    while (n > 3u) {                      /* байты с ACK, пока не останется три */
        if ((rc = i2c_wait(I2C_SR1_RXNE)) != 0)
            return rc;
        *buf++ = (uint8_t)I2C1->DR;
        n--;
    }
    if ((rc = i2c_wait(I2C_SR1_BTF)) != 0)  /* N-2 в DR, N-1 в сдвиговом */
        return rc;
    I2C1->CR1 &= ~I2C_CR1_ACK;            /* последний байт — с NACK */
    *buf++ = (uint8_t)I2C1->DR;
    if ((rc = i2c_wait(I2C_SR1_BTF)) != 0)
        return rc;
    I2C1->CR1 |= I2C_CR1_STOP;
    *buf++ = (uint8_t)I2C1->DR;
    *buf = (uint8_t)I2C1->DR;
    return 0;
}

/* ── сборка ───────────────────────────────────────────────────────────── */
int main(void)
{
    int clk = clock_72mhz();
    SystemCoreClockUpdate();              /* SystemCoreClock — по регистрам RCC */
    NVIC_SetPriorityGrouping(3u);         /* 4 бита — вытесняющий приоритет, как у HAL */
    SysTick_Config(SystemCoreClock / 1000u);
    NVIC_SetPriority(SysTick_IRQn, 0u);   /* SysTick_Config ставит 15 — самый низкий */

    gpio_init();
    uart_init(SystemCoreClock);           /* APB2 = HCLK */
    rx_dma_init();
    out_printf("clk %u%s\n", SystemCoreClock, clk ? " hse fail" : "");
    uint32_t t0 = ms;
    delay_ms(100u);
    out_printf("tick %u\n", ms - t0);

    uint32_t n = i2c_unstick();
    out_printf("i2c bus %s %u\n", n ? "freed" : "free", n);
    i2c_init(SystemCoreClock / 2u);
    uint8_t id = 0, cal[6] = {0};
    int rc = i2c_read(BMP280, 0xD0u, &id, 1u);
    out_printf("i2c id rc=%d 0x%02x\n", rc, id);
    rc = i2c_read(BMP280, 0x88u, cal, 6u);
    out_printf("i2c cal rc=%d %02x %02x %02x %02x %02x %02x\n", rc,
               cal[0], cal[1], cal[2], cal[3], cal[4], cal[5]);
    rc = i2c_read(BMP280 + 1u, 0xD0u, &id, 1u);
    out_printf("i2c 0x77 rc=%d\n", rc);

    adc_init();
    app_adc_report();
    tim_init();
    out_printf("ready\n");

    char line[32];
    for (;;) {
        button_poll();
        if (app_take_line(line, sizeof line))
            app_command(line);
        __WFI();                          /* до следующего прерывания: SysTick будит каждую мс */
    }
}

hal/main.c — the same project on HAL

/* main.c — раздел 5в, тот же проект на HAL (STM32CubeF1, HAL 1.1.10).
 * Поведение и вывод — как у проекта на регистрах; общая часть — app5c.c. */
#include "stm32f1xx_hal.h"
#include "app5c.h"

#define BMP280 0x76u

static UART_HandleTypeDef huart1;
static DMA_HandleTypeDef hdma_rx;
static TIM_HandleTypeDef htim2, htim3;
static ADC_HandleTypeDef hadc1;
static I2C_HandleTypeDef hi2c1;

/* ── 1. Тактирование: HSE 8 МГц × 9 = 72 МГц ──────────────────────────── */
static int clock_72mhz(void)
{
    RCC_OscInitTypeDef osc = {0};
    RCC_ClkInitTypeDef clk = {0};
    RCC_PeriphCLKInitTypeDef per = {0};
    osc.OscillatorType = RCC_OSCILLATORTYPE_HSE;
    osc.HSEState = RCC_HSE_ON;
    osc.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    osc.PLL.PLLState = RCC_PLL_ON;
    osc.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    osc.PLL.PLLMUL = RCC_PLL_MUL9;
    if (HAL_RCC_OscConfig(&osc) != HAL_OK)
        return -1;
    clk.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    clk.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    clk.AHBCLKDivider = RCC_SYSCLK_DIV1;
    clk.APB1CLKDivider = RCC_HCLK_DIV2;
    clk.APB2CLKDivider = RCC_HCLK_DIV1;
    if (HAL_RCC_ClockConfig(&clk, FLASH_LATENCY_2) != HAL_OK)  /* сама ставит такты ожидания */
        return -3;
    per.PeriphClockSelection = RCC_PERIPHCLK_ADC;
    per.AdcClockSelection = RCC_ADCPCLK2_DIV6;
    HAL_RCCEx_PeriphCLKConfig(&per);
    return 0;
}

/* ── 2. SysTick: 1 мс — его настраивает HAL_Init и заново ClockConfig ─── */
void SysTick_Handler(void)
{
    HAL_IncTick();
}

static void spin(uint32_t n)
{
    for (volatile uint32_t i = 0; i < n * (SystemCoreClock / 4000000u); i++) {
    }
}

/* ── 3. GPIO, кнопка на EXTI0 с антидребезгом ─────────────────────────── */
static volatile uint32_t btn_t0, btn_wait;

static void gpio_init(void)
{
    GPIO_InitTypeDef g = {0};
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_AFIO_CLK_ENABLE();

    HAL_GPIO_WritePin(GPIOC, GPIO_PIN_13, GPIO_PIN_SET);
    g.Pin = GPIO_PIN_13;
    g.Mode = GPIO_MODE_OUTPUT_PP;
    g.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOC, &g);

    g.Pin = GPIO_PIN_0;
    g.Mode = GPIO_MODE_IT_FALLING;        /* EXTI, AFIO и фронт — одним вызовом */
    g.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(GPIOA, &g);
    HAL_NVIC_SetPriority(EXTI0_IRQn, 3u, 0u);
    HAL_NVIC_EnableIRQ(EXTI0_IRQn);
}

void EXTI0_IRQHandler(void)
{
    HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
}

void HAL_GPIO_EXTI_Callback(uint16_t pin)
{
    if (pin == GPIO_PIN_0) {
        HAL_NVIC_DisableIRQ(EXTI0_IRQn);  /* у HAL нет вызова «заглушить линию» */
        btn_t0 = HAL_GetTick();
        btn_wait = 1u;
    }
}

static void button_poll(void)
{
    if (btn_wait && HAL_GetTick() - btn_t0 >= 20u) {
        btn_wait = 0u;
        if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == GPIO_PIN_RESET)
            app_button();
        __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_0);
        HAL_NVIC_ClearPendingIRQ(EXTI0_IRQn);
        HAL_NVIC_EnableIRQ(EXTI0_IRQn);
    }
}

/* ── 4. USART1 115 200: передача кусками из кольца ────────────────────── */
static ring_t tx;
static volatile uint16_t tx_n;

static void tx_kick(void)                 /* вызывать с запрещёнными прерываниями */
{
    const uint8_t *p;
    if (huart1.gState != HAL_UART_STATE_READY)
        return;
    tx_n = ring_chunk(&tx, &p);
    if (tx_n != 0u)
        HAL_UART_Transmit_IT(&huart1, (uint8_t *)p, tx_n);
}

void board_putc(char c)
{
    while (!ring_put(&tx, (uint8_t)c)) {
    }
    uint32_t pm = __get_PRIMASK();
    __disable_irq();
    tx_kick();
    __set_PRIMASK(pm);
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *h)
{
    (void)h;
    ring_skip(&tx, tx_n);
    tx_kick();
}

void HAL_UART_MspInit(UART_HandleTypeDef *h)
{
    GPIO_InitTypeDef g = {0};
    (void)h;
    __HAL_RCC_USART1_CLK_ENABLE();
    __HAL_RCC_DMA1_CLK_ENABLE();
    g.Pin = GPIO_PIN_9;
    g.Mode = GPIO_MODE_AF_PP;
    g.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &g);
    g.Pin = GPIO_PIN_10;
    g.Mode = GPIO_MODE_INPUT;
    g.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &g);

    hdma_rx.Instance = DMA1_Channel5;     /* USART1_RX */
    hdma_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
    hdma_rx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_rx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_rx.Init.Mode = DMA_CIRCULAR;
    hdma_rx.Init.Priority = DMA_PRIORITY_LOW;
    HAL_DMA_Init(&hdma_rx);
    __HAL_LINKDMA(&huart1, hdmarx, hdma_rx);
    HAL_NVIC_SetPriority(DMA1_Channel5_IRQn, 1u, 0u);
    HAL_NVIC_EnableIRQ(DMA1_Channel5_IRQn);
    HAL_NVIC_SetPriority(USART1_IRQn, 1u, 0u);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
}

/* ── 5. Приём по DMA кольцом до паузы: ReceiveToIdle ──────────────────── */
#define RX_SIZE 64u
static uint8_t rx_dma[RX_SIZE];
static uint32_t rx_pos;

static void uart_init(void)
{
    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200u;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;
    HAL_UART_Init(&huart1);
    HAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_dma, RX_SIZE);
}

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *h, uint16_t end)
{
    (void)h;                              /* end — сколько байт буфера занято: пауза, половина, конец */
    while (rx_pos != end % RX_SIZE) {
        app_rx_byte(rx_dma[rx_pos]);
        rx_pos = (rx_pos + 1u) % RX_SIZE;
    }
}

void USART1_IRQHandler(void)
{
    HAL_UART_IRQHandler(&huart1);
}

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

/* ── 6. Таймеры: TIM3_CH3 — ШИМ 1 кГц на PB0, TIM2 — прерывание 10 Гц ── */
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *h)
{
    (void)h;
    __HAL_RCC_TIM3_CLK_ENABLE();
}

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *h)
{
    (void)h;
    __HAL_RCC_TIM2_CLK_ENABLE();
    HAL_NVIC_SetPriority(TIM2_IRQn, 4u, 0u);
    HAL_NVIC_EnableIRQ(TIM2_IRQn);
}

static void tim_init(void)
{
    GPIO_InitTypeDef g = {0};
    TIM_OC_InitTypeDef oc = {0};
    g.Pin = GPIO_PIN_0;
    g.Mode = GPIO_MODE_AF_PP;
    g.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOB, &g);

    htim3.Instance = TIM3;
    htim3.Init.Prescaler = 72u - 1u;
    htim3.Init.Period = 1000u - 1u;
    htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
    HAL_TIM_PWM_Init(&htim3);
    oc.OCMode = TIM_OCMODE_PWM1;
    oc.Pulse = 0u;
    oc.OCPolarity = TIM_OCPOLARITY_HIGH;
    HAL_TIM_PWM_ConfigChannel(&htim3, &oc, TIM_CHANNEL_3);
    HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_3);

    htim2.Instance = TIM2;
    htim2.Init.Prescaler = 7200u - 1u;
    htim2.Init.Period = 1000u - 1u;
    htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
    HAL_TIM_Base_Init(&htim2);
    HAL_TIM_Base_Start_IT(&htim2);
}

void board_pwm(uint32_t pct)
{
    __HAL_TIM_SET_COMPARE(&htim3, TIM_CHANNEL_3, pct * (__HAL_TIM_GET_AUTORELOAD(&htim3) + 1u) / 100u);
}

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

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *h)
{
    if (h->Instance == TIM2)
        HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13);
}

/* ── 7. АЦП1: датчик температуры (16) и опорное (17), однократно ─────── */
static void adc_init(void)
{
    __HAL_RCC_ADC1_CLK_ENABLE();
    hadc1.Instance = ADC1;
    hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
    hadc1.Init.ContinuousConvMode = DISABLE;
    hadc1.Init.DiscontinuousConvMode = DISABLE;
    hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
    hadc1.Init.NbrOfConversion = 1u;
    HAL_ADC_Init(&hadc1);
    HAL_ADCEx_Calibration_Start(&hadc1);  /* включает АЦП и ждёт сама */
}

uint32_t board_adc(uint32_t ch)
{
    ADC_ChannelConfTypeDef c = {0};
    c.Channel = ch;                       /* ADC_CHANNEL_16 == 16 */
    c.Rank = ADC_REGULAR_RANK_1;
    c.SamplingTime = ADC_SAMPLETIME_239CYCLES_5;
    HAL_ADC_ConfigChannel(&hadc1, &c);    /* для 16 и 17 сама ставит TSVREFE */
    HAL_ADC_Start(&hadc1);
    if (HAL_ADC_PollForConversion(&hadc1, 10u) != HAL_OK)
        return 0u;
    return HAL_ADC_GetValue(&hadc1);
}

/* ── 8. I2C1 100 кГц: снять зависание шины, чтение регистров ─────────── */
static uint32_t i2c_unstick(void)
{
    GPIO_InitTypeDef g = {0};
    uint32_t n = 0;
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6 | GPIO_PIN_7, GPIO_PIN_SET);
    g.Pin = GPIO_PIN_6 | GPIO_PIN_7;
    g.Mode = GPIO_MODE_OUTPUT_OD;
    g.Speed = GPIO_SPEED_FREQ_LOW;
    HAL_GPIO_Init(GPIOB, &g);
    while (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_7) == GPIO_PIN_RESET && n < 9u) {
        HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);
        spin(5u);
        HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);
        spin(5u);
        n++;
    }
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_RESET);
    spin(5u);
    HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_SET);
    return n;
}

void HAL_I2C_MspInit(I2C_HandleTypeDef *h)
{
    GPIO_InitTypeDef g = {0};
    (void)h;
    g.Pin = GPIO_PIN_6 | GPIO_PIN_7;
    g.Mode = GPIO_MODE_AF_OD;
    g.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOB, &g);
    __HAL_RCC_I2C1_CLK_ENABLE();
}

static void i2c_init(void)
{
    hi2c1.Instance = I2C1;
    hi2c1.Init.ClockSpeed = 100000u;
    hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
    hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
    HAL_I2C_Init(&hi2c1);
}

static int i2c_read(uint8_t addr, uint8_t reg, uint8_t *buf, uint32_t n)
{
    HAL_StatusTypeDef st = HAL_I2C_Mem_Read(&hi2c1, (uint16_t)(addr << 1), reg,
                                            I2C_MEMADD_SIZE_8BIT, buf, (uint16_t)n, 10u);
    if (st == HAL_OK)
        return 0;
    return (hi2c1.ErrorCode & HAL_I2C_ERROR_AF) ? -1 : -2;   /* как у проекта на регистрах */
}

/* ── сборка ───────────────────────────────────────────────────────────── */
int main(void)
{
    HAL_Init();                           /* SysTick от HSI, группа приоритетов 4, предвыборка */
    int clk = clock_72mhz();

    gpio_init();
    uart_init();
    out_printf("clk %u%s\n", SystemCoreClock, clk ? " hse fail" : "");
    uint32_t t0 = HAL_GetTick();
    HAL_Delay(100u);
    out_printf("tick %u\n", HAL_GetTick() - t0);

    uint32_t n = i2c_unstick();
    out_printf("i2c bus %s %u\n", n ? "freed" : "free", n);
    i2c_init();
    uint8_t id = 0, cal[6] = {0};
    int rc = i2c_read(BMP280, 0xD0u, &id, 1u);
    out_printf("i2c id rc=%d 0x%02x\n", rc, id);
    rc = i2c_read(BMP280, 0x88u, cal, 6u);
    out_printf("i2c cal rc=%d %02x %02x %02x %02x %02x %02x\n", rc,
               cal[0], cal[1], cal[2], cal[3], cal[4], cal[5]);
    rc = i2c_read(BMP280 + 1u, 0xD0u, &id, 1u);
    out_printf("i2c 0x77 rc=%d\n", rc);

    adc_init();
    app_adc_report();
    tim_init();
    out_printf("ready\n");

    char line[32];
    for (;;) {
        button_poll();
        if (app_take_line(line, sizeof line))
            app_command(line);
        __WFI();
    }
}

hal/stm32f1xx_hal_conf.h — HAL settings

/* stm32f1xx_hal_conf.h — раздел 5в, проект на HAL: только нужные модули. */
#ifndef STM32F1XX_HAL_CONF_H
#define STM32F1XX_HAL_CONF_H

#define HAL_MODULE_ENABLED
#define HAL_ADC_MODULE_ENABLED
#define HAL_CORTEX_MODULE_ENABLED
#define HAL_DMA_MODULE_ENABLED
#define HAL_FLASH_MODULE_ENABLED
#define HAL_GPIO_MODULE_ENABLED
#define HAL_I2C_MODULE_ENABLED
#define HAL_RCC_MODULE_ENABLED
#define HAL_TIM_MODULE_ENABLED
#define HAL_UART_MODULE_ENABLED

#define HSE_VALUE            8000000U     /* кварц BluePill */
#define HSE_STARTUP_TIMEOUT  100U         /* мс */
#define HSI_VALUE            8000000U
#define LSI_VALUE            40000U
#define LSE_VALUE            32768U
#define LSE_STARTUP_TIMEOUT  5000U
#define VDD_VALUE            3300U
#define TICK_INT_PRIORITY    0U           /* шаблон ставит 0x0F — самый низкий */
#define USE_RTOS             0U
#define PREFETCH_ENABLE      1U

#include "stm32f1xx_hal_rcc.h"
#include "stm32f1xx_hal_gpio.h"
#include "stm32f1xx_hal_dma.h"
#include "stm32f1xx_hal_cortex.h"
#include "stm32f1xx_hal_adc.h"
#include "stm32f1xx_hal_flash.h"
#include "stm32f1xx_hal_i2c.h"
#include "stm32f1xx_hal_tim.h"
#include "stm32f1xx_hal_uart.h"

#define assert_param(expr) ((void)0U)

#endif

Next: section 5г "One project twice on STM32F405: CMSIS and registers only versus HAL — PLL at 168 MHz, flash latency, FPU, DMA streams, UART, PWM, ADC, I2C and a comparison" — the same project on STM32F405 twice: registers versus HAL1, a 168 MHz clock, DMA streams and a comparison of sizes and registers.

Open in the interactive handbook