You are on page 1of 64

cole Nationale des Sciences de lInformatique

Chapitre 4

tude des microcontrleurs STM32


Module : Introduction aux systmes embarqus Niveau : II2 Tronc commun
AU : 2011/2012

Copyright
Ce chapitre est extrait des documents prpars dans le cadre de ST Ecole. Intervenants dans le programme ST Ecole:
Abdellatif BEN RABAA (ENIT) Chadlia JERAD (ENSI) Emir DAMERGI (INSAT) Halim KACEM (STMicroelectronics) Hanen BEN FRAJ (ISI) Younes LAHBIB (ENISOU, ESTI)

Outline
Introduction Cortex-M3 Cortex-M3 based MCUs: The STM32F10x Family STM32 Programming STM32VL Discovery Kit
3

ARM (Advanced Risc Machines)


ARM is an UK company that designs innovative 32-bit microprocessors ARM leads the world of RISC microprocessor cores Licenses ARM core designs to semiconductor partners who fabricate and sell to their customers.
ARM does not fabricate silicon itself

Also develop technologies to assist with the design-in of the ARM architecture
Software tools, boards, debug hardware, application software, bus architectures, peripherals etc.
4

Why ARM?
One of the most licensed and thus widespread processor cores in the world
Used in PDA, cell phones, multimedia players, handheld game console, digital TV and cameras 75% of 32-bit embedded processors

Used especially in portable devices due to its low power consumption and reasonable performance

ARM Cortex processor family

Cortex profiles & applications


Cortex-X N X :Profile (A,R,M) N: Performance level (0..9)
Manufacturers Cortex-M3 STM32 L1xx STM32 F1xx STM32 F2xx Stellaris3x

Frequency (MHz) 375 475 2000

LPC17x, LPC3x SAM3x Cortex-A


Thumb/Thumb-2 MMU DSP ...

LM3S8x

Cortex-R Cortex-M
Thumb-2 NVIC MPU 3 stages pipeline Thumb/Thumb-2 MPU FP Unit 8 stages Pipeline

Analog Devices
13 stages Pipeline Multi-core (1-4)

ADuCRF101 TX03 S3FM

Toshiba Samsung

0,9 1,25 DMIPS

1,6 DMIPS

1,6 2,5 DMIPS

Outline
Introduction Cortex-M3 Cortex-M3 based MCUs: The STM32F10x Family STM32 Programming STM32VL Discovery Kit
8

Cortex-M3 Processor
Hierarchical processor integrating core and advanced system peripherals
Interrupt controller: -1 to 240 interrupts. - 256 Priority levels - NMI -SysTick (Porting !!!) CM3 Core: Harvard (Separate Busses) 32 Bits Register & ALUs.

Embedded Trace MacroCell Wakup Int. controller: Wakeup from Sleep modes throuht interrupts & exceptions

WIC

Optional Memory Protection Unit (8 regions) Integrated Trace module: Low cost (2 wires) 8 Hardware Breakpoints Multi layer Bus Matrix (Parallel transfers between core, memory, & peripherals 9

Debug Access port 4 Watch points

Cortex-M3 Processor

Cortex-M3 Core Features


3-stage pipeline:
Fetch, Decode and & Execute (with static branch prediction)

Simple adressing: linear 4GByte address space


10

Cortex-M3 Core Features


Harvard architecture
Separate Instruction & Data buses allow parallel instruction fetching & data storage

Write Buffer
Used to decouple writes to memory Data is placed in the buffer so the processor can continue execution Data is written to memory when possible

ALU with H/W divide and single cycle multiply

Instruction Bus

Core

I D

Write Buffer

Data Bus
11

Cortex-M3 Core Features


Thumb-2 and traditional Thumb

12

Cortex-M3 core: Register Set

13

Cortex-M3 Core: xPSR Register


xPSR Program Status Register
31 26 25 24 23 N Z C V Q ICI/IT T 16 15 ICI/IT 10 8 7 ISR Number 0

Allows access to APSR, EPSR and IPSR special purpose registers xPSR stored on stack during exceptions Condition code flags
N = Negative result from ALU Z = Zero result from ALU C = ALU Operation carried out V = ALU Operation overflowed Q = Saturated math overflow

IT/ICI Bits
Contain IF-THEN base condition code and Interrupt Continue information

ISR Number
ISR contains information on which exception was pre-empted
14

Cortex-M3: Data memory management


Cortex-M3 includes 2 technologies to reduce Data memory requirements:
Unaligned data support Atomic Bit Banding

These technologies can dramatically improve data (SRAM) memory utilization, potentially enabling designers and users to reduce the amount of SRAM required and dramatically impacting silicon usage

15

Cortex-M3: Unaligned Data Access


No support for unaligned data: The whole Data must reside in the same memory address Support for unaligned data: The Data can be split into many memory locations

long (32) char (8) long (32) char (8) char (8) char (8) char (8) long

long (32) long (32) char (8) char (8) char (8) long (32) int (16)c int (16) long

int (16) long

Data aligned

int (16) long (32) int (16)c int (16) long (32) char (8)

char (8)

long (32)

Unused (wasted) space

Free space for the rest of the application

Reduces SRAM Memory Requirements


16

Cortex-M3: Unaligned Data Access


Unaligned transfers are not supported in:
Stack operations (PUSH/POP). Bit-band operations

When an unaligned transfer takes place, it is broken into separate transfers and as a result it takes more clock cycles for a single data access and might not be good for situations in which high performance is required. Unaligned access: Better memory use but Performance degradation
17

Cortex-M3: Bit Banding


Atomic Bit access Allows fast and atomic data access

18

Cortex-M3: Bit Banding

19

Cortex-M3: Bit Banding


Each bit of the bit band region (1MB) is mapped to one 32 bit address (32 MB Bit Band Alias = Virtual zone ). Each bit in the Bit Band region can be accessed separately through the corresponding 32 bits register in the alias region.

20

Cortex-M3: Bit Banding


Word_offset 0xFFFFC .. 0x00008 0x00004 0x00000
b7b2 b1 b0 b7b2 b1 b0 b7b2 b1 b0 b7b2 b1 b0

Bit-Band region (220 Bytes = 1 MB)

Bit-Band Alias (32*220 Bytes=32 MB)


Word address X+0x20 . . X+8 X+4 X+3 X+2 X+1 X X+4 X=bit_band_base

byte number

byte_offset = Word_offset + byte_number


To access the first bit of the band region, we must go through the word address X of the alias region. To access the second bit of the band region, we must go through the word address X+4 of the alias region. And so on The word address in the Bit-Band Alias increases at a value of 4 when switching to the next bit. To access the first bit of the next byte in the band region, we must go through the word address X+0x20 (32 ) of the alias region. And so on The word address in the Bit-Band Alias increases at a value of 0x20 (32) when switching to the next byte.

Cortex-M3: Bit Banding


Bit Banding formula (mapping the bit to the register) is:
bit_word_addr = bit_band_base + (byte_offset x 32) + (bit_number 4) where: bit_word_addr: is the address of the word in the alias memory region that maps to the targeted bit. bit_band_base is the starting address of the alias region (0x22000000 or 0x42000000 ) byte_offset is the number of the byte in the bit-band region that contains the targeted bit bit_number is the bit position of the targeted bit(0-7).

22

Cortex-M3: Bit Banding


Example -1:
How to map bit 15 of the byte located at address 0x40000303 in the alias region. Solution: We are accessing the peripheral bit band region beginning at 0x 0x40000000 and mapped to the bit band alias zone with bit_band_base = 0x42000000

Byte_offset = 0x40000303 - 0x40000000 = 0x303 0x42000000 + ( 0x303*32) + (15 * 4) = 0x4200609C =bit_word_addr Reading address 0x4200609C returns the value of bit 15 of the byte at address 0x40000303. Writing to address 0x4200609C has the same effect as a readmodify-write operation on bit 15 of the byte at address 0x40000303.
23

Cortex-M3: Bit Banding


Example -2: Which bit is accessed when reading the word at address 0x22006008
Solution: We are accessing the SRAM bit band alias zone with bit_band_base =0x22000000 and corresponding to the bit band region beginning at 0x 0x20000000

0x22000000 + ( byte_offset*32) + (bit_number * 4) = 0x22006008 ( byte_offset*32) + (bit_number * 4) = 0x6008 ( byte_offset = 0x300) +and (bit_number =2 ) Accessing address 0x22006008 has the same effect as accessing the bit 2 of the byte at SRAM address 0x20000303.
24

Cortex-M3: Interrupt Handling


The Cortex-M3 processor integrates an advanced Nested Vectored Interrupt Controller (NVIC)
Automatic processor state save and restore Allows handler to be written entirely in C

The NVIC supports up to 240 dynamically reprioritizes interrupts each with up to 256 levels of priority
1-240 Interrupts + NMI

Supports advanced features for next generation real-time applications


Tail-chaining of pending interrupts Interrupt pre-emption Late arrival

25

Cortex-M3: Interrupt Handling


Asynchronous Exceptions = Interrupts
Generated by hardware peripherals (when enabled):
Signal toggle (P I/O ports). Data receive (Serial peripherals) A/D conversion finished (DAC) ...

Synchronous Exceptions = Exceptions


Generated after instruction execution errors such as:
Unauthorized Memory region access Overflow Divide by 0 ...
26

Cortex-M3: Interrupt Handling


No. 1 2 3 4 5 6 7-10 11 12 13 14 15 16 256 Exception Type Reset NMI Hard Fault MemManage Fault Bus Fault Usage Fault Reserved SVCall Debug Monitor Reserved PendSV SYSTICK Interrupt #0 .. Interrupt#240 Priority -3 (Highest) -2 -1 0 1 2 N.A. 3 4 N.A. 5 6 7 247 Type of Priority fixed fixed fixed settable settable settable N.A. settable settable N.A. settable settable settable settable settable Pendable request for System Device System Tick Timer External Interrupt #0 .. External Interrupt #240 27 System Service call Break points, watch points, external debug Reset Non-Maskable Interrupt Default fault if other hander not implemented MPU violation or access to illegal locations Fault if AHB interface receives error Exceptions due to program errors Descriptions

Cortex-M3: Interrupt Handling


Interrupt Latency
IRQ

PUSH

ISR

POP 12 cycles Restore Registers (Hardware)

12 cycles Save Registers (Hardware)

R0-R3 ; R12 R15 (Program Counter) R14 (Link register) PSR (Registre dtat)

For the ARM7 architecture ( Cortex-M predecessor), The PUSH and POP operations were coded in assembler and they last 26 and 16 cycles respectively
28

Cortex-M3: Interrupt Handling


Tail Chaining
Highest

IRQ1 IRQ2 42 CYCLES ARM7 PUSH 26


Tail-chaining

ISR 1

POP 16

PUSH 26

ISR 2

POP 16

Interrupt handling in assembler code

Cortex-M3
Interrupt handling in HW

PUSH 12

ISR 1 6 6 CYCLES

ISR 2

POP 12

ARM7 26 cycles from IRQ1 to ISR1 entered 42 cycles from ISR1 exit to ISR2 entry 16 cycles to return from ISR2

Cortex-M3 12 cycles from IRQ1 to ISR1 entered 6 cycles from ISR1 exit to ISR2 entry 12 cycles to return from ISR2
29

Cortex-M3: Interrupt Handling


Preemption
Highest

IRQ1 IRQ2 42 CYCLES ARM7 ISR 1 POP 16 PUSH 2 26 ISR 2 6 POP 12 ISR 2 POP 16

Cortex-M3

ISR 1

POP
112

7-18 CYCLES

Cortex-M3 ARM7 Load Multiple uninterruptible, and hence the core must complete the POP and the full stack PUSH POP may be abandoned early if another interrupt arrives If POP is interrupted it only takes 6 cycles to enter ISR2 ( Equivalent to Tail -chaining)

30

Cortex-M3: Interrupt Handling


<12 cycle IRQ1
Highest

Late Arrival

IRQ2 ARM7 PUSH 26 Cortex-M3


PUSH

PUSH 26 ISR 1 6
TailChaining

ISR 1

POP 16

ISR 2

POP 16

ISR 2

POP 12

ARM7 26 cycles to ISR2 entered Immediately pre-empted by IRQ1 and takes a further 26 cycles to enter ISR 1. ISR 1 completes and then takes 16 cycles to return to ISR 2.

Cortex-M3 Stack push to ISR 2 is interrupted Stacking continues but new vector address is fetched in parallel 6 cycles from late-arrival to ISR1 entry. Tail-chain into ISR 2

31

Cortex-M3: Interrupt Handling


>12 cycle
Highest

Example

NMI IRQ1 IRQ2 IRQ3

PUSH

PUSH

NMI

ISR 1

POP
Cortex-M3

ISR 2

ISR 3

POP

ISR 2 Starts

Push for ISR1 begins Pre-empted by NMI New instruction fetch in parallel minimises time to NMI

Following NMI processor tail-chains into ISR1 ISR2 Completed Pop only occurs on return to Main

32

Cortex-M3: Power management


8bit Microcontroller like power mode management SLEEP NOW Wait for Interrupt instructions to enter low power mode No more dedicated control register settings sequence Wait for Event instructions to enter low power mode No need of Interrupt to wake-up from sleep Rapid resume from sleep SLEEP on EXIT Sleep request done in interrupt routine Low power mode entered on interrupt return Very fast wakeup time DEEP SLEEP Long duration sleep From product side: PLL can be stopped or shuts down the power to digital parts of the system Enables low power consumption

Optimized RUN mode CORE power consumption


33

Cortex-M3: SysTick (System Timer)


Flexible system timer 24-bit self-reloading down counter with end of count interrupt generation 2 configurable Clock sources Suitable for Real Time OS or other scheduled tasks

In STM32F10x the SysTick clock can be: CPU clock or CPU clock/8 (provided externally by the Reset Clock Control)
34

Cortex-M3: Debug Capabilities


Serial Wire Debugging for optimized device pin-out

JTAG

SWD

More pins available for the application

Embedded break/watch capabilities for easy flashed application debugging


2 hardware breakpoints 2 hardware watchpoints 8 hardware breakpoints

Serial Wire Viewer for targeted low bandwidth data trace


Using serial wire interface or dedicated bus CKout+D[3..0] for better bandwidth Triggered by embedded break and watch points

ETM capability for better real time debugging


Instruction trace only External signal triggering capability Can be used in parallel with data watchpoint

Debugging features still kept whilst the core entered low power mode
35

ETM

Outline
Introduction Cortex-M3 Cortex-M3 based MCUs: The STM32F10x Family STM32 Programming STM32VL Discovery Kit
36

The Microcontroller
Microcontroller or MCU (MicroController Unit) :
a small computer on a single integrated circuit.

Processor Core

Memory (RAM)

Program Memory (Flash, Eeprom, Rom)

System BUS

Bridge

Programmable I/O Peripherals (Parallel, Serial (UART, SPI, CAN, I2C), Analog (ADC, DAC), Timers,

+ Size (High Integration) + Cost ( <1$ for large qty) + Energy Consumption

Large Spectrum of embedded Applications ($26 Billions, 2007)


37

Cortex based MCUs


The MCUs Manufacturers integrate the Cortex Processor and add the I/O & System peripherals, SRAM Memory, Flash, etc
ARMCore(CPU)

Decode Unit

(Fetch Fetch unit )

UAL + Registers

Debug component s
Data Bus Flash Memory

NVIC

Interface

Provided by ARM

Instruction Bus

MPU (optional)

Bus Matrix

Developped by MCUs Manufacturers

Input/Output Peripherals

System Peripherals

SRAM memory

38

STM32 Series

39

STM32: The Cortex-M3 MCU F1 Family


Designation: STM32F10x y z:
y: Number of pins (T: 36 pins, C: 48 pins, R : 64 pins, V : 100 pins et Z : 144 pins) z: Flash Memory Size (4 :16 Kbytes, 6: 32 Kbytes, 8: 64 Kbytes, B: 128 Kbytes,
C: 256 Kbytes, D: 384 Kbytes and E: 512 Kbytes) . 10x : Product line (see table below)
Product Line Connectivity Reference Common components Access Value 101 100 USART (up to 5) DAC 12 bits (up to 2) Timers 16 bts (up to 6) DMA channels (up to 12) Internal RC oscillators (40 KHz et 8 MHz) Real Time Clock. Freq (MHz) 72 SRAM /Flash Size (Kbyte) Up to 64 /256 Specific Peripherals USB, CAN, I2S (classe audio) et Ethernet USB, SDIO, CAN, I2S et Timer PWM. USB

105 & 107

Performance USB Access

103 102

72 48 36 24

Up to 96/1024 Up to16/128 Up to 80/1024 Up to 32/512

40

STM32F10x Series Block Diagram


ARM 32-bit Cortex-M3 CPU
Flash I/F

Nested Vectored Interrupt Controller (NVIC) w/ 43 maskable IT + 16 prog. priority levels Embedded Memories : SRAM: up 96Kbytes CRC calculation unit 7 Channels DMA Power Supply with internal regulator and low power modes : 2V to 3V6 supply 4 Low Power Modes with Auto Wake-up Integrated Power On Reset (POR)/Power Down Reset (PDR) + Programmable voltage detector (PVD) Backup domain w/ 20B reg Up to 72 MHz frequency managed & monitored by the Clock Control Rich set of peripherals & IOs Embedded low power RTC with VBAT capability Dual Watchdog Architecture 5 Timers w/ advanced control features (including Cortex SysTick) 9 communications Interfaces Up to 80 I/Os (100 pin package) w/ 16 external interrupts/event Up to 2x12-bits 1Msps ADC w/ up to 16 channels and Embedded temperature sensor w/ +/-1.5 linearity with T FLASH: up 1Mbytes

CORTEXM3 CPU 72 MHz


ARM Lite Hi Hi-Speed Bus Matrix / Arbiter (max 72MHz)

32kB-1MB Flash Memory

Power Supply Reg 1.8V POR/PDR/PVD

JTAG/SW Debug Nested vect IT Ctrl 1x Systic Timer

Up to 96kB SRAM

XTAL oscillators 32KHz + 4~16MHz Int. RC oscillators 40KHz + 8MHz

20B Backup Regs Reset Clock Control ARM Peripheral Bus (max 36MHz)

PLL

DMA 7 Channels

RTC / AWU

CRC
1x 1616-bit PWM
Synchronized AC Timer

Bridge Bridge

1x USB 2.0FS 1x bxCAN 2.0B 2x USART/LIN Smartcard / IrDa Modem Control 1x SPI

3x 16-bit Timer ARM Peripheral Bus Independent Watchdog Window Watchdog 2x 12-bit ADC 16 channels / 1Msps Temp Sensor

32/49/80 I/Os 1x SPI 1x USART/LIN Smartcard/IrDa Modem-Ctrl

(max 72MHz)

Up to 16 Ext. ITs

2x I2C

41

STM32F10x: Memory Mapping and Boot Modes


0xFFFF FFFF 0xE010 0000 0xE00F FFFF

Reserved Cortex-M3 internal peripherals

0xE000 0000

Addressable memory space of 4 GBytes RAM : up to 96 kBytes FLASH : up to 1MBytes


Reserved 0x1FFF F80F

Boot modes:
Depending on the Boot configuration
Embedded Flash Memory System Memory Embedded SRAM Memory
BOOT Mode Selection Pins

Reserved

Option Bytes SystemMemory

0x1FFF F800 0x1FFF F7FF 0x1FFF F000

Reserved

0x4000 0000

Peripherals Reserved
Flash

0x0801 FFFF

Boot Mode User Flash

Aliasing User Flash is selected as boot space SystemMemory is selected as boot space Embedded SRAM is selected as boot space 42

BOOT1
0x0800 0000

BOOT0

x 0

0 1 1

0x2000 0000

SRAM Reserved

SystemMemory Embedded SRAM

0x0000 0000

CODE

Contains Bit-Band region

STM32F10x:Boot Modes
Boot mode = user Flash: For finalized debuged and tested applications where update is not necessary (example: Washing machine). Boot mode = System Memory: For applications where firmware update is performed frequently (example: Satellite receiver, Playsattion, etc). The internal boot ROM memory contains the Bootloader (programmed by ST in production) used to re-program the FLASH. The CPU executes Data packets the boot loader: (code) 1) Data packets containing code are Received through through serial peripheral (UART).

CPU

System memory (Boot Loader)

UART

Bus Matrix

Flash (Application Code)

2) The Flash is reprogrammed with the new received code Boot mode = SRAM
43

STM32F10x: System Architecture


Multiply possibilities of bus accesses to SRAM, Flash, Peripherals, DMA BusMatrix added to Harvard architecture allows parallel access Efficient DMA and Rapid data flow Direct path to SRAM through arbiter, guarantees alternating access Harvard architecture + BusMatrix allows Flash execution in parallel with DMA transfer Increase Peripherals Speed for better performance Dual Advanced Peripheral buses (APB) architecture w/ High Speed APB (APB2) up to 72MHz and Low Speed APB (APB1) up to 36MHz Allows to optimize use of peripherals (18MHz SPI, 4.5Mbps USART, 72MHz PWM Timer, 18MHz toggling I/Os)
Flash I/F

I-bus

CORTEX-M3 Master 1

D-bus

FLASH

BusMatrix

System

SRAM Slave
APB2 AHB

GP-DMA Master 2
Arbiter

AHB-APB2 AHB-APB1
Bridges APB1

GPIOA,B,C,D,E - AFIO USART1- SPI1 - ADC1,2 TIM1 - EXTI USART2,3 - SPI2 - I2C1,2 TIM2,3,4 - IWDG WWDG USB CAN BKP PWR

Buses are not overloaded with data movement tasks 44

STM32F10x: Power Supply

Power Supply Schemes


VDD = 2.0 to 3.6 V: External Power Supply for I/Os and the internal regulator. VDDA = 2.0 to 3.6 V: External Analog Power supplies for ADC, Reset blocks, RCs and PLL. ADC working only if VDDA 2.4 V VBAT = 1.8 to 3.6 V: For Backup domain when VDD is not present.
Power pins connection: - VDD and VDDA must be connected to the same power source - VSS, VSSA and VREF- must be tight to ground - 2.4V VREF+ VDDA - VREF+ and VREF- available only on 100-pin (144-pin) packages, in other packages they are internally connected respectively to VDDA and VSSA
VBAT VREFVREF+ VDDA VSSA

VDDA domain

A/D converter Temp. sensor Reset block PLL

VDD domain
I/O Rings STANDBY circuitry (Wake-up logic, IWDG, RCC CSR reg) Voltage Regulator

V18 domain

VSS VDD

Core Memories Digital peripherals

Low Voltage Detector

Backup domain
LSE crystal 32K osc BKP registers RCC BDCR register RTC

45

STM32F10x: Power On Reset (POR)/Power Down Reset (PDR)


VDD

Integrated POR / PDR circuitry guarantees proper product reset when voltage is not in the product guaranteed voltage range (2V to 3.6V)
No need for external reset circuit

Vtrh Vtrl

POR
40mv hysteresis

PDR

Tempo 2ms

Reset

POR and PDR have a typical hysteresis of 40mV

Vtrl min 1.8V / Vtrh max 2V

46

STM32F10x: Programmable Voltage Detector (PVD)


Programmable Voltage

Detector
Enabled by software Monitor the VDD power supply by comparing it to a threshold Threshold configurable from 2.2V to 2.9V by step of 100mV Generate interrupt through EXTI Line16 (if enabled) when VDD < Threshold and/or VDD > Can be used to generate a warning message and/or put the MCU into a safe state
VDD

PVD Threshold

100mv hysteresis

PVD Output

Threshold

47

STM32F10x: Backup Domain


Backup Domain contains
RTC (Counter, Prescaler and Alarm mechanism) Separate 32KHz Osc (LSE) for RTC 20-byte user backup data RCC BDSR register: RTC source clock selection and enable + LSE config Reset only by Backup domain RESET
Backup domain
VBAT

power switch

RCC BDSR reg

32KHz OSC (LSE)

VDD

VBAT independent voltage supply


Automatic switch-over to VBAT when VDD goes lower than PDR level No current sunk on VBAT when VDD present

ANTI_ TAMP

20 byte data

RTC

Tamper detection: resets all user backup registers


Configurable level: low/high Configurable interrupt generation

48

STM32F10x: Low power modes


STM32F10x low power modes: uses Cortex-M3 sleep modes:
SLEEP, STOP and STANDBY modes the reset circuitry, POR/PDR, is active in STANDBY and STOP modes

49

Outline
Introduction Cortex-M3 Cortex-M3 based MCUs: The STM32F10x Family STM32 Programming STM32VL Discovery Kit
50

STM32 Programming: the software factor

+ CMSIS Standard (Cortex Microcontroller Software


Interface Standars Eases developpement and porting of applications

51

The CMSIS programming standard


Definition: The Cortex-M3 Microcontroller Software Interface Standard (CMSIS) is defined in close cooperation with various silicon and software vendors and provides a common approach to interface to peripherals, real-time operating systems and middleware components. For more details, please refer to www.onarm.com.

52

STM32F10xxx standard peripheral library architecture


- STM32 interrupt IRQ list/ Specific options for the Cortex-M3 core - STM32 peripheral memory mapping and physical register address definition - Configuration options User application

Cortex-M3 exceptions

Peripheral header file

Include NVIC and SysTick drivers

Low-level & API functions to Perform basic operations offered by the peripheral 53

Files to be modified by the user


system_stm32f10x.c
#include "stm32f10x.h /* #define SYSCLK_FREQ_HSE HSE_Value */ /* #define SYSCLK_FREQ_24MHz 24000000 */ /* #define SYSCLK_FREQ_36MHz 36000000 */ /* #define SYSCLK_FREQ_48MHz 48000000 */ /* #define SYSCLK_FREQ_56MHz 56000000 */ #define SYSCLK_FREQ_72MHz 72000000

main.c #include "stm32f10x.h int main(void) { /* Setup STM32 system (clock, PLL and Flash configuration) */ SystemInit(); /* main program*/ ... GPIO_WriteBit(GPIOD, GPIO_Pin_1, Bit_SET); }

stm32f10x_conf.h
/* Includes ----------------------------------------------------------------*/ /* Uncomment the line below to enable peripheral header file inclusion */ /* #include "stm32f10x_adc.h" */ /* #include "stm32f10x_bkp.h" */ /* #include "stm32f10x_can.h" */

stm32f10x_It.h /* Exported functions ----------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); stm32f10x_It.c


#include "stm32f10x_it.h" void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) {} } void EXTI1_IRQHandler(void) { GPIO_WriteBit(GPIOD, GPIO_Pin_1, Bit_SET); }

stm32f10x.h
/* Uncomment the line below according to the target STM32 device used in your application */ #if !defined (STM32F10X_LD) && !defined (STM32F10X_MD) && !defined (STM32F10X_HD) /* #define STM32F10X_LD */ /*!< STM32 Low density devices */ /* #define STM32F10X_MD */ /*!< STM32 Medium density devices */ #define STM32F10X_HD /*!< STM32 High density devices */ #endif

54

Coding conventions
All firmware is coded in ANSI-C
Strict ANSI-C for all library peripheral files

PPP is used to reference any peripheral acronym, e.g. TIM for Timer. Registers & Structures
STM32F10x registers are mapped in the microcontroller address space
FW library registers have the same names as in STM32F10x Datasheet & reference manual.

All registers hardware accesses are performed through a C structures :


Work with only one base address and indirect addressing Improve code re-use : e.g. the same structure to handle and initialize 3 USARTs.

55

STM32 programming: first steps

2
Optional step

56

STM32 programming: first steps


3

57

STM32 programming: first steps


Example : C port of the STM32 (GPIOC):
PPPi= GPIOC APBx = APB2
GPIO_InitTypeDef GPIO_InitStructure;

RCC_APB2PeriphClockCmd

( RCC_APB2Periph_GPIOC, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_InitStructure.GPIO_Speed = GPIO_InitStructure.GPIO_Mode =

GPIO_Init (GPIOC, &GPIO_InitStructure);


58

stm32f10x_conf.h

/* Includes ----------------------------------------------------------------*/ /* #include "stm32f10x_adc.h" */ /* #include "stm32f10x_bkp.h" */ /* #include "stm32f10x_can.h" */ #include "stm32f10x_NVIC.h"

Programming interrupts
1) Uncomment the NVIC header file in the stm32f10x_conf.h (if commented)

/* Uncomment the line below to enable peripheral header file inclusion */

main.c
#include "stm32f10x.h int main(void) { /* Setup STM32 system (clock, PLL and Flash configuration) */ SystemInit();

2) 3)

Declare the NVIC structure Define the peripheral generating the interrupt: For the complete STM32 Devices
IRQ Channels list, refer to stm32f10x.h file

NVIC_InitTypeDef NVIC_InitStructure;
/* main program*/ ...

4)

NVIC_InitStructure.NVIQ_IRQChannel= PPPx_IRQn ; NVIC_InitStructure.NVIQ_IRQChannelPremptionPriority = val1; NVIC_InitStructure.NVIQ_IRQChannelSubPriority = val2; NVIC_InitStructure.NVIQ_IRQChannelCmd=ENABLE NVIC_Init (&NVIC_InitStructure) ..


}

Define the priority and piority group of the interrupt

5) 6)

Enable the interrupt source Initialize the NVIC structure


59

Programming interrupts
stm32f10x_It.c #include "stm32f10x_it.h" . void PPPx_IRQHandler(void) { // code Clearpendingbit ( ) }

The same used in the IRQChannel property

The function prototype must be declared In the stm32f10x_it.h Dont forget to clear the interrupt bit

60

Outline
Introduction Cortex-M3 Cortex-M3 based MCUs: The STM32F10x Family STM32 Programming STM32VL Discovery Kit
61

STM32 Value Line Discovery board


A compact all in one board Ideal for quick evaluation, learning or prototyping The debugger ST-Link is on the board itsel Leds and button for immediate usage The extension connector with all STM32 pins enables building complex applications by using an extension board The board can be used as an independent ST-Link for your own board if needed Dedicated web site: www.st.com/stm32-discovery
62

Features and benefits

63

Now you are able to

64

You might also like