Stm32 - Riptutorial

Transcription

stm32#stm32

Table of ContentsAbout1Chapter 1: Getting started with stm322Remarks2What is STM32?2Product series2Development boards2Versions3Examples3First time setup with blink LED example using SW4STM32 and HAL library3IDE installation3Creating a project3Blink LED application6Chapter 2: Integrated development environments (IDEs)10Introduction10Remarks10Examples13SW4STM32: System Workbench for oduction14Installation15Atollic - roduction15Installation16Chapter 3: UART - Universal Asynchronous Receiver/Transmitter (serial communication)Introduction1717

Examples17Echo application - HAL library17Transmit large amount of data using DMA and interrupts - HAL library18Credits22

AboutYou can share this PDF with anyone you feel could benefit from it, downloaded the latest versionfrom: stm32It is an unofficial and free stm32 ebook created for educational purposes. All the content isextracted from Stack Overflow Documentation, which is written by many hardworking individuals atStack Overflow. It is neither affiliated with Stack Overflow nor official stm32.The content is released under Creative Commons BY-SA, and the list of contributors to eachchapter are provided in the credits section at the end of this book. Images may be copyright oftheir respective owners unless otherwise specified. All trademarks and registered trademarks arethe property of their respective company owners.Use the content presented in this book at your own risk; it is not guaranteed to be correct noraccurate, please send your feedback and corrections to info@zzzprojects.comhttps://riptutorial.com/1

Chapter 1: Getting started with stm32RemarksThis section provides an overview of what stm32 is, and why a developer might want to use it.It should also mention any large subjects within stm32, and link out to the related topics. Since theDocumentation for stm32 is new, you may need to create initial versions of those related topics.What is STM32?STM32 is a 32-bit Flash microcontroller family developed by ST Microelectronics. It is based onthe ARM Cortex ‑M processor and offers a 32‑bit product range that combines very highperformance, real-time capabilities, digital signal processing, and low‑power, low‑voltageoperation.A detailed description about each series, development tools and part number decoding can befound on Wikipedia.Product seriesCortex-M0 / -M0 High 2F4STM32F7, ower:STM32L0STM32L1STM32L4Development boardsSTM32 Nucleo (mbedenabled)Discovery kitsEvaluationboardsTypical use case:Flexible prototyping,communityPrototyping, creativedemosFull featureevaluationExtensionpossibilities: Connectivity:Arduino , ST, MorphoSTSThttps://riptutorial.com/2

VersionsVersionRelease Date1.0.02016-11-01ExamplesFirst time setup with blink LED example using SW4STM32 and HAL library(Note: There are many IDE, toolchain and library which are ready-to-use with STM32. Thefollowing setup requires minimal effort to get it work, but it is only one of the many. Feel free toexplore others, it is not the purpose of this example to force anyone to use the tools that will beused here.)IDE installationSystem Workbench for STM32: free IDE on Windows, Linux and OS X. It has been built by AC6and available for download after registration from the OpenSTM32 Community's website.The IDE itself is based on Eclipse, but comes with some extras for STM32 development like: Ac6 STM32 MCU GCC toolchain OpenOCD and GDB (arm-none-eabi-gdb) with automatically generated debug configurationsdepending on the target board Built-in options to program or erase chipTo start with STM32 before creating your own board, it is recommended to experiment with aDiscovery, a Nucleo or an Eval board, which come with an on-board SWD (Serial Wire Debug)programmer/debugger called ST-Link.Creating a projectThis example will use an STM32F4 Discovery kit, which features an STM32F407VGmicrocontroller. (Any other board can be used as well.)1. Open SW4STM32 and create a new C project: File New C Project2. Give it a name like "STM32F4 Discovery-Blinky" and from the Project Type list choose theExecutable/Ac6 STM32 MCU Project. By default the only available toolchain is Ac6 STM32MCU GCC. Click Next.https://riptutorial.com/3

3. Next step is Debug/Release settings, can be skipped now by clicking Next.4. Board selection. Existing boards can be selected as in this example the STM32F4 Discoveryor new custom boards can be added.https://riptutorial.com/4

5. Next step is Project Firmware configuration. Choose between No firmware, StandardPeripheral Library (SPL) or Hardware Abstraction Layer (HAL). It is questioned whichone is more suitable for development, but this question is out of scope in this example. Thisexample will use the HAL library as it is the currently supported by ST Microelectronics.Additional available software tool for HAL is STM32CubeMX, which is an initialization codegenerator. Also several example applications are available by the STM32CubeFx orSTM32CubeLx software packages. Download the target firmware if it's missing and it isrecommended select the "Add low level drivers in the project" and the "As sources inthe application" options. Finally, click Finish.https://riptutorial.com/5

Blink LED applicationAs this project has been created with an STM32F4 Discovery, there are already several ready-touse functions under the /STM32F4 Discovery-Blinky/Utilities/STM32F4-Discovery/ projectfolder which can be used to interface the Discovery kit's peripherals (accelerometer, audio, LEDs,push button). In this example the void BSP LED Init(Led TypeDef Led) and the voidBSP LED Toggle(Led TypeDef Led) functions will be used from the stm32f4 discovery.c file to blinkthe green LED, which is LED4. To decide which LED is which use the schematics of the Discoverykit.https://riptutorial.com/6

The actual pin and port names are already hidden by some #define and enum, use Ctrl Click totrack them.1. Inside the main, call the HAL Init() function which resets all peripherals, initializes the Flashinterface and the Systick. (Systick will be used to generate delay for the blinking.)2. The system clock have to be configured. It can be done by using the STM32CubeMX clockconfiguration feature or by the reference manual. In this example the system clock is fed bythe internal PLL (Phase Locked Loop), which is sourced by an external 8 MHz crystaloscillator (HSE). Prescalers have been set to achieve the maximum available frequency,which is 168 MHz in case of the F4 Discovery.3. Initialization of the peripherals, in this case a GPIO pin.4. Inside an endless loop, call the LED toggling and the HAL Delay() function. HAL Delay() usesthe Systick and generates a delay in miliseconds.The whole code is the following:#include "stm32f4xx.h"#include "stm32f4 discovery.h"void SystemClock Config(void);int main(void){/* Reset of all peripherals, Initializes the Flash interface and the Systick. */HAL Init();/* Configure the system clock */SystemClock Config();/* Initialize one of the LED GPIO pin */BSP LED Init(LED4);while(1){BSP LED Toggle(LED4);HAL Delay(1000);}// in miliseconds}/**https://riptutorial.com/7

* @brief System Clock Configuration*The system Clock is configured as*System Clock source*SYSCLK(Hz)*HCLK(Hz)*AHB Prescaler*APB1 Prescaler*APB2 Prescaler*HSE Frequency(Hz)*PLL M*PLL N*PLL P*PLL Q*VDD(V)*Main regulator output voltage*Flash Latency(WS)* @param None* @retval None*/void SystemClock Config(void){RCC ClkInitTypeDef RCC ClkInitStruct;RCC OscInitTypeDef RCC OscInitStruct;follow : PLL (HSE) 168000000 168000000 1 4 2 HSE VALUE (HSE VALUE/1000000u) 336 2 7 3.3 Scale1 mode 5// Enable Power Control clockPWR CLK ENABLE();// The voltage scaling allows optimizing the power consumption when the// device is clocked below the maximum system frequency, to update the// voltage scaling value regarding system frequency refer to product// datasheet.HAL PWR VOLTAGESCALING CONFIG(PWR REGULATOR VOLTAGE SCALE1);// Enable HSE Oscillator and activate PLL with HSE as sourceRCC OscInitStruct.OscillatorType RCC OSCILLATORTYPE HSE;RCC OscInitStruct.HSEState RCC HSE ON;RCC OscInitStruct.PLL.PLLState RCC PLL ON;RCC OscInitStruct.PLL.PLLSource RCC PLLSOURCE HSE;// This assumes the HSE VALUE is a multiple of 1MHz. If this is not// your case, you have to recompute these PLL constants.RCC OscInitStruct.PLL.PLLM (HSE VALUE/1000000u);RCC OscInitStruct.PLL.PLLN 336;RCC OscInitStruct.PLL.PLLP RCC PLLP DIV2;RCC OscInitStruct.PLL.PLLQ 7;HAL RCC OscConfig(&RCC OscInitStruct);// Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2// clocks dividersRCC ClkInitStruct.ClockType (RCC CLOCKTYPE SYSCLK RCC CLOCKTYPE HCLK RCC CLOCKTYPE PCLK1 RCC CLOCKTYPE PCLK2);RCC ClkInitStruct.SYSCLKSource RCC SYSCLKSOURCE PLLCLK;RCC ClkInitStruct.AHBCLKDivider RCC SYSCLK DIV1;RCC ClkInitStruct.APB1CLKDivider RCC HCLK DIV4;RCC ClkInitStruct.APB2CLKDivider RCC HCLK DIV2;HAL RCC ClockConfig(&RCC ClkInitStruct, FLASH LATENCY 5);}Build with the hammer, and download the application by right clicking on the project folder andselecting the Target Program chip. option.https://riptutorial.com/8

Another way to download is with using debug. To do so click on the arrow beside the bug iconin the toolbar and open Debug Configuration. menu. Creat a new Ac6 STM32Debugging configuration and if the C/C Application field is empty, fill in the following:Debug\STM32F4 Discovery-Blinky.elfOther debug parameters such as the OpenOCD configuration file and the used Telnet and GDBports are automatically generated and filled in by the framework. Finally, click the Debug button.Read Getting started with stm32 online: tartedwith-stm32https://riptutorial.com/9

Chapter 2: Integrated developmentenvironments (IDEs)IntroductionThe purpose of this topic is to list all integrated development environments (IDE) that can be usedto develop software for STM32 microcontrollers. The examples should contain: 1. List of the IDE'smain features. 2. List of the operating systems supported by the IDE. 3. Installation process. 4.Additional configuration steps (if there are any).RemarksListed IDEs by ST Microelectronics:Part NumberGeneral DescriptionCoIDECooCox CoIDE, a freeand highly-integratedsoftware developmentenvironment for ARMCortex MCUsCosmicIDECosmic ARM/Cortex "M"Cross DevelopmentTools for STM32MicrocontrollerCrossWorksRowley AssociatesCrossWorks, integrateddevelopmentenvironment with JTAGFlash download anddebugDS-5ARM DevelopmentStudio 5 (DS-5) providesbest-in-class tools for thebroadest range of ARMprocessor-basedplatformsEMP-ThunderEmprog ThunderBench,fully integrated and ctive10

Part NumberGeneral afted developmentC/C tools for ARMCortexHitop5Universal user interface,IDE and debugger for allHitex development toolsIAR-EWARMIAR Integrateddevelopmentenvironment andoptimizing C/C compiler for ARM CortexMMDK-ARMSTM32MDK-ARM softwaredevelopmentenvironment for CortexM based MCUsMULTIGreenHills integrateddevelopment and debugenvironment forembedded applicationsusing C and C ActiveGreenHillsSoftwareMen-Nucleus-SFNucleus SmartFit o run-time traceanalyser for STM32 MCUActivePercepioPLSUDE-STM32Debug and emulatorplatform with optimizedTrace and Flash supportfor STM32 Cortex-Mbased MCU's by PLSdevelopment toolsRIDE-STM32Raisonance brandedintegrated developmentenvironment for STM32MCUsSOMN-DRT-IDESOMNIUM DRT CortexM veSOMNIUMSWdevelopmentActive11

Part NumberGeneral esSW4STM32System Workbench forSTM32: free IDE onWindows, Linux and m's C/C compilerand debugger tools forARM based MCUsActiveTASKINGFirmwareTrueSTUDIOThe premier C/C development tool forSTM32 development,with its unrivalled featureset and iSYSwinIDEAOpeniSYSTEM's freeunlimited softwaredevelopment platform forall STM32 Cortex-Mbased oElektronika fullfeatured Basic compilerwhich makes STM32development suitable oCPROMikroElektronika fullfeatured ANSI Ccompiler for STM32devices. It features anintuitive IDE, powerfulcompiler with suitesmikroPascalPROMikroElektronika fullfeatured Pascal compilerfor STM32 devices. Ithas an intuitive IDE withdocking support, rich withfeatures, advanced texteditor, many availabletools, libraries utorial.com/ActiveActiveActiveActiveActive12

Part NumberGeneral veiSYSTEMFirmwareexampleswinIDEA-STM32iSYSTEM's completesoftware developmentand test solution for theSTM32 MCUsExamplesSW4STM32: System Workbench for STM32IntroductionSystem Workbench for STM32 is a free IDE on Windows, Linux and OS X. Description from STMicroelectronics:The System Workbench toolchain, called SW4STM32, is a free multi-OS softwaredevelopment environment based on Eclipse, which supports the full range of STM32microcontrollers and associated boards.The SW4STM32 toolchain may be obtained from the website www.openstm32.org,which incl

First time setup with blink LED example using SW4STM32 and HAL library 3 IDE installation 3 Creating a project 3 Blink LED application 6 Chapter 2: Integrated development environments (IDEs) 10 Introduction 10 Remarks 10 Examples 13 SW4STM32: System Workbench for STM32 13 Introduction 13 Installation 14 IAR-EWARM 14 Introduction 14 Installation 15 Atollic - TrueSTUDIO 15 Introduction 15 .