STM8S103F3P6 dev board schematicBoard Schematic

UART is one of the rudimentary and crucial peripheral. Using UART in STM8 microcontroller is also effortless. We will use STM8S003F3 or STM8S103F3 Blue pill board for the demo purposes. But this code will equally work well on other variants of the STM8S microcontrollers. As I had tested this code on STM8S903K3 micro controller as well.


We are going to write a code for the STM8S microcontroller to use its UART peripheral. As we are going to use STM8S003F3 blue pill board we are going to use the UART1. We are going to run the STM8S microcontroller with internal 16MHz Clock. Also we need to enable the clock for the UART1 peripheral in clock manager.

UART Registers

We are going to use the following UART related register which are grabbed from the stm8s reference manual. The list of the STM8S UART registers are as follows

  1. UART1_BRR1 & UART1_BRR2 for baud rate generation
  2. UART1_CR3 for stop bit selection
  3. UART1_CR2 for enabling the TX and RX mode
  4. UART1_SR register for status checking like is transmission completed or is there some data to read from UART

STM8 UART code

Here is the complete code for the STM8 UART peripheral. In that code after adding the proper header file we set the clock to 16Mhz. After that enable teh peripheral clock and put the required values from the reference manual into the BRR register to select the 9600 baud rate. Once baud rate is set we set the stop bits from the CR3 register. After that we enable the TX and RX bit in CR2 register. Once everything is done we are good to transmit the character to the serial terminal. Or receive character from serial terminal.

/* MAIN.C file

   Copyright (c) 2002-2005 STMicroelectronics

#include <iostm8s003.h>

void UART_TX(unsigned char val) {
  UART1_DR = val;
  while (!(UART1_SR & (1 << 6)));

unsigned char UART_RX(void) {
  while (!(UART1_SR & (1 << 5)));
  return UART1_DR;

  CLK_CKDIVR = 0x00;  //set clock 16MHZ
  CLK_PCKENR1 = 0xFF;  // Enable peripherals
  UART1_BRR2 = 0x03;
  UART1_BRR1 = 0x68;  // 9600 baud
  UART1_CR3 &= ~((1 << 4) | (1 << 5)); //1 STOP BIT
  UART1_CR2 |= (1 << 2) | (1 << 3); //ENABLE TX AND RX

  while (1) {
    unsigned char inChar = 0;
    if (UART1_SR & (1 << 5)) {
      inChar = UART_RX();
}Code language: PHP (php)

By Abdul Rehman

My name is Abdul Rehman and I love to do Reasearch in Embedded Systems, Artificial Intelligence, Computer Vision and Engineering related fields. With 10+ years of experience in Research and Development field in Embedded systems I touched lot of technologies including Web development, and Mobile Application development. Now with the help of Social Presence, I like to share my knowledge and to document everything I learned and still learning.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.