Thursday 17 October 2019

Getting Started with STM32

Every time that I’m free, I will be posting some interesting tutorials on CloudX, Microchip PIC and most especially STM32. Recently I discovered about Embedded Linux and its applications which I will also write tutorials about later. Migrating from Microchip PIC or ATMEL processors to Cortex M is almost like you’re starting embedded systems all over again because you will have to learn the selected MCU datasheet, reference manual, firmware library, the pin mapping and the peripherals. Though learning will be a bit faster since you’ve been writing embedded codes before. It took me about a week to fully understand the complete Cortex-M architecture and the Standard Peripheral Library (SPL) which will be discussed later in this tutorial.
                                       


I wrote my first ARM®-based 32-bit MCU tutorial “Programming STM32 on Linux” on medium.com showing how to program the microcontroller on Linux Distros without depending on any IDE. This tutorial is not for people completely new to the C language or embedded programming. I assume you have a decent knowledge of C and are not new to most fundamental concepts of digital electronics and MCU programming irrespective of the manufacturer.

Most new microcontrollers are nowadays based on the ARM architecture and specifically on the popular Cortex-M3 and Cortex-M4 processors. Using ARM Cortex-M3 and Cortex-M4 processors based devices today is straightforward since a wide range of development tools, debug utilities, and many example projects are available. However, writing efficient applications could require in-depth knowledge about the hardware architecture and the software model. It gives insight into popular software development tools along with extensive programming examples that are based on the Cortex Microcontroller Software Interface Standard (CMSIS).

                                                              

     

With the term ARM, it  refer to both a multitude of families of Reduced Instruction Set Computing (RISC) architectures and several families of complete cores which are the building blocks of CPUs produced by many microcontroller manufacturers or vendors like STMicroelectronics, Analog Devices, Atmel, Cypress, EnergyMicro, Freescale, Fujitsu, Holtek, Infineon, Microsemi, Milandr, NXP, Samsung, Silicon Laboratories, Texas Instrument, and Toshiba. ARM does not make microcontrollers. ARM designs processors and various components that silicon designers need and licenses these designs to various silicon design companies including microcontroller vendors. When dealing with ARM based processors, a lot of confusion may arise due to the fact that there are many different ARM architecture revisions (ARMv6, ATMv6-M, ARMv7-M, ARMv7-A, and so on) and many core architectures, which are in turn based on an ARM architecture revision. For the sake of clarity, for example, a processor based on the Cortex-M3 and Cortex-M4 core is designed on the ARMv7-M architecture. Both are high-performance processors that are designed for microcontrollers while the Cortex-M0, Cortex-M0+, and the Cortex-M1 processors are based on ARMv6-M, which has a smaller instruction set.

        
                                       


I don’t want to spend much time on the introduction, you can find books that would explain in details all you need to know about the Cortex-M series. I will quickly take us through what you need to know on how to create your first hello world project by blinking an LED.

In this tutorial series, I will be using Atollic TrueStudio for STM32 IDE, which I promised to write about when I wrote my first STM32 Linux tutorial on medium. I have tried different STM32 IDE in which most are not free, I also prefer Coocox but the developers have stopped improving and supporting the software. I prefer to code on Atollic Truestudio ever since it was acquired by ST Microelectronics and has been fully improved on with a lot of features supporting all STM32 devices and development boards, built on Eclipse, CDT, Highly optimizing C/C++ compiler, code editor and review, Build/Memory Analyzer, Stack Analyzer, Single and multi-core Debug, Project Management, Hard Fault Analysis, Version Control for Git, Trace & Profiling, Bug Tracking, RTOS-aware Debug.

Inputs, outputs, and peripherals accesses


Almost all microcontrollers have various Input/Output (I/O) interfaces and peripherals such as timers, Real-time Clock (RTC), and so on. For microcontroller products based on the ARM_ Cortex_-M3, and M4 processors, as well as common interface peripherals such as GPIO, SPI, UART, I2C, you can also find many advanced interface peripherals like USB, CAN, Ethernet, and analogue interfaces like ADCs (Analog to Digital Converters) and DACs (Digital to Analog Converters).

Understanding the STM32 Libraries.


There are basically two libraries (SPL and HAL) developed for STM32 MCUs while Cortex Microcontroller Software Interface Standard (CMSIS) is a hardware abstraction layer for all ARM Cortex-M devices developed to allow microcontroller and software vendors to use a consistent software infrastructure to develop software solutions for Cortex_-M microcontrollers. It means you don’t need to worry about compatibility issues across different Cortex-M manufacturers.

This two libraries, Standard Library Peripheral (SPL) and Hardware Abstraction Layer (HAL) which are the old and new library respectively. It was developed by ST to make project development faster for programmers. Actually, you can also program STM32 using embedded OS for multitasking purpose without having to bother about the hardware. I will also post tutorials on using my favourite RTOS API driver called ChibiOS developed by Giovanni, though there are many other good embedded OS like the popular FreeRTOS, embOS etc,

To be able to code any STM32, you will need to download the specific datasheet and reference manuals. In most of my tutorials, I advise you to use the SPL which will allow you to have deep understanding on how the peripherals really works, although there are many tutorials and books on the internet that shows more on how to use HAL for project development. Many RTOS drivers also support HAL. If you have enough time, you can also learn to use both libraries.

All this libraries are created to make programmers life easier, all you need to do is to learn how to use the library, there are also a lot of documentations and sample codes, and you also need to learn the ST microcontroller architecture which you want to use. I recommend you search on google for UM0427 User manual to understand and know how to use the SPL ARM®-based 32-bit MCU STM32F101xx and STM32F103xx firmware library properly.


Step and Step Guide to build your first Project


For this project, I have chosen to use STM32F103C8T6, it’s one of the popular Cortex-M3 device. I intentionally selected this MCU because it’s the cheapest you can find in the market, it cost about $2 but sold around 1500 Naira in the Nigeria market, the board comes in different PCB colors, The blue PCB color is referred to as “Blue Pill”, the black PCB as “Black Pill” and the Red PCB as “Red Pill”. I have used the blue pill and black pill board, the only difference in the PCB is that the blue pill has a 5v pinout which makes it very easy to quickly get it into any of your microcontroller project unlike the black pill that will still require an external 3.3v regulator.

Blue Pill
Black Pill



This is the breakdown of the name:

• STM32 (STMicroelectronics platform)
• F1 (device family)
• 03 (subdivision of the device family)
• C8T6 (physical manifestation affecting amount of SRAM, flash memory, and so on)


I strongly recommend you go through the datasheet to get full feature details on the pins assignments etc. The MCU is a Medium-density performance line ARM®-based 32-bit MCU with 64 or 128 KB Flash, USB, CAN, 7 timers, 2 ADCs, 9 com. Interfaces.


Features


·        4 x 16-bit GPIO Ports (most are 5-volt tolerant)
      3 x USART (Universal Synchronous/Asynchronous Receiver/ Transmitter)
·        2 x I2C controllers
·        2 x SPI controllers
·        2 x ADC (Analog Digital Converter)
·        2 x DMA (Direct Memory Address controllers)
·        4 x timers
·         watch dog timers
·        1 x USB controller
·        1 x CAN controller
·        1 x CRC generator
·        20K static RAM
·        64K (or 128K) FLASH memory
·        ARM Cortex M3 CPU, max 72 MHz clock



STLINK V2


The next important piece of hardware is a programming adapter and debugger. Fortunately, these are also very economically priced. These can be found on the local market or online stores like Hub360 in Nigeria for about $5 US approximately N1500 in Naira.
Most auctions will include four detachable wires to connect the unit to your STM32 device. Try to buy a unit that includes these unless you already have a cable. The USB programmer is usable from Windows, Raspberry Pi, Linux, and MacOS.

       
                                       



Programming STM32F103C8


I assumed you’ve downloaded Atollic TrueStudio IDE and you’ve setup your project, you can drop a comment if you want me to write a tutorial on how to setup the IDE and create a project.

The Black pill has an on-board LED which the negative pin is connected through a resistor to PB12 and its positive pin is connected to the MCU 3.3v. Using the Blue pill board, the on-board LED ground is connected through a resistor to PC13 while its positive pin is connected to the MCU 3.3v.
                            
                                       


You can either use the Blue or the Black pill because the same processor is being used in both PCBs and they are almost the same size too only the extra 5v input pin differ.

To create new project, Click on New  -> C Project, type in your Project Name and under the Project Type select Embedded C Project and click Next, In Target, type STM32F103C8 and select the MCU and then click Next, Under Debug Mode, select the ST-LINK and then Finish.
                                         




I will write and explain the blinking LED code below using the Standard Peripheral Library.


Navigate to src folder under the new project folder created and open main.c, delete all the initialized code that appears in the editor and then copy and paste this code below into it.


#include "stm32f10x.h"


void Delay()
{
       for(uint16_t i=0; i<1000; i++) for(uint16_t j=0; j<1000; j++);
}


void GPIO_Setup(void)
{
        GPIO_InitTypeDef GPIOx;

        // Enables the High Speed APB (APB2) peripheral clock
        // PORTB Enabled
        RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

        //configures the operating mode for the selected pins as Push-Pull Output
        GPIOx.GPIO_Mode = GPIO_Mode_Out_PP;

        //configure the speed for the selected pins
        GPIOx.GPIO_Speed = GPIO_Speed_2MHz;

        // selects the GPIO pins to configure. Multiple-pin configuration can be
        // performed by using the ‘|’ operator.
        // configure pin 12 of PORTB
        GPIOx.GPIO_PinGPIO_Pin_12;

       //Initialisess the GPIOx peripheral according to the specified parameters
        GPIO_Init(GPIOB, &GPIOx);
}


/**
**===========================================================================
**
**  Abstract: main program to blink LED on PB12
**
**===========================================================================
*/
int main(void)
{
       GPIO_Setup(); // call the GPIO pin setup function

       while(1)
       {

       GPIO_SetBits(GPIOB, GPIO_Pin_12);    //Off the LED since the negative pin is connected to PB12
                                                // You can also use GPIO_WriteBit(GPIOB, GPIO_Pin_12, SET);
       Delay();
       GPIO_ResetBits(GPIOB, GPIO_Pin_12);  //On the LED since the negative pin is connected to PB12
                                             // You can also use GPIO_WriteBit(GPIOB, GPIO_Pin_12, RESET);
       Delay();

       }
}


We can now build our code by clicking on the Build icon at the upper part of the IDE, once our code compiles successfully, ensure your STLINK is connected to the Serial Wire Debug (SWD) pin of the board and then click on the debug icon.

STLINK   ----   Black/Blue Pill

3.3V                3.3V
SWDIO           DIO
SWCLK          CLK
GND               GND



No comments:

Post a Comment