Mastering Microcontroller : TIMERS,
PWM, CAN, RTC,LOW POWER
      FastBit Embedded Brain Academy
          Check all online courses at
             www.fastbitlab.com
              Copyright © Bharati software 2018.
  About FastBit EBA
FastBit Embedded Brain Academy is an online training wing of Bharati Software.
We leverage the power of internet to bring online courses at your fingertip in the domain
of embedded systems and programming, microcontrollers, real-time operating systems,
firmware development, Embedded Linux.
All our online video courses are hosted in Udemy E-learning platform which enables you to
exercise 30 days no questions asked money back guarantee.
For more information please visit : www.fastbitlab.com
Email : contact@fastbitlab.com
STM32 Cube Framework Program Flow
   main.c                                        stm32f4xx_hal.c
  main(){}                                          HAL_Init(){}
         HAL_Init()                                                HAL_MspInit()
                                                            /* Init the low level hardware */
     SystemClock_Config()                                   •   Setting up of priority grouping ,
                                                            •   Enabling required system exceptions
 /* Configure the system clock */                           •   Setting priorities for system exceptions
                                                            •   Other Processor specific settings as
                                                                per your application need
                       Copyright © Bharati software 2018.
                        HAL_Init()
                            SysTick timer init to             Other Processor Specific
 Flash Interface Init                                              Low level init
                         generate interrupt for 1ms
                                                             Application
                         Requirement for Cube HAL            specific
Stm32f4xx_hal_conf.h     APIs to work properly
                                                                   HAL_MspInit()
                        Copyright © Bharati software 2018.
                SysTick Init
SysTick is used as time base for the HAL_Delay()
function, the application
 need to ensure that the SysTick time base is
always set to 1 millisecond to have correct HAL
operation.
                 Copyright © Bharati software 2018.
                               Application code and other source files
                             STM32-CUBE Layer ( STM32Fx_HAL_DRIVER)
(The HAL hardware abstraction layer, enabling portability between different STM32 devices via standardized API
                                                    calls)                               Startup file for mcu
            CMSIS-CORE                                                STM32Fx HAL go through CMSIS-CORE
(Core Access, Functions, Peripherals and                              when it wants to configure processor
         Interrupt Definitions)                                       specific features.
                                              Microcontroller
     NVIC      SYSTICK
                                                                         CAN      USART         CRC
                                TIMERS          SPI          I2C
      MPU        SCB
   ARM Cortex Mx Processor       GPIO          PWR          SDIO         I2S       DMA           RTC
                                           Copyright © Bharati software 2018.
      Application(main.c)                         msp.c                    It.c
                       Driver API                                          Interrupts handlers
Callbacks                                                 Peripheral
                                                          Initialization
                                    STM32 Cube HAL
                                    Microcontroller
                               Copyright © Bharati software 2018.
                                                         Hal_uart_msp.c
      Application(main.c)                                                                 It.c
            Uart_transmit_it()           Uart_Msp_init()
                                                     2                           4               Interrupt
  6                   3
                                                                             Interrupts          Processing
Callbacks                           1                                        handlers
                                 Uart_init()                                                         5
                                            STM32 CUBE HAL
              Stm32f4xx_hal_uart.c
                                             Microcontroller
                                        Copyright © Bharati software 2018.
         Peripheral Handle Structure
 Garden Spade With Handle
Handle                                     UART_HandleTypeDef huart2;
                                                                    UART peripheral
                     Spade                                            of the MCU
                            Copyright © Bharati software 2018.
UART Handle Structure
      Copyright © Bharati software 2018.
       Peripheral Handle Structure
                                        Used to hold Peripheral Register Base
                                        Addresses
                                                          Used to hold Peripheral
                                                          Configurable parameters
Handle Structure
    XXX_TypeDef    XXX_InitTypeDef
                   Copyright © Bharati software 2018.
         Handle Structure of different
          Peripherals in STM32 Cube
Peripheral   Handle Structure                            Driver file
Timer        TIM_HandleTypeDef                           stm32f4xx_hal_tim.h
RTC          RTC_HandleTypeDef                           stm32f4xx_hal_rtc.h
SPI          SPI_HandleTypeDef                           stm32f4xx_hal_spi.h
I2C          I2C_HandleTypeDef                           stm32f4xx_hal_i2c.h
USART        UART_HandleTypeDef                          stm32f4xx_hal_uart.h
CAN          CAN_HandleTypeDef                           stm32f4xx_hal_can.h
RCC
                            Copyright © Bharati software 2018.
         Handle Structure of different
                 Peripherals
Peripheral   Handle Structure
DMA          DMA_HandleTypeDef                           stm32f4xx_hal_dma.h
SDIO         SD_HandleTypeDef                            stm32f4xx_hal_sd.h
GPIO
MII          ETH_HandleTypeDef                           stm32f4xx_hal_eth.h
FLASH        FLASH_ProcessTypeDef                        stm32f4xx_hal_flash_ex.h
ADC          ADC_HandleTypeDef                           stm32f4xx_hal_adc.h
CRC          CRC_HandleTypeDef                           stm32f4xx_hal_crc.h
                            Copyright © Bharati software 2018.
               XXX_TypeDef
This structure you will find in device specific
header file
For example, in the case of STM32F446RE MCU,
it is stm32f446xx.h
This structure describes the register details of a
particular peripheral in the order they appear in
the memory map.
                  Copyright © Bharati software 2018.
XXX_TypeDef: Example
     Copyright © Bharati software 2018.
     Linking Handler Structure and
               Peripheral
Linking happens by means of base address of
the peripheral.
                Copyright © Bharati software 2018.
  How to find out the base address of
           the peripheral ??
1. Find out on which bus the peripheral is
   connected
2. Find out the base address of the Bus on which
   the peripheral is connected. (Reference manual )
3. Find out the offset of the peripheral from the
   base address of the bus on which it is connected
4. Add “offset” to base address of the bus
                  Copyright © Bharati software 2018.
    Address calculation : Example
Find out the base address of the UART4
peripheral
1. Refer to the microcontroller datasheet or RM
to find out on which bus it is connected
                 Copyright © Bharati software 2018.
    Address calculation : Example
2. Find out the base address of the bus in the
processor memory map
                  Copyright © Bharati software 2018.
                                         0xFFFF_FFFF
External memory
         0x5000_0000
                                                     Peripheral
                                                     0x4000_0000
                        Processor
                       memory map
                                                    SRAM
                                                 0x2000_0000
 Embedded Flash
  0x0800_0000
                                               0x0000_0000
                       Copyright © Bharati software 2018.
                        Peripheral base = 0x4000_0000
     APB1                   APB2                           AHB1               AHB2
   offset : 0        offset : 0x00010000           offset : 0x00020000   offset : 0x10000000
BA=0X4000_0000        BA=0X40001_0000               BA=0X4002_0000       BA=0X5000_0000
    UART4       offset : 0X4C00
                BA = 0x4000_4C00
                           Copyright © Bharati software 2018.
    Address calculation : Example
3. Find out the offset of the peripheral from the
base address of the bus on which it is connected
                  Copyright © Bharati software 2018.
             Peripheral Register Address
                     Calculation
     APB1                       Status register (USART_SR)    offset : 0x00
BA=0X4000_0000
                                 Data register (USART_DR)     offset : 0x04
                                     Baud rate register
                                       (USART_BRR)            offset : 0x08
                                Status register (USART_SR)    offset : 0x0C
    UART4
                             Control register 1 (USART_CR1)   offset : 0x10
offset : 0X4C00
BA = 0x4000_4C00             Control register 2 (USART_CR2)   offset : 0x14
                             Control register 3 (USART_CR3)   offset : 0x18
                     Copyright © Bharati software 2018.
         Linking Handler Structure and
                   Peripheral
Handle
                               UART_HandleTypeDef huart2;
                                                            UART peripheral
               Spade Copyright © Bharati software 2018.       of the MCU
 STM32 Cube Header File Hierarchy
 #include "stm32f4xx.h"      This is for MCU family
                                                                  This describes your
                                                                  microcontroller , its IRQ
#include "stm32f446xx.h"     This is for the device               definitions, memory map, register
                             (MCU)                                details of the peripheral, clock
                                                                  management macros and other
#include “stm32f4xx_hal.h”   This is for Cube HAL                 useful macros.
                             Copyright © Bharati software 2018.
                            Exercise
Write a program to send characters over UART to MCU . MCU should convert
all the lower case letters in to uppercase and send it back to the user
Consider the below UART Parameter settings
Baudrate = 115200
No of data bits = 8
Stop bits = 1
Parity = None
No UART hardware flow control.
Use USART2 peripheral of the MCU in Asynchronous mode(i.e UART mode)
                          Copyright © Bharati software 2018.
 Low Level Hardware Initializations
• Processor Specific
  – Configure the Priority group of the processor
  – Enable required Processor System Exceptions
     • Bus fault , mem manage, usage fault , Systick , etc
  – Configure the priority of system exceptions
  – Other Initializations related to MPU, Floating point
    unit, Sleep mode , etc
                     Copyright © Bharati software 2018.
  Peripheral Initializations : UART2
• First define a handle variable to Handle the
  required peripheral as a global variable in the
  program
• Link as well as initialize the handle variable
• Use the init. API of the Peripheral to initialize
  the peripheral .
                   Copyright © Bharati software 2018.
Low level initializations of the peripheral
                                             UART2
                                                                           Low level Inits
                                                                    (Pin settings or pin muxing
     High Level Inits
                                                                            Clock enable
(parameters initializations)
                                                                             IRQ enable
                                                                          NVIC settings )
                               Copyright © Bharati software 2018.
    Low level initializations of the peripheral
•   First enable the Required Peripheral clock
•   Do pin muxing configurations
•   Enable the peripheral IRQ in the NVIC
•   Set the priority as per your application need.
                    Copyright © Bharati software 2018.
      Pin Muxing Configurations
• UART needs 2 pins for Communication . One is
  called Tx Pin and another one is called Rx Pin
• We can use 2 GPIOs of the MCU for TX and RX
  functionalities of the UART.
• Before using GPIOs for UART communication
  purpose , we have to configure their mode as
  alternate functionality mode.
• In this case alternate functionality mode is UART.
                   Copyright © Bharati software 2018.
          Identifying Pin Packs
Identify all Pin Packs of the MCU on which
USART2 communicates.
Hint : Refer to the datasheet of the MCU
                 Copyright © Bharati software 2018.
                     Summary
• HAL_Init(); must be the very first API should be called
  in a project which uses stm32 cube HAL. This call also
  sets up systick timer ticking for every 1 ms which is the
  heart beat of stm32 cube project (mandatory )
• HAL_Init(); calls HAL_MspInit(); to do application
  specific low level processor inits. (optional )
• At this time you are good to go since most of the basic
  Inits are done
                     Copyright © Bharati software 2018.
                       Summary
• SystemClock_Config() has to be called next if you have any
  special clock requirements as per you application .
• Then we did , UART peripheral initialization ( high level
  inits). That is the parameter settings of the UART peripheral
• Then the cube framework calls for low level peripheral
  inits. , which we did in the msp.c . like enabling the
  peripheral clock, pin mux configuration and NVIC settings.
• After this, both your processor and microcontroller
  peripheral is good to go. Use data handling APIs to play
  with the peripheral .
                       Copyright © Bharati software 2018.
  Handing interrupts in the project
• Populate the it.c file with required IRQ handlers definitions
• The name of the IRQ handler you can get from the startup
  file
• STM32 Cube Framework gives IRQ processing API for every
  peripheral . For example : it gives HAL_UART_IRQHandler()
  to process UART global interrupt, which must be called
  from the IRQ handler.
• The IRQ handler then call the callbacks to the user
  application.
                       Copyright © Bharati software 2018.
                                     It.c
                        Other system exceptions
   Systick handler                                           Peripheral IRQ handlers
                                handlers
   Mandatory                      Optional                     As per application
Used to increment the                                            requirements
global tick variable
__IO uint32_t uwTick;
Defined in
stm32f4xx_hal.c
                        Copyright © Bharati software 2018.
                                                         Hal_uart_msp.c
      Application(main.c)                                                                 It.c
            Uart_transmit_it()           Uart_Msp_init()
                                                     2                           4               Interrupt
  6                   3
                                                                             Interrupts          Processing
Callbacks                           1                                        handlers
                                 Uart_init()                                                         5
                                            STM32 CUBE HAL
              Stm32f4xx_hal_uart.c
                                             Microcontroller
                                        Copyright © Bharati software 2018.
Stm32 Cube Peripheral Data Handling
            API Flavors
• Non Interrupt based ( Polling )
• Interrupt based
• DMA based ( Uses DMA and Interrupts )
                Copyright © Bharati software 2018.
                                Timers
• What exactly is a Timer ?
   – Its one of the peripheral of the Microcontroller .
• What are the uses of a Timer ?
   – Time base generation
   – Measuring/counting input signal frequency (measuring time periods
     of waveforms)
   – Producing different Waveforms
   – Measuring pules width
   – Generating pulse width modulation (PWM) signals
   – triggering external devices
                           Copyright © Bharati software 2018.
                        Timers
• What does a timer do ?
  – A timer at the basic level just counts from 0 to some
    pre-programmed value ( up counting ) or from some
    pre programmed value to 0 ( down counting )
                   Copyright © Bharati software 2018.
Job of the Timer Peripheral is to count
              Copyright © Bharati software 2018.
        Types of STM32 Timers
• Basic Timers ( Available in All STM32 MCUs)
• General Purpose timer ( Available in All
  STM32 MCUs)
• Advanced Timer (not available in all STM32
  MCUs)
                 Copyright © Bharati software 2018.
             Timer availability
• Refer to the timer availability table in
  application note
                  Copyright © Bharati software 2018.
                         Summary
• The number of timer peripherals and their respective features differ
  from one STM32 microcontroller family to another, but they all
  share some common features and operating modes.
• For example, the STM32F100 microcontrollers embed a timer
  peripheral named TIM17, but the total number of timer peripherals
  embedded by these microcontrollers is less than 17
• In general, across the STM32 microcontrollers families, the timer
  peripherals that have the same name also have the same features
  set, but there are a few exceptions
• The level of features integration for a given timer peripheral is
  decided based on the applications field that it targets.
                         Copyright © Bharati software 2018.
               Basic Timers
• These timers have basic counting engine and
  majorly used for time base generation
• These timers do not have input/output
  channels associated with them
                 Copyright © Bharati software 2018.
Stm32 Basic Timer Assembly (Block Diagram)
              Copyright © Bharati software 2018.
             Time base unit
Time base unit includes,
1. 16-bit upcounter
2. Counter Register (TIMx_CNT)
3. Prescaler Register (TIMx_PSC)
4. Auto-Reload Register (TIMx_ARR)
                Copyright © Bharati software 2018.
       We need to understand …..
•   TIM_CLK ?? → Timer Clock
•   CLK_PSC ?? → Prescaler output clock
•   CLK_CNT ??→ Counter Clock
•   ARR ?? → Auto Reload register
                  Copyright © Bharati software 2018.
                   Exercise
Use the basic timer to generate interrupt for
every 100 ms. Toggle the GPIO or LED inside the
Timer IRQ handler and verify using logic analyzer
                 Copyright © Bharati software 2018.
         We need more info ….
• What is the peripheral bus clock to which the
  timer peripheral is connected ?
• Use peripheral bus clock to deduce the Timer
  clock(TIM_CLK) frequency
We at least need to know the Timer Clock
frequency to generate desired time base
                 Copyright © Bharati software 2018.
Time base Handle Structure
        TIM_HandleTypeDef (stm32f4xx_hal_tim.h)
 TIM1        TIM2                        TIM3      TIM4
                TIM5                        TIMx
             Copyright © Bharati software 2018.
Time base Handle Structure
        Copyright © Bharati software 2018.
Timers and STM32 Cube Layer
       Time base unit of the Timer
            Copyright © Bharati software 2018.
How prescaler affects TIMx_CLK??
           Copyright © Bharati software 2018.
How pre-scaler affects counting ??
            Copyright © Bharati software 2018.
How prescaler affects counting ??
           Copyright © Bharati software 2018.
Period (ARR value)
    Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
Time base generation formula
         Copyright © Bharati software 2018.
                        The Time-Base unit
•   The time-base unit is made by the timer counter in addition to a prescaler stage and a repetition
    counter. The clock signal fed into the time-base unit passes first through a prescaling stage before
    reaching the time-base counter.
•   Depending on the content of the TIMx_PSC timer prescaler register, the counting signal frequency
    may be scaled down before reaching the counter stage. The output signal of the prescaling stage is
    the clock counting signal for the timer counter stage.
•   The timer counter is controlled by two timer registers: • The TIMx_CNT timer register is used to
    read and write the content of the timer counter. • The TIMx_ARR timer register contains the reload
    value of the timer counter. – If the timer counter is up-counting and it reaches the content of the
    timer autoreload register (TIMx_ARR), then the timer counter resets itself and a new counting cycle
    is restarted.
•   Each time a new counting cycle is restarted, a timer “update event” is triggered as long as the
    content of the repetition counter is null. If the content of the repetition counter is not null, then no
    “update event” is triggered, but a new counting cycle is restarted and the content of the repetition
    counter is decreased by one. Next to each “update event” the content of the repetition counter is
    set to the value stored by the TIMx_RCR timer register
                                      Copyright © Bharati software 2018.
  The master/slave controller unit
• The master/slave unit provides the time-base
  unit with the counting clock signal (for
  example the CK_PSC signal), as well as the
  counting direction control signal. This unit
  mainly provides the control signals for the
  time-base unit.
                 Copyright © Bharati software 2018.
        The timer-channels unit
• The timer channels are the working elements of
  the timer; they are the means by which a timer
  peripheral interacts with its external environment
• In general, the timer channels are mapped to the
  STM32 microcontroller pins
• A timer channel mapped to an STM32
  microcontroller pin can be used either as an input
  or as an output.
                  Copyright © Bharati software 2018.
        The timer-channels unit
• Timer channel configured as output
• When configured as an output, the timer channel is
  used to generate a set of possible waveforms. As long
  as the channel is configured in output mode, the
  content of the TIMx_CCRy channel register is compared
  to the content of the timer counter.
• The output signal of the channel output stage is
  mapped to the microcontroller pins as alternate
  function.
                   Copyright © Bharati software 2018.
• Timer channel configured as an input
  – When configured as an input, the timer channel
    can be used to time-stamp the rising and/or the
    falling edge of external signals. To handle this
    function, the channel input is mapped to one of
    the microcontroller pins.
                   Copyright © Bharati software 2018.
                   Master slave
• It is possible to configure one slave timer to increment
  its counter based on a master-timer events such as the
  timer update event. In this example the master-timer
  event is signaled by the master timer master/slave
  controller unit. This controlling unit uses the master
  timer output-TRGO signal. The master timer output-
  TRGO signal is connected to the slave timer TRGI-input
  signal. The master/slave controller unit of the slave
  timer is configured to use the TRGI-input signal as clock
  source to increment the slave timer counter.
                     Copyright © Bharati software 2018.
  Timer clocking using external clock-
                source
• The STM32 timer peripherals can be clocked by
  an external source clock, but it does not mean
  that the APB (advanced peripheral bus) clock is
  not required. An STM32 timer peripheral
  synchronizes the external clock signal with its
  own core clock (which is the APB clock). The
  resulting synchronized clock signal is fed into the
  timer’s prescaler which by turn feeds the timer’s
  counter.
                   Copyright © Bharati software 2018.
There are two ways to synchronize (or externally clock) an STM32 timer:
• External source clock mode 1: by feeding the external clock signal into one of the
timer channel inputs, TIx inputs. • External source clock mode 2: by feeding the
external clock signal into the timer ETR input (if it is implemented and available).
                            Copyright © Bharati software 2018.
                               Exercise
To measure the time period of a
signal using a Timer
Use LSE and HSI as input signal to Timer
                             Copyright © Bharati software 2018.
      Timer with input capture block
Apply your
signal here
                Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
    Input Signal       2
                                                                                                  4
               Rising event-1 occurred here                                    Rising event-2 occurred here
      51     52       53    54        55        56        57          58        59    60     61
1   Timer Counter                                       TIM_CNT_CLK = 1KHz
                                              1ms
                       3
                                                                           5
                            54                                                              61
                   Capture /Compare register                                     Capture /Compare register
                                 Copyright © Bharati software 2018.
 Rising event1 occurred here
Rising event2 occurred here
 Input Signal
           51        52   53   54        55        56        57          58   59   60   61
         Timer Counter                                     TIM_CNT_CLK = 1KHz
                                                 1ms
                54                                                 54
 Capture /Compare register                         Capture /Compare register
                                    Copyright © Bharati software 2018.
                                         536 Seconds
  0      1       2   ---   0x55   0x56     0x57     0x58        ---    0x600   0x601   0xFFFFFFFF
32 bit counter                                           TIM_CNT_CLK = 8MHz
                                              0.125µS
Counts from 0 to 0xFFFFFFFF
Max period = (0xFFFFFFFF+1) * 0.125µS
           = 536 Seconds
Min Frequency = 1 /536 = 0.002Hz
                                  Copyright © Bharati software 2018.
             Working with Timer Input Channel
                     and STM32 Cube
   1) Initialize the TIMER Input                                  2) Configure Input Channel of
        Capture Time base                                                   the Timer
                                                               HAL_TIM_IC_ConfigChannel(TIM_Ha
HAL_TIM_IC_Init(TIM_HandleTypeDef *htim)                       ndleTypeDef *htim,
                                                               TIM_IC_InitTypeDef* sConfig,
                                                               uint32_t Channel)
                                   Copyright © Bharati software 2018.
                         STM32 Cube structure for
                       Configuring TIM Input Channel
HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel)
                                      Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
How to measure the period of an input
             signal ??
•   The elapsed time between two consecutive rising edges CC2Rtn - CC2Rtn-1
    represents an entire period of the reference signal
•   When the capture event occurs, the CC2IF (register TIM2_SR) is set to 1. If the
    DMA function is enabled, it will generate a DMA request. If the capture occurs,
    CC2IF flag has been set, then the over sampling flag CC2OF is set.
•   When a rising edge comes, numerical timer current meter (TIM2_CNT) will write in
    the TIM2_CCR2. Wait until the next rising edge to, there will be another counter
    value in TIM2_CNT records. According to the two data value, we can calculate the
    cycle of input data. Overflow timer is not allowed.
                              Copyright © Bharati software 2018.
             Working with Timer Output
             Channels and STM32 Cube
   1) Initialize the TIMER output                             2) Configure output channel of
        Compare Time base                                               the timer
                                                            HAL_TIM_OC_ConfigChannel(TIM_Ha
HAL_TIM_OC_Init(TIM_HandleTypeDef *htim)                    ndleTypeDef *htim,
                                                            TIM_OC_InitTypeDef* sConfig,
                                                            uint32_t Channel)
                                Copyright © Bharati software 2018.
                         STM32 Cube structure for
                       Configuring TIM Input Channel
HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel)
                                      Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
                Timer Modes
1.   Basic Time base generation
2.   Input Capture Mode
3.   Output Compare Mode
4.   PWM Mode
5.   One Pulse Mode
                  Copyright © Bharati software 2018.
   TIMER Output Compare Mode
Exercise :
Write an application by using TIMER2 , to
produce square wave forms of
500Hz, 1KHz, 2KHz and 4KHz on 4 different
output channels.
                Copyright © Bharati software 2018.
TIM_OCMODE_TOGGLE
     Copyright © Bharati software 2018.
TIMER Output Compare Mode
                             TIM2_CH1           500Hz
                             TIM2_CH2           1KHz
 TIMER-2
                             TIM2_CH3            2KHz
                             TIM2_CH4             4KHz
           Copyright © Bharati software 2018.
How are we going to produce
 waveforms using OC mode?
        Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
                  Exercise
By using PWM mode, generate PWM signals of
25%, 45%, 75% and 90% Duty cycle on TIMER2’s
channels .
                Copyright © Bharati software 2018.
      Controller Area Network
• CAN Bus Protocol and its features
  (Fundamentals )
• Operating Principles of the CAN Bus
• Different Message Formats
• Working with STM32 bxCAN Peripherals
• Various Examples
                Copyright © Bharati software 2018.
                Intro to CAN Bus
• The Controller Area Network Protocol was originally
  developed during the late 1980’s by the German company
  Robert Bosch for the automotive industry
• It is a multi-master serial communication bus whose basic
  design specification called for high speed, high noise-
  immunity and error-detection features
• CAN offers data communication up to 1 Mbit/sec
• the Error Confinement and the Error Detection features
  make it more reliable in noise-critical environments. In the
  automotive industries
                       Copyright © Bharati software 2018.
     CAN's most attractive features
• Low cost
• Extreme robustness
• High data transmission speeds (up to 1 MBit/sec).
• Reliability. Excellent error handling and Error Confinement abilities.
• Automatic re-transmission of faulty messages.
• Automatic bus disconnection of nodes that are suspected to be
  physically faulty.
• Functional addressing – data messages do not contain source or
  destination addresses, only identifiers relating to their function
  and/or priority.
                          Copyright © Bharati software 2018.
   CAN's most attractive features
• It’s a broadcast type of Bus(Unlike a
  traditional network such as USB or Ethernet,
  or i2c , CAN does not send data point-to-point
  from node A to node B under the supervision
  of a central bus master )
                 Copyright © Bharati software 2018.
                                                              It’s a broadcast type of Bus
                                                             All devices can hear the transmission
                                                          No way to send a data specifically to a nod
                                                          its address or something
                                                        All nodes will pick up the traffic on the bus
The CAN standard defines a communication network that links all the
nodes connected to a bus and enables them to talk with one another.
There may or may not be a central control node, and nodes may be
added at any time, even while the network is operating (hot-
plugging).
                              Copyright © Bharati software 2018.
        Closer look at the CAN node
Note that a transmitting node constantly monitors each bit of its own transmission
This is the reason for the transceiver configuration of Figure 4 in which the CANH and
CANL output pins of the driver are internally tied to the receiver's input
Because each node continuously monitors its own transmissions,
                               Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
                   Details of a CAN Bus
r. Connection to the physical medium is then implemented through a line transceiver
such as TI's SN65HVD230 3.3-V CAN transceiver to form a system node as shown in
                                Copyright © Bharati software 2018.
                                 CAN signaling
•   Signalling is differential which is where CAN derives its robust noise immunity and fault tolerance
•   Balanced differential signalling reduces noise coupling and allows for high signalling rates over
    twisted-pair cable
•   Balanced means that the current flowing in each signal line is equal but opposite in direction,
    resulting in a field-cancelling effect that is a key to low noise emissions
•   The use of balanced differential receivers and twisted-pair cabling enhance the common-mode
    rejection and high noise immunity of a CAN bus.
•   The cable is specified to be a shielded or unshielded twisted-pair with a 120-Ω characteristic
    impedance (Zo)
•   The ISO 11898 Standard defines a single line of twisted-pair cable as the network topology as
    shown in, , terminated at both ends with 120-Ω resistors. which match the characteristic
    impedance of the line to prevent signal reflections
                                      Copyright © Bharati software 2018.
CAN signaling
 Copyright © Bharati software 2018.
                           CAN signaling
A CAN bus is based in differential signalling. The two lines, CAN-High (CAN+) and CAN-
Low (CAN-), are both at the same potential when the bus is idle. To send bits, a CAN
transmitter puts a differential voltage on the lines of about 2 volts.
A CAN transmitter first sees if the bus is idle and if it is, starts to transmit. How the
arbitration works is that a transmitter monitors the bus as it's transmitting.
Transmission is done as above by either keeping the two lines at the same potential or
at a differential potential. So if the transmitter transmits a bit by keeping the lines at
the same potential (sic), but it sees that the two transmit lines have a differential
potential, that means that some other node is transmitting and the first transmitter
has lost the arbitration. It must then stop transmitting.
When a node first starts transmitting, the bits transmitted are the same until the
address of the transmitting node which are obviously different. If two nodes start
                                 Copyright © Bharati software 2018.
transmitting together, they will transmit together in sync till the address part is
The Bit Fields of Standard CAN and
           Extended CAN
           Copyright © Bharati software 2018.
                  The Error Frame
• The error frame is a special message that violates the formatting
  rules of a CAN message
• It is transmitted when a node detects an error in a message, and
  causes all other nodes in the network to send an error frame as wel
• The original transmitter then automatically retransmits the
  message
• An elaborate system of error counters in the CAN controller ensures
  that a node cannot tie up a bus by repeatedly transmitting error
  frames.
• It is transmitted when a node detects a fault and will cause all
  other nodes to detect a fault – so they will send Error Frames, too
                         Copyright © Bharati software 2018.
                     The Error Frame
• The Error Frame consists of an Error Flag, which is 6 bits of the same value
  (thus violating the bit-stuffing rule) and an Error Delimiter, which is 8
  recessive bits
• The Error Delimiter provides some space in which the other nodes on the
  bus can send their Error Flags when they detect the first Error Flag
• an active error frame consists of six dominant bits—violating the bit
  stuffing rule
• This is interpreted as an error by all of the CAN nodes which then generate
  their own error frame.
• It is important to note that the retransmitted message still has to contend
  for arbitration on the bus
                            Copyright © Bharati software 2018.
Error Frame
 Copyright © Bharati software 2018.
               A valid frame
• A message is considered to be error free when
  the last bit of the ending EOF field of a
  message is received in the error-free recessive
  state. A dominant bit in the EOF field causes
  the transmitter to repeat a transmission
                 Copyright © Bharati software 2018.
           error-checking procedure
• The CAN protocol incorporates five methods of error checking:
    – three at the message level and two at the bit level
• If a message fails any one of these error detection methods, it is not
  accepted and an error frame is generated from the receiving node
• This forces the transmitting node to resend the message until it is
  received correctly
• y. However, if a faulty node hangs up a bus by continuously
  repeating an error, its transmit capability is removed by its
  controller after an error limit is reached
                            Copyright © Bharati software 2018.
               error-checking procedure
•   Error checking at the message level is enforced by the CRC and the ACK slots displayed in Figure 2
    and Figure 3.
•   The 16-bit CRC contains the checksum of the preceding application data for error detection with a
    15-bit checksum and 1-bit delimiter.
•   . The ACK field is two bits long and consists of the acknowledge bit and an acknowledge delimiter
    bit.
•   Also at the message level is a form check. This check looks for fields in the message which must
    always be recessive bits. If a dominant bit is detected, an error is generated. The bits checked are
    the SOF, EOF, ACK delimiter, and the CRC delimiter bits
•   At the bit level, each bit transmitted is monitored by the transmitter of the message. If a data bit
    (not arbitration bit) is written onto the bus and its opposite is read, an error is generated. The only
    exceptions to this are with the message identifier field which is used for arbitration, and the
    acknowledge slot which requires a recessive bit to be overwritten by a dominant bit.
•   The final method of error detection is with the bit-stuffing rule where after five consecutive bits of
    the same logic level, if the next bit is not a complement, an error is generated
                                       Copyright © Bharati software 2018.
           The Overload Frame
• It is very similar to the Error Frame with
  regard to the format and it is transmitted by a
  node that becomes too busy.
                  Copyright © Bharati software 2018.
                          Arbitration
• Bus access is event-driven and takes place randomly. If two nodes try to
  occupy the bus simultaneously, access is implemented with a
  nondestructive, bit-wise arbitration
• Nondestructive means that the node winning arbitration just continues on
  with the message, without the message being destroyed or corrupted by
  another node.
• the Arbitration Field, which determines the priority of the message when
  two or more nodes are contending for the bus.
• \The Arbitration Field contains:For CAN 2.0A, an 11-bit Identifier and one
  bit, the RTR bit, which is dominant for data frames.
• For CAN 2.0B, a 29-bit Identifier (which also contains two recessive bits:
  SRR and IDE) and the RTR bit.
                           Copyright © Bharati software 2018.
                  Arbitration
• . An actual application may include a temperature
  sensor sending out a temperature update that is
  used to adjust the motor speed of a fan. If a
  pressure sensor node wants to send a message at
  the same time, arbitration ensures that the
  message is sent.
• sending a '0' is dominant over a '1', which results
  in the lowest address winning arbitration
                   Copyright © Bharati software 2018.
                    Arbitration
• Example : Will be most grateful if you could just clear
  this up: Lets say the identifiers are "1011001" and
  "1000110" when the third bit is reached the first
  transmitter is sending "1" and second one is sending
  "0"; so as per CAN protocol the dominant bit is 0, and it
  overwrites the recessive bit. So now the Bus holds "0";
  the first module detects this and will stop transmission
  while the second one will keep on transmitting. Is my
  understanding correct ??
                     Copyright © Bharati software 2018.
Message Transfer : Example
        Copyright © Bharati software 2018.
                    Message priority
• The allocation of priority to messages in the identifier is a feature of CAN
  that makes it particularly attractive for use within a real-time control
  environment
• The lower the binary message identifier number, the higher its priority
• . An identifier consisting entirely of zeros is the highest priority message
  on a network because it holds the bus dominant the longest
• Therefore, if two nodes begin to transmit simultaneously, the node that
  sends a last identifier bit as a zero (dominant) while the other nodes send
  a one (recessive) retains control of the CAN bus and goes on to complete
  its message. A dominant bit always overwrites a recessive bit on a CAN
  bus.
• The allocation of message priority is up to a system designe
                            Copyright © Bharati software 2018.
       CAN arbitration process
• handled automatically by a CAN controller
• Because each node continuously monitors its
  own transmissions,
                Copyright © Bharati software 2018.
           CAN arbitration process
• displays the CAN arbitration process that is handled automatically
  by a CAN controller. Because each node continuously monitors its
  own transmissions, as node B's recessive bit is overwritten by node
  C’s higher priority dominant bit, B detects that the bus state does
  not match the bit that it transmitted. Therefore, node B halts
  transmission while node C continues on with its message. Another
  attempt to transmit the message is made by node B once the bus is
  released by node C. This functionality is part of the ISO 11898
  physical signaling layer, which means that it is contained entirely
  within the CAN controller and is completely transparent to a CAN
  user.
                         Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
R    D R D     D       R      D     R
                                      Node A
Node B
             Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
           CAN Message Types
• There are 4 different message types(or
  frames) in CAN Protocol
    Data       Remote                            Error   Overload
   Frame        Frame                           Frame     Frame
                  Copyright © Bharati software 2018.
        Most Common Message Types in CAN Communication .
 Data
        We use it very frequently
Frame
        A Node uses this frame to send a message to other
        nodes on the Can bus.
                   Here is a message !
CAN
Node
         Copyright © Bharati software 2018.
Data Frame Format
                                          Data
                                         Frame
    Copyright © Bharati software 2018.
Arbitration Field
                The Arbitration Field, which determines the
                priority of the message when two or more
                nodes are contending for the bus. The
                Arbitration Field contains: For CAN 2.0A, an 11-
                bit Identifier and one bit, the RTR bit, which is
                dominant for data frames.
                Identifier establishes the priority of the
                message. The lower the binary value, the
                higher its priority.
   Copyright © Bharati software 2018.
      Standard CAN Vs Extended CAN
• The original specification is the Bosch specification Version 2.0
• Version 2.0 specification is divided into two parts
   – Standard CAN (Version 2.0A). Uses 11 bit identifiers.
   – Extended CAN (Version 2.0B). Uses 29 bit identifiers.
• The difference between these two formats is that the length of bits, i.e., the
  standard CAN Frame format supports 11-bits length for the identifier, whereas
  the extended frame supports 29-bits length for the identifier, which is made
  up of 18-bit extension and an 11-bit identifier.
• Most 2.0A controllers transmit and receive only Standard format messages.
• 2.0B controllers can send and receive messages in both formats.
                                 Copyright © Bharati software 2018.
      Standard CAN Vs Extended CAN
• If you have a CAN network which Consists of both 2.0A and 2.0B based CAN
  devices and if you use extended frame format ( 29 bit identifiers ), then your
  network will not work, because 2.0A devices will generate an error
• 2.0B controllers are completely backward compatible with 2.0A controllers
  and can transmit and receive messages in either format.
• 2.0A controller based devices are capable of transmitting and receiving only
  messages in 2.0A format (standard format). With this type of controller,
  reception of any 2.0B message will flag an error.
                            Copyright © Bharati software 2018.
      Extended Frame Format or CAN 2.0 B
The IDE bit differs CAN extended frame format and the CAN standard frame
format wherein IDE is transmitted as dominant in an 11-bit frame case and
recessive in a 29-bit frame case.
                           Copyright © Bharati software 2018.
RTR bit (Remote Transmission Request )
                        A dominant (logic 0), RTR bit indicates that the
                        message is a Data Frame
                        A recessive (logic 1) value indicates that the
                        message is a Remote Transmission Request
                        (known as Remote Frame.) A Remote Frame is
                        a request by one node for data from some
                        other node on the bus. Remote Frames do not
                        contain a Data Field.
             Copyright © Bharati software 2018.
DLC, DATA and CRC Fields
                                            The 4-bit data length code (DLC)
                                            contains the number of bytes of
                                            data being transmitted
                                            The Data Field, which contains
                                            zero to eight bytes of data.
                                            The CRC Field contains a 15-bit
                                            checksum calculated on most
                                            parts of the message. This
                                            checksum is used for error
                                            detection
       Copyright © Bharati software 2018.
    ACK Bit
Copyright © Bharati software 2018.
                                 ACK Bit
It is worth noting that the presence of an
Acknowledgement Bit on the bus does not mean
that any of the intended devices has received the
message.
It just means that one or more nodes on the bus
has received it correctly and Transmitter concludes
that message sent successfully .
 If Transmitter sees recessive state at the ACK slot ,
then it retransmits the message until it sees
dominant state. That’s the reason when there is
only one node on the bus, transmitter keep sending
the same message since no one is there to ack it.
                             Copyright © Bharati software 2018.
                        ACK Significance
•   Every node receiving an accurate message overwrites this recessive bit in the
    original message with a dominate bit, indicating an error-free message has been
    sent. If a receiving node detects an error then it leaves this bit recessive, it discards
    the message and the sending node repeats the message after re-arbitration. In this
    way, each node acknowledges (ACK) the integrity of its data. ACK is 2 bits, one is
    the acknowledgment bit and the second is a delimiter
•   Because all receivers must participate in the acknowledgment algorithm regardless
    of whether the message is intended for them or not, an acknowledgment to the
    transmitter may occur even if the expected receiver is not present on the network
•   This means that the CAN Acknowledgment does not guarantee that a data transfer
    has occurred between the transmitter and a designated receiver. It does not
    confirm that a requested action has been understood or performed. CAN
    Acknowledgment only confirms that all resident network nodes agree that the
    CAN message did not violate any Data Link Layer rules.
                                 Copyright © Bharati software 2018.
             End of Frame and IFS
End of Frame : 7 Recessive State
IFS ( Inter Frame Spacing ) : 3 Recessive state
                        Copyright © Bharati software 2018.
                                    SOF
SOF–The single dominant start of frame (SOF) bit marks the start
of a message, and is used to synchronize the nodes on a bus after
being idle.
                                                                Beginning of Next
                                                                Data or Request
               Previous Frame
                                                                Frame
                           Copyright © Bharati software 2018.
                OK ! The bus
                                            SOF                          Bus is idle ,
                                                                            and I
                has become                                               detected a
               idle Lets send                                           dominant bit ,
                  message                                               must be SOF.
                                                                          Lets listen
    Node                                                        Node
     A           Transmitter                                     B          Receiver
*sends a message using data frame .                       *when Bus is idle, it detects a dominant
The first bit of the frame will be dominant               bit(SOF) , hence understands that
which marks the start of frame(SOF)                       someone is transmitting
                                  Copyright © Bharati software 2018.
             • The intended purpose of the remote frame is to
               solicit the transmission of data from another node
Remote       • The remote frame is similar to the data frame, with
 Frame         two important differences. First, this type of
               message is explicitly marked as a remote frame by a
               recessive RTR bit in the arbitration field, and
               secondly, there is no data.
                  Consider this request
CAN              and send me some data
Node
         Copyright © Bharati software 2018.
             • If, say, node A transmits a Remote Frame with the
               Arbitration Field set to 123, then node B, if properly
               initialized, might respond with a Data Frame with the
Remote         Arbitration Field also set to 123.
 Frame       • Remote Frames can be used to implement request-
               response type communication between nodes.
             • Most CAN controllers can be programmed either to
               automatically respond to a Remote Frame
                  Consider this request
CAN              and send me some data
Node
         Copyright © Bharati software 2018.
Remote
         RTR bit is Recessive and there is no Data
 Frame
          Copyright © Bharati software 2018.
   BUS access from Multiple Nodes
The CAN communication protocol is a carrier-sense, multiple-access
protocol with collision detection and arbitration on message priority
(CSMA/CD+AMP).
CSMA means that each node on a bus must wait for a prescribed
period of inactivity before attempting to send a message. CD+AMP
means that collisions are resolved through a bit-wise arbitration, based
on a preprogramed priority of each message in the identifier field of a
message
The higher priority identifier always wins bus access.
                          Copyright © Bharati software 2018.
 Bitwise Bus arbitration in CAN
Nodes                  Arbitration ID
NODE-1            0x65D (110 0101 1101 b)
NODE-2            0x676 (110 0111 0110 b)
NODE-3            0x659 (110 0101 1001 b)
           Copyright © Bharati software 2018.
             S                                                       R
                            Identifier
             O                                                       T             Data
             F   10 9   8 7 6 5 4               3 2 1            0       Control
                                                                     R
Node-1
Node-2
Node-3
      CANH
Bus State    D
      CANL
                            Copyright © Bharati software 2018.
             S                                                       R
                            Identifier
             O                                                       T             Data
             F   10 9   8 7 6 5 4               3 2 1            0       Control
                                                                     R
Node-1
Node-2
Node-3
      CANH
                 R
Bus State    D
      CANL
                            Copyright © Bharati software 2018.
             S                                                       R
                            Identifier
             O                                                       T             Data
             F   10 9   8 7 6 5 4               3 2 1            0       Control
                                                                     R
Node-1
Node-2
Node-3
      CANH
                 R R
Bus State    D
      CANL
                            Copyright © Bharati software 2018.
             S                                                       R
                            Identifier
             O                                                       T             Data
             F   10 9   8 7 6 5 4               3 2 1            0       Control
                                                                     R
Node-1
Node-2
Node-3
      CANH
                 R R
Bus State    D          D
      CANL
                            Copyright © Bharati software 2018.
             S                                                       R
                            Identifier
             O                                                       T             Data
             F   10 9   8 7 6 5 4               3 2 1            0       Control
                                                                     R
Node-1
Node-2
Node-3
      CANH
                 R R
Bus State    D          D D
      CANL
                            Copyright © Bharati software 2018.
             S                                                       R
                            Identifier
             O                                                       T             Data
             F   10 9   8 7 6 5 4               3 2 1            0       Control
                                                                     R
Node-1
Node-2
Node-3
      CANH
                 R R           R
Bus State    D          D D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R
Bus State    D          D D         D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R          R
Bus State    D          D D         D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R          R R
Bus State    D          D D         D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
                                                                          Listen only
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R          R R
Bus State    D          D D         D                D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
                                                                          Listen only
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R          R R
Bus State    D          D D         D                D D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
                                                                          Listen only
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R          R R                    R
Bus State    D          D D         D                D D              D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T             Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
                                                                          Listen only
Node-1
                                                                     Listen only
Node-2
Node-3
      CANH
                 R R           R          R R                    R
Bus State    D          D D         D                D D              D
      CANL
                            Copyright © Bharati software 2018.
             S                                                        R
                            Identifier
             O                                                        T               Data
             F   10 9   8 7 6 5 4               3 2 1            0        Control
                                                                      R
                                                                          Listen only
Node-1
                                                                     Listen only
Node-2
Node-3                                                                             Any Data
      CANH
                 R R           R          R R                    R                  Any Data
Bus State    D          D D         D                D D              D
      CANL
                            Copyright © Bharati software 2018.
         ST’s BxCAN Controller
The bxCAN(Basic xtended CAN ) module handles
the transmission and the reception of CAN
messages fully autonomously. Standard
identifiers (11-bit) and extended identifiers (29-
bit) are fully supported by the hardware
                  Copyright © Bharati software 2018.
            ST’s bxCAN features
•   2 CAN Controllers are available CAN1 and CAN2
•   CAN1 is called Master bxCAN and CAN2 is slave
•   Both Supports CAN protocol version 2.0 A, B
•   Bit rates up to 1 Mbit/s
•   Three transmit mailboxes
•   Two receive FIFOs with three stages
•   28 filter banks shared between CAN1 and CAN2
                   Copyright © Bharati software 2018.
What application can do with bxCAN ?
• Configure CAN parameters, e.g. bit rate, bit
  timings , etc
• Transmissions
• Handle receptions
• Manage interrupts
• Get diagnostic information
                  Copyright © Bharati software 2018.
         bxCAN block Diagram
Refer to RM : Figure 383. Dual CAN block
diagram
                 Copyright © Bharati software 2018.
          bxCAN Master and Slave
As mentioned in reference manual RM0390
"- CAN1: Master bxCAN for managing the communication between a Slave
bxCAN and the 512-byte SRAM memory.
-CAN2: Slave bxCAN, with no direct access to the SRAM memory."
                           Copyright © Bharati software 2018.
                     BxCAN Test Modes
CAN_TX =1                CAN_TX                              CAN_TX =1       CAN_RX
              CAN_RX                             CAN_RX
    TX       RX                  TX             RX                 TX       RX
    CAN Controller               CAN Controller                   CAN Controller
   Silent Mode                Loop Back Mode                 Silent+ Loop Back Mode
                        Copyright © Bharati software 2018.
                           Silent Mode
CAN_TX =1
                       CAN_RX              • Tx line is internally looped back to RX line
                                           • CAN TX is held at recessive state
                                           • bxCAN is able to receive valid frames
      TX          RX
                                           • It just listens and doesn’t change the bus state
      CAN Controller                         by putting dominant bit
                                           • Can be used as a sniffer which just analyzes
                                             the traffic on the bus.
                                Copyright © Bharati software 2018.
                      Loop Back Mode
CAN_TX                CAN_RX             • bxCAN can Transmit frames on the bus .
                                         • Also the frames are looped back to the RX
                                           line internally
         TX      RX                      • bxCAN will not listen to the bus, but just
                                           receives its own message which is looped
     CAN Controller                        back.
                                         • loop back mode is provided for self test
                                           functions
                               Copyright © Bharati software 2018.
              Silent Look Back Mode
CAN_TX =1              CAN_RX
                                           • bxCAN controller is totally disconnected
                                             from the bus
                                           • It neither transmits nor listens to the bus
      TX          RX
                                           • TX is internally looped back to the RX,
      CAN Controller                         hence receives its own messages.
                                Copyright © Bharati software 2018.
         CAN Bit Timings Configuration
                                                                        Each bit on the CAN bus is, for
                                                                        timing purposes, divided in to 4
                                                                        segments
                                                                        1) Synchronization Segment
                                                                        2) Propagation Segment
                                                                        3) Phase Segment 1
                                                                        4) Phase Segment 2
Width of these segments have to be adjusted properly to get desired bit rate on the CAN
bus. Width of each segment is mentioned in terms of time quanta
The Time Quanta is the smallest time unit for all configuration values.
                                   Copyright © Bharati software 2018.
    bXCAN Block Diagram(TX-Path)
• Three transmit mailboxes are provided to the software for setting up messages.
• The transmission Scheduler decides which mailbox has to be transmitted first.
• In order to transmit a message, the application must select one empty transmit
  mailbox, set up the identifier, the data length code (DLC) and the data before
  requesting the transmission
• Request Transmission by setting TXRQ bit in the control register.
• Immediately after the TXRQ bit has been set, the mailbox enters pending state
  and waits to become the highest priority mailbox
                              Copyright © Bharati software 2018.
    bXCAN Block Diagram(TX-Path)
• As soon as the mailbox has the highest priority it will be scheduled for
  transmission.
• The transmission of the message of the scheduled mailbox will start (enter
  transmit state) when the CAN bus becomes idle
• Once the mailbox has been successfully transmitted, it will become empty again
• The hardware indicates a successful transmission by setting the RQCP and TXOK
  bits in the CAN_TSR register.
• If the transmission fails, the cause is indicated by the ALST bit in the CAN_TSR
  register in case of an Arbitration Lost, and/or the TERR bit, in case of transmission
  error detection               Copyright © Bharati software 2018.
bxCAN Tx and STM32 Cube
       Copyright © Bharati software 2018.
      bxCAN Tx and STM32 Cube
HAL_CAN_AddTxMessage(CAN_HandleTypeDef *hcan,
                     CAN_TxHeaderTypeDef *pHeader,
                     uint8_t aData[], uint32_t *pTxMailbox)
                         Copyright © Bharati software 2018.
bXCAN Block Diagram(RX-Path)
         Copyright © Bharati software 2018.
                                                                                       CAN_TX
                       TX                              Parallel to Serial   PA11 TX
                     Mailbox                              Converter
                      (3)
Processor
                                                                            I/O Pins
            FIFO 1                                                                     CAN_RX
                           Acceptance                  Serial to Parallel
                                                          Converter         PA12 RX
                           Filter banks
                                (28)
            FIFO 2
                               Copyright © Bharati software 2018.
             bxCAN RX Path
• Two receive FIFOs are used by each CAN
  Controller to store the incoming messages
• Three complete messages can be stored in
  each FIFO
• The FIFOs are managed completely by
  hardware
                 Copyright © Bharati software 2018.
                       RX Filtering
• The controller will read any frames it sees on the bus and hold them
  in a small FIFO memory. It will notify the host processor that this
  data is available which the processor then reads from the controller
• The controller also contains a hardware filter mechanism that can
  be programmed to ignore and discard those CAN frames you do not
  want passed to the processor. This saves processor overhead.
• Acceptance filtering is introduced to manage the frame reception
                         Copyright © Bharati software 2018.
           Acceptance filtering
• There are 28 filter banks shared between
  Master bxCAN ( CAN1) and slave bxCAN(
  CAN2)
• Each Filter bank has 2 , 32 bit associated filter
  registers.
• You can use filter banks to filter the incoming
  messages. Lets see some examples.
                  Copyright © Bharati software 2018.
                       Filter Banks
                FB0_R1(32bit)                                   FB1_R1(32bit)
Filter Bank 0                              Filter Bank 1
                FB0_R2(32bit)                                   FB1_R2(32bit)
                FB2_R1(32bit)                                   FBx_R1(32bit)
Filter Bank 2                               Filter Bank x
                FB2_R2(32bit)                                   FBx_R2(32bit)
                                            X = 0 to 27
                           Copyright © Bharati software 2018.
  Frame acceptance Rules: Example
1. Accept frames only if first 3 msbs of the standard identifier are 1s
   e.g. 111xxxx
2. Accept frames only if first 3 msbs of the standard identifer are 0s and last 2 lsbs are 1s
3. Accept frames only if standard identifier value exactly = 0x65D or 0x651
4. Accept only Request frames
5. Accept only Extended Id Frames
6. Accept all frames
                                 Copyright © Bharati software 2018.
                                                       FB0_R1(32bit)
     Filter Bank 0
                                                       FB0_R2(32bit)
                                                                                                                                     Identifier Register
31   30   29     28   27    26   25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10   9   8   7   6    5    4   3   2    1   0
                                                                                                                                          Mask Register
31   30   29     28   27    26   25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10   9   8   7   6    5    4   3    2   1   0
31   30   29     28   27    26   25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10   9   8   7   6    5    4   3   2    1   0
                                                                                                                                          fields Mapping
                                                                                                                                                        R
                                                                                                                                                   ID
               STID[10:3]                  STID[2:0]           EXID[17:13]                         EXID[12:5]                    EXID[4:0]          E
                                                                                                                                                        T   0
                                                                                                                                                        R
                                                               Copyright © Bharati software 2018.
                                                       FB0_R1(32bit)
     Filter Bank 0
                                                       FB0_R2(32bit)
                                                                                                                                     Identifier Register-1
31   30   29     28   27    26   25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10   9   8   7   6    5    4   3   2    1   0
                                                                                                                                     Identifier Register-2
31   30   29     28   27    26   25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10   9   8   7   6    5    4   3    2   1   0
31   30   29     28   27    26   25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10   9   8   7   6    5    4   3   2    1   0
                                                                                                                                          fields Mapping
                                                                                                                                                        R
                                                                                                                                                   ID
               STID[10:3]                  STID[2:0]           EXID[17:13]                         EXID[12:5]                    EXID[4:0]          E
                                                                                                                                                        T   0
                                                                                                                                                        R
                                                               Copyright © Bharati software 2018.
     Receive FIFO State Machine
Refer RM : Figure 389. Receive FIFO states
                   Copyright © Bharati software 2018.
bxCAN Interrupts
    Copyright © Bharati software 2018.
  When does bxCAN issue interrupts ?
1.   Transmit Request Completed
2.   Frame is received in RX FIFO0
3.   Frame is received in RX FIFO1
4.   During CAN status change or Error
Four interrupt vectors(IRQs) are dedicated to bxCAN1
Four interrupt Vectors(IRQs) are dedicated to bxCAN2
                            Copyright © Bharati software 2018.
                         Exercise
Find out the bxCAN1 and bxCAN2 IRQ numbers
for STM32F446RE microcontroller
Hint : Refer Vector table information in RM
                       Copyright © Bharati software 2018.
       bxCAN interrupt generation
Refer RM : Figure 396. Event flags and interrupt
generation
                       Copyright © Bharati software 2018.
    Reception related interrupts
• Once a message has been stored in the FIFO
• interrupt request is generated
• When the FIFO becomes full interrupt is
  generated
• On overrun condition
                Copyright © Bharati software 2018.
Loop Back mode connection
                                                     +vcc
                                              3.3v
           CAN_TX
PA11 TX                             CAN_TX
                                                         CANH
                                                                     120Ω
                                         Transceiver            RL
                                                         CANL
          CAN_RX
PA12 RX                             CAN_RX
                                               ground
PA12
                    Copyright © Bharati software 2018.
Loop Back mode connection
                                              3.3v
           CAN_TX
PA11 TX                             CAN_TX
                                                         CANH
                                                         CANL
          CAN_RX
PA12 RX                             CAN_RX      3.3KΩ           +vcc
                                               ground
                                                                3.3V
PA12
                    Copyright © Bharati software 2018.
SN65HVD230 CAN Transceiver
       Schematic
        Copyright © Bharati software 2018.
                                          CAN Normal Mode
                                                                                              LED1           LED2        LED3          LED4
                                          +vcc                                        +vcc
                                          3.3v                                        3.3v
                 CAN_TX            3.3v                     CAN Bus                          3.3v
                                                                                                                CAN_TX
      PA12 T              CAN_TX                                                                    CAN_TX                   TX PA12
           X                                 CANH                                 CANH
                                                           120Ω      120Ω
N-1                          Transceiver
                                                       R
                                                       L
                                                                             R
                                                                             L           Transceiver                          N-2
                                             CANL                                 CANL
                CAN_RX                                                                                              CAN_RX
      PA11 RX             CAN_RX                                                                    CAN_RX                   RX PA11
                                    ground                                                ground
      PA12                                                                                                                      PA12
•   N1 sends a message(led number) using Data Frame for every 1sec to N2
•   After the reception of message(led number) N2 has to glow the corresponding LED
•   N1 also sends a Remote frame to request 2 bytes of data for every 4sec
•   N2 upon receiving the Remote frame should send back 2 bytes of data using Data Frame
•   Use Interrupt driven Code
                                                 Copyright © Bharati software 2018.
            CAN Normal Mode Exercise
                 Timer6                                                  CAN1
                                                                                       CAN1_Init()
  TIMER_Init()
                                                                 CAN1_FilterConfig()
        HAL_TIM_Base_MspInit()
                                                                            HAL_CAN_MspInit()
TIM6_DAC_IRQHandler()
       HAL_TIM_PeriodElapsedCallback()                          HAL_CAN_XXX_Callback()
                                                                        CAN1_XX_IRQHandler()
                                 Copyright © Bharati software 2018.
         N1 and N2 GPIO Inits
                             LED1              LED2         LED3          LED4
                                                      PC8          PB8
                                                                            PC6
                   3.3v
                           CAN_TX
                                                      PC9
        PC13
N-1            Button
                                                                    N-2
                          CAN_RX
 PA12
                                                                   PA12
               Copyright © Bharati software 2018.
                                                        FB0_R1(32bit)
     Filter Bank 0
                                                        FB0_R2(32bit)
                                  FilterIdHigh                                                                         FilterIdLow
31   30   29     28   27    26    25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10     9   8   7   6   5    4
                                                                                                                                                 Identifier
                                                                                                                                                   3  2   1
                                                                                                                                                            Register
                                                                                                                                                              0
                                 FilterMaskIdHigh                                                                     FilterMaskIdLow
31   30   29     28   27    26    25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10     9   8   7   6   5    4
                                                                                                                                                 Mask
                                                                                                                                                 3  2
                                                                                                                                                      Register
                                                                                                                                                        1   0
31   30   29     28   27    26    25   24   23   22   21   20    19   18   17   16   15   14   13     12   11    10     9   8   7   6   5    4    3   2    1   0
                                                                                                                                            fields Mapping
                                                                                                                                                           R
                                                                                                                                                      ID
               STID[10:3]                   STID[2:0]           EXID[17:13]                         EXID[12:5]                      EXID[4:0]          E
                                                                                                                                                           T   0
                                                                                                                                                           R
                                                                Copyright © Bharati software 2018.
Low Power Modes
    Copyright © Bharati software 2018.
         MCU Low power modes
• A number of low-power features are available in the
  Cortex-Mx processor.
• In addition, microcontroller vendors usually also implement
  a number of low power modes in their Cortex-Mx-based
  microcontrollers. This we call as device specific low power
  modes or features .
• Details for microcontroller-specific low-power features are
  usually available in user manuals or application notes
  available from the microcontroller vendor Web sites
                      Copyright © Bharati software 2018.
          MCU Low Power Modes
A Microcontroller can be in Run mode or in Low Power mode.
In Run mode the processor will be clocked always and it will be
doing its normal operation and it will be consuming the power for
its operation .
When processor has got nothing to do , you can send it to low
power mode. Otherwise it will be in busy idle loop wasting CPU
cycles thus consuming the power. For battery operated
applications this is not a good design.
                       Copyright © Bharati software 2018.
                  MCU Modes
Run Mode                                        Low Power Modes
           Copyright © Bharati software 2018.
                        Low Power modes
                                                                    Vendor
Processor Specific
                                                              Specific(MCU) Low
Low Power Modes
                                                            Power modes (e.g ST)
                                                    Additional sleep modes are
                                                    introduced by MCU vendors using
                                                    device-specific programmable
                                                    registers
                     Copyright © Bharati software 2018.
Processor Specific Low Power modes
                                ARM Cortex Mx
SLEEPDEEP feature is RESET                                            SLEEPDEEP feature is SET
         Normal Sleep                                                 Deep Sleep
Instruction : WFI and WFE
                                                              Instruction : WFI and WFE
  Feature : Sleep on exit
                                                                  Feature : Sleep on exit
                             Copyright © Bharati software 2018.
       Normal Sleep Vs Deep Sleep
• Inside the processor, the selection between normal sleep mode and deep
  sleep mode is defined by the SLEEPDEEP bit in the System Control
  Register(SCR)
• Normal sleep mode stops the processor clock
• Deep sleep mode stops the system clock and switches off the PLL and flash
  memory ( This is highly dependent on vendor who designs the
  microcontroller )
• The Exact behavior of Normal and Deep Sleep mode is Microcontroller
  vendor specific .
• For more information about the behavior of the sleep modes see the
  documentation supplied by your device vendor.
                           Copyright © Bharati software 2018.
      How to Enter Normal Sleep
• SLEEPDEEP bit of the ARM Cortex Mx processor must
  be reset
• Use instructions like WFI or WFE to trigger entering
  the sleep mode
• You can also use SLEEPONEXIT feature of the ARM
  Cortex Mx processor to enter in to sleep mode.
                   Copyright © Bharati software 2018.
        How to Enter Deep Sleep
• SLEEPDEEP bit of the ARM Cortex Mx processor
  must be set
• Use instructions like WFI or WFE to trigger entering
  the sleep mode
• You can also use SLEEPONEXIT feature of the ARM
  Cortex Mx processor to enter in to sleep mode.
                    Copyright © Bharati software 2018.
 Summary : Entering Low Power Mode
In ARM cortex Mx based processor there are only 3 ways by which
you can make processor enter in to the low power mode
    • execution of a WFE instruction
    • execution of a WFI instruction
    • using the Sleep-On-Exit feature
If you enable the Sleep on Exit the processor enters sleep
automatically when it exits ISR
Lets explore Sleep-On-Exit feature, WFI and WFE one by one
                       Copyright © Bharati software 2018.
Entering SLEEP mode using Sleep-on-Exit feature
✓ Sleep on exit is a feature given by the ARM Cortex Mx processor .
✓ Remember its not an instruction
✓ When this feature is enabled, the processor automatically enters a sleep mode when exiting
  an exception handler if no other exception is waiting to be processed
✓ It does not cause the processor to enter sleep if the exception handler is returning to another
  exception handler (nested interrupt).
When to use this ?
When your application does all its work in an Interrupt handler , then while exiting ISR the
Processor will automatically go to sleep if you enable this feature to save power .
• You would like to use this when processor runs only when an interrupt service require
    servicing.
• interrupt driven applications to stay in sleep mode as often as possible.
• The Sleep-On-Exit feature is ideal for interrupt-driven applications
                                    Copyright © Bharati software 2018.
Entering SLEEP mode using Sleep-on-Exit feature
✓ SLEEPONEXIT bit in the SCR of the ARM cortex Mx processor
  has to be set after all the initialization of your application
✓ No instruction is needed to enter sleep mode with this feature
  enabled
✓ When ISR finishes executing all the instructions you have
  written , processor goes in to sleep mode automatically without
  returning back to thread mode ( No thread related un-stacking
  happens , because processor is not going back to thread mode )
                       Copyright © Bharati software 2018.
Entering SLEEP mode using Sleep-on-Exit feature
Note :
In interrupt-driven applications, do not enable Sleep-On-Exit
feature too early during the initialization. Otherwise if the
processor receives an interrupt request during the initialization
process, it will enter sleep automatically after the interrupt
handler executed before the rest of the initialization process
completes.
                        Copyright © Bharati software 2018.
                     Exercise
• Write an application in which TIM6 triggers
  Update interrupt for every 10ms and in the
  ISR of TIM6 send some data over UART2.
▪ Measure the Current consumption without sleep mode
▪ Measure the Current Consumption With Sleep mode (
  Enter sleep mode using SLEEPONEXIT feature )
                   Copyright © Bharati software 2018.
                             Reset
 Processor Mode : Run      Initialization
                                                       Processor Mode : Run        Entry in to TIM6 ISR
                                                                                   Processor Mode : sleep
                        Enable SLEEPONEXIT              Processor Mode : Run         UART2 data send
Processor Mode : Run
                              feature
                                                         Processor Mode : Run          Exit from ISR
Processor Mode : Run        Start Timer
Processor Mode : Run      Wait in while(1)                Processor Mode : Sleep         Sleeping
                                       Copyright © Bharati software 2018.
       Waking up from SLEEPONEXIT
•   when the processor enters sleep mode using the Sleep-On-Exit feature or executing the WFI
    instruction the processor stops instruction execution, enters sleep mode and wakes up when
    a higher priority interrupt request arrives and needs to be serviced.(This what ARM Says, but
    MCU vendor may implement wakeup procedure differently , e.g in ST’s Case processor wakes
    up for any interrupt, i.e priority don’t care )
•   If the processor enters sleep in an exception handler, and if the newly arrived interrupt
    request has the same or lower priority compared to the current exception, the processor will
    not wake up and interrupt will remain in pending state. (This what ARM Says, but MCU
    vendor may implement wakeup procedure differently )
•   The processor can also be woken up by a halt request from the debugger or by reset
                                   Copyright © Bharati software 2018.
Power
                 Power consumption in Run mode                        Power consumption in Sleep mode
                     ISR entry          ISR exit
        Thread        Thread Handler               Handler             Handler
    Initialization   While(1)
                                        Sleeping             Sleeping        Sleeping
                                                                                            time
                          Enter Sleep automatically
                                 Copyright © Bharati software 2018.
           WFI(Wait For Interrupt)
• It is a 16 bit Thumb instruction
• When Cortex-Mx ( 0, 0+,3,4,7… ) processor executes
  a WFI instruction it stops executing instructions and enters
  sleep mode(Clocks to the processor is stopped ), until the
  arrival of an interrupt or if the processor enters a debug state
• Enter sleep unconditionally
• Can be used with both normal sleep and deep sleep mode
                        Copyright © Bharati software 2018.
          WFI(Wait For Interrupt)
• The WFI instruction is a Cortex-Mx instruction which cannot
  be directly accessible by ANSI C. The CMSIS (Cortex
  Microcontroller Software Interface Standard) provides an
  intrinsic function to generate a WFI instruction and is
  supported by C compiler. If a C compiler does not support the
  WFI intrinsic function, then the user will have to use assembly
  code to execute WFI instruction.
                       Copyright © Bharati software 2018.
                    Waking up from WFI
•   When processor goes to sleep executing WFI instruction in a thread mode , any
    interrupt request , debug request or reset can wake up the processor.
•   If the processor executes WFI instruction in an exception handler and enters sleep
    mode then only higher priority interrupt request ( > current level) can only wake
    up the processor. If the newly arrived interrupt request has the same or lower
    priority compared to the current exception, the processor will not wake up and
    the newly issued interrupt will remain in pending state. .(This what ARM Says, but
    MCU vendor may implement wakeup procedure differently )
•   The processor can also be woken up by a halt request from the debugger or by
    reset
                               Copyright © Bharati software 2018.
  WFI                     WFI executed
summary                        Is
                           SLEEPDEEP
                              set ?
 Normal Sleep(Wait                                           Deep Sleep(Wait
  until interrupt )                                          until interrupt )
                      Interrupt /Debug Req/Halt
                      Exit Sleep and Execute
                        next instruction in
                             Run mode
                        Copyright © Bharati software 2018.
                     Exercise
• Write an application in which TIM6 triggers
  Update interrupt for every 10ms and in the
  ISR of TIM6 send some data over UART2.
▪ Measure the Current consumption without sleep mode
▪ Measure the Current Consumption With Sleep mode (
  Enter sleep mode using WFI Instruction)
                   Copyright © Bharati software 2018.
            Tips to Reduce the Power
                  Consumption
• Stopping clock to the processor and to some or all the
  peripherals (clock gating )
• Reducing Clock frequency.
• Reducing Voltage to various parts of the microcontroller
• Turning off the power supply to some parts of the
  microcontroller
• Keeping unused pins in the analog mode
                        Copyright © Bharati software 2018.
• 500 milliamps for one hour before being
  "dead”
• 500 1 hour
• 2.7 ? 185 hour – 1 week
                Copyright © Bharati software 2018.
              WFE(Wait for Event)
• It is a 16 bit Thumb instruction
• Enter sleep conditionally
• Its intended usage is as part of a power saving strategy in
  spinlock loops in RTOS
• It is possible that execution of a WFE instruction will complete
  immediately without causing the processor to go into a low
  power (sleeping) state
• WFE success depends upon event register of the processor
                        Copyright © Bharati software 2018.
         Event register of the Processor
•   Inside a Cortex-M processor, there is a single-bit event register.
•   This event register bit will be 0, after reset
•   The event register is used to hold an event which happened in the past,
•    When set, an Event Register indicates that an event has occurred
•   When any event occurs this bit is set to 1
•   When you execute WFE and if WFE sees that event register bit is 1, it makes it 0
    and doesn’t cause processor to go to sleep. (A WFE instruction clears the Event
    Register.)
•   WFE succeeds (i.e puts processor to sleep) only when event register bit is 0 at the
    time of executing the WFE instruction .
•   Software cannot read or write the value of the Event Register directly.
                                Copyright © Bharati software 2018.
    Event register of the Processor
• The event register can be set by any of the following events:
    – An interrupt request arrives and need servicing
    – Exception entrance and exception exit
    – New pending interrupts (only when SEVONPEND bit in SCR is set),
      even if the interrupts are disabled
    – An external event signal from on-chip hardware (MCU specific )
    – Execution of an SEV (Send Event) instruction
    – Debug event
• When multiple events occur while the processor is awake, they will
  be treated as just one event because the event register is only one
  bit.
                          Copyright © Bharati software 2018.
  WFE                           WFE executed
                                                                yes
                                        Is
summary                            event_reg
                                    is set ?
                                                                        Clear the event reg. and
                                                                            proceed to next
                                                                        instruction in run Mode
                                                     no
                no                    Is                          yes
                                  SLEEPDEEP
                                     set ?
Normal Sleep(Wait                                                        Normal Sleep(Wait
   until Event )                                                            until Event )
                     Event/Interrupt Pend /Debug Req/Halt
                             Exit Sleep and Execute
                               next instruction in
                                    Run mode
                           Copyright © Bharati software 2018.
                               Wakeup from WFE
•   When the WFE instruction is used to enter sleep, it can be woken up by
     –   The execution of an SEV(Send Event) instruction
     –   Any exception entering the Pending state if SEVONPEND in the System Control Register is set
     –   An asynchronous exception at a priority that preempts any currently active exceptions
     –   An event from another processor/peripheral
•   WFE can also be woken up by interrupt requests if they have a higher priority than the current interrupt’s
    priority level,
•   The SEVONPEND feature can wake up the processor from WFE sleep even if the priority level of the newly
    pended interrupt is at the same or lower level than the current interrupt. However, in this case, the
    processor will not execute the interrupt handler and will resume program execution from the instruction
    following the WFE.
                                            Copyright © Bharati software 2018.
                         WFI and WFE sleep wake-up behavior
WFI behavior                    PRIMASK        SEVONPEND                 Wake Up   ISR execution
IRQ priority > current level
                                0              N/A                       Yes       Yes
IRQ priority <= current level
                                0              N/A                       No        No
IRQ priority > current level
                                1              N/A                       Yes       No
IRQ priority <= current level
                                1              N/A                       No        No
                                          Copyright © Bharati software 2018.
                         WFI and WFE sleep wake-up behavior
WFE behavior                           PRIMASK        SEVONPEND                 Wake Up   ISR execution
IRQ priority > current level
                                       0              0                         Yes       Yes
IRQ priority <= current level
                                       0              0                         No        No
IRQ priority > current level
                                       0              1                         Yes       Yes
IRQ priority <= current level(or IRQ
disabled
                                       0              1                         Yes       No
IRQ priority > current level
                                       1              0                         No        No
IRQ priority <= current level
                                       1              0                         No        No
IRQ priority > current level
                                       1              1                         Yes       No
IRQ priority <= current level
                                       1              1                         Yes       No
                                                 Copyright © Bharati software 2018.
                     Exercise
• Write an application in which TIM6 triggers
  Update interrupt for every 10ms and in the
  ISR of TIM6 send some data over UART2.
▪ Measure the Current consumption without sleep mode
▪ Measure the Current Consumption With Sleep mode (
  Enter sleep mode using WFE Instruction)
                   Copyright © Bharati software 2018.
     Differences and similarities of WFI and WFE
Similarities
▪Wake up on Interrupt requests
▪Wake up by debug events
▪Can be used to produce normal or deep sleep
Differences
▪WFI puts the processor immediately to sleep, where as WFE puts the processor to sleep only if event
register value is 0
▪No relation between event register and WFI , but WFE works along with event register .
▪New pending of a disabled interrupt can wake up the processor from WFE sleep if SEVONPEND is set
▪WFE can be woken up by an external event signal
                                     Copyright © Bharati software 2018.
            When to use what ?
Use WFI instruction in interrupt driven applications and
stand Alone application.
Use WFE in idle loops , Spinlocks , busy waiting and RTOS
related scenarios where processor will go to sleep if there
are no events are pending to be processed.
WFI is targeted at entering either standby, dormant or
shutdown mode, where an interrupt is required to wake-
up the processor.
                     Copyright © Bharati software 2018.
usage for WFE
  Copyright © Bharati software 2018.
                                     EVENTI
                                                        Processor-2
              EVENTO
Processor-1                          EVENTI
                                                        Processor-3
                                     EVENTI
                                                        Processor-4
                   Copyright © Bharati software 2018.
              How to generate events ?
•   The STM32F446xx microcontrollers are able to handle external or internal events in order to wake
    up the core (WFE). The wakeup event can be generated by:
     –   enabling an interrupt in the peripheral control register but not in the NVIC, and enabling
•   the SEVONPEND bit in the Cortex®-M4 with FPU System Control register. When the
•   MCU resumes from WFE, the peripheral interrupt pending bit and the peripheral NVIC
•   IRQ channel pending bit (in the NVIC interrupt clear pending register) have to be
•   cleared.
•   • or configuring an external or internal EXTI line in event mode. When the CPU resumes
•   from WFE, it is not necessary to clear the peripheral interrupt pending bit or the NVIC
•   IRQ channel pending bit as the pending bit corresponding to the event line is not set.
                                          Copyright © Bharati software 2018.
  How to generate events in STM32 MCU
1. Execute the SEV instruction .
2. Use Peripheral Interrupt as an event .
  -   Make SEVONPEND bit as 1
  -   Disable peripheral interrupt in the NVIC
  -   Make peripheral issue an interrupt
  -   Applicable to all peripherals
3. Use peripheral event
  - Applicable to Some of the peripherals
                     Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
          How to generate events ?
• To generate the event, the event line should be configured and enabled
• This is done by programming the two trigger registers with the desired
  edge detection and by enabling the event request by writing a ‘1’ to the
  corresponding bit in the event mask register
• When the
• selected edge occurs on the event line, an event pulse is generated
• pending bit
• corresponding to the event line is not set.
• Configure the mask bits of the 23 event lines (EXTI_EMR)
• Configure the Trigger selection bits of the event lines (EXTI_RTSR and
  EXTI_FTSR)
                            Copyright © Bharati software 2018.
Device Specific (MCU) Low Power
             Modes
          Copyright © Bharati software 2018.
Device Specific (MCU) Low Power Modes
Low Power modes of the MCU is further extended by the device vendor using
Power modes given by arm cortex M Processor
                                                                     Architectural Low power mode
                                       ARM Cortex M4
                                                                                 SLEEPDEEP feature is SET
       SLEEPDEEP feature is RESET
                     Normal Sleep                                        Deep Sleep
                                                                               MCU extension
                                                       STOP                             Stand By
                                                                   Specific to Vendor of the MCU
                                    Copyright © Bharati software 2018.
                                  Cortex®-M4 with FPU core stopped, peripherals kept running
Power Consumption
                                                all clocks are stopped
                                                                   all clocks are stopped
                                                                   + 1.2 V domain powered off
                    Run   Sleep            STOP             STANDBY                       Modes
                              Copyright © Bharati software 2018.
   Device Specific (MCU) Low Power Modes
• Sleep mode
  – In Sleep mode, only the CPU is stopped
  – All peripherals continue to operate and can wake
    up the CPU when an interrupt/event occurs
  – You can always do additional settings to save
    some more power ( like running the CPU at lower
    clock , disabling the peripheral clocks , etc )
                  Copyright © Bharati software 2018.
Voltage Domains
   Copyright © Bharati software 2018.
       VBAT
Copyright © Bharati software 2018.
            STM32F4x Voltage Regulator
              1.7 to 3.3V
                                                                  1.2V
                                                                         Core, SRAM,
                                                                            Digital
                                                                         Peripherals
                                                                             Backup
                                                                          Domain(RTC,BKP
                                                                         SRAM and others)
An embedded linear voltage regulator supplies all the digital circuitries except for the
backup domain and the Standby circuitry. The regulator output voltage is around 1.2 V.
                                  Copyright © Bharati software 2018.
             Regulator modes
                                                                Low Power
Main Regulator                                                   Regulator
          Normal Mode                                                   Normal Mode
         Over Drive Mode                                               Over Drive Mode
           Under Drive                                                   Under Drive
             Mode                                                          Mode
           Power Down                                                    Power Down
          You can select either MR or LPR by configuring
          the LPDS bit in the PWR power control register
          (PWR_CR)
                           Copyright © Bharati software 2018.
             Main regulator Modes
                                       Normal mode: The CPU and core logic operate
Main Regulator                         at maximum frequency at a given
                                       voltage scaling (scale 1, scale 2 or scale 3)
                                       Voltage scaling can be configured by VOS bit in
          Normal Mode
                                       PWR_CR
           Over Drive
             Mode                      Use “Normal Mode” in your RUN mode or in
           Under Drive                 STOP Mode
             Mode
          Power Down
                         Copyright © Bharati software 2018.
                   Voltage Scaling
• There are 3 Voltage Scales are available in STM32F4x
  Microcontroller (Scale 1 , scale 2, scale 3). The main goal of
  this is to reduce the power consumption by controlling the
  output voltage of the voltage regulator with respect to
  operating frequency
• Refer Table 16. General operating conditions In Datasheet
                        Copyright © Bharati software 2018.
                Voltage Scaling
The voltage scaling and over-drive mode are adjusted to fHCLK
frequency as follows:
❑Scale 3 for fHCLK ≤ 120 MHz
❑Scale 2 for 120 MHz < fHCLK ≤ 144 MHz
❑Scale 1 for 144 MHz < fHCLK ≤ 180 MHz. The over-drive is
only ON at 180 MHz.
                     Copyright © Bharati software 2018.
          Main regulator & Low power regulator Modes
  Main Regulator(MR) or
Low Power Regulator(LPR)                    Over Drive mode is used to run the CPU and
                                            Core logic at maximum possible frequency . In
                                            STM32F446RE microcontroller it is 180Mhz.
                 Normal Mode                The output voltage of the Main regulator will
                  Over Drive                be more than typical 1.2V thus consuming
                    Mode                    more power of your application
                  Under Drive
                    Mode                    If your application demands using 180Mz, then
                 Power Down                 you have to turn on the over drive mode.
                                Copyright © Bharati software 2018.
                     Main regulator Modes
  Main Regulator(MR) or
Low Power Regulator(LPR)
                                            Under-drive mode: the 1.2 V domain is
                                            preserved in reduced leakage mode
                 Normal Mode
                                          This mode of the regulator is can be used in
                  Over Drive
                    Mode                  STOP mode.
                  Under Drive   If the Under-drive mode was enabled, it is
                    Mode        automatically disabled after
                 Power Down
                                  *     exiting Stop mode.
                                  *     When the voltage regulator operates in
                                Under-drive mode, an additional
                                  *     startup delay is induced when waking
                                up from Stop mode.
                                Copyright © Bharati software 2018.
                     Main regulator Modes
  Main Regulator(MR) or
Low Power Regulator(LPR)
                                            Power-down is used in Standby mode. The
                                            Power-down mode is activated only when
                 Normal Mode                entering in Standby mode. The regulator
                                            output is in high impedance inducing zero
                  Over Drive
                    Mode                    consumption. The contents of the registers and
                  Under Drive               SRAM are lost
                    Mode
                 Power Down
                                Copyright © Bharati software 2018.
Summary
Copyright © Bharati software 2018.
     Device Specific (MCU) Low Power Modes
• STOP mode
   – The Stop mode achieves the lower power consumption compared to sleep
     mode.
   – All clocks in the 1.2 V domain are stopped (clocks to CPU, SRAM, digital
     peripherals )
   – Since Voltage regulator is not powered down , SRAM content will be retained
   – You can either use MR or LPR
   – The voltage regulator can be in either Normal mode or under drive mode
   – PLL, the HSI RC and the HSE crystal oscillators are disabled.
   – The device can be woken up from the Stop mode by any of the EXTI line (the
     EXTI line source can be one of the 16 external lines, the PVD output, the RTC
     alarm / wakeup / tamper / time stamp events, the USB OTG FS/HS wakeup).
                             Copyright © Bharati software 2018.
     Device Specific (MCU) Low Power Modes
• Stand by mode
   – The Standby mode is used to achieve the lowest power consumption
   – The internal voltage regulator is powered down so that the entire 1.2 V
     domain is powered off
   – SRAM loses its data since voltage regulator is powered down
   – The PLL, the HSI RC and the HSE crystal oscillators are also switched off
   – After entering Standby mode, the SRAM and register contents are lost except
     for registers in the backup domain and the backup SRAM when selected.
   – The device exits the Standby mode when an external reset (NRST pin), an
     IWDG reset, a rising edge on the WKUP pin, or an RTC alarm / wakeup /
     tamper /time stamp event occurs.
                            Copyright © Bharati software 2018.
          STOP Mode wakeup time
• In stop mode, wakeup time depends on the voltage regulator and
  the Flash memory wakeup time
• For example, if the voltage regulator is in run mode and the MCU is
  configured in stop mode, the wakeup time is about 13 μs.
• However when the voltage regulator and the Flash
• memory are configured in low power mode, the wakeup time
  increases to reach 110 μs(for
• more details about the wakeup time, please refer to the STM32F2xx
  datasheet).
                         Copyright © Bharati software 2018.
       STOP Mode wakeup time
• Observation:
• ● Current consumption and wakeup time in stop
  mode depends on the voltage regulator
• configuration (run mode or low power mode) and
  Flash memory configuration (stop
• mode or deep power mode)
• ● A lower current consumption means a longer
  the wakeup time
                 Copyright © Bharati software 2018.
                     Standby mode
• Standby mode is based on the Cortex-Mx deep sleep mode, with the
  voltage regulator
• disabled. The 1.2 V domain is consequently powered off. The PLL, the HSI
  oscillator and
• the HSE oscillator are also switched off. SRAM and register contents are
  lost except for
• registers in the Backup domain and Standby circuitry.
• The Standby mode current consumption depends on the backup SRAM
  and RTC
• configuration, which is between 5.8 μA when both backup SRAM and RTC
  are enabled, and
• 2.5 μA when both backup SRAM and RTC are disabled
                           Copyright © Bharati software 2018.
    Stand by Mode wakeup time
• Observation:
• ● Standby mode returns the lowest power
  consumption
• ● The wakeup time from Standby mode is the
  highest wakeup time. It is about 375 μs
• (refer to the section “Wakeup time from low-
  power mode” in the STM32F20xx/21xx
• datasheet)
                  Copyright © Bharati software 2018.
                                  Conclusion
•   Conclusion:
•   The global wakeup time of the device can be viewed as the sum of the following:
•   ● Wakeup time of the main voltage regulator (if it is switched off during the low-power
•   mode)
•   ● Stabilization time of the oscillator (if it is switched off during the low-power mode)
•   ● Wakeup time of the Flash memory (if it is switched off during the low-power mode)
•   ● Interrupt latency for the wake up event trigger
•   The results above shows the trade-off between consumption and wakeup time in the
•   STM32F2. Generally, the lower the power consumption is, the longer the wakeup time. You
•   should therefore try to find the best trade-off according to the application constraints.
                                    Copyright © Bharati software 2018.
How to put MCU in STOP mode?
                                                              Architectural Low power mode
                                ARM Cortex M4
                                                                          SLEEPDEEP feature is SET
SLEEPDEEP feature is RESET
              Normal Sleep                                        Deep Sleep
                                                                        MCU extension
                                                STOP                             Stand By
                                                            Specific to Vendor of the MCU
                             Copyright © Bharati software 2018.
    How to put MCU in STOP mode?
                               SLEEPDEEP = 1
                        0                              1
                                      PDDS
SLEEPONEXIT/WFI/WFE                                        SLEEPONEXIT/WFI/WFE
    STOP Mode                                                 Standby Mode
                      Copyright © Bharati software 2018.
     Voltage Regulator Settings in STOP Mode
Remember Voltage Regulator will not be OFF in STOP mode
                                            MR/LPR
           Normal Mode                                               Under Drive Mode
                                Copyright © Bharati software 2018.
                      Voltage Regulator Normal Mode
     MR                                                               LPR
MR ON+ FLASH ON(FPDS=0)                                 MR ON+ FLASH PD(FPDS=1
LPR ON+ FLASH ON(FPDS=0                                   LPR ON+ FLASH PD(FPDS=1
                          Copyright © Bharati software 2018.
                       Voltage Regulator Under Drive Mode
     MR                                                                          LPR
MR UD+ FLASH PD(FPDS=X)                                            LPR UD+ FLASH PD(FPDS=X)
 Main regulator in                                                 Low-power regulator in
 deepsleep under-drive mode                                        deepsleep under-drive mode
                              Copyright © Bharati software 2018.
mA/Micro sec              In Stop mode, the power consumption can be further reduced by using additional settings in
                          the PWR_CR register. However this will induce an additional startup delay when waking up
               191        from Stop mode
                                164
                                                     117
                                                                                             108
                                                                             89
                                                                                                                   45
MR ON+ FLASH ON(FPDS=0)                     LPR ON+ FLASH ON(FPDS=0)                     MR UD+ FLASH PD(FPDS=X)
                                                                                                                          STOP Sub modes
                      MR ON+ FLASH PD(FPDS=1)                        LPR ON+ FLASH PD(FPDS=1)                   LPR UD+ FLASH PD(FPDS=X)
                                                   Copyright © Bharati software 2018.
                        Exercise
• Test the Current Consumption in below STOP mode
  conditions
   –   STOP + MR ON + FLASH ON
   –   STOP + MR ON + FLASH Power Down
   –   STOP+ LPR ON + FLASH ON
   –   STOP + LPR ON + FLASH Power Down
   –   STOP + MR Under Drive + FLASH Power Down
   –   STOP + LPR Under Driver + FLASH Power Down
   –   Waking up using Button interrupt (EXTI)
                      Copyright © Bharati software 2018.
         Wakeup From STOP Mode
• When exiting Stop mode by issuing an interrupt or a wakeup event, the
  HSI RC oscillator is selected as system clock
• If the Under-drive mode was enabled, it is automatically disabled after
  exiting Stop mode.
• When the voltage regulator operates in low-power or low voltage mode,
  an additional startup delay is incurred when waking up from Stop mode.
  By keeping the internal regulator ON during Stop mode, the consumption
  is higher although the startup time is reduced.
• When the voltage regulator operates in Under-drive mode, an additional
  startup delay is induced when waking up from Stop mode.
• Wakeup latency Refer to Table 17: Stop operating modes in RM
                           Copyright © Bharati software 2018.
How to put MCU in Standby Mode?
                                                              Architectural Low power mode
                                ARM Cortex M4
                                                                          SLEEPDEEP feature is SET
SLEEPDEEP feature is RESET
              Normal Sleep                                        Deep Sleep
                                                                        MCU extension
                                                STOP                             Stand By
                                                            Specific to Vendor of the MCU
                             Copyright © Bharati software 2018.
  How to put MCU in Standby Mode?
                             SLEEPDEEP = 1
                      0                              1
                                    PDDS
SLEEPONEXIT/WFI/WFE                                        SLEEPONEXIT/WFI/WFE
    STOP Mode                                                 Standby Mode
                      Copyright © Bharati software 2018.
                Who is alive in Standby ?
•   RTC registers and RTC backup registers
•   backup SRAM
•   Standby circuitry(WKUP Logic and IWDG)
•   LSI and LSE
secondary clock sources:
• 32 kHz low-speed internal RC (LSI RC) which drives the independent watchdog and,
optionally, the RTC used for Auto-wakeup from the Stop/Standby mode.
• 32.768 kHz low-speed external crystal (LSE crystal) which optionally drives the RTC
clock (RTCCLK)
Each clock source can be switched on or off independently when it is not used, to optimize
power consumption.
                                       Copyright © Bharati software 2018.
                                 Exercise
• Test the Current Consumption in below STANDBY mode
  conditions
   – STANDBY + BKP SRAM ON + RTC ON
     (wakeup using RTC automatic wake up after 20s)
   – STANDBY + BKP SRAM OFF + RTC ON ON
     (wakeup using RTC automatic wake up after 20s)
   – STANDBY + BKP SRAM ON + RTC OFF
     (wakeup using wakeup pin)
   – STANDBY + BKP SRAM OFF + RTC OFF
     (wakeup using wakeup pin)
                             Copyright © Bharati software 2018.
                 RTC Intro
• What is “Real time” ??
                 Copyright © Bharati software 2018.
                         RTC Intro
• A real-time clock (RTC) is a peripheral of the MCU that keeps track
  of the current time and date information
• The real-time clock (RTC) embedded in STM32 microcontrollers acts
  as an independent BCD timer
• Although RTCs are often used in personal computers, servers and
  embedded systems, they are also present in almost any electronic
  device that requires accurate time keeping.
• As long as the supply voltage remains in the operating range, the
  RTC never stops regardless of the device status (Run mode, low
  power mode or under reset).
                         Copyright © Bharati software 2018.
              RTC Main features
• Calendar with sub-seconds, seconds, minutes, hours (12h
  or 24h format), day (day of week), date (day of month),
  month, and year.
• Two programmable alarms with interrupt function. The
  alarms can be triggered by any combination of the calendar
  fields.
• Automatic wakeup unit generating a periodic flag that
  triggers an automatic wakeup interrupt.
• 20 backup registers (80 bytes). The backup registers are
  reset when a tamper detection event occurs
                     Copyright © Bharati software 2018.
RTC calendar
 Copyright © Bharati software 2018.
                     RTC Clock Sources
The RTC features several prescalers that allow delivering a 1 Hz clock to
calendar unit,
regardless of the clock source. Copyright © Bharati software 2018.
            RTC Features
calendar,                                         programmable alarm
                                                       interrupts
             automatic wakeup
             unitto
             manage low power
             modes
             Copyright © Bharati software 2018.
                      Backup SRAM
• Backup SRAM is part of the backup domain
• In stm32f446re MCU , there is 4KBs of Backup SRAM
• This is introduced in order to hold some data like the serial
  numbers, cryptographic keys, or any other application data, even if
  the Vdd is removed. (Supported by VBAT)
• It can be considered as an internal EEPROM when VBAT is always
  present.
• It is by default write protected (Actually all back domain
  peripherals are write protected , you need to first get the access in
  order to change any settings or content of the back up domain
  peripherals )
                          Copyright © Bharati software 2018.
             Backup SRAM
• Dedicated voltage regulator called backup
  voltage regulator is used to preserve the
  contents of the backup SRAM when in standby
  mode(if selected) or in VBAT modes
                Copyright © Bharati software 2018.
 RTC Important features
                                 RTC
   RTC Calendar                                           RTC Alarm
RTC Tamper Detection                                   RTC Wakeup Unit
                  Copyright © Bharati software 2018.
                        RTC Calendar Unit
•   A calendar keeps track of the time (hours, minutes and seconds) and date (day,
    week, month, year).
•   Calendar comes with :
     –   sub-seconds (not programmable)
     –   seconds
     –   minutes
     –   hours in 12-hour or 24-hour format
     –   day of the week (day)
     –   day of the month (date)
     –   Month
     –   Year
•   The STM32 RTC calendar is provided in BCD format
•   Automatic management of 28-, 29- (leap year), 30-, and 31-day months
                                    Copyright © Bharati software 2018.
Copyright © Bharati software 2018.
          BCD vs Binary
Decimal    BCD                           Binary
0          0000                          0000
1          0001                          0001
2          0010                          0010
3          0011                          0011
9          1001                          1001
10         0001 0000                     1010
15         00010101                      1101
56         01011100                      111000
           Copyright © Bharati software 2018.
    RTC Calendar BCD fields Example
• Lets see an example
    – Program 2:40:58 AM in to RTC Time register
    – Program 12th June 2018 in to RTC Date register
•   BCD of 2 ➔ 0010
•   BCD of 40 ➔ 0100 0000
•   BCD of 58 → 0101 1000
•   BCD of 12 → 0001 0010
•   BCD of 6(june) ➔ 0110
•   Bcd of 2018 → 18 → 0001 1000
                         Copyright © Bharati software 2018.
RTC Block Diagram
                    Copyright © Bharati software 2018.
                       RTC Clock Source
The RTC can be driven by three clock sources LSE, LSI or HSE
                                                           RTCSEL bits are part of RCC_BDCR register
                                Copyright © Bharati software 2018.
     Generating 1Hz from different clock sources
Remember calendar unit needs 1Hz clock to update time
                              Copyright © Bharati software 2018.
          RTC and STM32 Cube
1. RTC Clock Selection
2. RTC Init
3. RTC Set Time and Date
4. RTC Get Time and Date
5. RTC Set/Get Alarm
6. RTC Deactivate Alarm
7. RTC Set/Deactivate Wakeup Timer
And various others.
                  Copyright © Bharati software 2018.
    RTC Clock Selection Procedure
1. Turn on the Required Clock (HSE/LSI/LSE)
For this we use :
 HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
2. Select the RTCCLK source as HSE/LSI/LSE in
    RCC_BDCR register
For this we use :
     HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef
     *PeriphClkInit)
                       Copyright © Bharati software 2018.
           RTC Init Procedure
For RTC Init, STM32 Cube layer provides below
  handle structure and API
HAL_RTC_Init(RTC_HandleTypeDef *hrtc)
                 Copyright © Bharati software 2018.
                           Exercise
• Write a program to set the current time, day and Date information
   in to the RTC and then print back the Date, time, day information
   via UART whenever user button is pressed.
  Case 1 : Time format 12h
  Case 2 : Time format 24h
  Case 3 : Do a system reset and observe the effect on your
   configuration made to the RTC
  Case 4 : See the effect on RTC when microcontroller exits Standby
   mode.
                         Copyright © Bharati software 2018.
                       RTC Alarm
• STM32 RTC embeds two alarms, alarm A
  and alarm B, which are similar.
•   An alarm can be generated at a given time
    or/and date programmed by the user.
                        Copyright © Bharati software 2018.
RTC Alarm Fields
   Copyright © Bharati software 2018.
   Example of RTC Alarm Masking
Example 1 :
Set Alarm @ 23:15:07 Every day
The above alarm means that,
1. We want alarm everyday , so date or day is don't
    care(mask it for comparison )
2. RTC calendar must be configured in 24h format
3. Alarm must be generated when calendar fields
    Hh:mm:ss exactly match with configured alarm fields
                    Copyright © Bharati software 2018.
   Example of RTC Alarm Masking
Example 2 :
Set Alarm @8AM on Every Sunday
The above alarm means that,
1. We want alarm only on Sunday
2. We are interested to compare day not date, so WDSEL bit
    of RTC_ALRMAR has to be 0
3. RTC calendar must be configured in 12h format
4. Alarm minutes and seconds fields are don't care (so just
    mask them for comparison )
                     Copyright © Bharati software 2018.
   Example of RTC Alarm Masking
Example 3 :
Set Alarm @ XX:45:09
The above alarm means that,
1. We want alarm at 45mins , 09 seconds every
   hour
2. Hour field is don't care
3. Date/Day field is don't care
                 Copyright © Bharati software 2018.
RTC Alarm and STM32 Cube APIs
          Copyright © Bharati software 2018.
                     Exercise
• Write a program to Set an Alarm @ xx:45:09
  – An interrupt must be triggered during alarm
  – Use buzzer(you can turn on led if you don't have
    buzzer) to indicate the alarm
  – Configure the RTC calendar and Alarm in Button
    ISR
                   Copyright © Bharati software 2018.
                    Exercise
• Write a program to Set an Alarm @ 12:00:15 PM
  Every day
  – An interrupt must be triggered during alarm
  – Use buzzer(you can turn on led if you don't have a
    buzzer) to indicate the alarm
  – Configure the RTC calendar and Alarm in Button ISR
                  Copyright © Bharati software 2018.
                    Exercise
• Write a program to Set an Alarm @ 8AM Every
  Sunday
  – An interrupt must be triggered during alarm
  – Use buzzer(you can turn on led if you don't have a
    buzzer) to indicate the alarm
  – Configure the RTC calendar and Alarm in Button ISR
                  Copyright © Bharati software 2018.
                     Exercise
• Write a program to wake up the MCU from
  STANDBY mode @ 23:15:30 Every day
  – Use RTC Alarm Interrupt as the wakeup source
  – Use buzzer(you can turn on led if you don't have a
    buzzer) to indicate STANDBY exit
                   Copyright © Bharati software 2018.
                    Exercise
• Write a program to wake up the MCU from STOP
  mode @ 23:15:30 Every day
  – Use RTC Alarm Interrupt as the wakeup source
  – Use buzzer(you can turn on led if you don't have a
    buzzer) to indicate STOP mode exit
  – Configure the RTC calendar and Alarm in Button ISR
                  Copyright © Bharati software 2018.
RTC Time Stamp Feature
      Copyright © Bharati software 2018.
                    Exercise
• Write a program which prints the time stamp
  of the LED ON Event by TIMER’s time base
  interrupt
  – Use Timestamp feature of the RTC
  – Use RTC Time Stamp interrupt to print the time
    stamp details .
  – Use TIM6 time base generation for every 5 sec
                  Copyright © Bharati software 2018.
      RTC periodic wakeup unit
• The STM32 features a periodic timebase and
  wakeup unit that can wake up the system when
  the STM32 operates in low power modes.
• This unit is a programmable down-counting auto-
  reload timer.
• When this counter reaches zero, a flag and an
  interrupt (if enabled) are generated.
                 Copyright © Bharati software 2018.
          Wakeup Unit Features
• It has Programmable down-counting auto-reload timer.
• Specific flag and interrupt capable of waking up the
  device from low power modes
• Wakeup alternate function output which can be routed
  to RTC_ALARM output (unique pad for alarm A, alarm
  B or Wakeup events) with configurable polarity.
• A full set of prescalers to select the desired waiting
  period.
                    Copyright © Bharati software 2018.
RTC Block Diagram
                    Copyright © Bharati software 2018.
Wakeup Timer Clock Config-1
         Copyright © Bharati software 2018.
Wakeup Timer Clock Config
        Copyright © Bharati software 2018.
Copyright © Bharati software 2018.