You are on page 1of 37

ST

TMicroellectronics: Corttex-M4
4 Trainiing STM
M32F4
Discovery
y evalua
ation board using
g ARM K eil MDK
K 5 toolkitt
fea
aturing Ser
rial Wire Viiewer Summer 2014

In
ntroductio
on:

Version
V
1.2 Rob
bert Boys, bob.b
boys@arm.com

The latest version of this document is here:


For a CAN lab on the
t
STM32F4 Discovery:
D

www.keil .com/appnotes
s/docs/apnt_23
30.asp
www.keil .com/appnotes
s/docs/apnt_23
36.asp

Thhe purpose of this


t lab is to inttroduce you to the STMicroeelectronics Corrtex-M4 proccessor using thhe ARM Keil
MDK
toolkit featuring the IDE Visiion. We will use
u the Serial Wire
W Viewer (S
SWV) and the on-board ST-L
Link V2 Debugg Adapter.
Att the end of thiis tutorial, you will be able to
o confidently work
w
with thesee processors annd Keil MDK. See www.keill.com/st.
Keil MDK supports and has ex
xamples for mo
ost ST ARM prrocessors. Cheeck the Keil Deevice Databasee on www.keiil.com/dd
foor the completee list which is also
a included in
n MDK: in V
Vision, select P
Project/Select D
Device for targeet
Liinux: For ST processors run
nning Linux, Android
A
and barre metal are suupported by AR
RM DS-5. ww
ww.arm.com/dds5.
Keil MDK-Lite is a free evalluation version
n that limits cod
de size to 32 K
Kbytes. Nearlyy all Keil exampples will comppile within
thhis 32K limit. The
T addition off a valid licensse number will turn MDK intoo a full commeercial version.
RTX RTOS: All
A variants of MDK
M
contain the
t full version
n of RTX with source code. S
See www.keil.com/rl-arm/kerrnel.asp.

W
Why Use Keil
K
MDK ?

MDK pro
ovides these features
f
partticularly suitted for Corteex-M processor users:

1.

Vision
n IDE with Inteegrated Debug
gger, Flash prog
grammer and th
the
ARM Compiler toolchain. MDK is
i a turn-key prroduct.
2. A full feature
f
Keil RT
TOS called RTX is included with
w MDK. RT
TX
comes with
w a BSD typ
pe license. Sou
urce code is prrovided.
3. Serial Wire
W Viewer an
nd ETM trace capability
c
is in
ncluded.
4. RTX Kernel
K
Awareneess window. Itt is updated in real-time.
5. Keil Teechnical Suppo
ort is included for
f one year an
nd is easily
renewaable. This helps you get your project completed faster.
Th
his document details these features:
f
1. Serial Wire
W Viewer (S
SWV) and ETM
M trace. Real-time tracing uppdated while thhe program is rrunning.
2.
3.
4.
5.

Real-tim
me Read and Write
W
to memorry locations forr Watch, Mem
mory and RTX T
Tasks windows. These are nnonintrusiv
ve to your prog
gram. No CPU
U cycles are stolen. No instruumentation codde is added to yyour source filees.
Six Harrdware Breakp
points (can be set/unset
s
on-thee-fly) and four Watchpoints ((also known ass Access Breakks).
RTX Viewer:
V
a kernel awareness prrogram for the Keil
K RTX RTO
OS that updatees while your program is runnning.
A DSP example progrram using ARM
M CMSIS-DSP
P libraries. ww
ww.arm.com/cm
msis

Serial Wire
e Viewer (SWV):
(
Seerial Wire Vieewer (SWV) diisplays PC Sam
mples, Exceptio
ons (including interrupts), daata reads and w
writes, ITM (priintf), CPU
coounters and a tiimestamp. Thiis information comes from th
he ARM CoreS
Sight debug m
module integraated into STM332 CPU.
SW
WV does not steal any CPU cycles
c
and is co
ompletely non--intrusive. (exccept for the ITM
M Debug printtf Viewer).
CooreSight displaays memory co
ontents and varriable values in
n real-time and these can be m
modified on-thee-fly.

Embedded Trace Ma
acrocell (E
ETM):
ET
TM records an
nd displays all instructions
i
thaat were executeed. This is verry useful for deebugging progrram flow probllems such
ass going into th
he weeds and how did I gett here?. Keil Vision

uses E
ETM to providee Code Coveraage, Performannce
Annalysis and cod
de execution tiimes. ETM req
quires a special debug adapteer such as the U
ULINKpro. Thhe Discovery sseries do
noot have the ETM
M connector ev
ven though thee processor hass ETM. Most oother ST and alll Keil boards ddo have this coonnector.

D
Discovery Board Deb
bug Adapter Conne
ections:
Thhe STM32F407
7 Discovery bo
oard lacks the standard
s
ARM
M debugger connnections. Thiss means it is noot easy to connnect a
UL
LINK2, ULIN
NKpro or J-Link
k to these boards. In order to
o use features liike ETM tracee, it is easier to obtain a boardd such as
thhe Keil MCBST
TM32 series orr a STM32xxx--EVAL board. Versions are available with Cortex-M3 annd Cortex-M4 pprocessors.
Keil MDK has examples
e
and laabs for these boards. This do
ocument uses oonly the on-boaard ST-LINK. See www.keill.com/st.
1

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

1.

Keil Evaluation Software:

2.

Keil Software Download and Installation:

3.

On-board ST-Link V2 Debug Adapter:

4.

Example Programs

5.

Getting Started MDK 5 Manual:

6.

Vision Software Packs Download and Install Process:

7.

Testing the ST-Link V2 Connection:

8.

Installing the ST-Link USB Drivers:

9.

Blinky example using the STM32F4 Discovery board:

10. Hardware Breakpoints:

11. Call Stack & Locals window:

12. Watch and Memory windows and how to use them:

13. How to view Local Variables in Watch and Memory windows:

14. View Variables Graphically with the Logic Analyzer (LA):

10

15. Watchpoints: Conditional Breakpoints

11

(Access Breakpoints)

16. RTX_Blinky example: Keil RTX RTOS:

12

17. RTX Kernel Awareness using RTX Viewer:

13

18. Logic Analyzer: View variables real-time in a graphical format:

14

19. ITM (Instrumentation Trace Macrocell):

15

20. Serial Wire Viewer (SWV) and how to use it:

16

1) Data Reads and Writes

16

2) Exceptions and Interrupts

17

3) PC Samples (program counter samples)

18

21. Serial Wire Viewer (SWV) Configuration:

19

22. DSP Sine Example using ARM CMSIS-DSP Libraries

20

23. Creating your own project from scratch:

24

24. Creating your own RTX RTOS project from scratch:

27

25. ETM Trace and its benefits:

28

for reference

26. Configuring the ST-Link V2:

33

27. Configuring the Keil Flash Programmer:

34

28. Serial Wire Viewer and ETM summary:

35

29. Document Resources:

36

30. Keil Products and contact information:

37

Notes on using this document:


1.

The latest version of this document and the necessary example source files are available here:
www.keil.com/appnotes/docs/apnt_230.asp

2.

MDK 5.10 was used in the exercises in this document.

3.

To use MDK 4.7x, see www.keil.com/appnotes/docs/apnt_261.asp

4.

The on-board ST-Link V2 is used by default in this document. All you need install is the USB driver to your PC.

5.

The ST-Link V2 interfaces very well with Keil Vision and its performance is quite good including SWV.

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

1) Keil Eva
aluation Software:
S
MDK 4.7x and MD K 5
M
MDK 5 now usees Software Paacks to distributte processor sp
pecific softwaree, examples annd middleware. MDK 5 is innstalled and
thhe Packs you neeed will be dow
wnloaded from
m the web. Theey can also be iimported manuually.
M
MDK 4.7x is stiill available. MDK
M
4.7x conttains all the filees needed to ruun projects. Thhe MDK 5 Soft
ftware Packs arre not used.
Thhe older versio
on of this docum
ment written fo
or MDK 4 is av
vailable here: www.keil.com
m/appnotes/doccs/apnt_261.aspp.
M
MDK 4 projects can be used with
w MDK 5 by
y using the Leg
gacy install soft
ftware availablee on www.keil.com. Then, M
MDK 5 can
thhen run legacy MDK
M
4 projects without any Software Pack
ks.
W
We recommend that MDK 5.10 Software paccks are used if they are availaable. New onees are continuallly being addedd.
Keil has several labs for variou
us STM32 proccessors including one using C
CAN. See www
w.keil.com/st ffor details.
his document uses only MD
DK 5.10 or lateer.
Th

2) Keil Sofftware Do
ownload and
a
Installation:
1.

Downlo
oad MDK 5.10
0 or later from the
t Keil websiite. www.keil.ccom/mdk5/insttall

2.

Install MDK
M
into the default directo
ory. You can in
nstall into any directory, but tthis lab uses thhe default C:\K
Keil_v5

3. We recommend you use


u the default directories forr this tutorial. W
We will use C::\MDK\ for thee examples.
4.

i
MDK in
nto a different directory,
d
you will
w have to addjust for the dirrectory differennces.
If you install

6. The exaample DSP5 iss available on the web where you got this doocument.
7. You cann use the evaluuation version (MDK-Lite)
(
fo
or this lab. No license is needded.
8. You doo not need any debug adapterss: just the Disccovery board, a USB cable annd MDK 5.10 iinstalled on youur PC.
T-Link V2 Debug
D
Ad
dapter:
3) The on--board ST
Thhe on-board ST
T-Link V2 is used exclusively
y in this lab. In
nstructions on configuring thhe ST-Link V2 are given. Pagge 5
coontains a test fo
or the ST-Link V2 drivers.

4) Examplle Program
ms:
M
MDK 5 Softwarre Pack contain
ns a Blinky and
d RTX_Blinky example progrrams. We willl use only Blinkky. An enhancced
RT
TX_Blinky5 an
nd the DSP exaample (DSP5) is available on
n the web wherre the latest verrsion of this doocument is storred:
ww
ww.keil.com/aappnotes/docs/aapnt_230.asp.

5) Getting
g Started MDK
M
5: Obbtain this usefuul book here: w
www.keil.com/m
mdk5/.
STM32F401C-DISCO Disco
overy Boa
ard:
STM32F4
4-Discovery: This
T tutorial is written for thee STM32F4-Diiscovery boardd with a STM322F407VGT6
processor using
u
a CPU sp
peed of 168 MH
Hz. The numb
ber MB997B oor similar is maarked on the booard.
STM32F4
401C-DISCO: This newer bo
oard will work
k but the CPU cclock speed muust be reduced to 84 MHz.
This board
d contains a ST
TM32F401VCT
T6U processor.. STM32F401 C-DISCO is m
marked on the bboard.
Changing the clock speeed:
In the file system_stm32
s
2f4xx.c near lin
nes 254 and 256 are two #deffines: #define PLL_M and #ddefine PLL_Q.
Change theese values acco
ording to the prrocessor you arre using as folllows:
You will have
h
to modify the Core Clock
k: value in the Trace Config window when using the Seriial Wire Vieweer.
The DSP5 example runs at 57 MHz so no
n modificatio
on is needed.
k for STM32F4
401C-DISCO contains
c
Blinkyy and RTX_Bllinky exampless at 84 MHz.
Note: The Software Pack

STM32
2F4-Discoverry 168 MHz

STM322F401C-DISC
CO 84 MHz

8
7

336
4

#defiine PLL_M
#defiine PLL_Q

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

6) Vision
n Software
e Packs Download and
a
Insta
all Process
s:
1)) Start Vision and open Pa
ack Installer: (after the firsst MDK installl is complete and if you aree connected too the
In
nternet, Visio
on and Softwa
are Packs will automatically
y startup. Oth
herwise, follow
w Steps 1 and 2 below)
1.

Connecct your computter to the intern


net. This is neeeded to downlooad the Softwaare Packs.

2.

Start V
Vision by click
king on its desk
ktop icon.

3.

Open th
he Pack Installer by clicking on its icon:

4.

This wiindow opens up


p: Under the Boards
B
tab, Sellect STM32F4--Discovery as shown below: This will filteer the list
under th
he Packs tab.

5.

You can
n enter Discov
very in Search to
t filter.

6.

Note: ONLINE

is displayed
d
at thee bottom
right. If OFFLINE is displayed, connect
nternet before continuing.
to the In

7.

If theree are no entries shown becausse you

A Pack Insttaller Welcomee screen will oppen. Read andd close it.

were no
ot connected to
o the Internet when
w
Pack Instaaller opened, sselect Packs/Chheck for Updattes or
you hav
ve connected to
o the Internet.

to reefresh once

2)) Install The STM32F4


S
Softtware Pack:
1.

Click on the Packs tab


b. Initially, thee Software Pacck ARM::CMS
SIS is installed by default.

2.

Select Keil::STM32F4
K
4xx_DFP and click on Install. This Softwaare Pack will ddownload and innstall to
C:\Keill_v5\ARM\Pacck\Keil\ST\ by default. This download
d
can take two to fouur minutes.

3.

Its statu
us will be indiccated by the U
Up to date icon
n:

TIIP: If you clicck on the Devicces tab, you can


n select the pro
ocessor you aree using and thiis will be displaayed in the Paccks tab.
3)) Install the Blinky
B
MDK 5.10 Example:
1.

Select the
t Examples tab
t to display th
his window:

2.

Select Blinky
B
(STM32
2F4-Discovery
y):

3.

Select Copy
C

4.

The Co
opy Example window
w
below opens
o
up: Seleect
Use Pacck Folder Struccture: Unselecct Launch Vission:

5.

Type in
n C:\MDK. Click OK to copy
y the Blinky prroject.

6.

The Bliinky example will


w now copy to C:\MDK\Bo
oards\ST\ STM
MF32F4-Discovvery.

7.

We do not need to cop


py CMSIS-RT
TOS Blinky. We
W will use a sppecial
version
n that has 4 threeads instead off two to make th
hings interestinng.

as shown
n here:

TIIP: The defau


ult directory forr copied examp
ples the first tim
me you install
M
MDK is C:\Userrs\<user>\Docu
uments. For simplicity, we will
w use the defa
fault
diirectory of C:\M
MDK\ in this tu
utorial. You caan use any direectory you preffer.
8.

Close th
he Packs Installler. You can open
o
it any tim
me by clicking oon its icon.

4)) Install the RTX_Blinky5


R
and
a DSP5 Exa
amples from Keil.com:
K
1.

Obtain the example so


oftware zip filee from www.keeil.com/appnottes/docs/apnt_2230.asp.

2.

Unzip this
t into the dirrectory C:\MDK\Boards\ST\S
STMF32F4-Diiscovery\.

3.

The DS
SP5 folder will be created witth the Blinky and
a RTX_Blinkky folder as shoown here:

TIIP: An Updatee icon means th


here is an updaated Software Pack
P
available for download..
TIIP: If you look
k in the directo
ory C:\Keil_v5\ARM\Pack\K
Keil\STM32F4xxx_DFP\1.0.6\\Boards\ST\ST
TM32F4-Discovvery, you
wiill find anotherr Blinky. This is a read-only version for backup purposess. Use only thee projects you ccopied over froom the
Exxamples tab in the Pack Instaaller window to
o the directory you chose. In this tutorial w
we are using C:\\MDK.
4

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

7) Testing
g the ST-Link V2 Co
onnection::
1.

Start V
Vision

iff it is not alread


dy running. Seelect Project/Oppen Project.

2.

Connecct the Discoverry board to you


ur PC with a US
SB cable as shhown on the first page of this tutorial.

3.

If the ST-Link
S
USB drivers
d
are instaalled correctly,, you should heear the usual U
USB connected dual-tone. If nnot, you
might have
h
to install the
t drivers man
nually. See the directions beloow.

4.

Two red LEDs will lig


ght:LD1 (COM
M) and LD2 (PWR)

5.

t Blinky projject C:\MDK\B


Boards\ST\STM
MF32F4-Discoovery\Blinky.uvvprojx.
Select the

6.

Select STM32F407
S
Flash as shown here:

7.

Select Target
T
Optionss

8.

Click on Settings: and


d the window below
b
opens up
p: If an IDCOD
DE and Devicee name is displlayed, ST-Linkk is
working
g. You can continue with thee tutorial. Clicck on OK twicee to return to thhe Vision maain menu.

9.

A numb
ber in the SN: box
b means V
Vision is conneccted to the ST--Link adapter.

or ALT-F
F7 and select th
he Debug tab:

ust be correcteed before you ccan continue. S


10. If nothiing or an error is displayed in
n this SW Deviice box, this mu
See the
next steep: Installing the
t ST-Link US
SB Drivers:
11. If you see
s a proper dissplay, your ST
T-Link USB driivers are
installed properly. Cllick OK twice to
t exit the Targ
get
Optionss windows and
d continue to th
he next page.
TIIP: To refresh
h the SW Devicce box, in the Port:
P
box selectt JTAG
annd then select SW
S again. You
u can also exit then re-enter this
t
wiindow.
TIIP: The main difference betw
ween ST-Link and ST-Link V2
V is the additiion of Serial W
Wire Viewer (SWV) trace cappability.

8
8) Installing ST-Lin
nk V2 USB
B Drivers: (might not be necessa
ary if the tes
st above pas
sses)
In
nstalling the ST-Link USB
B Drivers: (O
Only needed iff the above testt fails)
1.

Do not have the Disco


overy board US
SB port conneccted to your PC
C at this time.

2.

The US
SB drivers musst be installed manually
m
by ex
xecuting stlink__winusb_installl.bat. This filee is found in
C:\Keill_v5\ARM\STL
Link\USBDriv
ver. Find this file
f and double click on it. Thhe drivers will install.

3.

Plug in the Discovery


y board to USB
B CN1. The US
SB drivers willl now finish installing in the nnormal fashionn.

Su
uper TIP: Thee ST-Link V2 firmware updaater utility ST-L
LinkUpgrade.eexe is located hhere: C:\Keil_vv5\ARM\STLiink. If you
waant to update th
he ST-Link firm
mware, find th
his file and dou
uble click on it.. It is easy to uuse. It will cheeck and report the current
firrmware version
n. It is importaant you are usin
ng firmware V2.J16.S0
V
or latter for proper S
SWV operationn. Do not use
V22.J19.S0. Thiss version is inccompatible to th
he latest driverrs.
COM LED LD1
1 indication:
LE
ED is blinking RED: the startt of USB enum
meration with th
he PC is takingg place but not yet completedd.
LE
ED is RED: co
ommunication between
b
the PC
C and ST-LINK
K/V2 is establiished (end of eenumeration). Vision is nott connected
to ST-Link (i.e. in Debug mode).
LE
ED is GREEN: Vision is co
onnected in Deb
bug mode and the last comm
munication was successful.
LE
ED is blinking GREEN/RED
D: data is activeely being exchaanged betweenn the target andd Vision.
LE
ED is off, exceept for a brief RED
R
flash whille entering Deb
bug mode and a brief flash w
when clicking oon RUN happenns when
thhe SWV trace iss enabled in V
Vision.
NK/V2 communication with
h the target orr Vision has failed. Cycle the board pow
wer to restart.
No Led: ST-LIN

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

9) Blinky example
e
program
p
using
u
the STM32F4 Discoverry board:
W
We will connectt a Keil MDK development
d
sy
ystem using reeal target hardw
ware using the bbuilt-in ST-Linnk V2 debug aadapter.
1.

Start V
Vision by click
king on its desk
ktop icon.

Connect yourr PC to the boaard with a USB


B cable to CN1..

2.

Select Project/Open
P
Project.
P
Open the
t file C:\MD
DK\Boards\ST\S
STM32F4-Disscovery\Blinkyy\Blinky.uvprojjx

3.

By defaault, the ST-Lin


nk is selected. If this is the first
fi time you hhave run Visioon and the Disccovery board, yyou might
have to install the USB drivers. Seee the configuration instructionns on the previious page.

4.

Compille the source fiiles by clicking


g on the Rebuilld icon.

. Y
You can also uuse the Build iccon beside it.

5.

Program
m the STM32 flash
f
by clickin
ng on the Load
d icon:

Proogress will be iindicated in thee Output Winddow.

6.

Enter Debug
D
mode by
y clicking on th
he Debug icon.
Select O
OK if the Evaluation Mode boox appears.
Note: You
Y only need to use the Loaad icon to down
nload to FLAS H and not for R
RAM operatioon if it is chosenn.

7.

Click on the RUN ico


on.

Note:: you stop the program with tthe STOP iconn.

The 4 LEDs
L
on the
e STM32F4 Discovery board
b
will n
now blink in
n succession
n.
Press the
t blue USE
ER button and
a
they wiill all come on.
No
ow you know
w how to compile a program
m, program it into the STM
M32 processo
or Flash, run it and stop it !
No
ote: The boarrd will start Blin
nky stand-alon
ne. Blinky is no
ow permanent ly programmed
d in the Flash until reprogram
mmed.

TIIP: If you aree using a STM


M32F401C-DIS
SCO board an
nd the LEDs d
do not blink, yyou might havee the clock
frrequency set to
oo high. See the instruction
ns on page 3 un
nder STM32F
F401C-DISCO
O Discovery Board:

10) Hardw
ware Breakpoints:
Thhe STM32F4 has
h six hardwarre breakpoints that can be sett or unset on thhe fly while thee program is ruunning.
1.

With Blinky running, in the Blinky.c window, clicck on a darker ggrey block in tthe left margin on a line in maain() in the
while lo
oop. Between around lines 59
5 through 74 will
w suffice.

2.

A red circle
c
will appeear and the prog
gram will stop..

3.

Note th
he breakpoint iss displayed in both
b
the disasssembly and souurce windows as shown beloow:

4.

You can
n set a breakpo
oint in either th
he Disassembly
y or Source winndows as long there is a grayy rectangle indiicating the
existencce of an assem
mbly instruction
n at that point.

5.

Every time
t
you click on the RUN iccon

6.

You can
n also click on
n Single Step (S
Step In)

the pro
ogram will run until the breakkpoint is again encountered.
, Step Over

and Step Ouut

TIIP: If single sttep (Step In) doesnt work, cllick on the


Diisassembly win
ndow to bring it into focus. If
I needed, click
k on a
diisassembly linee. This tells V
Vision you wan
nt to single step
p at the
r
than at th
he C source lev
vel.
asssembly level rather
TIIP: A hardwarre breakpoint does
d
not executte the instructio
on it is
seet to. ARM Co
oreSight breakp
points are no-sk
kid. Your instrructions
inn Flash are not substituted or modified.
m
Theese are rather
im
mportant features for efficientt software deveelopment.
Remove all breakpoints when
n you are done for the next
exxercise by click
king on them again.
TIIP: You can delete
d
the breakpoints by cliccking on them or
o
seelecting Debug/Breakpoints (o
or Ctrl-B) and selecting Kill All.
Cllick on Close to return.
TIIP: You can view
v
the break
kpoints set by selecting
Debug/Breakpoiints or Ctrl-B.
6

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

11) Call Stack + Locals Window:

Local Variables:
The Call Stack and Local windows are incorporated into one integrated window. Whenever the program is stopped, the Call
Stack + Locals window will display call stack contents as well as any local variables belonging to the active function.
If possible, the values of the local variables will be displayed and if not the message <not in scope> will be displayed. The
Call + Stack window presence or visibility can be toggled by selecting View/Call Stack window.
1.

Run and Stop Blinky. Click on the Call Stack + Locals tab.

2.

Shown is the Call Stack + Locals window.

The contents of the local variables are displayed as well as


names of active functions. Each function name will be
displayed as it is called from the function before it or from
an interrupt or exception.
When a function exits, it is removed from the list.
The first called function is at the bottom of this table.
This table is active only when the program is stopped.
3.

Click on the Step In icon or F11:

4.

Note the function different functions displayed as you step through them. If you get trapped in the Delay function,
use Step Out

or Ctrl-F11 to exit it faster.

5.

Click numerous times on Step In and see other functions.

6.

Right click on a function name and try the Show Callee Code and Show Caller Code options as shown here:

7.

Click on the StepOut icon

to exit all functions to return to main().

TIP: If single step (Step In) does not work, click on the Disassembly window to
bring it into focus. If needed, click on a disassembly line to step through
assembly instructions. If a source window is in focus, you will step through the
source lines instead.
TIP: You can modify a variable value in the Call Stack & Locals window when the program is stopped.
TIP: This is standard Stop and Go debugging. ARM CoreSight debugging technology can do much better than this. You
can display global or static variables updated in real-time while the program is running. No additions or changes to your code
are required. Update while the program is running is not possible with local variables because they are usually stored in a
CPU register. They must be converted to global or static variables so they always remain in scope.
If you have a ULINKpro and ETM trace, you can see a record of all the instructions executed. The Disassembly and Source
windows show your code in the order it was written. The ETM trace shows it in the order it was executed. ETM additionally
provides Code Coverage, Performance Analysis and Execution Profiling.
Changing a local variable to a static or global normally means it is moved from a CPU register to RAM. CoreSight can view
RAM but not CPU registers when the program is running.

Call Stack:
The list of stacked functions is displayed when the program is stopped as you have seen. This is useful when you need to
know which functions have been called and what return data is stored on the stack.
TIP: You can modify a local variable value when the program is stopped.
TIP: You can access the Hardware Breakpoint table by clicking on Debug/Breakpoints or Ctrl-B. This is also where
Watchpoints (also called Access Points) are configured. You can temporarily disable entries in this table.
Selecting Debug/Kill All Breakpoints deletes Breakpoints but not Watchpoints.
7

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

12) Watch
h and Mem
mory Wind
dows and how to us
se them:
Thhe Watch and Memory
M
windo
ows will displaay updated variiable values in real-time. It ddoes this througgh the ARM C
CoreSight
deebugging techn
nology that is part
p of Cortex-M
M processors. It is also possiible to put orr insert values into these mem
mory
locations in real--time. It is posssible to drag and drop variiable names intto windows orr enter them maanually.
W
Watch windo
ow:

Add a global va
ariable: Recalll the Watch an
nd Memory win
ndows cant seee local variablles unless stoppped in their funnction.
1.

Stop the processor

and exit Debug mode.

2.

In Blink
ky.c, declare a global variablle (I called it vaalue) near linee 20 like this: u
unsigned int vvalue = 0;

3.

Add thee statements vaalue++; and iff

4.

Select File/Save
F
All or
o click

5.

Click on Rebuild.

6.

Enter Debug
D
mode.
Click on RUN
R
. Recaall you can set Watch and
Memorry windows wh
hile the program
m is running.

7.

In Blink
ky.c, right click
k on the variab
ble value and select Add vallue to and select Watch 1. Watch 1 will open if
needed and value wiill be displayed
d as shown heree:

8.

value will incrementt until 0x10 in real-time.

(value > 0x
x10) value = 0;as

shown hhere near line 771:

. Click on Lo
oad

to prog
gram the Flashh.

TIIP: You can also


a block valu
ue, click and hold
h
and drag itt
innto a Watch or Memory
M
windo
ow.
TIIP: Make suree View/Periodiic Window Upd
date is selected
d.
9.

You can
n also enter a variable
v
manuaally by double--clicking underr Name or presssing F2 and ussing copy and ppaste or
typing the
t variable. Use
U the View/S
Symbols windo
ow to enter a vaariable fully quualified.

TIIP: To Drag n
n Drop into a taab that is not acctive, pick up the
t variable annd hold it over tthe tab you waant to open; whhen it
oppens, move you
ur mouse into the
t window and release the variable.
v
M
Memory wind
dow:

1.

Right-cclick on value
e and enter into
o the Memory 1 window or ennter it manuallyy. Select View
w/Memory Winndows if
necessaary.

2.

Note th
he value of val
lue is displayiing its address in Memory 1 aas if it is a poin
nter. This is useful to see whhat address
a pointeer is pointing to
o but this not what
w we want to
t see at this tim
me.

3.

Add an
n ampersand &
& in front of th
he variable nam
me and press E
Enter. The phyysical address is shown (0x20000_0014).

4.

Right click
c
in the mem
mory window and
a select Unsigned/Int.

5.

The datta contents of value


v
is now displayed
d
as a 32
3 bit value.

6.

Both th
he Watch and Memory
M
windo
ows are
updated
d in real-time.

7.

You can
n modify valuee in the Memorry window
with a right-click
r
with
h the mouse cu
ursor over the
data fieeld and select Modify
M
Memorry.

TIIP: No CPU cycles


c
are norm
mally used to peerform these
opperations. See the next page How It Work
ks for an
exxplanation on how
h DAP functtions.
TI
IP: To view variables
v
and th
heir location use the Symbol window. Seleect View/Symbbol Window whhile in Debug m
mode.

Seerial Wire View


wer (SWV) does not need to be configured in order for thee Memory andd Watch window
ws to operate aas shown.
Thhis mechanism
m uses a differen
nt feature of CoreSight than SWV.
S
These R
Read and Writee accesses are handled by thee Serial
which providees on-the-fly memory
W
Wire Debug (SW
WD) or JTAG connection
c
via the CoreSightt Debug Accesss Port (DAP), w
acccesses.
8

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

13) How to
t view Lo
ocal Variab
bles in the
e Watch o
or Memory
y windows:
1.

Make sure
s
Blinky.c iss running. We will use the lo
ocal variables fr
from main(): nnum, dir and bttns.

2.

Locate where the threee local variables are declared


d in Blinky.c neear line 46, at tthe start of thee main functionn.

3.

Enter each of the three variables into


o Watch 1 win
ndow by right-cclicking on them. Note it sayys < not in scoppe >
which is wheree value is probbably located. IIf Vision
becausee Vision cann
not access the CPU
C
registers while
w
running w
says yo
ou are unable to
o add a variable, stop and starrt the Blinky prrogram.

4.

Set a brreakpoint in thee Blinky.c whiile loop. The problem


p
will
stop thee program and the current varriable values will
w appear.

5.

Remove this breakpoiint.

6.

Set a brreakpoint at iff

7.

Hold do
own the blue USER
U
button an
nd start the pro
ogram. The
program
m will stop. A btns value of 1 will display. Without
USER pressed,
p
a 0 wiill be displayed
d if you click on
o Run again.

(btns != (1
1UL << 0))

neear line 61.

TIIP: Remembeer: you can set and


a unset hard
dware breakpoiints on-the-fly in the Cortex-M
M4 while the pprogram is runnning !
8.

Vision
n is unable to determine
d
the value
v
of these three
t
variables when the proggram is runningg because theyy exist only
when main
m is running
g. They disappear in function
ns and handlerss outside of maain. They are a local or autom
matic
variablee and this mean
ns it is probablly stored in a CPU
C
register w
which Vision iis unable to acccess during runn time.

9.

Removee the breakpoiint and make su


ure the program
m is not runninng

. Exit Debug mode.

H
How to view
w local varia
ables update
ed in real-tim
me:

Alll you need to do is to make the


t local variab
bles num, dir and
a btns globall where it is deeclared in Blinkky.c !
1.

Move th
he declarationss for num, dir and
a btns out off main() and too the top of Blinnky.c to make them global vaariables:
unsigned int va
alue = 0;
t32_t num = -1;
int
int
t32_t dir =

1;

uin
nt32_t btns = 0;

TIIP: You could also make the them static ! i.e.


i static int322_t

num = -1 ;

TIIP: You can ed


dit files in edit or debug mode. However, you
y can compille them only inn edit mode.
2.

Compille the source fiiles by clicking


g on the Rebuilld icon. They w
will compile w
with no errors oor warnings.

3.

To prog
gram the Flash
h, click on the Load
L
icon.

4.

Enter Debug
D
mode.

5.

Now th
he three variablles are updated
d in real-time. Press and releaase the User buutton and btns will update to 0 or 1.
This is ARM CoreSig
ght technology working.

6.

You can
n read (and wrrite) global, staatic variables an
nd structures. Anything that stays around inn a variable froom
function
n to function. This includes reads
r
and writees to peripheraals.

7.

Stop the CPU and exiit debug mode for the next steep.

. A progress bbar will be dispplayed at the boottom left.

Click on RUN.
R

and

TIIP: View/Periiodic Window Update must be


b selected. Ottherwise variabbles update onlly when the proogram is stopped.

H
How It Wo
orks:
V
Vision uses AR
RM CoreSight technology to read or write memory
m
locatioons without steealing any CPU
U cycles. This is nearly
alw
ways non-intru
usive and does not impact thee program execcution timings. Remember thhe Cortex-M4 iis a Harvard arrchitecture.
Thhis means it haas separate instrruction and datta buses. Whille the CPU is ffetching instrucctions at full sppeed, there is pplenty of
tim
me for the CoreeSight debug module
m
to read or write valuees without stealling any CPU ccycles.
Thhis can be sligh
htly intrusive in
n the unlikely event
e
the CPU
U and Vision rreads or writes to the same m
memory locationn at
exxactly the samee time. Then th
he CPU will bee stalled for on
ne clock cycle. In practice, thhis cycle stealinng never happeens.

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

14) View Variables


V
Graphically with th
he Logic A
Analyzer (
(LA):
W
We will display the global variiable value you
u created earlieer in the Logic Analyzer. Noo code stubs in the user code w
will be
ussed. This uses the Serial Wire Viewer and therefore
t
does not steal CPU cycles.
1.

Stop the processor

and exit Debug mode.

Configure Seria
al Wire Vieweer (SWV):
2.

Select Target
T
Optionss
or ALT-F
F7 and select th
he Debug tab. Select Settinggs: on the rightt side of this wiindow.
Confirm
m SW is selected. SW selectiion is mandato
ory for SWV. S
ST-Link uses oonly SW. Seleect the Trace taab.

3.

In the Trace
T
tab, selecct Trace Enablee. Unselect Peeriodic and EX CTRC. Set Coore Clock: to 168 MHz. Eveerything
else is set
s as shown heere:

4.

Click OK
O once to retu
urn to the Debu
ug tab.

5.

Click OK
O return to thee main menu. Enter debug mode.
m

Configure Logiic Analyzer:


1.

Windows and select Logic Analyzer


Open View/Analysis
V
A
or selecct the LA wind
dow on the toollbar.

c
the LA
L while the prrogram is runniing.
TIIP: You can configure
2.

Click on the Blinky.c tab. Right clicck on value an


nd select
Add vaalue to and th
hen select Logiic Analyzer. You
Y can
also Drrag and Drop or enter it manu
ually.

3.

Click on the Select bo


ox and the LA Setup window
w appears:

4.

With va
alue selected,, set Display Range Max: to 0x15
0
as shownn here:

5.

Click on Close.

Ru
un Program: Note: The LA
A can be config
gured while thee program is ruunning.

1) Click on Run.

Cllick on Zoom Out


O until Grid is about 1 secoond.

2) The varriable value will


w increment to
t 0x10 (decim
mal 16) and theen is set to 0.
TIIP: If you do not
n see a waveeform, exit and re-enter Debu
ug mode to refrresh the LA. Y
You
m
might also have to repower thee Discovery board. Confirm the
t Core Clockk: value is corrrect.
TIIP: You can show up to 4 vaariables in the Logic
L
Analyzeer. These variaables must be
gllobal, static or raw
r addresses such as *((unssigned long *)0
0x20000000).

3) Enter thhe static variabble btns into thee LA and set thhe Display Rannge Max: to 0xx2. Click on R
RUN and press tthe User
button and
a see the volltages below:

4) Note thhe variable valuue stops increm


menting while USER
U
is held ddown. Also noote how easy itt is to view thiss effect.
5)

Select Signal Info, Sh


how Cycles, Amplitude
A
and Cursor
C
to see thhe measuring ccapabilities of the LA. You ccan stop
the LA by clicking
on the Stop
S
icon in
the Upd
date Screen
box.

6) Stop the CPU.


7) Click on Setup in
the LA and delete
btns. You
Y can use
the Dellete key or
this icon:

8) Click on Close.
10

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

15) Watch
hpoints: Conditional
C
Breakpointts: This do
oes not need
d or use Serrial Wire Vie
ewer:
Reecall STM32 processors
p
havee 6 hardware breakpoints. Th
hese breakpoinnts can be set oon-the-fly withoout stopping thhe CPU.
Thhe STM32 also
o have four Waatchpoints. Waatchpoints can be thought of as conditional breakpoints. T
The Logic Anaalyzer uses
thhe same comparrators as Watch
hpoints in its operations
o
and they must be sshared. This m
means in Visioon you must haave two
vaariables free in the Logic Anaalyzer to use Watchpoints.
W
Watchpoints
W
aree also referred to as Access B
Breakpoints.
1.

c
as
a the previouss page. Stop thhe program if nnecessary. Stayy in debug modde.
Use thee same Blinky configuration

2. We willl use the globa


al variable valu
ue you created
d in Blinky.c too explore Watcchpoints.

3.

The SW
WV Trace does not need to bee configured fo
or Watchpointss. However, w
we will use it in this exercise.

4.

The varriable value should be still entered


e
in the Logic
L
Analyzerr from the last exercise on the previous pagge.

5.

Select Debug
D
in the main
m Vision window
w
and sellect Breakpointts or press Ctrll-B.

6.

Select both
b
the Read and
a Write Access. In the Exp
pression box ennter: value = = 0x5 withoout the quotes.

7.

Click on Define and it will be accep


pted as shown here:
h
Click on Close.

8.

Enter th
he value to th
he Watch 1 win
ndow if it is nott
already
y listed.

9.

Open Debug/Debug
D
Settings
S
and sellect the trace taab.
Check on
Data R/W sample and uncheck
u
EXTR
RC.

10. Click on OK twice. Open


O
the Tracee Records
window
w.
11. Click on RUN.
12. You wiill see value change
c
in the Logic
L
Analyzerr as
well as in the Watch window.
w
v
equals 0x5,
0 the Watch
hpoint will stop
p
13. When value
the prog
gram.

14. Note th
he data writes in
n the Trace Reecords window
shown below.
b
0x5 is in the last Data column. Plu
us the address thhe data writtenn to and the PC
C of the write innstruction.
This is with the ST-Liink. A ULINK
K2 will show th
he same windoow. A ULINKppro or a J-Linkk (black case) w
will show
a slighttly different dissplay.
15. There are
a other types of expressionss you
can enter and are detaailed in the Hellp button
in the Breakpoints
B
win
ndow. Not all are
currentlly implemented in Vision.
16. To repeeat this exercise, click on RU
UN.
17. When you
y are finished, stop the prog
gram, click on Debug and sellect Breakpoinnts (or Ctrl-B) aand Kill the W
Watchpoint.
18. Leave Debug
D
mode.
TIIP: You canno
ot set Watchpoiints on-the-fly while the prog
gram is runningg like you can w
with hardwaree breakpoints.
TIIP: To edit a Watchpoint,
W
double-click on it
i in the Breakp
points window and its inform
mation will be ddropped down into the
coonfiguration areea. Clicking on Define will create
c
another
W
Watchpoint. Yo
ou should delette the old one by
b highlighting
g it and
cliick on Kill Sellected or try thee next TIP:
TIIP: The checkb
box beside the expression allows you to
tem
mporarily unseelect or disablee a Watchpointt without deletiing it.
TIIP: Raw addreesses can also be
b entered into the Logic Anaalyzer.
Ann example is: *((unsigned lo
ong *)0x20000000)
Shhown above rig
ght is the Logicc Analyzer win
ndow displayin
ng the variable value triggeer point of 0x5. This is three runs.

11

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

16) RTX_B
Blinky Exa
ample Pro
ogram with Keil RTX
X RTOS: A Stepperr Motor ex
xample
Keil provides RT
TX, a full featu
ure RTOS. RT
TX is included as part of Keill MDK includinng source. Thiis example expplores the
RT
TX RTOS projject. MDK willl work with an
ny RTOS. An RTOS is just a set of C functtions that gets compiled withh your
prroject. RTX co
omes with a BS
SD type licensee and source co
ode is providedd with all versiions of MDK.
NOTE: RTX_B
Blinky supplied
d with MDK 5 is a two task project
p
that blinnks one LED. Supplied withh this documentt is an
RT
TX_Blinky thaat has fours tasks and lights four
fo LEDs. It is more interestting.
RT
TX and all its components
c
arre located here:: C:\Keil_v5\A
ARM\Pack\AR
RM\CMSIS\3.220.4\CMSIS_R
RTX.
Yoou must have copied
c
RTX_B
Blinky5 to C:\M
MDK\Boards\S
ST\STM32F4-D
Discovery\ as ddescribed on paage 4.
1.

With V
Vision in Edit mode (not in debug
d
mode): Select Project//Open Project.

2.

Open th
he file C:\MDK
K\Boards\ST\S
STM32F4-Disccovery\RTX_B
Blinky5\Blinky.uvprojx.

3.

If the Update
U
Config
guration Files window open
ns, select Canccel.

4.

This project is pre-con


nfigured for th
he ST-Link V2 debug adapterr.

5.

g on the Rebuilld icon.


Compille the source fiiles by clicking

6.

To prog
gram the Flash
h manually, clicck on the Load
d icon.

7.

Enter th
he Debug mode by clicking on
o the debug iccon

8.

The fou
ur LEDs will blink in successsion simulating
g the signals fo r a stepper motor.

. They will com


mpile with no eerrors or warninngs.
. A pprogress bar w
will be at the boottom left.
and cliick on the RUN
N icon.

TIP: If you
u are using a STM32F401C
S
C-DISCO boarrd and the LED
nk, you might have the clock
k
Ds do not blin
frequency set
s too high. See
S the instrucctions on pagee 3 under STM
M32F401C-DIISCO Discoverry Board:.
9.

Click on STOP

W
We will explore the operation of RTX with th
he Kernel Awaareness window
ws.
Th
he Configuration Wizar
rd for RTX:

1.

Click on the RTX_Co


onf_CM.c sourrce file tab as sh
hown below onn the left. Youu can open it w
with File/Open if needed.

2.

Click on the Configurration Wizard tab


t at the botto
om and your vi ew will changee to the Configguration Wizard.

3.

Open up
u the individuaal directories to
o show the various configuraation items avaiilable.

4.

See how
w easy it is to modify
m
these seettings here as opposed to finnding and channging entries inn the source codde.

5.

Changing an attributee in one tab chaanges it in the other


o
automaticcally. You shoould save a moodified window
w.

6.

You can
n create Config
guration Wizarrds in any sourrce file with thee scripting langguage as used iin the Text Ediitor.

7.

This scrripting languag


ge is shown below in the Tex
xt Editor as com
mments startingg such as a </hh> or <i>.
See ww
ww.keil.com/su
upport/docs/273
35.htm for insttructions.

Text Editor: Source Codee

Configguration Wizaard
12

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

17) RTX Kernel


K
Awa
areness using
u
Seria
al Wire Vi ewer (SW
WV):
Users often wan
nt to know the number
n
of the current
c
operatiing task and thee status of the other tasks. Thhis informationn is
ussually stored in
n a structure or memory area by
b the RTOS. Keil provides a Task Awaree window for R
RTX. Other RT
TOS
coompanies also provide
p
awaren
ness plug-ins for
f Vision.
1.

Run RT
TX_Blinky by clicking on thee Run icon.

2.

Open Debug/OS
D
Supp
port and select System and Th
hread
Viewerr and the windo
ow on the rightt opens up. Yo
ou might
have to grab the wind
dow and move it
i into the center of the
screen. These values are updated in
n real-time usin
ng the
same reead write techn
nology as used in the Watch and
a
Memorry windows.

Im
mportant TIP:: View/Period
dic Window Up
pdate must be selected
s
!
3.

Open Debug/OS
D
Supp
port and select Event Viewer. There
is probaably no data diisplayed because SWV is not configured.

RT
TX Viewer: Configuring
g Serial Wir
re Viewer (S
SWV):

W
We must activatte Serial Wire Viewer
V
to get the
t Event View
wer working.
1.

Stop the CPU and exiit debug mode.

2.

Click on the Target Options


O
icon

3.

Click th
he Settings box
x next to ST-Liink Debugger.

4.

In the Debug
D
window
w, make sure Po
ort: is set to SW
W and
not JTA
AG. SWV worrks only with SW
S mode.

5.

Click on the Trace tab


b to open the Trace
T
window.

6.

Set Corre Clock: to 16


68 MHz (84 forr STM32F401 board)
and seleect Trace Enab
ble.

7.

Unselecct the Periodic and EXCTRC


C boxes as show
wn:

8.

ITM Sttimulus Port 31


1 must be check
ked. This is th
he
method
d the RTX View
wer gets the keernel awarenesss
informaation out to be displayed in th
he Event Viewer.
It is slig
ghtly intrusive..

9.

Click on OK twice to return to Vission.


The Serial Wire View
wer is now conffigured !

next to the target box. Sellect the Debug tab.

10. Enter Debug


D
mode an
nd click on RUN
N.
11. Select Tasks

and Sysstem tab: the display


d
is updaated.
12. Click on the Event Viiewer tab.
13. This wiindow displayss task events in
n a graphical
format as shown in th
he RTX Kernel window below
w.
You pro
obably have to
o change the Raange to about 0.1
0
sec by clicking
c
on thee Zoom ALL an
nd + and icon
ns.
TIIP: If Event Viewer doesnt work,
w
open up the Trace
Reecords and con
nfirm there are good ITM 31 frames presentt. Is
Coore Clock correct ? This projject is running at 168 or 84 MHz
M
deepending on the board you are using.
Cortex-M3 Alerrt: Vision wiill update all RTX informatio
on in real-time oon a target boaard due to its reead/write capabbilities as
alrready describeed. The Event Viewer
V
uses IT
TM and is sligh
htly intrusive.
Thhe data is updaated while the program
p
is runn
ning. No instrrumentation co de needs to be inserted into yyour source. Y
You will
finnd this feature very useful ! Remember,
R
RT
TX with sourcee code is includded with all veersions of MDK
K.
TIIP: You can use
u a ULINK2, ULINK-ME, ULINKpro, ST
T-Link V2 or JJ-Link for thesee RTX Kernel Awareness wiindows.
13

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

18) Logic Analyzer Window: View variiables rea


al-time in a graphic
cal formatt:
V
Vision has a grraphical Logic Analyzer wind
dow. Up to fou
ur variables can
an be displayedd in real-time uusing the Seriall Wire
Viiewer in the ST
TM32. RTX_B
Blinky uses fou
ur tasks to creaate the waveforrms. We will ggraph these fouur waveforms.
1.

Close th
he RTX Vieweer windows. Stop the program
m

and exitt debug mode.

2.

Add 4 global
g
variablees unsigned int
i
phasea through
t
unsig
gned int pha
ased to Blinky
y.c as shown here:

3.

Add 2 lines
l
to each off the four threaads phaseA thro
ough phaseD inn Blinky.c as sshown
below: phasea=1; and
d phasea=0;. The first two lines are shownn added near linnes 50
and 53 (just after the LED_On
L
and LED_Off
L
functtion calls). Forr each of the thhree
remainiing threads, ad
dd the correspon
nding statemen
nts phaseb, phaasec and phaseed.

4.

Select File/Save
F
All or
o click

5.

Rebuild
d the project.

6.

Enter debug
d
mode

7.

You can
n run the progrram at this poin
nt.

8.

Open View/Analysis
V
Windows and select Logic Analyzer
A
or seleect the LA

t Flash
Program the

window
w on the toolbaar.
En
nter the Var
riables into the Logic Analyzer (LA
A):

9.

Click on the Blinky.c tab. Right clicck on phasea, select Add phhasea
to an
nd finally selectt Logic Analyzzer. Phasea wiill be added to the LA.

10. Repeat for phaseb, phasec


p
and ph
hased. These variables will be listed on th
he left side of thhe LA window
w as shown.
Now we
w have to adjusst the scaling.
TIIP: If you cant get these varriables entered into the LA, make
m
sure the T
Trace Config iss set correctly. The Serial Wiire Viewer
must be configu
ured correctly in
n order to enterr variables in the
t LA.
Thhe Logic Analy
yzer can displaay static and global variables,, structures andd arrays.
IIt cant see locaals: just make them
t
static or global.
g
To see peripheral reggisters read or w
write to them aand enter them in the LA.
11. Click on the Setup ico
on and click on
n each of the fo
our variables annd set Max. in the Display Raange: to 0x3.
12. Click on Close to go back
b
to the LA
A window.
13. Using the
t All, OUT and
a In buttons set
s the range to
o 0.2 second orr so. Move thee scrolling bar tto the far right if needed.

14. Select Signal


S
Info and
d Show Cycles. Click to marrk a place movee the cursor to get timings. P
Place the cursoor on one
of the waveforms
w
and
d get timing and
d other informaation as shownn in the insertedd box labeled pphasec:
15. Click on Stop in Updaate Screen to sttop (and start) the data collecction.
TIIP: You can allso enter these variables into the Watch and
d Memory winddows to displayy and change thhem in real-tim
me.
TIIP: You can viiew signals thaat exist mathem
matically in a vaariable and nott available for measuring in tthe outside worrld.
14

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

19) ITM (I
Instrumen
ntation Tr
race Macro
ocell) ITM
M uses Serrial Wire Viiewer.
Reecall that we sh
howed you can
n display inform
mation about th
he RTOS in reaal-time using tthe RTX Vieweer. This is donne through
IT
TM Stimulus Port 31. ITM Port 0 is availab
ble for a printf type of instrum
mentation that requires minim
mal user code. After the
wrrite to the ITM
M port, zero CPU
U cycles are reequired to get the
t data out of the processor aand into Vision for display in its
Debug (printf) Viewer
V
window
w. Note: the global variable value
v
from 12)) Watch and M
Memory Wind
dows must bbe entered
annd compiled in Blinky.c in orrder for this exeercise to work.
1.

Stop the program if it is running

2.

Open th
he project C:\M
MDK\Boards\S
ST\STM32F4-D
Discovery\Blinnky\Blinky.uvpprojx. (do not uuse RTX_Blinkky).

3.

Add thiis code to Blink


ky.c. A good place
p
is near lin
ne 19, just afteer the #include "LED.h".
#define ITM
M_Port8(n)

4.

and exit Debu


ug mode.

(*((volatile
e unsigned ch
har *)(0xE000
00000+4*n)))

In the main
m function in
i Blinky.c afteer the second Delay(200);
D
neaar line 72, enteer these lines:
ITM_Port8(0
0) = value + 0x30;

/*
* displays va
alue in ASCII
I */

while (ITM_
_Port8(0) == 0);
ITM_Port8(0
0) = 0x0D;
while (ITM_
_Port8(0) == 0);
ITM_Port8(0
0) = 0x0A;

5.

Rebuild
d the source filles, program th
he Flash memorry and enter deebug mode.

6.

Open Select
S
Target Options
O

7.

Configu
ure the Serial Wire
W Viewer ass described on page 10. Use 168 MHz for tthe Core Clockk.

8.

Unselecct On Data R/W


W Sample, EXCTRC and PC
C Sample. (this is to help not ooverload the SW
WO port)

9.

Select ITM
I
Port 0. IT
TM Stimulus Port
P 0 enabless the Debug (pprinftf) Viewerr.

or ALT-F7 and select the Debuug tab, and thenn the Trace tab.

10. Click OK
O twice. Enteer Debug modee.
11. Click on View/Serial Windows and select Debug (printf)
(
Viewerr and click on R
RUN.
12. In the Debug
D
(printf) Viewer you wiill see the ASC
CII of value apppear.
13. As valu
ue is incrementted its ASCII character
c
is disp
played.
Trrace Record
ds

1.

Open th
he Trace Recorrds if not alread
dy open. Doub
ble click on it tto clear it.

2.

You wiill see a window


w such as the one
o below with
h ITM and Excception frames..

W
What Is This ?

You can see thee ITM writes and


a Data writes (value beiing displayed in the LA).
1. ITM 0 frames (Num column)
c
are ou
ur ASCII characters from vallue with carriagge return (0D) and line feed ((0A) as
yed the Data column.
display
2.

All thesse are timestam


mped in both CPU
C
cycles and
d time in secondds.

3.

When you
y are done, stop
s
the processor and exit deebug mode.

IT
TM Conclusion

Thhe writes to ITM Stimulus Po


ort 0 are intrusiive and are usu
ually one
cyycle. It takes no
n CPU cycles to get the data out the processsor and
to your PC via th
he Serial Wire Output (SWO) pin.
TIIP: It is importtant to select as few options in
i the Trace
coonfiguration as possible to avoid overloadin
ng the SWO pin
n. Enter
onnly those featurres that you reaally need.
Su
uper TIP: ITM
M_SendChar iss a useful functtion you can usse to send
IT
TM characters. It is found in the header corre.CM3.h.
Su
uper TIP: To see
s how to usee printf in your code, see the DSP
D example.
15

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

20) Serial Wire Viewer (SWV) and how to use it:


1) Data Reads and Writes: (Note: Data Writes but not Reads are enabled in the current version of Vision).

You have already configured Serial Wire Viewer (SWV) on page 13 under RTX Viewer: Configuring the Serial Wire Viewer:
Now we will examine some of the features available to you. SWV works with Vision and ST-Link V2, ULINK2/ME,
ULINKpro or a Segger J-Link V6 or higher. SWV is included with MDK and no other equipment must be purchased.
Everything shown here is done without stealing any CPU cycles and is completely non-intrusive. Your program runs at full
speed and needs no code stubs or instrumentation software added to your source code. Screens are shown using a ST-Link.
1.

Use RTX_Blinky5 from the previous exercise. Enter Debug mode and Run the program if not already running.

2.

Select View/Trace/Records or click on the Trace icon

3.

The Trace Records window will open up as shown here:

4.

The ITM frames are the data from the RTX Kernel Viewer which uses Port 31 as shown under Num. here:

5.

To turn this off, select Debug/Debug Settings and click on the Trace tab. Unselect ITM Stimulus Port 31.
TIP: Port 0 is used for Debug printf Viewer.

6.

Unselect EXCTRC and Periodic.

7.

Select On Data R/W Sample.

8.

Click on OK twice to return.

and select Records.

TIP: If the SWV trace fails to work properly after this


change, exit Debug mode, cycle the power to the Discovery
board and re-enter Debug mode.
If you are using the STM32F401 board see page 3.
9.

Click on the RUN icon.

10. Double-click in Trace Records window to clear it.


11. Only Data Writes will appear now.
TIP: You could have right clicked on the Trace Records
window to filter the ITM frames out. Unselecting a feature
is better as it reduces SWO pin traffic and trace overflows.
What is happening here ?
1.

When variables are entered in the Logic Analyzer


(remember phasea ?), the reads and/or writes will
appear in Trace Records.

2.

The Address column shows where the variable is.

3.

The Data column displays the data values written


to phasea.

4.

PC is the address of the instruction causing the


writes. You activated it by selecting On Data R/W
Sample in the Trace configuration window.

5.

The Cycles and Time(s) columns are when these


events happened.

TIP: You can have up to four variables in the Logic


Analyzer and subsequently displayed in the Trace Records
window. You must have all Watchpoints off.
TIP: If you select View/Symbol Window you can see where
the addresses of the variables are located.
Note: You must have Browser Information selected in the Options for Target/Output tab to use the Symbol Browser.
TIP: ULINKpro and Segger J-Link adapters display the trace frames in a slightly different style trace window. The J-Link
currently does not display Data writes.
16

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

2) Exceptions and Interrupts:

The STM32 family using the Cortex-M4 processor has many interrupts and it can be difficult to determine when they are
being activated and how often. Serial Wire Viewer (SWV) on the STM32 family makes this task easy.
1.

Stop the RTX_Blinky example program. Be in Debug mode. Open Debug/Debug Settings and select the Trace tab.

2.

Unselect On Data R/W Sample, PC Sample and ITM Ports 31 and 0. (this is to minimize overloading the SWO port)

3.

Select EXCTRC as shown here:

4.

Click OK twice.

5.

Double click on Trace Records to clear it.

6.

Click RUN to start the program.

TIP: If the SWV trace fails to work properly after this


change, exit and re-enter Debug mode.
7.

You will see a window similar to the one below


with Exceptions frames displayed.

.What Is Happening ?
1.

You can see two exceptions happening.

Entry: when the exception enters.

Exit: When it exits or returns.

Return: When all the exceptions have


returned to the main program. This is useful
to detect tail-chaining.

2.

Num 11 is SVCall from the RTX calls.

3.

Num 15 is the Systick timer.

4.

In my example you can see one data write from


the Logic Analyzer.

5.

Note everything is timestamped.

6.

The X in Ovf is an overflow and some data was


lost. The X in Dly means the timestamps are
delayed because too much information is being
fed out the SWO pin. Always limit the SWV features to only those you really need.

TIP: The SWO pin is one pin on the Cortex-M4 family processors that all SWV information is fed out. There are limitations
on how much information we can feed out this
one pin. These exceptions are happening at a
very fast rate. Vision easily recovers gracefully
from these overflows. Overflows are shown
when they happen. Using a ULINKpro helps
reduce overruns, especialy if the 4 bit Trace Port
connection is used rather than the 1 bit SWO pin.
1.

Select View/Trace/Exceptions or click on the Trace icon and select Exceptions.

2.

The next window opens up and more information about the exceptions is displayed as shown below:

3.

Note the number of times these have happened under Count. This is very useful information in case interrupts come
too fast or slow. Click on Count to bring the most active exceptions to the top of the window.

4.

ExtIRQ are the peripheral interrupts.

5.

You can clear this trace window by double-clicking on it.

6.

All this information is displayed in real-time and without stealing any CPU cycles or stubs in your code !

TIP: Num is the exception number: RESET is 1. External interrupts (ExtIRQ), which are normally attached to peripherals,
start at Num 16. For example, Num 41 is also known as 41-16 = External IRQ 25. Num 16 = 16 16 = ExtIRQ 0.
17

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

3) PC Samples:

Serial Wire Viewer can display a sampling of the program counter.


SWV can display at best every 64th instruction but usually every 16,384 is more common. It is best to keep this number as
high as possible to avoid overloading the Serial Wire Output (SWO) pin. This is easily set in the Trace configuration.
1.

Open Debug/Debug Settings and select the Trace tab.

2.

Unselect EXCTRC, On Data R/W Sample and select Periodic in the PC Sampling area.

3.

Click on OK twice to return to the main screen.

4.

Close the Exception Trace window


and leave Trace Records open.
Double-click to clear.

5.

Click on RUN and this window


opens:

6.

Most of the PC Samples in the


example shown are 0x0800_055A
which is a branch to itself in a loop
forever routine.
Note: the exact address you get
depends on the source code and the
compiler settings.

7.

Stop the program and the


Disassembly window will show this Branch as shown below:

8.

Not all the PCs will be captured. Still, PC Samples can give you some idea of where your program is; especially if it
is not caught in a tight loop like in this case.

9.

Set a breakpoint in one of the tasks.

10. Run the program and when the breakpoint


is hit, you might see another address at the
bottom of the Trace Records window. See
the screen below:
11. Scroll to the bottom of the Trace Records window and you might (probably not) see the correct PC value displayed.
Usually, it will be a different PC depending on when the sampling took place.
12. To see all the instructions executed, you can use the ETM instruction trace with a ULINKpro.
13. Remove the breakpoint.
14. Stop the program.
15. Leave Debug mode.

18

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

21) Serial Wire View


wer (SWV
V) Configu
uration wiindow: (ffor referen
nce)
Thhe essential plaace to configurre the trace is in
n the Trace tab
b as shown beloow. You cannnot set SWV gloobally for Vision. You
m
must configure SWV
S
for every
y project and ad
dditionally for every target seettings within a project you w
want to use SW
WV. This
coonfiguration infformation will be saved in the project. Theere are two wayys to access thiis menu:
A. In Editt mode: Select Target Option
ns
or ALT
T-F7 and selectt the Debug tabb. Select Settinngs: on the righht side of
this win
ndow and then the Trace tab. Edit mode is selected by de fault when youu start Visionn.
B. In Debug mode: Sellect Debug/Deb
bug Settings an
nd then select tthe Trace tab. Debug mode iis selected withh

1) Core Clock:
C
The CP
PU clock speed
d for
SWV. The CPU speeed can be found
d in
your staartup code or in
n Abstract.txt. It is
usually called SYSCL
LK or Main Clo
ock.
This mu
ust be set correectly for all
adapterrs except ULIN
NKpro.
2) Trace Enable:
E
Enables SWV and ITM.
I
It can only
o
be changed
d in Edit modee.
This do
oes not affect th
he Watch and
Memorry window disp
play updates.
3) Trace Port:
P
This is preset
p
for ST-L
Link.
4) Timesttamps: Enablees timestamps and
a
selects the Prescaler. 1 is the defaullt.
5) PC Sam
mpling: Samplles the program
m
counterr:
a. Prescaler 10
024*16 (the default) means ev
very 16,384th P
PC is displayedd. The rest aree not collected.
b. Periodic: En
nables PC Sam
mpling.
c. On Data R/W
W Sample: Diisplays the add
dress of the insttruction that caaused a data read or write of a variable
listed in the Logic
L
Analyzeer. This is not connected
c
withh PC Sampling but rather withh data tracing.
6) ITM Sttimulus Ports: Enables the thirty-two
t
32 bit
b registers useed to output daata in a printf tyype statement tto
Vision
n. Port 31 (a) is used for the Keil RTX Vieewer which is a real-time kernnel awareness window. Port 0 (b) is
used for the Debug (p
printf) Viewer. The rest are currently
c
unuseed in Vision.

Enable: Dissplays a 32 bit hex number in


ndicating whichh ports are enaabled.

d by an RTOS to specify whicch ITM ports ccan be used byy a user program
m.
Privilege: Prrivilege is used
E
Enablles various CPU
U counters. All
A except EXC
CTRC are 8 bit counters. Each counter is cuumulative
7) Trace Events:
and an event is created when this co
ounter overflow
ws every 256 cyycles. These vvalues are displlayed in the Coounter
window
w. The event created when a counter wraps around is dispplayed in the Innstruction Tracce window.
a. CPI: Cycless per Instructiion: The cumullative number of extra cycless used by each instruction beyyond the
first, one including any insttruction fetch stalls.
s
b. Fold: Cumullative number of folded instru
uctions. Thesee results from a predicted braanch instructionn where
unused instru
uctions are rem
moved (flushed
d) from the pipeeline giving a zzero cycle execcution time.
c. Sleep: Cum
mulative number of cycles the CPU is in sleeep mode. Usess FCLK for tim
ming.
d. EXC: Cumu
ulative cycles CPU
C
spent in exception
e
overhhead not includding total timee spent processiing the
exception co
ode. Includes stack
s
operation
ns and returns.
e. LSU: Cumu
ulative numberr of cycles spen
nt in load/store operations beyyond the first ccycle.
f. EXCTRC: Exception Traace. This is diffferent than thee other items inn this section. T
This enables thhe display
d Exception wiindows. It is nnot a counter. T
This is a very uuseful
of exceptions in the Instrucction Trace and
feature to dissplay exception
n events and iss often used in debugging.
TIIP: Counters will
w increment while single sttepping. This can provide soome very usefuul information. You can readd these
coounters with yo
our program as they are memo
ory mapped.
19

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

22) DSP SINE


S
exam
mple using
g ARM CMS
SIS-DSP L
Libraries:
AR
RM CMSIS-D
DSP libraries arre offered for ARM
A
Cortex-M
M3 and Cortex--M4 processorss. DSP librariees are providedd in MDK
inn C:\Keil_v5\ARM\Pack\ARM
M\CMSIS. Seee www.arm.com/cmsis for m
more informatioon. CMSIS is aan acronym forr Cortex
M
Microcontroller Software Interrface Standard.. CMSIS is an ARM standardd.
Thhis example creates a sine waave with noise added, and theen the noise is ffiltered out. T
The waveform iin each step is displayed
inn the Logic Anaalyzer using Seerial Wire View
wer.
Thhis example incorporates Keiil RTX RTOS. RTX is availaable free with a BSD type liccense. RTX source code is prrovided.
Too obtain this ex
xample file, go
o to www.keil.ccom/appnotes/docs/apnt_2330.asp Extractt DSP to \ST
TM32F4-Discoovery\.
1.

Open th
he project file sine:
s
C:\Keil\A
ARM\Boards\S
ST\STM32F4-D
Discovery\DSP
P\sine.uvproj

2.

Build th
he files.

3.

Program
m the STM32 flash
f
by clickin
ng on the Load
d icon:

4.

Enter Debug
D
mode by
y clicking on th
he Debug icon.

5.

Click on the RUN ico


on.

6.

Four waveforms will be displayed in


n the Logic An
nalyzer using thhe Serial Wire Viewer as shoown below. Addjust
Zoom Out
O for an apprropriate display
y. Displayed are
a 4 global varriables: sine, nnoise, disturbedd and filtered.

There will be no
n errors or waarnings.
Proggress will be inndicated in thee Output Windoow.

Select O
OK if the Evaluation Mode boox appears.

Open the Logic Anaalyzer window..

TIIP: If one variaable shows no waveform, dissable the ITM Stimulus


S
Port 331 in the Tracee Config windoow.
7.

The pro
oject provided has Serial Wirre Viewer confi
figured and the Logic Analyzer loaded withh the four variabbles.

8.

Open th
he Trace Recorrds window an
nd the Data Wriites to the fourr variables are llisted as shownn here:

9.

You can
n right click in
n this window and
a deselect IT
TM Events to gget only Data W
Writes displayeed.

10. Leave the


t program ru
unning.
11. Close th
he Trace Recorrds window.
TIIP: The ULINK
Kpro trace disp
play is differen
nt
annd the program
m must be stopp
ped to update itt.
Thhe Watch 1 win
ndow will disp
play the four
vaariables updatin
ng in real time as shown
beelow:

20

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

Signal Timings in Logic Analyzer (LA):

1.

In the LA window, select Signal Info, Show Cycles, Amplitude and Cursor.

2.

Click on STOP in the Update Screen box. You could also stop the program but leave it running in this case.

3.

Click somewhere in the LA to set a reference cursor line.

4.

Note as you move the cursor various timing information is displayed as shown below:

RTX Tasks and System:

5.

Click on Start in the Update Screen box to resume the collection of data.

6.

Open Debug/OS Support and select System and Thread Viewer. A window similar to below opens up. You probably
have to click on its header and drag it into the middle of the screen.

7.

Note this window does not update: nearly all the processor time is spent in the idle daemon: it shows it is Running.
The processor spends relatively little time in the other threads. You will see this illustrated clearly on the next page.

8.

Set a breakpoint in four of the threads in DirtyFilter.c by clicking in the left margin on a grey area.

9.

Click on Run and the program will stop at each thread in turn and the Thread Viewer window will be updated
accordingly. Here, I set a breakpoint in the disturb_gen thread:

10. Clearly you can see that disturb_gen was running when the breakpoint was activated.
11. Remove the breakpoints. Click on them or enter Ctrl-B and select Kill All.
TIP: You can set hardware breakpoints
while the program is running.
TIP: Recall this window uses the CoreSight
DAP read and write technology to update this
window. Serial Wire Viewer is not used and
is not required to be activated for this window
to display and be updated.
The Event Viewer does use SWV and this is
demonstrated on the next page.

21

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

Event Viewer:
1.

Stop the program. Click on Setup... in the Logic Analyzer. Select Kill All to remove all variables. This is necessary
because the SWO pin will likely be overloaded when the Event Viewer is opened up. Inaccuracies might occur. If
you like you can leave the LA loaded with the four variables to see what the Event Viewer will look like.

2.

Select Debug/Debug Settings.

3.

Click on the Trace tab.

4.

Enable ITM Stimulus Port


31. Event Viewer uses this
to collect its information.

5.

Click OK twice.

6.

Click on RUN.

7.

Open Debug/OS Support


and select Event Viewer.
The window here opens up:

8.

Note the main(1) thread.


This screen is scrolled to the
beginning after RESET.
Main() runs only once.

Important TIP: If SWV trace fails to work after this change, exit Debug, cycle the board power and re-enter Debug mode.
TIP: If Event Viewer is blank or erratic, or the LA variables are not displaying or blank: this is likely because the Serial Wire
Output pin is overloaded and dropping trace frames. Solutions are to delete some or all of the variables in the Logic Analyzer
to free up some bandwidth.
ULINKpro is much better with SWO bandwidth issues. These have been able to display both the Event and LA windows.
ULINKpro uses the faster Manchester format than the slower UART mode that ST-Link, ULINK2 and J-Link uses.
ULINKpro can also use the 4 bit Trace Port for faster operation for SWV. The Trace Port is mandatory for ETM trace.
9.

Note on the Y axis each of the 5 running tasks plus the idle daemon. Each bar is an active task and shows you what
task is running, when and for how long.

10. Click Stop in the Update Screen box.


11. Click on Zoom In so three or four tasks are displayed.
12. Select Cursor. Position the cursor over one set of bars and click once. A red line is set at the first arrow:
13. Move your cursor to the right over the
next set (where the second arrow is) and
total time and difference are displayed.
14. Note, since you enabled Show Cycles, the
total cycles and difference is also shown.
The 10 msec shown is the SysTick timer value.
This value is set in RTX_Conf_CM.c . The next
page describes how to change this.
TIP: ITM Port 31enables sending the Event
Viewer frames out the SWO port. Disabling this
can save bandwidth on the SWO port if you are not
using the Event Viewer.

22

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

Ev
vent Viewer
r Timing:

1.

Click on Zoom In unttil one set of tasks is visible as


a shown below
w:

2.

Enable Task Info (as well


w as Cursorr and Show Cyccles from the pprevious exerciise).

3.

Note on
ne entire sequeence is shown. This screen iss taken with ST
T-Link V 2withh LA cleared of variables.

4.

Click on a task to set the cursor and move it to the end. The timee difference is noted. The Taask Info box w
will appear.

TIIP: If the Even


nt Viewer does not display co
orrectly, the dissplay of the varriables in the L
Logic Analyzerr window mighht be
ovverloading the SWO pin. In th
his case, stop the
t program an
nd delete all varriables (Kill A
All) and click onn Run.

Thhe Event View


wer can give you
u a good idea if
i your RTOS is
i configured ccorrectly and ruunning in the right sequence.
Ch
hanging the
e SysTick Tim
mer Value:

and exit debu


ug mode.

1.

Stop the processor

2.

Open th
he file RTX_Conf_CM.c from
m the Project window.
w
You ccan also select File/Open in
C:\Keill\ARM\Boards\ST\STM32F4
4-Discovery\DS
SP.

3.

Select the
t Configuratiion Wizard tab
b at the bottom of the window
w. See page 122 for an explanaation on how thhe Wizard
works.

4.

This wiindow opens up


p. Expand SyssTick Timer Co
onfiguration.

5.

Note th
he Timer tick value is 1000 ussec or 1 msec.

6.

Changee this value to 2,000.


2

TIIP: The 5,376,,000 is the CPU


U speed. The Discovery
D
boarrd has a 8 MHzz
crrystal. This pro
ogram was designed for 168 MHz
M with a 25
5 MHZ crystal..
Thherefore it runss 8/25 slower th
han designed for.
f
The PLL is
i configured inn
CM
MSIS file systeem_stm32f4xx
x.c and is easily
y modified.
7.

Rebuild
d the source filles and program
m the Flash.

8.

Enter debug
d
mode

9.

When you
y check the timing
t
of the taasks in the Eveent Viewer winndow as you diid on the previoous page, they will now
be spacced at 2 msec.

and click on RUN

TIIP: The SysTicck is a dedicateed timer on Co


ortex-M processors that is useed to switch tassks in an RTOS
S. It does this by
geenerating an ex
xception 15. You
Y can view th
hese exceptionss in the Trace R
Records windoow by enablingg EXCTRC in tthe Trace
Coonfiguration window.
w
1.

Sett the SysTick timer back to 1,000. You willl need to recom
mpile the sourcce files and repprogram the Flaash.

2.

Cliick on File/Sav
ve All or selectt the Save All icon:
i

Th
This ends thee exercises. Thank you !
Next is how to make
m
a new pro
oject from scraatch, how ETM
M trace works annd Keil producct and contact iinformation.
23

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

23) Creating your own MDK 5 project from scratch:


All examples provided by Keil are pre-configured. All you have to do is compile them. You can use them as a template for
your own projects. However, we will start an example project from the beginning to illustrate how easy this process is. Once
you have the new project configured; you can build, load and run a bare Blinky example. It will have an empty main()
function so it does not do much. However, the processor startup sequences are present and you can easily add your own
source code and/or files. You can use this process to create any new project, including one using an RTOS.
Install the STM32 Software Pack for your processor:
1.

Start Vision and leave in Edit mode. Do not be in Debug mode.

2.

Pack Installer: The Pack for the STM32F4 processor must be installed. This has already been done on page 4.

3.

You do not need to copy any examples over.

Create a new Directory and a New Project:


1.

Click on Project/New Vision Project

2.

In the window that opens, shown below, go to the


folder C:\MDK\Boards\ST\STMF32F4-Discovery\

3.

Right click in this window and select New and


create a new folder. I called it BlinkyNEW.

4.

Double click on BlinkyNew to open it or highlight


it and select Open.

5.

In the File name: box, enter Blinky. Click on Save.

6.

This creates the project Blinky.uvproj in C:\MDK\Boards\ST\STMF32F4-Discovery\BlinkyNEW.

7.

As soon as you click on Save, the next window opens:

Select the Device you are using:


1.

Expand STMicroelectronics, then STM32F4 Series, then STM32F407 and then finally
select STM32F407VG:

TIP: Processor icons in green are from the Software Packs. Grey icons are from MDK 4.7x.
2.

Click OK and the Manage Run Time window shown below bottom right opens.

Select the CMSIS components you want:


1.

Expand all the items and select CORE and Startup as shown below. They will be
highlighted in Green indicating there are no other files needed. Click OK.

2.

Click on File/Save All or select the Save All icon:

3.

The project Blinky.uvproj will now be changed to Blinky.uvprojx.

4.

You now have a new project list as shown on the bottom left below: The appropriate CMSIS files you selected have
been automatically entered and configured.

5.

Note the Target Selector says Target 1. Highlight Target 1 in the Project window.

6.

Click once on it and change its name to CMSIS-DAP and press Enter. The Target selector name will also change.

What has happened to this point:


You have created a blank Vision project using MDK 5 Software
Packs. All you need to do now is add your own source files.

24

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

Create a blank C Source Filee:


c
on Sourcee Group 1 in the Project wind
dow and select
1. Right click
2.

This wiindow opens up


p:

3.

Highlig
ght the upper leeft icon: C filee (.c):

4.

In the Name:
N
field, en
nter Blinky.

5.

Click on Add to closee this window.

6.

Click on File/Save Alll or

7.

Expand
d Source Grou
up 1 in the Project window
and Bliinky.c will now
w display.

8.

It will also
a open in thee Source windo
ow.

Add Some Code to Blinky.c:


9.

In the blank
b
Blinky.c,, add the C cod
de below:

10. Click on File/Save Alll or


11. Build th
he files.

n errors or waarnings if all w


was entered corrrectly.
There will be no
#include "stm32f4xx.h"
unsigned int counter = 0;
--------------------------------------/*------MAIN fu
unction
*---------------------------------------------*/
int main (void) {
while(1
1) {
counter++;
if (counter > 0x0F) counter = 0;
}
}

a add existin
ng source files:
TIIP: You can also

N
No need to at thhis time.

Configure the Target


T
CMSIS
S-DAP: Please complete theese instruction s carefully to pprevent unusu
ual problems

1.

Select the
t Target Optiions icon

. Select the Ta
arget tab.

2.

Enter 8 in Xtal (MHz)). This is used


d for timing callculations. Select Use MicroL
LIB to optimizze for smaller ccode size.

3.

Select the
t Output tab
b. Click on Sellect Folder for Objects:

4.

In the Browse
B
for Folder window th
hat opens: rightt click and creaate a new foldeer called
Flash.

5.

h to enter this folder


f
and click
k OK. Compilaation files willl now be storedd in this Flash ffolder.
Doublee click on Flash

6.

Click on the Listings tab. Click on Select Folder for


f Objects: Double click on Flash and cclick OK to cloose.

7.

Click on
o the Debug tab.
t
Select St-L
Link Debuggerr in the Use: boox:

8.

Select the
t Settings: icon.

9.

Select SW
S as shown here
h in the Portt: box:
JTAG heere will not woork with SWV.. If your boardd is
connectted to your PC, you must now
w see a valid ID
DCODE and D
Device Name inn the SW Deviice box.

10. Click on OK once to go back to the Target Config


guration window
w. Otherwise,, fix the connecction problem.
11. Click on the Utilities tab. Select Seettings and Add
d the correct Fllash algorithm:: Shown is thee correct one foor the
STM32
2Fx series proccessors:
12. Click on OK twice to return to the main
m menu.
13. Click on File/Save Alll or
14. Build th
he files.

There
T
will be no
n errors or warrnings if all waas entered correectly. If there are, please fix them !

he Next Step ? Let us run your


y
program
m and see whatt happens ! Pllease turn the page.
Th
25

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

Ru
unning Your Program:
1.

Program
m the ST Flash
h by clicking on
n the Load icon
n:

2.

Enter Debug
D
mode by
y clicking on th
he Debug icon .

3.

Click on the RUN ico


on.

4.

No LED
Ds will blink siince there is no
o source to acccomplish this taask. You couldd add such codde yourself.

5.

Right click
c
on counterr in Blinky.c an
nd select Add counter to aand select Wattch 1.

6.

counterr should be upd


dating as shown
n here:

7.

You can
n also set a breeakpoint in Blin
nky.c and the program
p
shouldd stop at
this poiint if it is runniing properly. If
I you do this, remove
r
the breeakpoint.

8.

You should now be ab


ble to add yourr own source code to create a
meanin
ngful project.

Progresss will be indiccated in the Ouutput Window.

Note:: you stop the program with tthe STOP iconn.

TIIP: The Watch


h 1 is updated periodically,
p
no
ot when a variaable value channges. Since Bllinky is running very fast witthout any
tim
me delays inserrted, the valuess in Watch 1 will
w appear to ju
ump and skip ssequential valuues you know m
must exist.
Cllock Frequenccy: The CPU clock
c
speed is 53.76
5
MHz. To change it to 168 MHz:
1.

Open th
he file system_
_stm32f4xx.c.

2.

Locate the line #defin


ne PLL_M 25 as shown below
w:

3.

8
Changee the value to 8.

4.

Click on File/Save Alll or

5.

Build th
he files.

6.

The CP
PU speed is now
w 168 MHz.

TIIP: If PLL_M = 336 and PLL


L_Q = 4, then the
t clock speed
d is 84 MHz.
Clleaning up your Project: (y
you only need to
t do this oncee: this is not a ccritical step)
W
We modified thee folder where the output and
d listings files are
a stored. Thiis was in Stepss 3 through 7 onn the precedingg page. If
yoou did a Build before
b
this wass done, there will
w be files in your
y
project rooot directory. N
Now we want tthem
onnly in .\Flash.
1.

Exit V
Vision. Otherw
wise, you cant delete files thaat it still has oppen.

2.

Open Microsoft
M
Explo
orer and navigaate to:
C:\MD
DK\Boards\ST\\STMF32F4-Discovery\Blink
kyNEW\.

3.

Delete all files and folders except th


hese: (you can delete Flash a Build will reecreate it.)

4.

You can
n also leave an
ny backup or V
Vision files thaat identify youur computer to retain your setttings.

5.

Restart Vision. Hav


ving all compilaation files stored in the .\Flassh folder makes it cleaner.

TIIP: If you wan


nt to save or sen
nd the project files
f
to someon
ne, you can dellete the folder F
Flash to reducee file size. Thiis folder
annd its contents are easily reconstructed with a Build.

26

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

24) Creatiing your own


o
RTX MDK
M
5 pro
oject from
m scratch:
Thhe MDK Softw
ware Packs mak
kes it easy to configure an RT
TX project. Thhere are two veersions of RTX
X: The first com
mes with
M
MDK 4.7x and earlier.
e
The second comes with MDK 5.10 and later. Thiis second one iis CMSIS-RTO
OS compliant.
Coonfiguring RTX
X is easy in MDK
M
5.10 and later. These steeps use the sam
me configuratioon as in the preeceding Blinkyy example.
1.

Using the
t same examp
ple from the prreceding pagess, Stop the proggram

and E
Exit Debug moode.

2.

Select ST-Link
S
Flash::

3.

In Blink
ky.c, at the top
p, add this line: #include "cm
msis_os.h"

4.

Open th
he Manage Run
n-Time Enviro
onment window
w:

5.

Expand
d all the elemen
nts as shown heere:

6.

Select Keil
K RTX as sh
hown and click
k OK.

7.

Approp
priate RTX filees will be added
d to your projeect. See the Prooject window.

8.

Click on File/Save Alll or

Configure RTX
X:
1.

In the Project
P
window
w, expand the CMSIS
C
group.

2.

Doublee click on RTX


X_Conf_CM.c to
t open it.

3.

Select the
t Configuratiion Wizard tab
b: Select Expan
nd All.

4.

The win
ndow is display
yed here:

5.

Set Tim
mer clock valuee: to 16800000
00 as shown: (168
(
MHz)

6.

Unselecct User Timerss. Use defaultss for the other settings.


s

uild and Run Your RTX Prrogram:


Bu
1.

Build th
he files.

2.

Enter Debug
D
mode:

3.

Select Debug/OS
D
Sup
pport/System an
nd Thread View
wer. The
window
w below opens up.

4.

You can
n see two threaads: the main th
hread is the on
nly one
running
g. As you add more threads to
t create a real RTX
program
m, these will au
utomatically bee added to this window.

Program
P
the Flaash:

Click on th
he RUN icon.

W
What you have to do now:
1.

You mu
ust add the RTX framework into
i
your code and create youur threads to m
make this into a real RTX projject
configu
ured to your needs.

2.

See thee DSP5 and RT


TX_Blinky5 ex
xamples to use as templates annd hints.

3.

If you copy
c
Blinky.c from
f
the RTX_
_Blinky projecct, it will blink the LEDs. It hhas the RTX coode incorporateed into it.

4.

Getting
g Started MDK
K 5: Obtain th
his useful book
k here: www.keeil.com/mdk5//. It has very uuseful information on
implem
menting and maaintaining
RTX.

This comple
etes the exe
ercise of
crreating you
ur own RTX
X project
frrom scratch
h.

27

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

25) ETM Trace


T
Exam
mples:

Fo
or reference onlyNote:
o
MDK 5 has e
enhanced win
ndows and trig
iggers:

Thhese examples were run on th


he STM3240G-EVAL evaluaation board. Thhese are appliccable for the Keeil MCBSTM332F400
booard. These ex
xamples are inccluded for referrence. A ULIN
NKpro debug aadapter is requuired for ETM ooperation.
ET
TM provides serious debuggiing power as sh
hown on the neext few pages. It is worth thee small added ccost.
M
Most STM32 processors are ET
TM equipped.
1.

Connecct the ULINKp


pro to the STM
M3240G board using
u
the 20 piin CN13 Trace connector.

2.

Start V
Vision by click
king on its desk
ktop icon.

3.

Select Project/Open
P
Project.
P
Open C:\Keil\ARM\B
C
Boards\ST\STM
M3240G-EVA
AL\ Blinky_Ulpp\Blinky.uvprooj.

4.

Select TracePort
T
Instrruction Trace in
n the Target Options box as sshown here:

5.

Compille the source fiiles by clicking


g on the Rebuilld icon.

. Y
You can also uuse the Build iccon beside it.

6.

Program
m the STM32 flash
f
by clickin
ng on the Load
d icon:

Proogress will be iindicated in thee Output Winddow.

7.

Enter Debug
D
mode by
y clicking on th
he Debug icon.

8.

DO NO
OT CLICK ON
N RUN YET !!!!

9.

Open th
he Data Trace window
w
by cliccking on the sm
mall arrow besside the Trace W
Windows icon..

Select O
OK if the Evaluation Mode boox appears.

ne the Instruction Trace wind


dow as shown below:
b
This is a complete reccord of all the program flow since
10. Examin
RESET
T until Vision
n halted the pro
ogram at the staart of main() sinnce Run To m
main is selected in Vision.
11. In this case,
c
086 444 s shows the lasst instruction to
o be executed. (BX r0). In thhe Register winndow the PC w
will display
the valu
ue of the next instruction
i
to be
b executed (0x
x0800_0188 inn my case). Cliick on Single S
Step once.

12. The insstruction PUSH


H will display as
a shown on the last line in thhe trace window
w. Note the fuunction columnn diplsyas
the funcction where thee assembly isn
nstructions are located
l
with thhe start highlighhted in orange.
13. Scroll to
t the top of thee Instruction Trace
T
window to
t frame # 1. T
This is the
instructtion executed after
a
RESET.

first

TIIP: You can seet Trace Triggeers to start and stop the Tracee collection. Thhis allows
to save only the frames you aree interested in.

you

S
EVAL board connected to a ULINKpro ussing the
A STM3240G-E
speecial CoreSigh
ht 20 pin ETM
M connector:

28

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

3) Code Co
overage: For reference only
14. Click on the RUN ico
on.

After a second or so
o stop the progrram with the S
STOP icon.

15. Examin
ne the Disassem
mbly and Blink
ky.c windows. Scroll and nottice different ccolor blocks in the left marginn:
16. This is Code Coverag
ge provided by ETM trace. This
T indicates iff an instructionn has been execcuted or not.
Coolour blocks in
ndicate which assembly
a
instru
uctions have beeen executed.
1. Green: this assembly in
nstruction was executed.
2. Gray: th
his assembly instruction was not
n executed.
3. Orange: a Branch is alw
ways not taken
n.
4. Cyan: a Branch is alwaays taken.
5. Light Grray: there is no
o assembly insstruction at
this
t point.
6. RED: Brreakpoint is sett here.
7. Next insstruction to be executed.
e
o the right you
u can easily seee examples of each
e
type of
Inn the window on
Coode Coverage block
b
and if th
hey were execu
uted or not and if branches
were taken (or not).
n
W
Why was the braanch BCC alwaays taken resullting in 0x0800
0_1048 never bbeing executedd ? Or why thee branch BGE aat
0xx800_105C waas never taken ? You should devise tests to execute these instructions soo you can test tthem.
Coode Coverage tells
t
what assembly instructio
ons were execu
uted. It is impoortant to ensurre all assembly code producedd by the
coompiler is execcuted and tested
d. You do not want a bug or an unplanned circumstance tto cause a sequuence of untestted
innstructions to be executed. Th
he result could
d be catastrophiic as unexecuteed instructions cannot be testted. Some agenncies such
ass the US FDA require
r
Code Coverage
C
for ceertification.
Goood programm
ming practice reequires that theese unexecuted instructions bee identified annd tested.
Coode Coverage is
i captured by the ETM. Cod
de Coverage iss also availablee in the Keil Sim
mulator.
A Code Coverag
ge window is available
a
as sho
own below. Th
his window is aavailable in Viiew/Analysis/C
Code Coveragee. Note
yoour display may
y look differen
nt due to differeent compiler op
ptions.

29

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

4) Perform
mance Ana
alysis (PA
A): For refference onlly
Peerformance An
nalysis tells you
u how much tim
me was spent in
i each functionn. The data caan be provided by either the S
SWV PC
Saamples or the ETM.
E
If provid
ded by the SW
WV, the results will
w be statisticcal and more acccuracy is impproved with lonnger runs.
Sm
mall loops could be entirely missed.
m
ETM provides
p
comp
plete Performannce Analysis. Keil provides only ETM PA.
Keil provides Peerformance An
nalysis with thee Vision simu
ulator or with E
ETM and the U
ULINKpro. SW
WV PA is not ooffered.
Thhe number of total calls madee as well as thee total time speent in each funcction is displayyed. A graphiccal display is generated
foor a quick reference. If you arre optimizing for
f speed, work
k first on thosee functions takiing the longestt time to execute.
1.

Use thee same setup ass used with Code Coverage.

2.

Windows/Perrformance Anallysis. A windoow similar to thhe one below w


Select View/Analysis
V
will open up.

3.

Exit Deebug mode and


d immediately re-enter
r
it.
This clears thhe PA window
w and resets thee STM32 and reeruns it to
main() as before. Or select the Reseet icon in the PA
P window to cclear it. Run thhe program forr a short time.

4.

Expand
d some of the module
m
names as
a shown below
w.

5.

Note th
he execution information that has been colleected in this iniitial short run. Both times annd number of calls is
display
yed.

6.

We can
n tell that most of the time at this
t point in th
he program has been spent in the GLCD rouutines.

7.

Click on the RUN ico


on.

8.

Note th
he display chan
nges in real-tim
me while the pro
ogram Blinky iis running. Thhere is no need to stop the proocessor to
collect the information. No code stu
ubs are needed
d in your sourcee files.

9.

Select Functions
F
from
m the pull down
n box as shown
n here and noti ce the differennce.

10. Exit and re-enter Debug mode again


n and click on RUN.
R
Note th e different dataa set displayedd.
11. When you
y are done, exit
e Debug mod
de.

TIIP: You can allso click on thee RESET icon


but the processor
p
will sstay at the initiial PC and willl not run to maiin(). You
caan type g, main
n in the Comm
mand window to
o accomplish th
his.
W
When you click on the RESET
T icon, the Initiialization File .ini will no long
nger be in effecct and this can ccause SWV annd/or ETM
to stop working. Exiting and re-entering
r
Deb
bug mode execcutes the .ini sccript again.
30

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

5) Execution Profiling: For reference only


Execution Profiling is used to display how much time a C source line took to execute and how many times it was called. This
information is provided by the ETM trace. It is possible to group source lines (called collapse) to get combined times and
number of calls. This is called Outlining. The Vision simulator also provides Execution Profiling.
1.

Enter Debug mode.

2.

Select Debug/Execution Profiling/Show Time.

3.

In the left margin of the disassembly and C source


windows will display various time values.

4.

Click on RUN.

5.

The times will start to fill up as shown below right:

6.

Click inside the yellow margin of Blinky.c to refresh it.

7.

This is done in real-time and without stealing CPU cycles.

8.

Hover the cursor over a time and ands more information appears as in the yellow box here:

9.

Recall you can also select Show Calls and this information rather than the execution times will be displayed in the
margin.

31

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

6) In-the--Weeds Ex
xample: For
F referenc
ce only A U
ULINKpro is needed for Instruction Trace:
Soome of the hard
dest problems to
t solve are tho
ose when a craash has occurreed and you havve no clue whatt caused this. Y
You only
knnow that it happ
pened and the stack is corrup
pted or providees no useful cluues. Modern prrograms tend tto be asynchronnous with
innterrupts and RTOS task switcching plus unexpected and sp
purious events.. Having a recording of the pprogram flow is useful
esspecially when a problem occcurs and the con
nsequences aree not immediattely visible. A
Another problem
m is detecting rrace
coonditions and determining
d
how
w to fix them. ETM trace haandles these prooblems and othhers easily andd is not hard to use.
Iff a Hard Fault occurs,
o
the CPU
U will end up at
a the address specified
s
in thee Hard Fault veector located att 0x00 000C. T
This
adddress points to
o the Hard Fault handler. Thiis is usually a branch
b
to itselff and this Brannch instruction will run foreveer. The
traace buffer will save millions of the same brranch instructio
ons. This is noot useful. We nneed to stop thee CPU at this ppoint.
Thhis exception vector
v
is found in the file starrtup_stm32f4xx
x.s. If we set a breakpoint byy double-clickking on the Harrd Fault
haandler and run the program: at
a the next Hard
d Fault event th
he CPU will juump to the Harrd Fault handleer (in this case llocated at
0xx0800 01B0 as shown to the right)
r
and stop.
Thhe CPU and alsso the trace colllection will sto
op. The trace
buuffer will be visible and extreemely useful to
o investigate an
nd
deetermine the caause of the crassh.
1.

Open th
he Blinky_Ulp example, rebu
uild, program th
he
Flash an
nd enter Debug
g mode. Open
n the Data Tracce
window
w.

2.

Locate the Hard fault vector near lin


ne 207 in the diisassembly winndow or in starrtup_stm32f4xxx.s.

3.

Set a brreakpoint at thiis point. A red


d block will app
pear as shown above.

4.

Run thee Blinky examp


ple for a few seeconds and clicck on STOP.

5.

Click on the Step_Ou


ut icon

6.

In the Disassembly
D
window,
w
scroll down
d
until you
u find a POP innstruction. I foound one at 0x00800 1256 as shown
below in
i the third win
ndow:

7.

Right click
c
on the PO
OP instruction (or at the MOV
V at
0x0800
0 124E as show
wn below) and select
s
Set Prog
gram
Counter. This will bee the next instru
uction executed.

8.

mmediately the program will stop


s
on
Click on RUN and im
the Harrd Fault excepttion branch insttruction.

9.

Examin
ne the Data Traace window an
nd you find thiss POP plus eveerything else thhat was previouusly executed. In the
bottom screen are the 4 MOV instru
uctions plus thee offending PO
OP.

to go
g back to the main()
m
program
m as shown in the Call Stack + Locals winddow:

TIIP: The addreesses you get will


w be differentt than these onees.
10. Note th
he Branch at thee Hard Fault does not show in
n the trace winndow
becausee a hardware brreakpoint doess execute the in
nstruction it is sset to
thereforre it is not reco
orded in the traace buffer.

Thhe frames abov


ve the POP are a record of alll previous instrructions executted and tells yoou the complete program flow
w.
32

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

26) Config
guring the
e ST-Link Debug Co
onnection to the tarrget:

The folloowing steps are alrready done

by default in the example programs. These


T
instructions are
a provided for reeference.

1.

Connecct your PC to th
he Discovery board
b
with a US
SB cable. Starrt Vision. It m
must be in Editt mode (as it iss when
first staarted the alterrnative to Debu
ug mode) and you
y have seleccted a valid prooject. Blinky w
will do fine.

2.

Select Target
T
Optionss
or ALT-F
F7 and select th
he Debug tab. In the drop-doown menu boxx select ST-Linnk
Debugg
ger as shown here:
h

TIIP: Do NOT select


s
ST-Link (Deprecated Version).
V
3.

Select Settings
S
and th
he next window
w below opens up.
u This is thee control
panel fo
or the ULINKss and ST-Link. (they are the same).
s

4.

In Portt: select SW. JTAG is not a valid option fo


or ST-Link andd this board. S
SW is also know
wn as SWD.

5.

In the SW
S Device area: ARM CoreS
Sight SW-DP MUST
M
be disp layed. This coonfirms you aree connected to the target
processsor. If there is an error displaayed or it is blaank this must bbe fixed beforee you can continue. Check thhe target
power supply.
s
Cycle the power to th
he board.

TIIP: To refresh
h this screen select Port: and change
c
it or cliick OK
onnce to leave and then click on
n Settings again
n.
TIIP: You can do everything with SW (SW
WD) as you can with
JT
TAG except forr boundary scaan.
nfigure the Keil Flash progrramming tool:
Next page: con

Debug Adapterrs:
It is easy to selecct a USB debugging adapter in Vision. You must configgure the connection to both thhe target and too Flash
prrogramming in two separate windows
w
as desscribed below. They are eachh selected usinng the Debug aand Utilities tabbs.
Using other Deb
bug Adapters: This documeent uses the on
n-board ST-Linnk. You can usse a ULINK2 oor a ULINKproo with
suuitable adjustm
ments. You wou
uld need a suitaable adapter to
o connect a diffferent adapter tto the SWD coonnector on thee
Diiscovery board
d. Some step(ss) to turn off the on-board ST-Link adapter m
might also be nnecessary to avvoid conflicts. It is
reported that sho
orting solder brridge SB10 willl hold the ST-L
Link processorr in RESET alllowing externaal adapter operaation.
Iff your debuggin
ng sessions are unreliable, pleease check for additional connflicts or loadinng on the SWD
D pins. The SW
WD
des the ability to
t use the Disccovery board ass a debug adappter on anotherr board. Its maain purpose is nnot to
coonnector provid
coonnect an exterrnal tool such as
a a Keil ULIN
NK2. Some adaaptation is requuired but not diifficult to do.
It is possible to use
u a Segger J--Link with Viision. Serial Wire
W Viewer is supported.
Thhe ST-Link is selected
s
as the default debug adapter for thee Keil examplees for this Disccovery board.
Seerial Wire View
wer (SWV) is completely
c
sup
pported by ST--LINK Versionn 2. Firmware V2.16.S0 or laater except V2..19.S0.

33

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

27) Config
gure the Keil
K
Flash Programm
mer:
6.

Click on OK once and


d select the Utiilities tab.

7.

Select the
t ST-Ling Deebugger similaar to Step 2 abo
ove.

8.

Click Settings
S
to selecct the programm
ming algorithm
m if it is not vissible or is the w
wrong one.

9.

Select STM32F4xx
S
Flash as shown here or the onee for your proccessor:

10. Click on OK once.


TIIP: To program the Flash ev
very time you enter
e
Debug mo
ode,
chheck Update tarrget before Debugging.
TIIP: If you seleect Use Debug Driver, the debugger you sellected
inn the Debug tab
b will be used.
11. Click on OK to return
n to the Vision
n main screen.
12. Select File/Save
F
All.
13. You haave successfully
y connected to the STM32 taarget
processsor and configu
ured the Visio
on Flash
program
mmer.
TIIP: The Tracee tab is where you
y configure the
t Serial Wiree
Viiewer (SWV). You will learn
n to do this lateer.

COM led LD1 indication:


i
LE
ED is blinking RED: the firstt USB enumeraation with the PC
P is taking pllace.
LE
ED is RED: co
ommunication between
b
the PC
C and ST-LINK
K/V2 is establiished (end of eenumeration). Vision is nott connected
to ST-Link (i.e. in Debug mode).
LE
ED is GREEN: Vision is co
onnected in Deb
bug mode and the last comm
munication was successful.
LE
ED is blinking GREEN/RED
D: data is activeely being exchaanged betweenn the target andd Vision.
No Led: ST-LIN
NK/V2 communication with
h the target orr Vision has failed. Cycle the board pow
wer to restart.

R
Running prog
grams in the internal
i
STM
M32 RAM:
It is possible to run
r your prograam in the processor RAM ratther than Flashh. In this case, the Flash proggramming tool is not
ussed nor is the Load
L
icon. Afteer successfully
y compiling thee source files, cclick on Debugg icon
prrocessor and lo
oads your execu
utable into RAM.

. Ann .ini file confi


figures the

Thhe Discovery Blinky


B
project has
h a RAM settting. Select STM32F407 RA
AM as shown
heere if you wantt to try this mod
de.
unning your program
p
into RAM:
R
Looading and Ru
1.

Select STM32F407
S
RAM
R
as shown above.

2.

Select Target
T
Optionss

3.

The ini file is located in the Initialization File: box


x as shown heree:

4.

Click on Edit to vieew its contents.

5.

Click on the Target taab. Note the RA


AM at 0x2000
0_0000 is split
between
n the R/O and R/W memory areas.

6.

Click on OK to return
n to the main Vision window
w.

7.

Return to the STM32F


F407 Flash settting.

or ALT-F
F7 and select th
he Debug tab.

34

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

28) Serial Wire Viewer and ETM Trace Summary:


Serial Wire Viewer can see:

Global variables.

Static variables.

Structures.

Peripheral registers just read or write to them.

Cant see local variables. (just make them global or static).

Cant see DMA transfers DMA bypasses CPU and SWV by definition.

Serial Wire Viewer displays in various ways:

PC Samples.

Data reads and writes.

Exception and interrupt events.

CPU counters.

Timestamps.

ETM Trace is good for:

Trace adds significant power to debugging efforts. Tells where the program has been.

A recorded history of the program execution in the order it happened.

Trace can often find nasty problems very quickly. Weeks or months can be replaced by minutes.

Especially where the bug occurs a long time before the consequences are seen.

Or where the state of the system disappears with a change in scope(s).

Plus - dont have to stop the program. Crucial to some projects.

These are the types of problems that can be found with a quality ETM trace:

Pointer problems. Illegal instructions and data aborts (such as misaligned writes).

Code overwrites writes to Flash, unexpected writes to peripheral registers (SFRs), a corrupted stack.
How did I get here ?

Out of bounds data. Uninitialized variables and arrays.

Stack overflows. What causes the stack to grow bigger than it should ?

Runaway programs: your program has gone off into the weeds and you need to know what instruction caused this. Is
very tough to find these problems without a trace. ETM trace is best for this.

Communication protocol and timing issues. System timing problems.

ETM facilitates Code Coverage, Performance Analysis and program flow debugging and analysis.

For information on Instruction Trace (ETM) pleas e visit www.keil.com/st for other labs discussing ETM.

35

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

29) Document Resources:

See www.keil.com/st

Books:
1.

NEW! Getting Started MDK 5:

Obtain this free book here: www.keil.com/mdk5/.

2.

There is a good selection of books available on ARM processors. A good list of books on ARM processors is found at
www.arm.com/university by selecting Teaching Resources. You can also select ARM Related Books but make
sure to also select the Books suited for Academia tab to see the full selection.

3.

Vision contains a window titled Books. Many documents including data sheets are located there.

4.

A list of resources is located at:


www.arm.com/products/processors/cortex-m/index.php
Click on the Resources tab. Or search for Cortex-M3 on www.arm.com and click on the Resources tab.

5.

The Definitive Guide to the ARM Cortex-M0/M0+ by Joseph Yiu.

Search the web for retailers.

6.

The Definitive Guide to the ARM Cortex-M3/M4 by Joseph Yiu.

Search the web for retailers.

7.

Embedded Systems: Introduction to Arm Cortex-M Microcontrollers (3 volumes) by Jonathan Valvano.

Application Notes:
8.

Using Cortex-M3 and Cortex-M4 Fault Exceptions

www.keil.com/appnotes/files/apnt209.pdf

9.

Segger emWin GUIBuilder with Vision

www.keil.com/appnotes/files/apnt_234.pdf

10. Porting mbed Project to Keil MDK

www.keil.com/appnotes/docs/apnt_207.asp

11. MDK-ARM Compiler Optimizations

www.keil.com/appnotes/docs/apnt_202.asp

12. Using Vision with CodeSourcery GNU

www.keil.com/appnotes/docs/apnt_199.asp

13. RTX CMSIS-RTOS in MDK 5

C:\Keil_v5\ARM\Pack\ARM\CMSIS\3.20.4\CMSIS_RTXDownload

14. RTX CMSIS-RTX

www.keil.com/demo/eval/rtx.htm and www.arm.com/cmsis

15. Barrier Instructions

http://infocenter.arm.com/help/topic/com.arm.doc.dai0321a/index.html

16. Lazy Stacking on the Cortex-M4:

www.arm.com and search for DAI0298A

17. Cortex Debug Connectors:

www.arm.com and search for cortex_debug_connectors.pdf

18. Sending ITM printf to external Windows applications:

Keil Tutorials for STMicroelectronics Boards:

www.keil.com/appnotes/docs/apnt_240.asp

see

www.keil.com/st

Community Forums: www.keil.com/forum and http://community.arm.com/groups/tools/content


ARM University program: www.arm.com/university. Email: university@arm.com
ARM Accredited Engineer Program: www.arm.com/aae
mbed: http://mbed.org
For comments or corrections on this document please email bob.boys@arm.com.
For more information on the ARM CMSIS standard: www.arm.com/cmsis,

36

STMicroelectronics Discovery STM32F4 Lab with ARM Keil MDK toolkit

Copyright 2014 ARM Limited or its affiliates. All rights reserved

www.keil.com/st

30) Keil Products and Contac


ct Informa
ation:
K
Keil Microc
controller Developm
ment Kit (MDK-ARM
M)

MDK-L
Lite (Evalua
ation version)) $0

NEW !! MDK-ARM
M-CM (for Cortex-M
C
series processorrs only unli mited code liimit)

MDK-S
Standard (u
unlimited com
mpile and deb
bug code and data size)

MDK-P
Professional
(Includes Flash File, TCP//IP, CAN and U
USB driver libra
aries)

Fo
or special pr
romotional pricing
p
and offers, plea
ase contact Keil Sales fo
for details.

U
USB-JTAG adapters (for Flash program
mming too
o)

ULINK2 -

(ULINK2
2 and ME - SW
WV only no
o ETM)

nly with a board by Keil or OEM.


ULINK-ME sold on

pro Cortex
x-Mx SWV & ETM trace.
ULINKp
MDK
K also supporrts ST-Link, CMSIS-DAP
C
a
and Segger J--Link Debug a
adapters.

Thhe Keil RTX RTOS


R
is now provided under a Berkeley BS
SD type licensee. This makes it free.
Alll versions, inccluding MDK-L
Lite, includes Keil
K RTX RTO
OS with sourcee code !
ww
ww.keil.com/d
demo/eval/rtx.h
htm or C:\Keil_
_v5\ARM\Pack
k\ARM\CMSI S
Keil provides freee DSP librariees with source code for Corteex-M processorrs.
Caall Keil Sales for
f details on current pricing, specials and quantity
q
discouunts.
Saales can also prrovide advice about
a
the vario
ous tools option
ns available to you.
Thhey will help you
y find variou
us labs and appn
notes that are useful.
u
Alll products are available from
m stock.
Alll products incllude Technicall Support for 1 year. This is easily
e
renewedd.
Caall Keil Sales for
f special univ
versity pricing.. Go to www.aarm.com/univeersity to
viiew various pro
ograms and ressources.
M
MDK supports STM32
S
Cortex
x-M3 and Corteex-M4 processo
ors. Keil suppports
m
many other ST processors
p
inclu
uding 8051, AR
RM7, ARM9 and ST10
prrocessors. See the Keil Devicce Database on
o www.keil.co
om/dd for the ccomplete list of STMicroelecctronics supporrt. This
innformation is allso included in MDK.
Contact Keil Sa
ales for USA prices.
p
Contacct sales.intl@k
keil.com for priicing in other ccountries.
Foor the entire Keeil catalog see www.keil.com
m or contact Keeil or your locaal distributor.
Foor Linux, Andrroid and bare metal
m
(no OS) support
s
on ST processors
p
succh as SPEAr, pllease see DS-55 www.arm.com
m/ds5.

Fo
or more in
nformatio
on:
K
Keil Sales In US
SA: sales.us@k
keil.com or 800
0-348-8051. Outside
O
the US : sales.intl@kkeil.com
K
Keil Technical Support in US
SA: support.us@keil.com or 800-348-8051.. Outside the U
US: support.inntl@keil.com.
Foor comments or corrections please
p
email bo
ob.boys@arm.ccom.
Foor the latest verrsion of this do
ocument and fo
or more STMiccroelectronics sspecific inform
mation, go to w
www.keil.com/sst
CM
MSIS Version 3: See www.aarm.com/cmsiss and http://com
mmunity.arm.ccom/groups/toools/content forr more informaation.
Allso see www.k
keil.com/st and www.keil.co
om/forum

37

ST
TMicroelectronics
s Discovery STM
M32F4 Lab with ARM
A
Keil MDK toolkit

Copyright 2014 ARM Limited or its afffiliates. All rights reserrved

www.keil.co
om/st

You might also like