STM32CubeSTM32 Blue PillLab virtual

STM32 registers: blink with CMSIS, no HAL

Bare-metal register code on the Blue Pill: the PLL to 72 MHz, SysTick, GPIOC->BSRR and USART1->DR.

STM32 registers: blink with CMSIS, no HAL in Argynix Lab

The code

main.cC
/* A blink with no HAL at all: CMSIS register code on the Blue Pill. It starts the
   8 MHz crystal and the PLL (x9) itself, as system_stm32f1xx.c does, makes PC13 an
   output in GPIOC->CRH, counts milliseconds in SysTick_Handler and writes to USART1's
   data register. The LED (lit when PC13 is low) flashes 100 ms every second. */
#include "stm32f1xx.h"

static volatile uint32_t ms;

void SysTick_Handler(void)
{
  ms++;
}

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

static void clock_72mhz(void)
{
  RCC->CR |= RCC_CR_HSEON;
  while (!(RCC->CR & RCC_CR_HSERDY)) {}
  FLASH->ACR = FLASH_ACR_PRFTBE | FLASH_ACR_LATENCY_2;
  RCC->CFGR |= RCC_CFGR_PPRE1_DIV2 | RCC_CFGR_PLLSRC | RCC_CFGR_PLLMULL9;
  RCC->CR |= RCC_CR_PLLON;
  while (!(RCC->CR & RCC_CR_PLLRDY)) {}
  RCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | RCC_CFGR_SW_PLL;
  while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL) {}
  SystemCoreClockUpdate();
}

static void uart_print(const char *s)
{
  while (*s)
  {
    while (!(USART1->SR & USART_SR_TXE)) {}
    USART1->DR = (uint8_t)*s++;
  }
}

static void uart_number(uint32_t v)
{
  char digits[11];
  int i = 10;
  digits[i] = 0;
  do { digits[--i] = (char)('0' + v % 10); v /= 10; } while (v);
  uart_print(&digits[i]);
}

int main(void)
{
  clock_72mhz();
  SysTick_Config(SystemCoreClock / 1000);

  RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPCEN | RCC_APB2ENR_USART1EN;
  /* PC13: output, 2 MHz, push-pull */
  GPIOC->CRH = (GPIOC->CRH & ~(GPIO_CRH_MODE13 | GPIO_CRH_CNF13)) | GPIO_CRH_MODE13_1;
  /* PA9: USART1 TX, alternate function push-pull */
  GPIOA->CRH = (GPIOA->CRH & ~(GPIO_CRH_MODE9 | GPIO_CRH_CNF9)) | GPIO_CRH_MODE9_1 | GPIO_CRH_CNF9_1;
  USART1->BRR = SystemCoreClock / 115200;
  USART1->CR1 = USART_CR1_UE | USART_CR1_TE;

  uart_print("SystemCoreClock = ");
  uart_number(SystemCoreClock);
  uart_print("\r\n");

  for (uint32_t n = 1;; n++)
  {
    GPIOC->BSRR = GPIO_BSRR_BR13; /* low: the LED on */
    delay_ms(100);
    GPIOC->BSRR = GPIO_BSRR_BS13;
    delay_ms(900);
    uart_print("flash ");
    uart_number(n);
    uart_print(" at ");
    uart_number(ms);
    uart_print(" ms\r\n");
  }
}