Reliable data exchange between microcontrollers is a core requirement in embedded systems. UART (Universal Asynchronous Receiver/Transmitter) is one of the simplest and most widely used serial communication protocols for point-to-point communication.

This article outlines a practical approach to implement UART communication between two STM32 microcontrollers using a structured data frame and interrupt-based reception.

System Overview

Two STM32 boards are connected via UART:

  • TX (Master) → RX (Slave)
  • RX (Master) ← TX (Slave)
  • Common GND

Baud rate and frame format must match on both sides (e.g., 115200, 8N1).

image.png

Data Frame Design

To avoid parsing errors, use a structured frame:

<stx> ID,VAL1,VAL2,CHK <etx></etx> </stx>

Example:

$01,123,456*5A#

Where:

  • $ = start (STX)
  • 01 = device ID
  • 123,456 = payload
  • *5A = checksum (optional)
  • = end (ETX)

A clear delimiter-based frame prevents partial reads and simplifies parsing.

Transmit (TX) Implementation

On the master:

  1. Format payload into string
  2. Append delimiters and checksum
  3. Send via UART

Pseudocode:

sprintf(txBuf, "$%02d,%d,%d*%02X#", id, v1, v2, checksum);
HAL_UART_Transmit(&huart1, (uint8_t*)txBuf, strlen(txBuf), 100);

Receive (RX) Using Interrupt

Use interrupt (or DMA) to avoid blocking:

  • Enable HAL_UART_Receive_IT (or DMA)
  • Buffer incoming bytes
  • Detect end marker #
  • Parse complete frame

image.png

Parsing Strategy

After a full frame is received:

  1. Validate start/end markers
  2. Verify checksum (if used)
  3. Split CSV payload
  4. Convert to numeric values

Example (concept):

  • Find $ and #
  • Extract substring
  • sscanf or tokenization

This ensures deterministic and error-tolerant parsing.

Timing and Reliability

Key considerations:

  • Match baud rate on both devices
  • Use hardware UART (not bit-bang)
  • Keep frames short to reduce latency
  • Add timeout/reset for incomplete frames
  • Consider DMA for high throughput

Error Handling

Improve robustness with:

  • Checksum (XOR or CRC)
  • Frame timeout (discard incomplete data)
  • Re-sync on next $ if corruption occurs

Practical Applications

  • Sensor node → controller communication
  • HMI ↔ controller data exchange
  • Multi-board modular systems
  • Industrial gateways

UART provides a simple and effective method for microcontroller communication. By combining a structured data frame, interrupt-based reception, and basic error handling, STM32 systems can achieve reliable and maintainable serial communication.

#EmbeddedSystems#
#STM32#
#UART#
#SerialCommunication#
#Microcontroller#
#Firmware#

#EmbeddedSystems#
#STM32#
#UART#
#SerialCommunication#
#Microcontroller#
#Firmware#
Embedded Systems2

No comments yet. Be the first to comment!