Starting STM8 Microcontrollers

STM8S003K3 Discovery


Should I or should I not feel fortunate was my question at the time of writing this article and that’s because STM8CubeMX was released in late February 2017. Yes, that’s the time when I was compiling all these STM8 stuffs together. Prior to that I was wondering about a software similar to STM32CubeMX but for STM8s. Back then, I could not find one and raw documentations were only helpers. Although it is still in its early stages of development and still not as robust as its STM32 cousin in terms of code generation capabilities and other areas, we can expect great innovations in the near future. It reminds me of the early days of STM32CubeMX. Not everyone expected it to overcome all the challenges in a very short period of time.  At present, we can use STM8CubeMX for common info on STM8 chips like pin assignments/mapping, basic technical specs like memory capacities, possible clock configurations, etc. I can just wonder the potential future integrations and bug fixes. Power consumption calculator is one such tool hopefully to be integrated. STM, most likely, has some serious big plans for it. Nevertheless, we must thank STM for this cool software.

Visit to download.


I recommend using it only as reference. Don’t make yourself dependent on it. There are still many bugs fixes that are yet to be addressed. One example is as in the above screenshot. Notice Timer 3 (TIM3) is missing although STM8S003 has this timer. I’m pretty sure the software developers are working hard on such silly issues. For now, it is more like a promise of good tidings to come. This is why I haven’t included it in the “must-have” software list and wanted it to be discussed separately.

Preparing the Software Tools

Firstly, we need three major documents before starting to program STM8 micros. These are as follows:

  1. STM8 Reference Manual.
  1. Datasheet of the MCU (STM8S003) that we’ll be using.
  2. STM8SVLDiscovery Board User Manual.

These docs will be needed everywhere during learning session. The reference manual states the use and purpose of all the hardware blocks in details. It includes register descriptions, naming conventions, modes of operation of all hardware, etc. However, it does not specify the specifications of a given STM8 micro and that’s because it is a generalized literature for all STM8S and STM8AF micros. As we know even within a family of micros, one MCU differs from another in many aspects. Most commonly this variation comes in the form of memory capacities and I/O pin counts. Sometimes electrical specs also vary and so to know the limits and general specs of our target MCUs we need to checkout their respective datasheets. Lastly the Discovery board user manual is most useful for the hardware schematics, pin assignments and layouts. If you are using some other board then I suggest that you acquire at least its schematic.

Now with Cosmic, STVD and STVP installed our software tool setup is almost ready. There are two approaches to STM8 programming. The first uses the traditional concepts of register-access-based coding, meaning you’ll have to set up every register on your own. The second way utilizes a specialized method of coding by using standard libraries developed by STM that are both universal and platform independent, meaning your C code will be same for any compiler using these libraries. These libraries are called Standard Peripheral Libraries (SPL). With these libraries, no one will ever need to get down to register-level access. The libraries are so coded that a coder will only have to know his/her chips’ hardware specs and some basics of these hardware. On the coding part, he/she will only have to set properties and desired values. The SPL manages the rest. For instance, when setting up a UART, we will only need to set interrupts, IOs and UART properties like baud rate, parity, etc. All of these setups are done with meaningful numbers and texts.

The STMicroelectronics Standard Peripheral Libraries (SPL) for STM8 microcontrollers can be found here:

I wrote this article using SPL since it will be ridiculous to code STM8s using the old-fashioned way of configuring registers one-by-one manually. Thus, it is a mandatory download item. You should preserve and retain the downloaded SPL zip file fully intact. You may need it when things get messy.

Now make two folders and name them “inc” and “src”. The “inc” folder will be filled with all the header files (“.h” extension files) from the extracted zip file. Similarly, the “src” folder will be holding the source files (“.c” extension files). For ease of work, it is better to keep these folders secured just like the SPL zip file because every time when we will be making new projects the files in these folders will be needed. You can copy these files to your project folder or you can keep it centrally somewhere. I prefer the former method as doing so will not have any conflicting issue with other projects needing modifications. However, it will cost hard-drive space. This method is however less confusing and trouble-free for beginners. Extract all the files as shown below:

Source and Header Files

Note that there are more header files than source files. This is because there are two extra header files – stm8s.h and stm8s_conf.h that define processor type and processor properties. To make things work, we will have to comment one line of the stm8s_conf.h. You will find a line at the bottom of this file written as:

#define USE_FULL_ASSERT    (1).

You need to comment or disable this line, otherwise the compiler will throw tons of error messages.  Always check this at the start of a project. Surely, we don’t want to assert our code.

Creating a New Code Project

Assuming that STVD, STVP and Cosmic are properly installed, we will see how to create a new project.

  • Firstly, run STVD.
  • Select File >> New Workspace.

New Workspace

  • Select Create workspace and project.

Create New Workspace

  • Select workspace folder and workspace name.

Workspace Title

  • Set project name and select toolchain STM8 Cosmic. You may need to set the path of your Cosmic compiler’s installation location. In my case, it is:
    C:\Program Files (x86)\COSMIC\FSE_Compilers\CXSTM8

Project Details

  • Type and select target chip part number. Last two or three digits and letters are enough for finding the correct micro.

Chip Selection

  • Now add the source and header files from the previously mentioned SPL folder.

File Inclusion

  • After file inclusions, the workspace tab changes as shown below:


  • Locate and open c file from the source tab, and then type #include “stm8s.h” at the top as shown below:

main file

  • You’ll have to edit the h header file and uncomment the chip number you are going to use as shown below:

STM8S.h Chip Identification

  • Compile the code once using the key combination CTRL+F7 or by pressing the compile button. If everything is okay, there should be no error or warning message. The reason for this blank compilation is to use the compiler’s powerful code assistant feature. With this feature, we can predict or complete a piece of code line by only writing the first few letters and then pressing CTRL + SPACE keys simultaneously.

Code Assistant

During compilation, you may get tons of errors for hardware files that are not available in your target STM8S micro. For instance, CAN hardware is not available in STM8S003K3 and so if you have added CAN source and header files you will get an error for that. Once identified by the error messages, the corresponding header and source files for that particular hardware must be removed.

Similarly, one more caution must be observed. Unless your code is using any interrupt, interrupt source and header files (stm8s_it.h and stm8s_it.c) must be excluded. Sometimes it is better to add only those files that you will need to complete a project. For example, if your project is just using GPIOs, it is better to add GPIO files only along with stm8s.h and stm8s_conf.h. However, I recommend this technique only after you have mastered STM8 coding well because in most cases you will need multiple hardware which have dependencies on each other. As an example, when using SPI, you’ll need both GPIO and SPI modules. If you understand these dependencies, it is okay to select files as per need. You can, then, comment out unnecessary hardware module files specified in the stm8s.h header file and get a faster compilation and build process. After compilation, you should always build/rebuild your project by hitting the Build or Rebuild button. This will generate the final s19 output file in either Debug or Release folder according to the generation mode selected. If things are in order, there should be no error or warning message.

Coding Final

Lastly, I have not found any useful simulation software like Proteus VSM or Electronic Workbench that support STM8 family. Thus, we have to debug our code in real-life with real hardware. It may sound difficult but actually it is not so. We can, however, use such software to make models of STM8 micros and make our PCBs. I don’t like simulations as they are not always accurate and real-world type.

One more advice I would like to give to the readers. Please read the SPL help file. It is located in the SPL zip file under the name stm8s-a_stdperiph_lib_um.chm. It explains each function, definition, data structure, all internal hardware modules and how to use them properly. This is a very important document and your best friend in coding STM8 micros. Apart from this document the reference manual is equally important as it details the capabilities of all internal hardware. I won’t be detailing the internal hardware much as these docs will be doing so.

Uploading Code

Codes generated by Cosmic C compiler have s19 file extensions. It is similar to typical hex file format, containing user code as hex values. Well since we don’t need to modify finally generated output files, it doesn’t really matter in which format it is. All we will need is to upload them to our target MCUs. We can do it in two ways – either by using STVP or STVD.

Firstly, let’s check the method with STVP. Run STVP software. For the first time the following window will appear. From here we have to select ST-Link programmer, SWIM interface and our target chip.

Selecting Programmer

STVP interface looks like any other programmer interface as shown below:


Notice the mid tabs at the bottom of the hex values. From here we can see the hex values for program memory, data/EEPROM memory and configuration settings. The configuration setting bits are intended for setting some special hardware configurations or extending features of the target as well as setting memory readout protection.

Configuration Bits

Try not to mess with security or protection bit at first or during tests as it will lock your chip up, rendering it useless. You won’t simply be able to write it again until you unlock it. Unless needed, we won’t be changing any default configuration bit. One thing to note is the fact that upon new compilation and build, the newly generated output file is automatically reloaded. The rest of the stuffs like loading or saving a s19 file, reading, writing and others are as simple as like with other programmers. I won’t be explaining these steps as I assume that readers of this article already know how to do all these from their previous experiences with other MCUs.

Now we will explore how we can upload a code to our target using STVD. After compiling and building a project successfully without any error, the compiler will generate a s19 output file either in Debug or Release folder depending on which mode of compilation selected. By default, Debug mode is selected unless the coder changed it and so our desired s19 file will be in this folder. First, we need to open the programmer interface. We can do that either by clicking the icon as shown below:


or we can go to Tools >> Programmer.

We will get a new window as shown below:

STVD Programmer Interface

As the name of the new window suggests, it is a light-weight programmer interface but good enough for our purpose. Notice that there are many options and four tabs. Here again we need to select programmer, programming interface (SWIM) and erase/blank check options. Then we go to the next tab to select files for EEPROM (if any) and Program (also Flash/Code) memory as shown below. You can add/remove files just as usually.

STVD Programmer Interface 2

Next, we set configuration bits if needed from the tab as shown below:

STVD Programmer Interface 3

Finally, we are ready to upload code. Just hit the start button and wait for the process to finish.

STVD Programmer Interface 4

Every time a code is programmed, it is verified automatically.

Continue Reading ...

Related Posts


  • Hi there, i solve the previous ADC problem. Anyway, u make some good tutorial on stm8 chips. Nice work

    • What was causing that issue? How did you solve it?

      • because i put all these

        ADC_SamplingTimeConfig(ADC1, ADC_Group_SlowChannels, ADC_SamplingTime_4Cycles);
        ADC_SchmittTriggerConfig(ADC1, ADC_Channel_7, DISABLE);
        ADC_ChannelCmd(ADC1, ADC_Channel_7, ENABLE);
        ADC_Init(ADC1, ADC_ConversionMode_Continuous, ADC_Resolution_12Bit, ADC_Prescaler_1);
        ADC_Cmd(ADC1, ENABLE);
        ADC_ExternalTrigConfig(ADC1, ADC_ExtEventSelection_None, ADC_ExtTRGSensitivity_All);

        in ‘while(1)’. It keeps looping.

        Once i put it before ‘while (1)’, it becomes normal.

  • Hi there, thanks for sharing. I learn alot thru your example, but I have encounter a problem with adc. Im currently using stm8l151k4t6. I wanna use the pin D7 as to read the voltage from my battery and monitor it (display on LCD). Can u please check where it goes wrong on my code?

    ADC_SamplingTimeConfig(ADC1, ADC_Group_SlowChannels, ADC_SamplingTime_4Cycles);
    ADC_SchmittTriggerConfig(ADC1, ADC_Channel_7, DISABLE);
    ADC_ChannelCmd(ADC1, ADC_Channel_7, ENABLE);
    ADC_Init(ADC1, ADC_ConversionMode_Continuous, ADC_Resolution_12Bit, ADC_Prescaler_1);
    ADC_Cmd(ADC1, ENABLE);
    ADC_ExternalTrigConfig(ADC1, ADC_ExtEventSelection_None, ADC_ExtTRGSensitivity_All);
    while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC));
    battery = ADC_GetConversionValue(ADC1);

  • hi shawon great tutorials it would be nice too if you covered the coide compiler for arm it’s a good free compiler

  • hi shawon thanks for your response and support it turns out that my problem was a license issue I stupidly thought i use one license on multiple pc’s I used the license for a particular computer for mine that’s why I’ve been having compilation issues you have to use the license file stm8 sends you that is generated by your own pc else it won’t compile it’ll jus kip throwing you errors

  • I haven’t compiled any of the examples yet I just tried to compile the main source file just for test purpose n it just keeps showing me the same errors

  • yes the comic compiler was installed properly i even received a license file from my mail with the instructions to copy the license file to the license folder in the install directory if you fail to do this it will keep popping up for you to put in the license file. iincluded all the source files and header files as instructed i am working with the cheap stm8s103f i uncommented the stm8s103f in the stm8.h header file as you instructed and just to compile the main file it just throws me errors

  • no I just followed your instructions I just compiled it after setup i did not write any code yet just compiled the default main file

    • Need more details….

      1. The version of STVD and Cosmic
      2. Which example is giving this issue?
      3. The chip you are using if it other than STM8S003
      4. Have you tried to compile something else other than my examples?
      5. Are the paths to libraries and other folders properly added?
      6. Is the Cosmic compiler registered properly?

  • it throws this line The command: “cxstm8 -iinc +debug -pxp -no -l +mods0 -pp -i”C:\Program Files (x86)\COSMIC\FSE_Compilers\Hstm8″ -clDebug\ -coDebug\ main.c ” has failed, the returned value is: 1
    exit code=1.

  • hi I’m having compilation issues when I compile it just throws me error about comic compiler located in the program file ialso excluded unwanted header files but my problems still weren’t solved

  • hi thanks for the tutorials but i am having compiler error issues even when I remove unnecessary header files it say comic compiler error

  • I am new to STM8S003k3 Discovery board.I have done UART communication using STM standard peripheral library example. Now I want to define any other GPIO pin for UART communication. Is it possible to use d0 and d1 pin for the UART communication? If yes, then please let me know how?

  • thank you very much for this article!

  • Thank you for your time and effort.

  • Good job bro

  • Thank you for this exceptionally comprehensive article, much appreciated


  • It seems that you didn’t follow my instructions completely…. I found some issues:

    1. You have included header and source files of ADC2, CAN, UART2, etc which are unavailable in STM8S103…. Add only files for the peripherals available in your target MCU…. Exclude the rest….

    2. You have not included stm8s_delay header and source files…. Either disable it from stm8s_conf.h header file if you are not going to use it or add both the header and the source files for it in your project….

    Resolve these and you are good to go….


Leave a Reply

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