STM32 to PC & Browser Communication

Minimal STM32 USB and UART communication library

Speed up STM32 development with a small, predictable set of communication functions.
USB functions (usb_helper.c for STM32):
UART functions (serial_helper.c for STM32, serial_helper.js for HTML):
Fully compatible with STM32 HAL. No need to replace drivers, rewrite interrupt handling, or modify peripheral initialization.
Zero configuration on most STM32 series. Enable the peripheral in STM32CubeMX, copy the helper files, and it is ready to use.
Works on STM32F103, STM32F407, STM32G474, STM32H743, STM32L476, STM32U5, and other STM32 families. USB on STM32U5 series is not supported yet.

STM32 USB Transmit

Configure STM32 and PC to send data over USB

Fixed data transmit example for APP_Loop():
void APP_Loop(void)
{
  HAL_Delay(1000);
  USB_Write(0xAA, 0xBB, 0xCC);
}
Incrementing value transmit example:
uint8_t number = 0;

void APP_Loop(void)
{
  HAL_Delay(1000);
  USB_Write(number);
  number++;
}

STM32 USB Receive

Receive commands from PC without blocking

Use USB_ReadNoWait() to receive commands without halting execution.
void APP_Loop(void)
{
  uint8_t cmd = 0xFF;

  USB_ReadNoWait(cmd);

  // 0x01: Turn LED on
  if (cmd == 0x01)
  {
    HAL_GPIO_WritePin(GPIOC,
                          GPIO_PIN_13,
                          GPIO_PIN_RESET);
  }

  // 0x02: Turn LED off
  if (cmd == 0x02)
  {
    HAL_GPIO_WritePin(GPIOC,
                          GPIO_PIN_13,
                          GPIO_PIN_SET);
  }
}
Ensure GPIO_PIN_13 is configured as GPIO output and connected to an LED.

Control From Browser

Control STM32 directly from the browser

Paste this minimal HTML into a file and open it in your browser:
<body>
  <h1>LED Control</h1>

  <script src="serial_helper.js"></script>

  <button onclick="COM_Write([0x01]); COM_Close();">
    LED On
  </button>

  <button onclick="COM_Write([0x02]); COM_Close();">
    LED Off
  </button>
</body>
Copy serial_helper.js from HTML_TOOLKIT to the same directory as this HTML file.
You can also read data sent by the STM32. Use COM_Read() to receive bytes into a JavaScript array. For example, let rx = COM_Read(5); reads five bytes from the microcontroller.

STM32 UART TX/RX

Switch from USB to UART with minimal changes

To use UART instead of USB, simply replace the USB_ prefix with COM_ when calling read and write functions. The APIs are intentionally designed to be almost identical, so switching between USB and UART requires very few code changes.
In STM32CubeMX, make sure UART is configured as follows:
With matching function names and behavior, you can easily swap between USB and UART by changing only the prefix in your code.
© HexFlashLab.com