STM32Cube-Presentation
STM32Cube-Presentation
• Installation of STM32CubeMX
• CubeMX features
• HAL overview
• CubeMX tool
• http://www.st.com/web/catalog/tools/FM147/CL1794/SC961/SS1533/PF259242?s_searchtype=
partnumber
• Optionally you can download the Cube packages for STM32 device if you
don’t want to download them throe CubeMX
• STM32CubeL0
• STM32CubeL1
• STM32CubeF0
• STM32CubeF1
• STM32CubeF2
• STM32CubeF3
• STM32CubeF4
A CubeMX install 5
CubeMX
Project
repository
A CubeMX install 6
• In case you download the package from web we need to find the place where
they need to be stored
• MENU>Help>Updater Settings…
Specifying path to
repository
A CubeMX install 7
• The comparison of the CubeMX repository settings and structure in this folder
• The comparison of the CubeMX repository settings and structure in this folder
• For the code generation the CubeMX use the package from the Repository
folder
• For driver installation you will need the Admin rights on your PC
10
STM32CubeMX presentation
STM32Cube: STM32CubeMX 11
Step by step:
• MCU selector
• Pinout configuration
• Peripherals and
middleware parameters
• Code generation
• Power consumption
calculator
12
STM32CubeMX
Power Consumption
Wizard
Clock Tree wizard
13
STM32CubeMX
• Series
• Line
• Package
• Peripherals
STM32CubeMX: Pinout configuration 15
• Pinout from:
• Peripheral tree
• Manually
• Automatic signal
remapping
• Management of
dependencies
between
peripherals and/or
middleware
(FatFS, LWIP, …)
STM32CubeMX: Pinout configuration 16
Dimmed:
The additional
periphery must
be selected
STM32CubeMX: Pinout configuration 17
Green:
Periphery will
be functional
STM32CubeMX: Pinout configuration 18
Yellow:
On ADC only
some channels
can be used
STM32CubeMX: Pinout configuration 19
Red:
Periphery
cannot be used
in this pinout
setup
STM32CubeMX: Pinout configuration 20
3. SWD
selected
STM32CubeMX: Pinout configuration 21
1. Ctrl+Click on pin
STM32CubeMX: Clock tree 23
• Immediate
display of all
clock values
• Management of
all clock
constraints
• Highlight of
errors
STM32CubeMX: Peripheral and
middleware configuration 24
• Highlight of
configuration errors
+ Not configured
ⱱ OK
x Error
• Parameters with
management of
dependencies and
constraints
• Interrupts
• GPIO
• DMA
STM32CubeMX: Peripheral and
middleware configuration 26
• Manage Interruptions
• priorities can only be set in the NVIC
global view
• Manage DMA
• Configure all the parameters of the
DMA request
• Runtime parameters (start address, …)
are not managed
NVIC Panel 27
• Help->Updater settings
• Choose location of STM32CubeFx firmware libraries repository
• Choose manual or automatic check
• Set Connection proxy
• Inside ST use lps5.sgp.st.com port 8080 with your windows login name and password
Project Driver
CubeMX repository
Folder
Copy all driver files In project are used only peripheral files selected in CubeMX
from CubeMX
repository
Stored in
project_folder/Drivers/STM32XXXX_HAL_Driver folder
STM32Cube Firmware Library package 35
Project Driver
CubeMX repository
Folder
Project Driver
CubeMX repository
Folder
MX_GPIO_Init
MX_SPI_Init
Initialization done directly in
MX_USART_Init main.c file
…
MX_XXX_Init
Generate peripheral initialization as a pair
of ‘.c/.h’ files per IP 38
• Advantage is that with .h file we can call MX_XXX init functions from
every file in project not only from main.c
Main.c gpio.c
Initialization in separated .c
and .h files called from main
spi.c
usart.c
xxx.c
Backup previously generated files when
re-generating 39
• Backup old files from Src and Inc folder into Backup folder
CubeMX
Project folder Project folder
Regenerating
Src Folder Src Folder
Backup Folder Backup Folder
• This areas are reserved in new code generation, if this option is selected
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */ Here can user put his code,
/* USER CODE BEGIN 0 */
code will be preserved during
/* USER CODE END 0 */
int main(void)
project generation
{
/* USER CODE BEGIN 1 */
}
/* USER CODE END 3 */
}
Keep User Code when re-generating 41
CubeMX
Project Regenerating Project
gpio.c gpio.c
usart.c usart.c
spi.c
CubeMX
Not used pins(grays) Project
will be in project Generating
configured as analog MX_GPIO_Init
Initialization of unused
pins is in MX_GPIO_Init
• Function input parameters are checked if they are in correct range, if not
application jump into assert_failed function in main.c
This function trying to
/* USER CODE BEGIN 2 */
configure not existing
HAL_GPIO_TogglePin(GPIOA,(0x1<<17));
pin PA17
/* USER CODE END 2 */
• Power step
definitions
• Battery selection
• Creation of
consumption graph
• Display of
• Average
consumption
• Average DMIPS
• Battery lifetime
STM32CubeMX Documentation 46
Document Description
UM1718: STM32CubeMX for STM32 Description how use CubeMX tool
configuration and initialization C code
generation
RN0094: STM32CubeMX release 4.8.0 Changes made in new versions
GPIO Test Lab
Configure GPIO for LED toggling 48
• Objective
• Learn how to setup pin and GPIO port in CubeMX
• How to Generate Code in CubeMX and use HAL functions
• Goal
• Configure GPIO pin in CubeMX and Generate Code
• Add in to project HAL_Delay function and HAL_GPIO_Toggle function
• Verify the correct functionality on toggling LED
Configure GPIO for LED toggling 49
• GPIO Configuration
• TAB>Configuration>System>GPIO
Configure GPIO for LED toggling 52
• GPIO(Pin) Configuration
• Select Push Pull mode
• No pull-up and pull-down
• Output speed to HIGH
Is important for faster
peripheries like SPI, USART
• Button OK
Configure GPIO for LED toggling 53
• STM32CubeTM Version 1:
• A configuration tool, STM32CubeMX generating initialization code from user choices
• A full embedded software offer, delivered per series (like STM32CubeF4) with:
• An STM32 Abstraction Layer embedded software: STM32Cube HAL
• A consistent set of Middlewares: RTOS, USB, TCP/IP, Graphics, …
• Available at st.com as free solution
STM32CubeMX
STM32CubeL1
STM32CubeF4
STM32CubeF0
STM32CubeF2
STM32CubeF1 STM32CubeF3
STM32Cube HAL 57
Networking Utilities
USB Graphics File system RTOS
LwIP TCP/IP
Host & Device STemWin FATFS FreeRTOS
& Polar SSL
Middleware
Drivers
STM32F4 STM32F7
Document Description
UM1725: Description of STM32F4xx Important document with list of HAL
HAL drivers functions and description
UM1730: Getting started with Simple description of HAL package
STM32CubeF4 firmware package for
STM32F4 Series
STM32Cube HAL Middleware doc 60
Document Description
UM1713: Developing applications on Use LwIP stack with STM32Cube
STM32Cube with LwIP TCP/IP stack
UM1721: Developing Applications on Possibility of file system
STM32Cube with FatFs
UM1722: Developing Applications on How to work together with Cube and
STM32Cube with RTOS RTOS
UM1734: STM32Cube USB device USB device library possibility
library explanation
UM1720: STM32Cube USB host library USB host library possibility explanation
STM32Cube HAL Example doc 61
Document Description
UM1709: STM32Cube Ethernet IAP Description of IAP example
example
UM1743: STM32CubeF4 demonstration Explanation of demonstration examples
platform
UM1723: STM32Cube PolarSSL Explanation of PolarSSL example
example
STM32Cube FW Package Organization 62
Can be found in
CubeMX repository
Cube F4 HAL
package
Drivers
Advanced set of
libraries
Developed/Owned by ST
Middlewares
Third Party libraries
ST Third Party
PolarSSL
STM32Cube FW Package Projects 65
STM32F-Discovery
….
Networking Utilities
USB Graphics File system RTOS
LwIP TCP/IP
Host & Device STemWin FATFS FreeRTOS
& Polar SSL
Middleware
Drivers
• All HAL drivers follow a strict C coding rules and were tested using
CodeSonar C code static analysis tool from GrammaTech
User Code
stm32f4xx_it.c stm32f4xx_it.h
stm32f4xx_hal.h
stm32f4xx_hal_ppp.c
stm32f4xx_hal_ppp_ex.c
HAL Drivers stm32f4xx_hal_conf.h
stm32f4xx_hal.c
stm32f4xx_hal_ppp.h
stm32f4xx_hal_ppp_ex.h
Note;
system_stm32f4xx.c stm32f4xx_hal_def.h
keeps the system
clock as HSI
system_stm32f4xx.c stm32f4xx.h
CMSIS
startup_stm32f4xx.s
HAL general concepts
76
Introduction to HAL
• Structure of project generated with CubeMX with HAL
Use standard
system_stm32f4xx.c
from CMSIS
CMSIS
User Code
Stm32f4xx_hal_msp.c
contains initialization of HAL Drivers
service peripherals (RCC,
GPIO, DMA, …)
User Code
stm32f4xx_it.c stm32f4xx_it.h
stm32f4xx_hal.h
stm32f4xx_hal_ppp.c
stm32f4xx_hal_ppp_ex.c
HAL Drivers stm32f4xx_hal_conf.h
stm32f4xx_hal.c
stm32f4xx_hal_ppp.h
stm32f4xx_hal_ppp_ex.h
stm32f4xx_hal_def.h
system_stm32f4xx.c stm32f4xx.h
LDRstm32f4xx_hal.c
R0, =SystemInit
BLX R0 2. Memory initialization
stm32f4xx_hal_ppp.h
LDR R0, =__main and jump to main
stm32f4xx_hal_ppp_ex.h
BX R0 stm32f4xx_hal_def.h
ENDP
system_stm32f4xx.c stm32f4xx.h
User Code
stm32f4xx_it.c stm32f4xx_it.h
stm32f4xx_hal.h
stm32f4xx_hal_ppp.c
stm32f4xx_hal_ppp_ex.c
HAL Drivers stm32f4xx_hal_conf.h
stm32f4xx_hal.c
stm32f4xx_hal_ppp.h
stm32f4xx_hal_ppp_ex.h
stm32f4xx_hal.h
stm32f4xx_hal_ppp.c
stm32f4xx_hal_ppp_ex.c
HAL Drivers stm32f4xx_hal_conf.h
stm32f4xx_hal.c
stm32f4xx_hal_ppp.h
Extended peripheral stm32f4xx_hal_ppp_ex.h
system_stm32f4xx.c stm32f4xx.h
HAL global APIs (HAL_Init,
CMSIS
startup_stm32f4xx.s HAL_DeInit, HAL_Delay,…)
HAL general concepts 84
HAL based project organization
Source files Include files
user_code.c user_code.h
Config file for HAL, should
User Code
stm32f4xx_it.c be customized by user to
stm32f4xx_it.h
select the peripherals to be
included
stm32f4xx_hal.h
stm32f4xx_hal_ppp.c
stm32f4xx_hal_ppp_ex.c
HAL Drivers stm32f4xx_hal_conf.h
stm32f4xx_hal.c
stm32f4xx_hal_ppp.h
Contains HAL common stm32f4xx_hal_ppp_ex.h
type definitions and macros
stm32f4xx_hal_def.h
system_stm32f4xx.c stm32f4xx.h
CMSIS
startup_stm32f4xx.s
STM32 register definition
HAL general concepts
85
HAL drivers Vs. Refman peripherals
• In order to offer easy to use APIs, each HAL driver handles a unique
usage of the peripheral
• For example in F4x reference manual you have SPI peripheral which can be used
as SPI or I2S. In this case the two HAL module drivers are defined:
• stm32f4xx_hal_spi.c and stm32f4xx_i2s.c
• In F4x family, this is also the case for
• USART which can be: USART, UART, IRDA or Smartcard
• FMC which can be: NOR, NAND, SRAM ,SDRAM or PCCARD
• SDIO which can be: SD or SDMMC
Example: case of Flash APIs which depend on part number in F4x family
/* Extension Program operation functions *************************************/
#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\
defined(STM32F401xC) || defined(STM32F401xE) || defined(STM32F411xE)
HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram (FLASH_AdvOBProgramInitTypeDef *pAdvOBInit);
void HAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit);
HAL_StatusTypeDef HAL_FLASHEx_OB_SelectPCROP(void);
HAL_StatusTypeDef HAL_FLASHEx_OB_DeSelectPCROP(void);
#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F401xC || STM32F401xE || STM32F411xE */
/**
* @brief Tx Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_TxCpltCallback could be implemented in the user file
*/
}
HAL general concepts
95
Init functions
• HAL_XXX_Init() functions
HAL_xxx_Init() start
MSP callback defined as __weak
HAL_xxx_MspInit()
HAL_Init() end
HAL general concepts
96
HAL API returns parameters
• A HAL API can return a value of enumerated type
HAL_StatusTypeDef:
• HAK_OK : API executed with success
• HAL_ERROR : API call parameters error or operation execution error
• HAL_BUSY : API was not executed because peripheral is busy with other
operation
• HAL_TIMEOUT : API timeout error
HAL_XXX Function
HAL_Init() start
HAL_Init() end
HAL_Init() function complete
HAL general concepts
98
HAL global APIs HAL_Init()
• HAL_Init() : need to be called as first function in main
• Initializes data/instruction cache and pre-fetch queue
• Sets Time base to generate interrupt each 1ms with lowest priority , it can use systick (default)
or other time source
• Sets priority grouping to 4 preemption bits
• Calls function HAL_MspInit() which a is user callback function to do MCU system level
initializations (Clocks, GPIOs, DMA, Interrupts).
HAL_Init() end
HAL general concepts
99
HAL global APIs HAL_Init()
• HAL_Init() : need to be called as first function in main
HAL_StatusTypeDef HAL_Init(void)
{
/* Configure Flash prefetch, Instruction cache, Data cache */
#if (INSTRUCTION_CACHE_ENABLE != 0)
__HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
#endif /* INSTRUCTION_CACHE_ENABLE */ Instruction/data cache and
#if (DATA_CACHE_ENABLE != 0) prefetch initialization based
__HAL_FLASH_DATA_CACHE_ENABLE();
#endif /* DATA_CACHE_ENABLE */ on stm32f4xx_hal_conf.h
#if (PREFETCH_ENABLE != 0)
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
#endif /* PREFETCH_ENABLE */
/* Set Interrupt Group Priority */
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
/* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */
HAL_InitTick(TICK_INT_PRIORITY);
/* Init the low level hardware */
HAL_MspInit();
/* Return function status */
return HAL_OK;
}
HAL general concepts
100
HAL global APIs HAL_Init()
• HAL_Init() : need to be called as first function in main
HAL_StatusTypeDef HAL_Init(void)
{
/* Configure Flash prefetch, Instruction cache, Data cache */
#if (INSTRUCTION_CACHE_ENABLE != 0)
__HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
#endif /* INSTRUCTION_CACHE_ENABLE */
#if (DATA_CACHE_ENABLE != 0)
__HAL_FLASH_DATA_CACHE_ENABLE();
NVIC priority grouping
#endif /* DATA_CACHE_ENABLE */ setup
#if (PREFETCH_ENABLE != 0)
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
#endif /* PREFETCH_ENABLE */
/* Set Interrupt Group Priority */
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
/* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */
HAL_InitTick(TICK_INT_PRIORITY);
/* Init the low level hardware */
HAL_MspInit(); Default systick init with
/* Return function status */
return HAL_OK;
default interrupt priority
} 0 (HIGH priority)
HAL general concepts
101
HAL global APIs HAL_Init()
• HAL_Init() : need to be called as first function in main
HAL_StatusTypeDef HAL_Init(void)
{
/* Configure Flash prefetch, Instruction cache, Data cache */
#if (INSTRUCTION_CACHE_ENABLE != 0)
__HAL_FLASH_INSTRUCTION_CACHE_ENABLE();
#endif /* INSTRUCTION_CACHE_ENABLE */
#if (DATA_CACHE_ENABLE != 0)
__HAL_FLASH_DATA_CACHE_ENABLE();
#endif /* DATA_CACHE_ENABLE */
#if (PREFETCH_ENABLE != 0)
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
#endif /* PREFETCH_ENABLE */
/* Set Interrupt Group Priority */
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
/* Use systick as time base source and configure 1ms HAL_MspInit callback
tick (default clock after Reset is HSI) */
HAL_InitTick(TICK_INT_PRIORITY);
/* Init the low level hardware */ function generated by
HAL_MspInit();
/* Return function status */
CubeMX in
return HAL_OK; stm32f4xx_hal_msp.c
}
HAL general concepts
102
HAL global APIs HAL_Init()
• HAL_MspInit() generated by CubeMX
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
• HAL_DeInit()
• Resets all peripherals
• Calls function HAL_MspDeInit() which a is user callback function to do system level De-
Initalizations. HAL_MspDeInit() is defined as “weak” empty function in HAL
• HAL_GetTick()
• Get current tick counter (incremented in Time base interrupt)
• Used by peripherals drivers for timeout management
• HAL_Delay()
• Implements a delay in ms
• HAL_InitTick()
• Weak function that configures the source of the time base, by default it is systick but can be
redefined by user
HAL general concepts
105
HAL global APIs (2/2)
• HAL_IncTick()
• Increment a global variable "uwTick" used as application time base . Should be called from
Time base ISR (systick, timer, …)
• HAL_SuspendTick() / HAL_ResumeTick()
• Suspend Tick increment
• Resume Tick increment.
• HAL_GetHalVersion()
• Returns the HAL revision
HAL general concepts
106
HAL Tick functions
• In case you want change the clock source you need to change all Tick methods
• HAL_GetTick
• HAL_InitTick
• HAL_SuspendTick()
• HAL_ResumeTick()
• Use HAL_SuspendTick before MCU enter into low power mode, interrupt can wake up STM32 from
LP mode
• The HAL offers simple to use, portable APIs for above system IPs with
extensions provided also for non common features (ex: product
specific low power mode, specific clock configurations ,…)
109
Application
HAL macros
STM32F4xx
HAL service peripherals
111
RCC macros
• Simple macros for RCC operations
• Enabling peripheral clocks (_CLK_ENABLE) Enable peripheral clock
• Disabling peripheral clocks (_CLK_DISABLE))
Ex.:
__GPIOA_CLK_ENABLE();
• Force periphery reset (_FORCE_RESET)
• Release periphery reset (RELEASE_RESET)
Disable peripheral clock
Ex.:
__GPIOA_CLK_DISABLE();
• RCC macro example:
• After Force periphery rese the reset must be release otherwise the
periphery will not react on changes
/** @brief Force or release AHB1 peripheral reset.
*/
#define __AHB1_FORCE_RESET() (RCC->AHB1RSTR = 0xFFFFFFFF)
Held periphery in
#define __GPIOA_FORCE_RESET()
#define __GPIOB_FORCE_RESET()
(RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOARST))
(RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOBRST))
RESET, periphery
#define __GPIOC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOCRST)) registers are in
#define __GPIOD_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIODRST))
#define __GPIOE_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOERST)) default state
#define __GPIOH_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_GPIOHRST))
#define __CRC_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_CRCRST))
#define __DMA1_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA1RST))
#define __DMA2_FORCE_RESET() (RCC->AHB1RSTR |= (RCC_AHB1RSTR_DMA2RST)) In file
#define __AHB1_RELEASE_RESET() (RCC->AHB1RSTR = 0x00) stm32f4xx_hal_rcc.h
#define __GPIOA_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOARST))
#define __GPIOB_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOBRST))
#define __GPIOC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOCRST))
#define
#define
__GPIOD_RELEASE_RESET()
__GPIOE_RELEASE_RESET()
(RCC->AHB1RSTR
(RCC->AHB1RSTR
&= ~(RCC_AHB1RSTR_GPIODRST))
&= ~(RCC_AHB1RSTR_GPIOERST))
Release RESET,
#define __GPIOF_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOFRST)) periphery can be
#define __GPIOG_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOGRST))
#define __GPIOH_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOHRST)) now enabled
#define __GPIOI_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_GPIOIRST))
#define __CRC_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_CRCRST))
#define __DMA1_RELEASE_RESET() (RCC->AHB1RSTR &= ~(RCC_AHB1RSTR_DMA1RST))
HAL service peripherals
114
RCC – macros
• RCC macros are defined in stm32f4xx_hal_rcc.h file, they are needed for
peripherals clock gating, reset control and sleep mode clock config
• Peripheral clock enable/disable: __TIM1_CLK_ENABLE() / __TIM1_CLK_DISABLE()
• Peripheral reset enable/disable: __GPIOA_FORCE_RESET()/ __GPIOA_RELEASE_RESET()
• Peripheral Sleep mode clock enable/disable: __SPI3_CLK_SLEEP_ENABLE()/
SPI3_CLK_SLEEP_DISBALE()
• Other RCC macros are available for direct register access, they can be used
in the application instead of the HAL clock config APIs, for example, when
restoring clock after Stop mode, user can use directly below macros
• __HAL_RCC_HSE_CONFIG
• __HAL_RCC_PLL_ENABLE
• __HAL_RCC_GET_FLAG
HAL structures 115
/**
* @brief GPIO Init structure definition
*/ stm32f4xx_hal_gpio.h
typedef struct
{
uint32_t Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
uint32_t Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIO_mode_define */
uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins.
This parameter can be a value of @ref GPIO_pull_define */
uint32_t Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIO_speed_define */
uint32_t Alternate; /*!< Peripheral to be connected to the selected pins.
This parameter can be a value of @ref GPIO_Alternate_function_selection */
}GPIO_InitTypeDef;
• To discover what parameter fill into structure find the @ref name
/** @defgroup GPIO_pins_define GPIO pins define
* @{
*/
#define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */
#define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */
#define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */
#define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */
#define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */
#define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */
#define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */
#define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */
#define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */
#define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */
#define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */
#define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */
HAL service peripherals
117
RCC - clock configuration (1/2)
• Two functions needed for clock configuration
• HAL_RCC_OscConfig
• HAL_RCC_ClockConfig
/**
* @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition
*/
typedef struct
{
uint32_t OscillatorType; /*!< The oscillators to be configured.
This parameter can be a value of @ref RCC_Oscillator_Type */
uint32_t HSEState; /*!< The new state of the HSE.
This parameter can be a value of @ref RCC_HSE_Config */
uint32_t LSEState; /*!< The new state of the LSE.
This parameter can be a value of @ref RCC_LSE_Config */
uint32_t HSIState; /*!< The new state of the HSI.
This parameter can be a value of @ref RCC_HSI_Config */
uint32_t HSICalibrationValue; /*!< The calibration trimming value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */
uint32_t LSIState; /*!< The new state of the LSI.
This parameter can be a value of @ref RCC_LSI_Config */
RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */
}RCC_OscInitTypeDef;
HAL service peripherals
118
RCC - clock configuration (1/2)
• Two functions needed for clock configuration
• HAL_RCC_OscConfig
• HAL_RCC_ClockConfig
/**
/**
* @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition
* @brief RCC PLL configuration structure definition
*/ */
typedef struct typedef struct
{ {
uint32_t OscillatorType; /*!< uint32_t PLLState; to/*!<
The oscillators be The new state of the PLL.
configured.
This parameter can be This parameter
a value can RCC_Oscillator_Type
of @ref be a value of @ref RCC_PLL_Config */
uint32_t HSEState; /*!< The new state of the HSE.
uint32_t PLLSource; /*!< RCC_PLLSource: PLL entry clock source.
This parameter can be This
a value of @ref
parameter mustRCC_HSE_Config
be a value of @ref RCC_PLL_Clock_Source */
uint32_t LSEState; /*!< The new state of the LSE.
This parameter
uint32_t PLLM; can/*!<
be PLLM:
a value of @ref
Division RCC_LSE_Config
factor for PLL VCO input clock. */
uint32_t HSIState; /*!< The new state of the HSI. This parameter must be a number between Min_Data = 0 and Max_Data = 63
This parameter can be a value of @ref RCC_HSI_Config */
uint32_t HSICalibrationValue; /*!< uint32_t PLLN;
The calibration /*!< PLLN: Multiplication factor for PLL VCO output clock.
trimming value.
This parameter must be a number between Min_Data = 192 and Max_Data =
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */
uint32_t LSIState; /*!< uint32_t
The newPLLP;
state of the
/*!<LSI.
PLLP: Division factor for main system clock (SYSCLK).
This parameter can be This
a value of @ref
parameter mustRCC_LSI_Config
be a value of @ref RCC_PLLP_Clock_Divider */
RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */
}RCC_OscInitTypeDef; uint32_t PLLQ; /*!< PLLQ: Division factor for OTG FS, SDIO and RNG clocks.
This parameter must be a number between Min_Data = 0 and Max_Data = 63
}RCC_PLLInitTypeDef;
HAL service peripherals
119
RCC - clock configuration (2/2)
• HAL_RCC_ClockConfig (RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t
FLatency)
• Selects system clock source
• Configures AHB, APB1 and APB2 clock dividers
• Configures Flash Wait States
• Updates systick config following HCLK clock changes to generate 1ms timebase
/**
* @brief RCC System, AHB and APB busses clock configuration structure definition
*/
typedef struct
{
uint32_t ClockType; /*!< The clock to be configured.
This parameter can be a value of @ref RCC_System_Clock_Type */
uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock.
This parameter can be a value of @ref RCC_System_Clock_Source */
uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK).
This parameter can be a value of @ref RCC_AHB_Clock_Source */
uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK).
This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */
uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK).
This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */
}RCC_ClkInitTypeDef;
HAL service peripherals
120
RCC - clock configuration (2/2)
• HAL_RCC_ClockConfig (RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t
FLatency)
• Selects system clock source
• Configures AHB, APB1 and APB2 clock dividers
• Configures Flash Wait States
• Updates systick config following HCLK clock changes to generate 1ms timebase
/**
* @brief RCC System, AHB and APB busses clock configuration structure definition
*/
typedef struct
{
uint32_t ClockType; /*!< The clock to be configured.
This parameter can be a value of @ref RCC_System_Clock_Type */
uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock.
This parameter can be a value of @ref RCC_System_Clock_Source */
uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK).
This parameter can be a value of @ref RCC_AHB_Clock_Source */
uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK).
This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */
uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK).
This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */
}RCC_ClkInitTypeDef;
HAL service peripherals
121
RCC– APIs
• Main function structure, generated by CubeMX
int main(void)
{
/* USER CODE BEGIN 1 */
Initialize Systick,
/* USER CODE END 1 */ NVIC, and call
/* MCU Configuration----------------------------------------------------------*/
/* HAL_Init_MSP
Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
Initialize
/* Initialize all configured peripherals */ STM32
MX_GPIO_Init(); clock tree,
based on
/* USER CODE BEGIN 2 */
Clock Configuration
/* USER CODE END 2 */ in CubeMX
/* USER CODE BEGIN 3 */
/* Infinite loop */
while (1)
{
}
/* USER CODE END 3 */
}
HAL service peripherals
122
RCC – APIs
• MX_GPIO_Init function structure, generated by CubeMX
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
Enable clocks for
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct; PWR periphery
__PWR_CLK_ENABLE(); Configure voltage
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
scale (refer RM)
RCC_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;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 4;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|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);
}
HAL service peripherals
123
RCC – APIs
• SystemClock_Config function structure, generated by CubeMX
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
__PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_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;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 4;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|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);
}
HAL service peripherals
124
RCC – APIs
• SystemClock_Config function structure, generated by CubeMX
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
__PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
RCC_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;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 4;
HAL_RCC_OscConfig(&RCC_OscInitStruct);
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK|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);
}
HAL service peripherals
125
RCC – other APIs
• Clock DeInit: returns to reset clock config
• HAL_RCC_DeInit()
• User can decide how many bits will be used for Pre-empt (Group)
priorities and for Subpriorities
• By default set in HAL_Init() to 4bit for Group priorities
• Possible settings:
Priority level
IRQ 2 IRQ 1
pending pending
High priority 0
IRQ 1
IRQ 2 IRQ 2
Low priority 16
IRQ 1
IRQ 2
Low priority 16
time
IRQ 2
IRQ 1
Low priority 16
time
• We use this project for better demonstration how the HAL library
works
HAL service peripherals
136
GPIO - initialization structure
• Two new features compared to std library GPIO driver
• A pin can be configured as EXTI with interrupt or event generation
• Alternate field allows selection of the Alternate function for a pin (AFxx)
/**
* @brief GPIO Init structure definition
*/
typedef struct
{
uint32_t Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
uint32_t Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIO_mode_define */
uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins.
This parameter can be a value of @ref GPIO_pull_define */
uint32_t Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIO_speed_define */
GPIO_MODE_OUTPUT_PP GPIO_MODE_OUTPUT_OD
GPIO_MODE_INPUT GPIO_MODE_ANALOG
GPIO_MODE_AF_PP GPIO_MODE_AF_OD
GPIO_MODE_IT_RISING_FALLING GPIO_MODE_EVT_RISING
GPIO_MODE_EVT_FALLING GPIO_MODE_EVT_RISING_FALLING
VSS
HAL service peripherals
140
GPIO – initialization – GPIO Speed
• GPIO(Pin) output speed configuration
• Change the rising and falling edge when pin change state from high to low or low to high
• Higher GPIO speed increase EMI noise from STM32 and increase STM32 consumption
• It is good to adapt GPIO speed with periphery speed. Ex.: Toggling GPIO on 1Hz is LOW
optimal settings, but SPI on 45MHz the HIGH must be set
HIGH HIGH
LOW LOW
HIGH HIGH
HAL service peripherals
141
GPIO – initialization – GPIO Alternate
Select alternate function for GPIO
TIM
UART
GPIO
pin
SPI
…
…
…
HAL service peripherals
142
GPIO – APIs
• The following APIs are provided
int main(void)
{
/* USER CODE BEGIN 1 */
Initialize Systick,
/* USER CODE END 1 */ NVIC, and call
/* MCU Configuration----------------------------------------------------------*/
/* HAL_Init_MSP
Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
Initialize
/* Initialize all configured peripherals */ STM32
MX_GPIO_Init(); clock tree,
based on
/* USER CODE BEGIN 2 */
Clock Configuration
/* USER CODE END 2 */ in CubeMX
/* USER CODE BEGIN 3 */
/* Infinite loop */
while (1)
{
Initialize GPIO which
are not used with any
}
/* USER CODE END 3 */
other periphery
}
HAL service peripherals
144
GPIO – APIs
• MX_GPIO_Init function structure, generated by CubeMX
GPIO_InitTypeDef GPIO_InitStruct;
• We use this project for better demonstration how the HAL library
works
Use EXTI lab 147
Peripheral Initializations
including peripheral interrupt NVIC
initializations
HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
GPIO_InitStruct.Pin = GPIO_PIN_0;
Configure the GPIO to generate interrupt on
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING; rising or falling edge
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
HAL_NVIC_EnableIRQ(EXTI0_IRQn);
}
NVIC configuration
Use EXTI lab 150
HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
• Use now the same example but now use two or more
EXTI pins
Peripheral Initializations
including peripheral interrupt NVIC
initializations
HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
HAL_GPIO_EXTI_IRQHandler EXTI9_5_IRQHandler
HAL_GPIO_EXTI_IRQHandler call
for interrupts only one callback
Interrupts from PX5 to PX9
share same interrupt vector
Use EXTI lab 155
HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
; HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
Peripheral Initializations
including peripheral interrupt NVIC
initializations
; HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
HAL_GPIO_EXTI_IRQHandler EXTI9_5_IRQHandler
Use EXTI lab 157
; HAL_GPIO_EXTI_IRQHandler EXTI0_IRQHandler
HAL_GPIO_EXTI_IRQHandler EXTI9_5_IRQHandler
158
• We use this project for better demonstration how the HAL library
works
Handle structures 160
/**
* @brief DMA handle Structure definition
Defined in
*/
typedef struct __DMA_HandleTypeDef
stm32f4xx_hal_dma.h
{
DMA_Stream_TypeDef *Instance; /*!< Register) base
Pointer to DMA stream instance (ex: DMA1_Stream0 address */
DMA_InitTypeDef Init; DMA channel init structure /*!< DMA communication parameters */
void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */
void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */
void (* XferM1CpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete Memory1 callback */
void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */
• DMA channel callbacks need to be initialized by user only in case of memory to memory transfer.
• For peripheral - memory transfers, the HAL peripheral driver offer APIs that handles DMA transfer for peripheral (( ex:
HAL_USART_Receive_DMA()) these APIs will assign callback functions.
HAL service peripherals
164
DMA – HAL APIs Init structure
/**
* @brief DMA Configuration Structure definition
*/
IN this structure are
typedef struct
{
stored information
uint32_t Channel; /*!< Specifies the channel used for the specified stream.
This parameter can be a value of @ref DMA_Channel_selection about DMA.
*/
Define in
uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral,
from memory to memory or from peripheral to memory.
This parameter can be a value of @ref DMA_Data_transfer_direction */
uint32_t PeriphInc; stm32f4xx_hal_dma.h
/*!< Specifies whether the Peripheral address register should be incremented or not.
This parameter can be a value of @ref DMA_Peripheral_incremented_mode */
uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not.
This parameter can be a value of @ref DMA_Memory_incremented_mode */
uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width.
This parameter can be a value of @ref DMA_Peripheral_data_size */
uint32_t MemDataAlignment; /*!< Specifies the Memory data width.
This parameter can be a value of @ref DMA_Memory_data_size */
uint32_t Mode; /*!< Specifies the operation mode of the DMAy Streamx.
This parameter can be a value of @ref DMA_mode
@note The circular buffer mode cannot be used if the memory-to-memory
data transfer is configured on the selected Stream */
uint32_t Priority; /*!< Specifies the software priority for the DMAy Streamx.
This parameter can be a value of @ref DMA_Priority_level */
uint32_t FIFOMode; /*!< Specifies if the FIFO mode or Direct mode will be used for the specified stream.
This parameter can be a value of @ref DMA_FIFO_direct_mode
@note The Direct mode (FIFO mode disabled) cannot be used if the
memory-to-memory data transfer is configured on the selected stream */
uint32_t FIFOThreshold; /*!< Specifies the FIFO threshold level.
This parameter can be a value of @ref DMA_FIFO_threshold_level */
uint32_t MemBurst; /*!< Specifies the Burst transfer configuration for the memory transfers.
It specifies the amount of data to be transferred in a single non interruptable
transaction.
This parameter can be a value of @ref DMA_Memory_burst
@note The burst mode is possible only if the address Increment mode is enabled. */
uint32_t PeriphBurst; /*!< Specifies the Burst transfer configuration for the peripheral transfers.
It specifies the amount of data to be transferred in a single non interruptable
transaction.
This parameter can be a value of @ref DMA_Peripheral_burst
@note The burst mode is possible only if the address Increment mode is enabled. */
}DMA_InitTypeDef;
HAL service peripherals
165
DMA M2M code from CubeMX
• CubeMX create DMA handler in main.c
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/**
* Enable DMA controller clock
* Configure DMA for memory to memory transfers
* hdma_memtomem_dma2_stream0
*/
void MX_DMA_Init(void)
{
/* DMA controller clock enable */ DMA clock enable
__DMA2_CLK_ENABLE();
/* Configure DMA request hdma_memtomem_dma2_stream0 on DMA2_Stream0 */
hdma_memtomem_dma2_stream0.Instance = DMA2_Stream0; Store parameters which
hdma_memtomem_dma2_stream0.Init.Channel = DMA_CHANNEL_0;
hdma_memtomem_dma2_stream0.Init.Direction = DMA_MEMORY_TO_MEMORY; was selected in CubeMX
hdma_memtomem_dma2_stream0.Init.PeriphInc = DMA_PINC_ENABLE;
hdma_memtomem_dma2_stream0.Init.MemInc = DMA_MINC_ENABLE;
into init structure
hdma_memtomem_dma2_stream0.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
hdma_memtomem_dma2_stream0.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
hdma_memtomem_dma2_stream0.Init.Mode = DMA_NORMAL;
hdma_memtomem_dma2_stream0.Init.Priority = DMA_PRIORITY_LOW;
hdma_memtomem_dma2_stream0.Init.FIFOMode = DMA_FIFOMODE_ENABLE;
hdma_memtomem_dma2_stream0.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_HALFFULL;
hdma_memtomem_dma2_stream0.Init.MemBurst = DMA_MBURST_SINGLE;
hdma_memtomem_dma2_stream0.Init.PeriphBurst = DMA_PBURST_SINGLE;
HAL_DMA_Init(&hdma_memtomem_dma2_stream0);
/* DMA interrupt init */ Write content of Init structure
}
into DMA registers
Now is DMA ready to use
HAL service peripherals
168
DMA – APIs
• The following table lists the DMA APIs
DMA HAL APIs Description
HAL_DMA_Init Initializes a DMA channel
HAL_DMA_DeInit De-initalizes a DMA channel
HAL_DMA_Start Starts DMA transfer
HAL_DMA_Start_IT Starts DMA channel with interrupt
generation at end of transfer or half transfer
or on DMA error
HAL_DMA_Abort Aborts a DMA transfer
HAL_DMA_PollForTransfer Blocking function that polls for transfer
complete or half complete, this function can
also return a Timeout or a DMA error
HAL_DMA_IRQHandler Interrupt handler for DMA
HAL_DMA_GetState Gets DMA channel state
HAL_DMA_GetError Gets DMA error code
HAL service peripherals
169
DMA – extension APIs
• Extension APIs for DMA are present in F4x family for handling double
buffer feature, API include:
DMA HAL EX APIs Description
HAL_DMAEx_MultiBufferStart double buffer DMA transfer in polling mode
HAL_DMAEx_MultiBufferStart_IT double buffer DMA transfer with Interrupt
generation
HAL_DMAEx_ChangeMemory allows changing non used buffer address on
the fly
DMA Poll lab result 170
status=HAL_DMA_PollForTransfer(&hdma_memtomem_dma2_stream0,HAL_DMA_FULL_TRANSFER,100);
/*ERROR*/
switch(status)
Store function return status
{
case HAL_ERROR:
If error detected
error=HAL_DMA_GetError(&hdma_memtomem_dma2_stream0);
/*Handle ERROR*/
switch(error){
default: Discover what type of error
break; was detected
}
break;
case HAL_TIMEOUT:
/*Handle TIMEOUT*/
Function timeouted
break;
case HAL_BUSY:
/*Handle BUSY*/ Periphery is in use
break;
case HAL_OK:
/*Handle BUSY*/ Function ends successfully
break;
default:
break;
}
Use DMA with Interrupt lab 172
• We use this project for better demonstration how the HAL library
works
HAL Library DMA with IT flow 173
DMA Initializations
including peripheral interrupt NVIC
initializations
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */ DMA Initializations
including peripheral interrupt NVIC
SystemClock_Config(); initializations
/* Initialize all configured peripherals */
MX_DMA_Init();
Start process with interrupt generation at end
/* USER CODE BEGIN 2 */ of process
HAL_DMA_Start_IT
/* USER CODE END 2 */
/* USER CODE BEGIN 3 */
/* Infinite loop */ HAL_OK HAL_ERROR HAL_BUSY HAL_DMA_IRQHandler DMA2_Stream0_IRQHandler
while (1)
{
end of process callback
} DMA_XferCpltCallback
/* USER CODE END 3 */
}
process Error callback
DMA_XferErrorCallback
DMA with Interrupt lab 175
/**
* @brief This function handles DMA2 Stream0 global interrupt.
*/
void DMA2_Stream0_IRQHandler(void) Standard DMA inrrupt handler
{
/* USER CODE BEGIN DMA2_Stream0_IRQn 0 */ defined in startup_stm32f439xx.s
/* USER CODE END DMA2_Stream0_IRQn 0 */
DMA Initializations
HAL_DMA_IRQHandler(&hdma_memtomem_dma2_stream0); including peripheral interrupt NVIC
initializations
/* USER CODE BEGIN DMA2_Stream0_IRQn 1 */
/* USER CODE END DMA2_Stream0_IRQn 1 */ Start process with interrupt generation at end
of process
} HAL_DMA_Start_IT
HAL_DMA_IRQHandler
can call correct process Error callback
DMA_XferErrorCallback
callback function
DMA with Interrupt lab 177
• We use this project for better demonstration how the HAL library
works
Peripheral HAL driver model
183
HAL peripheral Handle
/**
* @brief UART handle Structure definition
*/
typedef struct
{
USART_TypeDef *Instance; /*USART instance
UART registers (ex.
base address USART1,
*/ USART2, …)
uint8_t *pTxBuffPtr;
parity, …)
/* Pointer to UART Tx transfer Buffer */
}UART_HandleTypeDef;
Peripheral HAL driver model
186
Driver API groups
• Peripheral drivers APIs are organized in four groups
• Initialization and de-initialization APIs
• Process APIs : can be polling, interrupt or DMA based
• Peripheral subsystem configuration and feature control APIs
• Peripheral GetState and Get Errors APIs
• User callback functions are defined as empty functions with “weak” attribute ,
they need to be redefined in application code when used
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600; Store UART parameters into
huart1.Init.WordLength = UART_WORDLENGTH_8B;
Init structure in UART
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE; handler
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart1); HAL UART initialization
procedure
}
HAL Init structure 190
}
HAL HAL_UART_MspInit structure 191
}
Peripheral HAL driver model
192
Blocking polling process
• Blocking polling process APIs
• Block until end of the process, or exit with timeout , error or busy
• Ex: HAL_USART_Receive()
Peripheral Initializations
Peripheral Initializations
HAL_USART_Receive HAL_BUSY
RX not empty
byte
HAL_OK
Use UART with Interrupt lab 195
• We use this project for better demonstration how the HAL library
works
UART MSP file 196
/**
* @brief This function handles USART1 global interrupt.
*/
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */ As parameter is used
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
USART1 handle
/* USER CODE END USART1_IRQn 1 */
}
Callback creation 198
HAL_USART_Receive_IT
HAL_UART_IRQHandler(&huart1)
HAL_BUSY HAL_ERROR
Move data to rx buffer
Rx buffer
HAL_UART_RxCpltCallback
End interrupt
UART receive with interrupt 202
HAL_USART_Receive_IT
HAL_UART_IRQHandler(&huart1)
HAL_UART_ErrorCallback
End interrupt
Use UART with DMA lab 203
• We use this project for better demonstration how the HAL library
works
UART with DMA initialization 204
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
HAL_UART_Init(&huart1);
}
UART with DMA initialization 206
• Without this UART cannot cooperate with DMA on HAL base library
UART with DMA - HAL_UART_MspInit 208
__HAL_LINKDMA(huart,hdmarx,hdma_usart1_rx);
Stream selection,
DMA direction,
data width, …
__HAL_LINKDMA macro description 210
}UART_HandleTypeDef;
tx and RX
heandles
__HAL_LINKDMA macro description 211
Imported DMA
handler into MSP
DMA_HandleTypeDef *hdmatx; /* UART Tx DMA Handle parameters */
DMA_HandleTypeDef *hdmarx; /* UART Rx DMA Handle parameters file
*/
__HAL_LINKDMA macro description 212
__HAL_LINKDMA(huart,hdmarx,hdma_usart1_rx)
Imported DMA
handler into MSP
DMA_HandleTypeDef *hdmatx; /* UART Tx DMA Handle parameters */
DMA_HandleTypeDef *hdmarx; /* UART Rx DMA Handle parameters file
*/
__HAL_LINKDMA function description 213
DMA TX handle
Parent pointer
UART with DMA - HAL_UART_MspInit 214
__HAL_LINKDMA(huart,hdmatx,hdma_usart1_tx);
/* USER CODE BEGIN USART1_MspInit 1 */
/* USER CODE END USART1_MspInit 1 */
}
}
UART with DMA Interrupt 215
Peripheral Initializations
including DMA stream initializations
HAL_DMA_IRQHandler DMA_Stream_IRQHandler
HAL_UART_RxCpltCallback
HAL_UART_RxHalfCpltCallback
HAL_UART_ErrorCallback
UART receive with DMA 217
HAL_USART_Receive_DMA
HAL_UART_IRQHandler(&huart1)
HAL_OK HAL_ERROR
HAL_DMA_IRQHandler(&hdma_usart1_tx)
End interrupt
Examples for other peripherals 218
Peripheral
Initializations
Start Process
(ex: HAL_ADC_Start)
• The template project includes all HAL files and implements a main.c files with startup code
to initialize system clock (@ max speed)
• Start by writing the peripheral HAL_PPP_MspInit function, in this function you need to:
• Enable the peripheral clock
• Configure the peripheral GPIOs
• configure DMA channel and enable DMA interrupt (if needed)
• Enable peripheral interrupt (if needed)
• Edit the stm32f4xx_it.c to call required interrupt handlers (periph and DMA)
• Write process complete callback functions if you plan to use peripheral interrupt or DMA
• In your main.c file, initialize the peripheral handle structure then call function
HAL_PPP_Init() to initialize your peripheral
• At this step you can call any peripheral process or control function
222
Recapitulation
What is CubeMX 223
• MCU selector
• Clock configurator
• Periphery configurator
• Code generator
Code generation 224
• TIM trigger DMA transfer, which move data from RAM to GPIO
(TIM DMA lab)
• They are also some situation where HAL functions not exists and we
must use direct access into registers
228
• The board support package architecture was defined in order to allow easy
portability and reuse of the same components (LCD, IO expander,…) on different
boards
• Drivers for the components present on the board are written according to the
component class definition (see .h files in \Drivers\BSP\Components\Common)
which is board and MCU independent
Discovery drivers
Components
HAL API
stm32f4xx_hal_spi.c
stm32f4xx_II_fmc.c stm32f4xx_hal_sdram.c stm32f4xx_hal.c
stm32f4xx_hal_i2c.c