STMicroelectronics STM8 User Manual

Starting STM8 Microcontrollers
STM8 microcontrollers are 8-bit general purpose microcontrollers from STMicroelectronics (STM). STM is famous mainly for its line of 32-bit ARM Cortex microcontrollers – the STM32s. STM8 microcontrollers are rarely discussed in that context. However, STM8 MCUs are robust and most importantly they come packed with lots of hardware features. Except for the ARM core, 32-bit architecture, performance and some minor differences, STM8s have many peripheral similarities to STM32s. In my opinion, STM8s are equally or sometimes more matched than the popular PICs and AVRs in all areas. Unlike PICs and AVRs however, I have seen STM8s mostly in various SMD packages. Only a handful of STM8 chips are available in PDIP/through-hole packages. I think it is a big reason for which most small industries and hobbyists don’t play with them as much as with other 8-bit families. People like to setup their test projects in breadboards, trial PCBs or strip-boards first, prototype and then develop for production. To cope with this issue, STM has provided several affordable STM8 Discovery (Disco) boards to get started with. Besides there are many cheap STM8 breakout-boards from China.
I have experience playing with AVRs, PICs, 8051s, STM32s, MSP430s, TivaC and so on. To be honest, I thought learning about STM8 micros is a pure waste of time and energy. The learning curve will be steep. Things and tools would be different and thus difficult. However, gradually I found these MCUs very useful and there’s literally no complexity at all. The main drive factor for learning STM8s is the price factor. They are hell cheap. When it comes down to other things, I have not found any book on STM8s written in English. There’s literally no 100% complete blog post on the internet that shows the basics. Similarly, same story with tools. I have been using MikroC for AVRs, 8051s and ARMs and it is my favourite but at the time of writing, there’s no MikroC compiler for STM8 family. I have also not stumbled upon any Arduino-like IDE that supports STM8 micros. Arduino-based solutions are also not my favourite as they don’t go deep and have several limitations. Maybe it is not my luck. After much study and search, I found out that there are a few C compilers for STM8s. However, any new tool is both different and difficult at first. It is not always easy to adapt to new environments. You may never know what unanticipated challenges and harshness a new environment may throw at you even when you reach certain levels of expertise. I also dont want to use any pirated software and so a free compiler was a major requirement. I found out ST Visual Develop and Cosmic COSC compiler are both free tools. Cosmic used to be a paid tool but now it is absolutely free. The only easy thing till then was buying the STM8S Value Line Discovery board for just a few dollars and downloading the stuffs.
The STM8 Family
There are over a hundred STM8 microcontrollers available today. The STM8 family can be simplified into three categorical groups as shown below.
There are subgroups within these groups but broadly speaking these three groups are what by which we can define the entire family. STM8S micros are general purpose robust and reliable micros that can be employed in almost all scopes. This is the most commonly used group and in fact we will be exploring it in this article. They are also cheap and smart. The second group – the STM8A family is intended mainly for automotive industries. This group is packed with additional hardware interfaces like CAN and LIN that are musts according to present-day automotive industry doctrine. The STM8As are also very robust and are designed to withstand the harsh extremes of an automobile. For instance, STM8As can withstand high temperatures, in excess of 100°C. The last group consists of STM8L micros which are crafted for low power or battery-backed applications. Virtually they consume no power in idle mode. Thus, if you need high power savings or energy cuts in your projects, this group is the best choice. There are also low power versions of automotive-standard STM8 micros that are labelled STM8AL. Apart from all these there is also one version of STM8 micros that are specifically designed for capacitive touch applications. These are called STM8Ts.
The features and benefits of STM8 micros are numerous and can’t simply be expressed in few words. The more you explore, the more you will feel. STM8s can be powered with 3.3V or 5V DC power supplies and have built-in brownout detection circuitry. The low power editions can operate at much lower voltages than these values. Official STM8 Discovery boards come with voltage selection jumpers to allow users to select operating voltage level as required. There is very minimum risk of program corruption due to EMI or some other similar unprecedented factors. There is fail-safe security for the clock system which ensures that a system based on a STM8 micro won’t stop working or stuck up should its external clock source fail. All internal hardware possesses more features than any other competitive 8-bit microcontroller families that are widely available in the market. The best part is the price benefit. You pay less for the most. All these features are well-suited for extremely harsh industrial environments. STM8s are designed with maximum possible combinations of features. Beyond your wildest wet dream, there are many extraordinary stuffs waiting to be unboxed.
Overview of the Discovery Board
For getting started with STM8s, STM has provided several STM8 Disco boards. There are also other third party boards too. However, I strongly recommend Disco boards for learning and experimental purposes. There are several reasons for this recommendation. One main reason is the fact that all Disco boards come with on-board detachable ST-Link programmers and they are extremely cheap. Shown below is the top layout of a STM8S discovery board.
The board I used here in this article hosts a STM8S003K3T6 micro. It is an 32 pin entry-level micro with 8kB flash, 1kB RAM and 128 byte true data EEPROM. It comes with some additional hardware – a LED connected to PD0 and a push button connected to PB7. Just as I said it also houses a detachable ST­Link programmer. However, I don’t recommend separating the programmer from the whole package. The board also has a prototyping area should one needs to prototype something. The overall board has a small form-factor and is a bit longer than a standard credit card. There are several other similar and popular STM8 Discovery boards like the STM8S105 Discovery.
There are also bulks of cheap Chinese minimum system STM8 dev boards hosting different STM8 chips. Overall the boards and the chips are so cheap that many simple cheap gadgets from China are based on STM8 MCUs.
Some cheap STM8-based simple products are shown below:
The first one is a cheap DIY LC meter LC-100A. The other one is a simple DC panel meter. These are just simple examples. There are many industrial and sophisticated products based on STM8 micros.
Hardware Tools
The list of hardware tools needed is not very long. We will obviously need a STM8 board and I prefer a Discovery board over other boards since it comes with a built-in ST-Link programmer/debugger hardware. If you have some other board like the ones I already showed, you will need a ST-Link programmer. I recommend an additional ST-Link programmer apart from the one available on board.
ST-Link programmers/debuggers communicate with target STM8 micros via SWIM interface. This interface is the standard for all STM8 micros. Basically, it is a four-wire interface with two wire (VDD and GND) being used for powering the target. The rest two are reset I/O and SWIM I/O. In the official ST-Link V2 programmer unlike other ST-Link programmers, there is a dedicated port for SWIM interface with STM8 inscribed near it. Cheap USB flash drive-sized ST-Links are also available in the market and they are portable and as good as the official ones.
Apart from these we will also require some basic electronic lab stuffs like a USB-to-serial converter, connecting/jumper wires, LEDs, buttons, various types of sensors, etc. that are typically found in a common Arduino starter kit.
It is yet better if you have either a logic analyser or oscilloscope. A good multimeter and a well­regulated DC power supply/source are must haves. You can also use a cell phone charging power bank as a power source since Disco boards have USB ports.
Software Tools
Just like any other software developer, my choice of language for software development is C language.
I don’t want to spend time coding complex stuffs in assembly language. Apart from that I chose C
language for the fact that STMicroelectronics has provided a Standard Peripheral Library (SPL) that is very easy to use. With SPL, it becomes totally unnecessary to program each register with meaningless numbers and maintain coding sequence. We will never need to access registers for any reasons as everything is done under the hood of SPL. All sequences are deal inside the SPL. All that we will ever need is the clear concept of each hardware block, their working principles, their capabilities and limitations.
We will need an Integrated Development Environment (IDE) and a C-language toolchain. The best stuffs you can get your hands on at zero costs are ST Visual Develop (STVD) IDE and Cosmic C compiler. Both are free but a rather difficult to use at first. STVD also comes with a programmer software tool called ST Visual Programmer (STVP). We’ll need STVP to upload codes to target STM8 micros.
Cosmic used to be a paid tool just like your PC’s antivirus software but at the time of writing this article, the Cosmic team has made it absolutely free for STM8 family. However, to use it you will need to register and acquire a license key via email. Usually this procedure of acquiring license and registration is maintained automatically by the software company’s server but with Cosmic it is different story. You will need to wait for some guy at Cosmic end to respond to your license request. It may take a few minutes or even a day but still the best part is getting a full version compiler for nothing.
You can get STVD from here: http://www.st.com/en/development-tools/stvd-stm8.html and Cosmic C compiler from here: http://www.cosmic-software.com/download.php.
You need to register in order to download both software. For Cosmic you will also need to acquire a free license for it work. So just fill in some basic info about you.
Firstly, we will need to install STVD. Installation procedure is simple and same as typical software installation. Just click next, next and next. After that we will need to install Cosmic C compiler. Again, just next, next and next until the screen as shown below.
After installation, you’ll prompted for licence. You must register your license unless you have already registered. If you have already registered, then you’ll be asked if to overwrite registration. You should
skip reregistering.
For the first run, you’ll get the following screen looking for a valid license.
You must fill all the starred (*) points to complete the process of registration. Select “Write to File” option and save the file as a text (.txt) file. The file name should be “CM8_license.txt”. Send this file to stm8_Free@cosmic.fr with subject “STM8FSE, STM32 32K License Request. Now you’ll need to
wait for the Cosmic team to respond to you. They’ll send you an email back with an electronic key license. The file will have a name like “license.lic” and the email will have some instructions.
This was my emailed license.
Once you get the license, you’ll need to show the software its location and complete the licensing process as shown below. Save the license file in a secured location.
At the end of this process, we can enjoy the compiler without any limitations.
I also recommend that you download Sublime Text (https://www.sublimetext.com/) or Notepad++ (https://notepad-plus-plus.org/) for viewing your code with ease. These are very cool software. This is not mandatory though.
STM8CubeMX
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 http://www.st.com/en/development-tools/stm8cubemx.html to download STM8CubeMX.
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.
http://www.st.com/content/ccc/resource/technical/document/reference_manual/9a/1b/85 /07/ca/eb/4f/dd/CD00190271.pdf/files/CD00190271.pdf/jcr:content/translations/en.CD001
90271.pdf
2. Datasheet of the MCU (STM8S003) that we’ll be using.
http://www.st.com/content/ccc/resource/technical/document/datasheet/42/5a/27/87/ac/ 5a/44/88/DM00024550.pdf/files/DM00024550.pdf/jcr:content/translations/en.DM0002455
0.pdf
3. STM8SVLDiscovery Board User Manual.
http://www.st.com/content/ccc/resource/technical/document/user_manual/c8/37/11/ba/b 5/e7/4c/ee/DM00040810.pdf/files/DM00040810.pdf/jcr:content/translations/en.DM00040
810.pdf
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: http://www.st.com/en/embedded-software/stsw-stm8069.html.
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:
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.
1. Firstly, run STVD.
2. Select File >> New Workspace.
3. Select Create workspace and project.
4. Select workspace folder and workspace name.
5. 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
6. Type and select target chip part number. Last two or three digits and letters are enough for
finding the correct micro.
7. Now add the source and header files from the previously mentioned SPL folder.
8. After file inclusions, the workspace tab changes as shown below.
9. Locate and open main.c file from the source tab, and then type #include "stm8s.h" at the top
as shown below:
10. You’ll have to edit the STM8S.h header file and uncomment the chip number you are going to
use as shown below:
11. 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.
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.
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.
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.
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:
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.
Next, we set configuration bits if needed from the tab as shown below:
Finally, we are ready to upload code. Just hit the start button and wait for the process to finish.
Every time a code is programmed, it is verified automatically.
General Purpose Input Output (GPIO)
The very first “Hello World” project that we do with every new embedded device is a simple LED blinking program. Here we do the same. We will be basically testing both input and output function by making a variable flash rate blinking LED. Check the schematic of the Disco board. Check the pins with which the on-board LED and the push button are connected.
You can also use the STM8CubeMX in board selector mode for this too.
Shown below is the internal block diagram of GPIO pins:
Because each I/O is independently configurable and have many options associated with it, its block looks complex at first sight. Check the various options every I/O possess:
Shown below are the SPL functions associated with the GPIO module.
Observe the code below. This is the power of the ST’s SPL. The code is written with no traditional
register access. Everything here has a meaningful nomenclature, just like regular naming/words of the reference manual/comments. There shouldn’t be any issue understanding the code. The code is almost Arduino-like. Here we are polling an input pin’s state to alter the blink rate of a LED.
Hardware Connection
Co de Example
#include "STM8S.h"
void main (void) { bool i = 0;
GPIO_DeInit(GPIOB); GPIO_DeInit(GPIOD);
GPIO_Init(GPIOB, GPIO_PIN_7, GPIO_MODE_IN_FL_NO_IT); GPIO_Init(GPIOD, GPIO_PIN_0, GPIO_MODE_OUT_PP_LOW_FAST);
for(;;) { if(GPIO_ReadInputPin(GPIOB, GPIO_PIN_7) == FALSE) { while(GPIO_ReadInputPin(GPIOB, GPIO_PIN_7) == FALSE);
i ^= 1; }
switch(i) { case 0: { delay_ms(1000); break; } case 1: { delay_ms(200); break; } }
GPIO_WriteReverse(GPIOD, GPIO_PIN_0); } }
Explanation
The following lines deinitialize the GPIOs we used. Every time you reconfigure or setup a hardware peripheral for the first time you must deinitialize it before using it. Though it is not mandatory, it will remove any chance of wrong/conflicting configurations.
GPIO_DeInit(GPIOB); GPIO_DeInit(GPIOD);
After deinitialization, we are good to go for initializing or setting up the GPIOs. Inputs can be with or without internal pull-up resistors. Outputs can be either push-pull totem-pole or open drain types. Each pin can be individually configured and does not have any dependency on another. The following codes set GPIO PB7 as a floating input with no interrupt capability and GPIO PD0 as a fast push-pull output. PB7 is set up as a floating input rather than an internally pulled-up input because the button on the Disco board is already pulled up externally.
GPIO_Init(GPIOB, GPIO_PIN_7, GPIO_MODE_IN_FL_NO_IT); GPIO_Init(GPIOD, GPIO_PIN_0, GPIO_MODE_OUT_PP_LOW_FAST);
The remaining part of the code in the main loop is just polling the button’s state and altering the delay
time for toggling the LED if the button is pressed.
for(;;) { if(GPIO_ReadInputPin(GPIOB, GPIO_PIN_7) == FALSE) { while(GPIO_ReadInputPin(GPIOB, GPIO_PIN_7) == FALSE); i ^= 1; }
switch(i) { case 0: { delay_ms(1000); break; }
case 1: { delay_ms(200); break; } }
GPIO_WriteReverse(GPIOD, GPIO_PIN_0); }
Demo
Video link: https://www.youtube.com/watch?v=Rr1vpfoze4w
Clock System (CLK)
The internal network of STM8 clock system allows us to tune up operating speeds of peripherals and CPU according to our needs. Software delays and power consumption depend on how the clock system is set.
In STM8 micros, there are three main clock sources – High Speed Internal Clock (HSI), High Speed External Clock (HSE) and Low Speed Internal Clock (LSI). The HSI has an oscillating frequency of 16MHz and is an internal RC oscillator with good precision – about 1% tolerant over a wide temperature range. HSE can be an external clock circuitry, temperature-compensated crystal oscillator (TCXO) or ordinary crystal resonator. It accepts all frequencies from 1MHz to 24MHz. Lastly, LSI clock is also an independent internal RC oscillator-based clock source that is mainly intended for idle or low power operating modes and the independent watchdog timer (IWDG). It has a fixed factory calibrated operating frequency of 128kHz and is not as accurate as HSI or HSE. There are also clock dividers/prescalers at various points to scale clocks as per requirement. Mainly two prescalers are what we need – the HSI prescaler and the CPU divider. Peripherals are directly feed by the main clock source. Additionally, there is a clock output pin (CCO) that outputs a given clock frequency. It can be used to clock another micro, generate clock for other devices like logic ICs. It can also be used as a free oscillator or perform clock performance tests. There’s fail-safe clock security that makes HSI backup of HSE. Should HSE fail, HSI takes over automatically. Check the internal block diagram below:
Loading...
+ 96 hidden pages