UART Based Sensor Emulation Part 4: Configuring and Streaming the Emulated Sensor

In the previous parts, we set up the environment, established UART communication between the master and the DUT, and built a lightweight framed protocol with checksum validation. In this final part, we bring everything together by turning the DUT into a configurable serial temperature sensor that the master can configure, read back, start streaming from, and automatically recover if the sensor resets.

Introduction

In the previous parts, we set up the environment, established UART communication between the master and the DUT, and built a lightweight framed protocol with checksum validation. In this final part, we bring everything together by turning the DUT into a configurable serial temperature sensor that the master can configure, read back, start streaming from, and automatically recover if the sensor resets.

By the end of this part you will have:

  • A DUT that behaves like a real serial sensor: it accepts configuration, reports it back, and streams temperature samples at a configurable rate with an alarm flag.
  • A master that configures the sensor, verifies the configuration, prints every sample, switches profiles at run time, and recovers on its own when the sensor stops answering.
  • A stream parser that handles partial and back-to-back frames, which is what UART receive-to-idle actually delivers in practice.

In this guide, we shall cover the following:

  1. Extending the protocol.
  2. DUT: sensor configuration.
  3. DUT: sensor emulator.
  4. DUT: main.c integration.
  5. Master: sensor client.
  6. Master: main.c with auto-recovery.
  7. System flow.
  8. Testing and results.

Hardware setup

The system has two STM32 boards linked by UART1 at 115200 8N1. The master configures and reads the sensor; the DUT plays the sensor.

BoardMCUUART1 (link)UART2Role
MasterSTM32F411REPA9 TX, PA10 RX, DMA RXST-Link virtual COM port (log)Configures the sensor and prints samples
DUTSTM32F446REPA9 TX, PA10 RX, DMA RXnot usedEmulates the serial sensor

Wiring: Master PA9 to DUT PA10, Master PA10 to DUT PA9, and a common GND.

1. Extending the protocol

The frame format from Part 3 stays exactly the same; we only add three commands and make every reply a full frame.

Request (Master to DUT)Reply (DUT to Master)Meaning
WRITE [rate, threshold]ACK [WRITE] or NACK [WRITE, err]Set sample rate (1 to 50 Hz) and alarm threshold (deg C)
READ []READ [rate, threshold, streaming]Read the configuration back; the reply is the acknowledgement
START []ACK [START]Start streaming samples
STOP []ACK [STOP]Stop streaming samples
noneDATA [seq, temp_hi, temp_lo, flags]One sample, sent every 1/rate seconds while streaming
unknown commandNACK [cmd, CFG_ERR_UNKNOWN_CMD]Command not supported

Why ACK and NACK became frames

In Part 3 the DUT answered with a single raw byte, 0x06 or 0x15. That works only while nothing else is on the line. Once the DUT streams DATA frames, a lone ACK byte can arrive glued to the front of a DATA frame, and the master cannot tell them apart. Wrapping replies in frames fixes this: ACK and NACK are now command codes, and the payload names the command being answered, so the master knows exactly which request succeeded or failed.

The DATA payload

ByteFieldNotes
0Sequence counterWraps at 255; a gap means a lost frame
1 to 2TemperatureSigned 16-bit, big-endian, in 0.1 deg C (250 = 25.0 deg C)
3FlagsBit 0 = ALARM, set when temperature is at or above the threshold

Example: AA 10 04 0E 00 FA 01 4B is sample 14 at 25.0 deg C with ALARM set. The CRC 4B is AA ^ 10 ^ 04 ^ 0E ^ 00 ^ FA ^ 01.

A byte-wise stream parser

cfg_parse_frame() from Part 3 expects one whole frame in a buffer. UART receive-to-idle does not guarantee that: one idle event can carry half a frame, or an ACK followed by a DATA frame. So we add a small state machine that takes one byte at a time and reports a frame only when it is complete. It reuses cfg_parse_frame() for the final length and CRC check, so validation logic lives in one place.

Add the following to config_protocol.h. The new command codes go with the other frame constants, and CFG_IN_PROGRESS goes at the end of cfg_status_t:

#define CFG_CMD_START       0x03    /* Master -> DUT : start streaming samples */
#define CFG_CMD_STOP        0x04    /* Master -> DUT : stop streaming samples  */
#define CFG_CMD_DATA        0x10    /* DUT -> Master : one sensor sample       */

typedef enum {
    CFG_OK = 0,
    CFG_ERR_TOO_SHORT,
    CFG_ERR_BAD_START,
    CFG_ERR_TOO_LONG,
    CFG_ERR_BAD_CRC,
    CFG_ERR_UNKNOWN_CMD,
    CFG_ERR_BAD_PAYLOAD,
    CFG_IN_PROGRESS             /* stream parser: frame not complete yet */
} cfg_status_t;

/* ---- Byte-wise stream parser ----
 * UART "receive to idle" may deliver half a frame, or several frames glued
 * together (e.g. an ACK followed by a DATA frame). Feed every received byte
 * into cfg_stream_feed():
 *   CFG_IN_PROGRESS -> keep feeding
 *   CFG_OK          -> `frame` holds a complete, CRC-checked frame
 *   anything else   -> frame dropped, parser already re-synchronised
 */
typedef enum {
    CFG_RX_WAIT_START = 0,
    CFG_RX_CMD,
    CFG_RX_LEN,
    CFG_RX_PAYLOAD,
    CFG_RX_CRC
} cfg_rx_state_t;

typedef struct {
    cfg_rx_state_t state;
    uint8_t        buf[CFG_MAX_FRAME];
    uint16_t       idx;
    uint8_t        len;
} cfg_stream_t;

void         cfg_stream_init(cfg_stream_t *s);
cfg_status_t cfg_stream_feed(cfg_stream_t *s, uint8_t byte, cfg_frame_t *frame);

/* Command byte of the frame currently/last being parsed (for NACK replies) */
static inline uint8_t cfg_stream_last_cmd(const cfg_stream_t *s) { return s->buf[1]; }

Append the parser to config_protocol.c:

void cfg_stream_init(cfg_stream_t *s)
{
    if (s == NULL) return;
    s->state = CFG_RX_WAIT_START;
    s->idx   = 0;
    s->len   = 0;
}

cfg_status_t cfg_stream_feed(cfg_stream_t *s, uint8_t byte, cfg_frame_t *frame)
{
    if ((s == NULL) || (frame == NULL)) return CFG_ERR_TOO_SHORT;

    switch (s->state) {
        case CFG_RX_WAIT_START:
            if (byte == CFG_START_BYTE) {
                s->idx = 0;
                s->buf[s->idx++] = byte;
                s->state = CFG_RX_CMD;
            }
            return CFG_IN_PROGRESS;          /* noise before START is ignored */

        case CFG_RX_CMD:
            s->buf[s->idx++] = byte;
            s->state = CFG_RX_LEN;
            return CFG_IN_PROGRESS;

        case CFG_RX_LEN:
            if (byte > CFG_MAX_PAYLOAD) {
                s->state = CFG_RX_WAIT_START;
                return CFG_ERR_TOO_LONG;
            }
            s->buf[s->idx++] = byte;
            s->len   = byte;
            s->state = (byte == 0) ? CFG_RX_CRC : CFG_RX_PAYLOAD;
            return CFG_IN_PROGRESS;

        case CFG_RX_PAYLOAD:
            s->buf[s->idx++] = byte;
            if (s->idx == (uint16_t)(3 + s->len)) {
                s->state = CFG_RX_CRC;
            }
            return CFG_IN_PROGRESS;

        case CFG_RX_CRC:
        default:
            s->buf[s->idx++] = byte;
            s->state = CFG_RX_WAIT_START;
            /* Re-use the block parser for the final validation */
            return cfg_parse_frame(s->buf, s->idx, frame);
    }
}

The rest of config_protocol.c (cfg_checksum(), cfg_build_frame(), cfg_parse_frame()) is unchanged from Part 3. Copy the same config_protocol.h and config_protocol.c into the Master project’s Core/Inc and Core/Src, so both boards speak exactly the same protocol.

2. DUT: sensor configuration

The configuration module stores the sensor settings and answers every command with a reply frame. It no longer parses raw bytes itself; it receives a complete, CRC-checked cfg_frame_t from the stream parser and writes the reply into a buffer that main.c transmits.

Two rules are enforced here:

  • The sample rate must be between 1 and 50 Hz. A rate of 0 would mean dividing by zero when the emulator computes its period, so it is rejected with NACK [WRITE, CFG_ERR_BAD_PAYLOAD].
  • The streaming flag is part of the configuration, so READ reports whether the sensor is currently sending data. The master relies on this to recover a sensor that has reset.

Replace sensor_config.h with:

#ifndef SENSOR_CONFIG_H
#define SENSOR_CONFIG_H

#include "config_protocol.h"

/* Valid range for the sample rate (Hz) */
#define SENSOR_RATE_MIN     1
#define SENSOR_RATE_MAX     50

/* Configuration of the emulated sensor */
typedef struct {
    uint8_t  sample_rate;   /* Hz, SENSOR_RATE_MIN..SENSOR_RATE_MAX        */
    uint8_t  threshold;     /* deg C, sample >= threshold sets ALARM flag  */
    uint8_t  streaming;     /* 1 = DATA frames are being sent              */
    uint8_t  reserved;
} sensor_config_t;

/* Called once at boot */
void sensor_config_init(void);

/* Handle one complete, CRC-checked frame from the master.
 * Writes the reply frame into `tx` and returns its length (0 = no reply).
 *
 *   Request                          Reply
 *   WRITE [rate, threshold]     ->   ACK  [WRITE]        / NACK [WRITE, err]
 *   READ  []                    ->   READ [rate, threshold, streaming]
 *   START []                    ->   ACK  [START]
 *   STOP  []                    ->   ACK  [STOP]
 *   anything else               ->   NACK [cmd, CFG_ERR_UNKNOWN_CMD]
 */
uint16_t sensor_config_handle_frame(const cfg_frame_t *frame,
                                    uint8_t *tx, uint16_t tx_max);

/* Build a NACK frame (also used for frames that failed CRC/length checks) */
uint16_t sensor_config_build_nack(uint8_t cmd, cfg_status_t err,
                                  uint8_t *tx, uint16_t tx_max);

/* Accessor for other emulation code */
const sensor_config_t *sensor_config_get(void);

#endif /* SENSOR_CONFIG_H */

Replace sensor_config.c with:

#include "sensor_config.h"
#include <string.h>

static sensor_config_t g_cfg;

void sensor_config_init(void)
{
    g_cfg.sample_rate = 10;
    g_cfg.threshold   = 50;
    g_cfg.streaming   = 0;
    g_cfg.reserved    = 0;
}

const sensor_config_t *sensor_config_get(void)
{
    return &g_cfg;
}

static uint16_t build_ack(uint8_t cmd, uint8_t *tx, uint16_t tx_max)
{
    if (tx_max < CFG_FRAME_OVERHEAD + 1) return 0;
    return cfg_build_frame(tx, CFG_ACK, &cmd, 1);
}

uint16_t sensor_config_build_nack(uint8_t cmd, cfg_status_t err,
                                  uint8_t *tx, uint16_t tx_max)
{
    uint8_t p[2] = { cmd, (uint8_t)err };
    if (tx_max < CFG_FRAME_OVERHEAD + 2) return 0;
    return cfg_build_frame(tx, CFG_NACK, p, 2);
}

uint16_t sensor_config_handle_frame(const cfg_frame_t *frame,
                                    uint8_t *tx, uint16_t tx_max)
{
    if ((frame == NULL) || (tx == NULL)) return 0;

    switch (frame->cmd) {
        case CFG_CMD_WRITE: {
            if (frame->length < 2) {
                return sensor_config_build_nack(frame->cmd, CFG_ERR_BAD_PAYLOAD, tx, tx_max);
            }
            uint8_t rate = frame->payload[0];
            if ((rate < SENSOR_RATE_MIN) || (rate > SENSOR_RATE_MAX)) {
                return sensor_config_build_nack(frame->cmd, CFG_ERR_BAD_PAYLOAD, tx, tx_max);
            }
            g_cfg.sample_rate = rate;
            g_cfg.threshold   = frame->payload[1];
            return build_ack(frame->cmd, tx, tx_max);
        }

        case CFG_CMD_READ: {
            /* The read-back frame itself acts as the acknowledgement */
            uint8_t p[3] = { g_cfg.sample_rate, g_cfg.threshold, g_cfg.streaming };
            if (tx_max < CFG_FRAME_OVERHEAD + sizeof(p)) return 0;
            return cfg_build_frame(tx, CFG_CMD_READ, p, sizeof(p));
        }

        case CFG_CMD_START:
            g_cfg.streaming = 1;
            return build_ack(frame->cmd, tx, tx_max);

        case CFG_CMD_STOP:
            g_cfg.streaming = 0;
            return build_ack(frame->cmd, tx, tx_max);

        default:
            return sensor_config_build_nack(frame->cmd, CFG_ERR_UNKNOWN_CMD, tx, tx_max);
    }
}

3. DUT: sensor emulator

The emulator is the “physics” of our fake sensor. While streaming is on, it produces one temperature sample every 1/rate seconds and packs it into a DATA frame.

The signal is a triangle wave between 18.0 and 32.0 deg C, moving 0.5 deg C per sample. This range is chosen on purpose: both demo thresholds (25 and 30 deg C) fall inside it, so you can watch the ALARM flag switch on and off in the log. The emulator is non-blocking; sensor_emu_poll() returns immediately with 0 when no sample is due, so it can sit in the main loop next to command handling.

Create sensor_emulator.h in Core/Inc:

#ifndef SENSOR_EMULATOR_H
#define SENSOR_EMULATOR_H

#include "config_protocol.h"

/* DATA frame payload (DUT -> Master), 4 bytes:
 *   [0]    sequence counter (wraps at 255)
 *   [1..2] temperature, signed 16-bit big-endian, in 0.1 deg C
 *   [3]    flags
 */
#define SENSOR_DATA_LEN         4
#define SENSOR_FLAG_ALARM       0x01    /* temperature >= threshold */

void sensor_emu_init(void);

/* Call often from the main loop with HAL_GetTick().
 * When streaming is enabled and a sample is due (1 / sample_rate),
 * a DATA frame is written to `tx` and its length returned; otherwise 0. */
uint16_t sensor_emu_poll(uint32_t now_ms, uint8_t *tx, uint16_t tx_max);

#endif /* SENSOR_EMULATOR_H */

Create sensor_emulator.c in Core/Src:

#include "sensor_emulator.h"
#include "sensor_config.h"

/* Emulated signal: triangle wave between 18.0 and 32.0 deg C,
 * 0.5 deg C per sample, so changing the threshold visibly toggles ALARM. */
#define TEMP_MIN_X10    180
#define TEMP_MAX_X10    320
#define TEMP_STEP_X10   5

static uint32_t g_last_ms;
static uint8_t  g_seq;
static int16_t  g_temp_x10;
static int8_t   g_dir;

void sensor_emu_init(void)
{
    g_last_ms  = 0;
    g_seq      = 0;
    g_temp_x10 = TEMP_MIN_X10;
    g_dir      = 1;
}

static int16_t next_sample(void)
{
    int16_t t = g_temp_x10;

    g_temp_x10 += (int16_t)(g_dir * TEMP_STEP_X10);
    if (g_temp_x10 >= TEMP_MAX_X10) { g_temp_x10 = TEMP_MAX_X10; g_dir = -1; }
    if (g_temp_x10 <= TEMP_MIN_X10) { g_temp_x10 = TEMP_MIN_X10; g_dir =  1; }

    return t;
}

uint16_t sensor_emu_poll(uint32_t now_ms, uint8_t *tx, uint16_t tx_max)
{
    const sensor_config_t *cfg = sensor_config_get();

    if (!cfg->streaming || (cfg->sample_rate == 0)) return 0;
    if (tx_max < CFG_FRAME_OVERHEAD + SENSOR_DATA_LEN) return 0;

    uint32_t period_ms = 1000u / cfg->sample_rate;
    if ((now_ms - g_last_ms) < period_ms) return 0;
    g_last_ms = now_ms;

    int16_t t = next_sample();
    uint8_t flags = 0;
    if (t >= (int16_t)(cfg->threshold * 10)) flags |= SENSOR_FLAG_ALARM;

    uint8_t p[SENSOR_DATA_LEN];
    p[0] = g_seq++;
    p[1] = (uint8_t)((uint16_t)t >> 8);
    p[2] = (uint8_t)((uint16_t)t & 0xFF);
    p[3] = flags;

    return cfg_build_frame(tx, CFG_CMD_DATA, p, SENSOR_DATA_LEN);
}

Note that (now_ms - g_last_ms) uses unsigned arithmetic, so it stays correct when HAL_GetTick() wraps after about 49 days. To emulate a different sensor, you only need to change next_sample() and the DATA payload; the protocol and the rest of the code stay the same.

4. DUT: main.c integration

In Part 2 the DUT echoed every received byte straight from the interrupt. Now the interrupt does only one thing: copy the received bytes into a ring buffer. All parsing, command handling and transmitting happen in the main loop. This keeps the interrupt short and avoids calling a blocking HAL_UART_Transmit() from interrupt context.

Two details matter for reliable reception:

  • Disable the DMA half-transfer interrupt. With HAL_UARTEx_ReceiveToIdle_DMA() in normal mode, HAL also fires the RX event callback when the DMA buffer is half full. The DMA keeps running, so the next event reports the size from the start of the buffer again, and the first bytes would be copied twice. Disabling DMA_IT_HT after each re-arm prevents this.
  • Restart reception on errors. An overrun, noise or framing error aborts the DMA reception. HAL_UART_ErrorCallback() simply re-arms it.

All code goes inside the CubeMX USER CODE sections, so regenerating the project from the .ioc file keeps it.

Includes:

/* USER CODE BEGIN Includes */
#include "config_protocol.h"
#include "sensor_config.h"
#include "sensor_emulator.h"
/* USER CODE END Includes */

Private variables:

/* USER CODE BEGIN PV */
#define BufferSize 50
uint8_t RxBuffer[BufferSize];

extern DMA_HandleTypeDef hdma_usart1_rx;

/* ISR -> main loop byte queue (single producer / single consumer) */
#define RX_RING_SIZE 128u               /* must be a power of two */
static volatile uint8_t  rx_ring[RX_RING_SIZE];
static volatile uint16_t rx_head;       /* written by ISR       */
static volatile uint16_t rx_tail;       /* written by main loop */

static cfg_stream_t cfg_rx;             /* frame parser state   */
static cfg_frame_t  cfg_frame;          /* last parsed frame    */
static uint8_t      TxFrame[CFG_MAX_FRAME];
/* USER CODE END PV */

Function prototypes:

/* USER CODE BEGIN PFP */
static void uart1_start_rx(void);
static void process_rx(void);
/* USER CODE END PFP */

Receive path and command processing:

/* USER CODE BEGIN 0 */
static void uart1_start_rx(void)
{
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1, RxBuffer, BufferSize);
	/* Half-transfer events would report the same bytes twice, disable them */
	__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
}

/* Idle line (or buffer full): copy bytes to the ring and re-arm DMA.
 * No parsing / transmitting inside the interrupt. */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	if(huart->Instance == USART1)
	{
		for (uint16_t i = 0; i < Size; i++)
		{
			uint16_t next = (uint16_t)((rx_head + 1u) & (RX_RING_SIZE - 1u));
			if (next == rx_tail) break;           /* ring full: drop */
			rx_ring[rx_head] = RxBuffer[i];
			rx_head = next;
		}
		uart1_start_rx();
	}
}

/* Overrun/noise/framing error aborts the reception: restart it */
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
	if(huart->Instance == USART1)
	{
		uart1_start_rx();
	}
}

/* Drain received bytes, parse frames, answer each command */
static void process_rx(void)
{
	while (rx_tail != rx_head)
	{
		uint8_t byte = rx_ring[rx_tail];
		rx_tail = (uint16_t)((rx_tail + 1u) & (RX_RING_SIZE - 1u));

		cfg_status_t st = cfg_stream_feed(&cfg_rx, byte, &cfg_frame);
		uint16_t len = 0;

		if (st == CFG_OK)
		{
			len = sensor_config_handle_frame(&cfg_frame, TxFrame, sizeof(TxFrame));
		}
		else if (st != CFG_IN_PROGRESS)
		{
			/* Bad CRC / too long: tell the master which command failed */
			len = sensor_config_build_nack(cfg_stream_last_cmd(&cfg_rx), st,
			                               TxFrame, sizeof(TxFrame));
		}

		if (len > 0)
		{
			HAL_UART_Transmit(&huart1, TxFrame, len, 100);
		}
	}
}
/* USER CODE END 0 */

Initialisation, after the MX_..._Init() calls:

  /* USER CODE BEGIN 2 */
  sensor_config_init();
  sensor_emu_init();
  cfg_stream_init(&cfg_rx);
  uart1_start_rx();
  /* USER CODE END 2 */

Main loop:

    /* USER CODE BEGIN 3 */
	  /* 1) Handle configuration commands from the master */
	  process_rx();

	  /* 2) Emit a DATA frame when a sample is due (only while streaming) */
	  uint16_t len = sensor_emu_poll(HAL_GetTick(), TxFrame, sizeof(TxFrame));
	  if (len > 0)
	  {
		  HAL_UART_Transmit(&huart1, TxFrame, len, 100);
	  }
  }
  /* USER CODE END 3 */

The ring buffer is safe without disabling interrupts because only the interrupt writes rx_head and only the main loop writes rx_tail. Using a power-of-two size lets the index wrap with a cheap bit mask instead of a division.

5. Master: sensor client

On the master, everything that talks to the sensor lives in one module, sensor_client. It gives the application four simple calls (write, read, start, stop) and hides the framing, parsing and waiting.

How it works:

  • Receiving. The UART callback hands received bytes to sensor_client_rx_isr(), which only pushes them into a ring buffer. sensor_client_process() drains the ring through the stream parser and dispatches each complete frame.
  • Requests. Each request sends a frame, then waits up to 200 ms for the matching reply. It matches on the command named in the ACK or NACK payload, so a reply to an older request can never be mistaken for the current one.
  • Samples while waiting. The wait loop keeps calling sensor_client_process(), so DATA frames that arrive during a request are still printed and nothing is lost.
  • Liveness. The tick of the last DATA frame is recorded, so main.c can detect a sensor that has gone silent.

The log goes to USART2, which on Nucleo boards is the ST-Link virtual COM port. Temperatures are printed with integer arithmetic, so you do not need to enable float support in printf.

Create sensor_client.h in the Master’s Core/Inc:

#ifndef SENSOR_CLIENT_H
#define SENSOR_CLIENT_H

#include "stm32f4xx_hal.h"
#include "config_protocol.h"

/* Must match the DUT (sensor_emulator.h) */
#define SENSOR_DATA_LEN         4
#define SENSOR_FLAG_ALARM       0x01

#define SENSOR_REPLY_TIMEOUT_MS 200

typedef struct {
    uint8_t sample_rate;
    uint8_t threshold;
    uint8_t streaming;
} sensor_remote_cfg_t;

/* link : UART wired to the emulated sensor (DUT)
 * log  : UART used for human-readable output (ST-Link VCP) */
void sensor_client_init(UART_HandleTypeDef *link, UART_HandleTypeDef *log);

/* Call from HAL_UARTEx_RxEventCallback with the bytes received on `link` */
void sensor_client_rx_isr(const uint8_t *data, uint16_t len);

/* Call from the main loop: parses incoming frames and prints DATA samples */
void sensor_client_process(void);

/* Blocking requests (sample frames keep being printed while waiting).
 * Return CFG_OK on ACK, CFG_ERR_* from the NACK, or CFG_IN_PROGRESS on timeout. */
cfg_status_t sensor_client_write(uint8_t sample_rate, uint8_t threshold);
cfg_status_t sensor_client_read(sensor_remote_cfg_t *out);
cfg_status_t sensor_client_start(void);
cfg_status_t sensor_client_stop(void);

/* HAL tick of the last DATA frame received (0 = none yet) */
uint32_t sensor_client_last_data_tick(void);

/* printf-style output on the log UART */
void sensor_client_log(const char *fmt, ...);

#endif /* SENSOR_CLIENT_H */

Create sensor_client.c in the Master’s Core/Src:

#include "sensor_client.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#define RX_RING_SIZE 256u   /* power of two */

static UART_HandleTypeDef *g_link;
static UART_HandleTypeDef *g_log;

static volatile uint8_t  rx_ring[RX_RING_SIZE];
static volatile uint16_t rx_head;
static volatile uint16_t rx_tail;

static cfg_stream_t g_rx;
static cfg_frame_t  g_frame;

/* Reply tracking for the blocking requests */
static volatile uint8_t      g_wait_cmd;      /* 0 = not waiting */
static volatile uint8_t      g_reply_done;
static cfg_status_t          g_reply_status;
static sensor_remote_cfg_t   g_reply_cfg;
static volatile uint32_t     g_last_data_tick;

/* ------------------------------------------------------------------ */
void sensor_client_log(const char *fmt, ...)
{
    char buf[96];
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    if (n <= 0) return;
    if (n > (int)sizeof(buf) - 1) n = sizeof(buf) - 1;
    HAL_UART_Transmit(g_log, (uint8_t *)buf, (uint16_t)n, 100);
}

static const char *cmd_name(uint8_t cmd)
{
    switch (cmd) {
        case CFG_CMD_WRITE: return "WRITE";
        case CFG_CMD_READ:  return "READ";
        case CFG_CMD_START: return "START";
        case CFG_CMD_STOP:  return "STOP";
        default:            return "?";
    }
}

void sensor_client_init(UART_HandleTypeDef *link, UART_HandleTypeDef *log)
{
    g_link = link;
    g_log  = log;
    rx_head = rx_tail = 0;
    g_wait_cmd = 0;
    cfg_stream_init(&g_rx);
}

void sensor_client_rx_isr(const uint8_t *data, uint16_t len)
{
    for (uint16_t i = 0; i < len; i++) {
        uint16_t next = (uint16_t)((rx_head + 1u) & (RX_RING_SIZE - 1u));
        if (next == rx_tail) return;               /* full: drop */
        rx_ring[rx_head] = data[i];
        rx_head = next;
    }
}

/* ------------------------------------------------------------------ */
static void print_sample(const cfg_frame_t *f)
{
    if (f->length < SENSOR_DATA_LEN) return;

    uint8_t seq   = f->payload[0];
    int16_t t_x10 = (int16_t)(((uint16_t)f->payload[1] << 8) | f->payload[2]);
    uint8_t flags = f->payload[3];
    int16_t whole = (int16_t)(t_x10 / 10);
    int16_t frac  = (int16_t)(t_x10 % 10);
    if (frac < 0) frac = (int16_t)-frac;

    sensor_client_log("DATA  seq=%3u  T=%d.%d C  %s\r\n",
                      seq, whole, frac,
                      (flags & SENSOR_FLAG_ALARM) ? "ALARM" : "ok");
}

static void handle_frame(const cfg_frame_t *f)
{
    switch (f->cmd) {
        case CFG_CMD_DATA:
            g_last_data_tick = HAL_GetTick();
            print_sample(f);
            break;

        case CFG_ACK:
            if (g_wait_cmd && f->length >= 1 && f->payload[0] == g_wait_cmd) {
                g_reply_status = CFG_OK;
                g_reply_done   = 1;
            }
            break;

        case CFG_NACK:
            if (g_wait_cmd && f->length >= 2 && f->payload[0] == g_wait_cmd) {
                g_reply_status = (cfg_status_t)f->payload[1];
                g_reply_done   = 1;
            }
            break;

        case CFG_CMD_READ:   /* read-back reply */
            if (g_wait_cmd == CFG_CMD_READ && f->length >= 3) {
                g_reply_cfg.sample_rate = f->payload[0];
                g_reply_cfg.threshold   = f->payload[1];
                g_reply_cfg.streaming   = f->payload[2];
                g_reply_status = CFG_OK;
                g_reply_done   = 1;
            }
            break;

        default:
            sensor_client_log("RX unknown frame cmd=0x%02X\r\n", f->cmd);
            break;
    }
}

void sensor_client_process(void)
{
    while (rx_tail != rx_head) {
        uint8_t b = rx_ring[rx_tail];
        rx_tail = (uint16_t)((rx_tail + 1u) & (RX_RING_SIZE - 1u));

        cfg_status_t st = cfg_stream_feed(&g_rx, b, &g_frame);
        if (st == CFG_OK) {
            handle_frame(&g_frame);
        } else if (st != CFG_IN_PROGRESS) {
            sensor_client_log("RX frame error %d\r\n", st);
        }
    }
}

/* ------------------------------------------------------------------ */
static cfg_status_t request(uint8_t cmd, const uint8_t *payload, uint8_t len)
{
    uint8_t tx[CFG_MAX_FRAME];
    uint16_t n = cfg_build_frame(tx, cmd, payload, len);
    if (n == 0) return CFG_ERR_BAD_PAYLOAD;

    g_reply_done   = 0;
    g_reply_status = CFG_IN_PROGRESS;
    g_wait_cmd     = cmd;

    HAL_UART_Transmit(g_link, tx, n, 100);

    uint32_t t0 = HAL_GetTick();
    while (!g_reply_done && (HAL_GetTick() - t0) < SENSOR_REPLY_TIMEOUT_MS) {
        sensor_client_process();
    }
    g_wait_cmd = 0;

    if (!g_reply_done) {
        sensor_client_log("%-5s -> TIMEOUT\r\n", cmd_name(cmd));
    } else if (g_reply_status == CFG_OK) {
        sensor_client_log("%-5s -> ACK\r\n", cmd_name(cmd));
    } else {
        sensor_client_log("%-5s -> NACK (err %d)\r\n", cmd_name(cmd), g_reply_status);
    }
    return g_reply_status;
}

cfg_status_t sensor_client_write(uint8_t sample_rate, uint8_t threshold)
{
    uint8_t p[2] = { sample_rate, threshold };
    sensor_client_log("WRITE rate=%u Hz threshold=%u C\r\n", sample_rate, threshold);
    return request(CFG_CMD_WRITE, p, sizeof(p));
}

cfg_status_t sensor_client_read(sensor_remote_cfg_t *out)
{
    cfg_status_t st = request(CFG_CMD_READ, NULL, 0);
    if (st == CFG_OK) {
        if (out) *out = g_reply_cfg;
        sensor_client_log("      cfg: rate=%u Hz threshold=%u C streaming=%u\r\n",
                          g_reply_cfg.sample_rate, g_reply_cfg.threshold,
                          g_reply_cfg.streaming);
    }
    return st;
}

uint32_t sensor_client_last_data_tick(void) { return g_last_data_tick; }

cfg_status_t sensor_client_start(void) { return request(CFG_CMD_START, NULL, 0); }
cfg_status_t sensor_client_stop(void)  { return request(CFG_CMD_STOP,  NULL, 0); }

6. Master: main.c with auto-recovery

The master application runs a small demo. At boot it sends one deliberately invalid request (0 Hz) to prove the DUT rejects bad input. It then applies a profile and starts streaming, and every 10 seconds it switches between two profiles while the sensor keeps running.

ProfileSample rateAlarm threshold
05 Hz25 deg C
12 Hz30 deg C

Why the master must recover on its own

A first version sent START only once, about 100 ms after the master booted. On the bench this failed in a very realistic way: when the DUT booted later than the master, or was reset or re-flashed while the master kept running, that START was lost. WRITE and READ still worked, but every read-back showed streaming=0 and no samples arrived until the master was reset by hand.

A real sensor can reset at any time, so the master now handles it in three places:

  • At boot, sensor_apply_profile() is retried every 500 ms until the DUT confirms the configuration. The two boards can be powered in any order.
  • On every profile switch, the read-back is checked, and START is sent again if the sensor reports streaming=0.
  • In the main loop, a watchdog re-applies the profile if no DATA frame has arrived for 2 seconds.

If the master resets while the DUT keeps streaming, the read-back shows streaming=1 and START is simply skipped.

Includes:

/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "sensor_client.h"
#include <stdbool.h>
/* USER CODE END Includes */

Private variables:

/* USER CODE BEGIN PV */
#define BufferSize 50
uint8_t RxBuffer[BufferSize];

extern DMA_HandleTypeDef hdma_usart1_rx;

/* Demo profiles applied alternately every PROFILE_PERIOD_MS */
#define PROFILE_PERIOD_MS 10000u
typedef struct { uint8_t rate_hz; uint8_t threshold_c; } demo_profile_t;
static const demo_profile_t profiles[] = {
	{ 5, 25 },     /* 5 samples/s, alarm at >= 25 C */
	{ 2, 30 },     /* 2 samples/s, alarm at >= 30 C */
};

/* No DATA for this long while streaming is expected -> re-initialise DUT
 * (covers a DUT that booted late, was reset, or was re-flashed) */
#define DATA_TIMEOUT_MS   2000u
#define RETRY_PERIOD_MS   500u
/* USER CODE END PV */

Function prototypes:

/* USER CODE BEGIN PFP */
static void uart1_start_rx(void);
static bool sensor_apply_profile(const demo_profile_t *p);
/* USER CODE END PFP */

UART callbacks and the profile helper:

/* USER CODE BEGIN 0 */
static void uart1_start_rx(void)
{
	HAL_UARTEx_ReceiveToIdle_DMA(&huart1, RxBuffer, BufferSize);
	/* Half-transfer events would report the same bytes twice, disable them */
	__HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
}

/* Bytes from the emulated sensor: hand them to the client, re-arm DMA */
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	if(huart->Instance == USART1)
	{
		sensor_client_rx_isr(RxBuffer, Size);
		uart1_start_rx();
	}
}

/* Write the profile, verify it by reading back, and make sure the sensor is
 * streaming. Returns true when the DUT confirmed everything. */
static bool sensor_apply_profile(const demo_profile_t *p)
{
	sensor_remote_cfg_t cfg;

	if (sensor_client_write(p->rate_hz, p->threshold_c) != CFG_OK) return false;
	if (sensor_client_read(&cfg) != CFG_OK)                         return false;

	if ((cfg.sample_rate != p->rate_hz) || (cfg.threshold != p->threshold_c))
	{
		sensor_client_log("      read-back mismatch!\r\n");
		return false;
	}

	if (!cfg.streaming)
	{
		if (sensor_client_start() != CFG_OK) return false;
	}
	return true;
}

void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
	if(huart->Instance == USART1)
	{
		uart1_start_rx();
	}
}
/* USER CODE END 0 */

Start-up sequence, after the MX_..._Init() calls:

  /* USER CODE BEGIN 2 */
  sensor_client_init(&huart1, &huart2);
  uart1_start_rx();

  HAL_Delay(100);   /* give the DUT time to boot */
  sensor_client_log("\r\n=== Serial sensor emulation demo ===\r\n");

  /* Negative test: 0 Hz is out of range, the DUT must NACK it */
  sensor_client_write(0, 25);

  /* Configure, verify by reading back, then start streaming.
   * Keep retrying until the DUT answers (it may boot after the master). */
  uint8_t profile = 0;
  while (!sensor_apply_profile(&profiles[profile]))
  {
	  sensor_client_log("DUT not ready, retrying...\r\n");
	  HAL_Delay(RETRY_PERIOD_MS);
  }

  uint32_t last_switch = HAL_GetTick();
  uint32_t last_retry  = HAL_GetTick();
  /* USER CODE END 2 */

Main loop:

    /* USER CODE BEGIN 3 */
	  /* Print every sample the emulated sensor streams */
	  sensor_client_process();

	  /* Re-configure the running sensor periodically */
	  if ((HAL_GetTick() - last_switch) >= PROFILE_PERIOD_MS)
	  {
		  last_switch = HAL_GetTick();
		  profile = (uint8_t)((profile + 1u) % (sizeof(profiles) / sizeof(profiles[0])));

		  sensor_client_log("\r\n--- switching to profile %u ---\r\n", profile);
		  sensor_apply_profile(&profiles[profile]);
		  last_retry = HAL_GetTick();
	  }

	  /* Watchdog: sensor went silent (reset / re-flashed DUT) -> bring it back */
	  uint32_t now = HAL_GetTick();
	  if (((now - sensor_client_last_data_tick()) >= DATA_TIMEOUT_MS) &&
	      ((now - last_retry) >= DATA_TIMEOUT_MS))
	  {
		  last_retry = now;
		  sensor_client_log("\r\n--- no data from sensor, re-initialising ---\r\n");
		  sensor_apply_profile(&profiles[profile]);
	  }
  }
  /* USER CODE END 3 */

The last_retry timestamp stops the watchdog from firing again before the sensor has had 2 seconds to produce data, so a disconnected DUT is retried every 2 seconds rather than flooded with requests. You can remove the Part 2 counter demo from the Master; it is fully replaced by this code.

7. System flow

The two boards run independent loops that meet only on UART1. The diagram shows both side by side.

Dashed arrows are the frames crossing UART1: commands go to the DUT, while replies and DATA frames come back to the master’s main loop. On the master, all three recovery paths (the boot retry, the 10-second profile switch and the 2-second no-data watchdog) return to Apply profile, which is why a single function handles configuration, verification and restarting the stream.

8. Testing and results

Build and flash both projects, connect the wiring from the first section, and open a serial terminal on the Master’s ST-Link virtual COM port at 115200 8N1.

1. Normal start-up

Power both boards. The master sends one invalid request to check the DUT rejects it, then configures it, reads it back and starts streaming. At 5 Hz the temperature climbs 0.5 deg C per sample, and ALARM appears from 25.0 deg C:

=== Serial sensor emulation demo ===
WRITE rate=0 Hz threshold=25 C
WRITE -> NACK (err 6)
WRITE rate=5 Hz threshold=25 C
WRITE -> ACK
READ  -> ACK
      cfg: rate=5 Hz threshold=25 C streaming=0
START -> ACK
DATA  seq=  0  T=18.0 C  ok
DATA  seq=  1  T=18.5 C  ok
DATA  seq=  2  T=19.0 C  ok
...
DATA  seq= 13  T=24.5 C  ok
DATA  seq= 14  T=25.0 C  ALARM
DATA  seq= 15  T=25.5 C  ALARM

err 6 is CFG_ERR_BAD_PAYLOAD: the DUT refused the 0 Hz rate, which is exactly what we want.

2. Run-time profile switch

Every 10 seconds the master changes the configuration while the sensor is running. The read-back shows streaming=1, so START is not sent again, and samples continue at the new rate with the new threshold:

--- switching to profile 1 ---
WRITE rate=2 Hz threshold=30 C
WRITE -> ACK
READ  -> ACK
      cfg: rate=2 Hz threshold=30 C streaming=1
DATA  seq= 51  T=28.5 C  ok
DATA  seq= 52  T=29.0 C  ok
DATA  seq= 53  T=29.5 C  ok
DATA  seq= 54  T=30.0 C  ALARM

3. Sensor reset

Press the reset button on the DUT only. Its configuration returns to defaults and streaming stops. Within about 2 seconds the master notices and brings it back:

--- no data from sensor, re-initialising ---
WRITE rate=2 Hz threshold=30 C
WRITE -> ACK
READ  -> ACK
      cfg: rate=2 Hz threshold=30 C streaming=0
START -> ACK
DATA  seq=  0  T=18.0 C  ok

4. Power-up order

Hold the DUT in reset, reset the master, then release the DUT. The master prints WRITE -> TIMEOUT and DUT not ready, retrying... until the DUT answers, then continues exactly as in test 1.

The sequence numbers and temperatures in these logs depend on timing and will differ on your bench. What matters is the order of events, the ACKs, and the ALARM flag switching at the configured threshold.

Conclusion

This completes the series: the DUT now behaves like a real serial sensor, and the master can configure it, verify it and keep it running.

The key lessons from this part:

  • Keep interrupts short. Copy bytes into a ring buffer and do the real work in the main loop.
  • Never assume one UART event equals one frame. Parse byte by byte.
  • Make every reply a frame once more than one kind of message shares the line.
  • Verify configuration by reading it back, and design the master to recover when the device resets, because in the field it will.

The same structure can emulate other serial sensors. Change next_sample() and the DATA payload in sensor_emulator.c to model a different device, add commands to sensor_config_handle_frame(), and the protocol, parser and master client stay as they are. Natural next steps are adding noise or fault injection to the emulator, storing the configuration in flash, or replacing the XOR checksum with a CRC-8 for stronger error detection.

EmbeddedExpertIO courses

Explore the course catalogue

Find a course for your next embedded project.

Browse coursesstudy.embeddedexpert.ioOpens in a new tab

Discussion

Join the discussion

Your email address will not be published. Required fields are marked *