Keil Microvision
Keil Microvision
Keil Microvision
www.keil.com
2 Preface
Information in this document is subject to change without notice and does not
represent a commitment on the part of the manufacturer. The software described
in this document is furnished under license agreement or nondisclosure
agreement and may be used or copied only in accordance with the terms of the
agreement. It is against the law to copy the software on any medium except as
specifically allowed in the license or nondisclosure agreement. The purchaser
may make one copy of the software for backup purposes. No part of this manual
may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording, or information storage and
retrieval systems, for any purpose other than for the purchaser’s personal use,
without written permission.
Keil Software and Design®, the Keil Software Logo, µVision®, RealView®,
C51™, C166™, MDK™, RL-ARM™, ULINK®, Device Database®, and
ARTX™ are trademarks or registered trademarks of Keil, Tools by ARM, and
ARM Ltd.
Microsoft® and Windows™ are trademarks or registered trademarks of Microsoft
Corporation.
PC® is a registered trademark of International Business Machines Corporation.
NOTE
This manual assumes that you are familiar with Microsoft Windows and the
hardware and instruction set of the ARM7, ARM9, Cortex-Mx, C166, XE166,
XC2000, or 8051 microcontroller.
Every effort was made to ensure accuracy in this manual and to give appropriate
credit to persons, companies, and trademarks referenced herein.
Getting Started: Creating Applications with µVision 3
Preface
This manual is an introduction to the Keil development tools designed for
Cortex-Mx, ARM7, ARM9, C166, XE166, XC2000, and 8051 microcontrollers.
It introduces the µVision Integrated Development Environment, Simulator, and
Debugger and presents a step-by-step guided tour of the numerous features and
capabilities the Keil embedded development tools offer.
The chapters of this book can be studied individually, since they do not strictly
depend on each other.
4 Preface
Chapter Overview
“Chapter 1. Introduction”, provides an overview of product installation and
licensing and shows how to get support for the Keil development tools.
“Chapter 7. Debugging”, describes how to use the µVision Simulator and Target
Debugger to test and validate your embedded programs.
Document Conventions
Examples Description
README.TXT1 Bold capital text is used to highlight the names of executable programs,
data files, source files, environment variables, and commands that you
can enter at the command prompt. This text usually represents
commands that you must type in literally. For example:
Variables Text in italics represents required information that you must provide. For
example, projectfile in a syntax string means that you must supply the
actual project file name
Occasionally, italics are also used to emphasize words in the text.
Elements that repeat… Ellipses (…) are used to indicate an item that may be repeated
Omitted code Vertical ellipses are used in source code listings to indicate that a
. fragment of the program has been omitted. For example:
. void main (void) {
. .
.
.
while (1);
«Optional Items» Double brackets indicate optional items in command lines and input
fields. For example:
C51 TEST.C PRINT «filename»
{ opt1 | opt2 } Text contained within braces, separated by a vertical bar represents a
selection of items. The braces enclose all of the choices and the vertical
bars separate the choices. Exactly one item in the list must be selected.
Keys Text in this sans serif typeface represents actual keys on the keyboard.
For example, “Press Enter to continue
1
It is not required to enter commands using all capital letters.
6 Contents
Contents
Preface................................................................................................................... 3
Document Conventions........................................................................................ 5
Contents ................................................................................................................ 6
Chapter 1. Introduction...................................................................................... 9
Last-Minute Changes ....................................................................................... 11
Licensing.......................................................................................................... 11
Installation ....................................................................................................... 11
Requesting Assistance ..................................................................................... 13
Index.................................................................................................................. 151
Getting Started: Creating Applications with µVision 9
Chapter 1. Introduction
Thank you for allowing Keil to provide you with software development tools for
your embedded microcontroller applications.
This book, Getting Started, describes the µVision IDE, µVision Debugger and
Analysis Tools, the simulation, and debugging and tracing capabilities. In
addition to describing the basic behavior and basic screens of µVision, this book
provides a comprehensive overview of the supported microcontroller architecture
types, their advantages and highlights, and supports you in selecting the
appropriate target device. This book incorporates hints to help you to write better
code. As with any Getting Started book, it does not cover every aspect and the
many available configuration options in detail. We encourage you to work
through the examples to get familiar with µVision and the components delivered.
The Keil Development Tools are designed for the professional software
developer, however programmers of all levels can use them to get the most out of
the embedded microcontroller architectures that are supported.
Tools developed by Keil endorse the most popular microcontrollers and are
distributed in several packages and configurations, dependent on the architecture.
CAN Interface
Last-Minute Changes
As with any high-tech product, last minute changes might not be included into
the printed manuals. These last-minute changes and enhancements to the
software and manuals are listed in the Release Notes shipped with the product.
Licensing
Each Keil product requires activation through a license code. This code is
obtained via e-mail during the registration process. There are two types of
product licenses:
Installation
Please check the minimum hardware and software requirements that must be
satisfied to ensure that your Keil development tools are installed and will
function properly. Before attempting installation, verify that you have:
Keil products are available on CD-ROM and via download from www.keil.com.
Updates to the related products are regularly available at www.keil.com/update.
12 Chapter 1. Introduction
Contents Subfolder
Executable Program Files \BIN\
C Include/Header Files \INC\
On-line Help Files and Release Notes \HLP\
Common/Generic Example Programs \EXAMPLES\
Example Programs for Evaluation Boards \BOARDS\
Getting Started: Creating Applications with µVision 13
Requesting Assistance
At Keil, we are committed to providing you with the best embedded development
tools, documentation, and support. If you have suggestions and comments
regarding any of our products, or you have discovered a problem with the
software, please report them to us, and where applicable make sure to:
1. Read the section in this manual that pertains to the task you are attempting
2. Check the update section of the Keil web site to make sure you have the latest
software and utility version
3. Isolate software problems by reducing your code to as few lines as possible
If you are still having difficulties, please report them to our technical support
group. Make sure to include your license code and product version number. See
the Help – About Menu. In addition, we offer the following support and
information channels, all accessible at www.keil.com/support1.
1
You can always get technical support, product updates, application notes, and sample programs
at www.keil.com/support.
14 Chapter 2. Microcontroller Architectures
The µVision IDE supports the latest trends, like custom chip designs based
on IP cores, which integrate application-specific peripherals on a single chip.
16-bit (Infineon C166, XE166, XC2000) devices are tuned for optimum
real-time and interrupt performance and provide a rich set of on-chip
peripherals closely coupled with the microcontroller core. They include a
Peripheral Event Controller (similar to memory-to-memory DMA) for high-
speed data collection with little or no microcontroller overhead.
These devices are the best choice for applications requiring extremely fast
responses to external events.
ARM7 and ARM9 devices provide separate stack spaces for high-speed
context switching enabling efficient multi-tasking operating systems. Bit-
addressing and dedicated peripheral address spaces are not supported. Only
two interrupt priority levels, - Interrupt Request (IRQ) and Fast Interrupt
Request (FIQ), are available.
Getting Started: Creating Applications with µVision 15
32-bit (Cortex-Mx based) devices combine the cost benefits of 8-bit and
16-bit devices with the flexibility and performance of 32-bit devices at
extremely low power consumption. The architecture delivers state of the art
implementations for FPGAs and SoCs. With the improved Thumb2
instruction set, Cortex-Mx1 based microcontrollers support a 4GB address
space, provide bit-addressing (bit-banding), and several interrupts with at
least 8 interrupt priority levels.
Selecting an Architecture
Choosing the optimal device for an embedded application is a complex task. The
Keil Device Database (www.keil.com/dd) supports you in selecting the
appropriate architecture and provides three different methods for searching. You
can find your device by architecture, by specifying certain characteristics of the
microcontroller, or by vendor.
The following sections explain the advantages of the different architectures and
provide guidelines for finding the microcontroller that best fits your embedded
application.
8051-based devices are typically used in small and medium sized applications
that require high I/O throughput. Many devices with flexible peripherals are
available, even in the smallest chip packages.
1
Cortex-M0 devices implement the Thumb instruction set.
16 Chapter 2. Microcontroller Architectures
These devices are used in medium to large sized applications that require high
I/O throughput. This architecture is well suited to the needs of embedded
systems that involve a mixture of traditional controller code and DSP algorithms.
ARM7 and ARM9-based microcontrollers are used for applications with large
memory demands and for applications that use PC-based algorithms.
0x100
0xFFFF
F8
98 CODE
SFR
0x100 SPACE 8051 Bit
90 addressable
0x0000
88
IDATA
80
256 Bytes
0x80
0x80
2F 0xFFFF
DATA
128 8051
DATA Bitspace
Bytes 20 XDATA
128 Bytes 1F
4 Register
Banks
0x 0 0 0x0000
SFR and IDATA memory are located in the same address space but are
accessed through different assembler instructions
For extended devices, the memory layout provides a universal memory map
that includes all 8051-memory types in a single 16MByte address region
8051 Highlights
Fast interrupt service routines with two or four priority levels and up to 32-
vectored interrupts
Four register banks for minimum interrupt prolog/epilog
Bit-addressable space for efficient logical operations
128 Bytes of Special Function Register (SFR) space for tight integration of
on-chip peripherals. Some devices extend the SFR space using paging.
Low-power, high-speed devices up to 100 MIPS are available
The prefix P: is a special case, since it always must be followed by a name. The
name in turn is searched for in a special symbol table that contains the register’s
pin names.
Example:
C:0x100 Address 0x100 in CODE memory
ACC Address 0xE0 in DATA memory, D:
I:100 Address 0x64 in internal RAM
X:0FFFFH Address 0xFFFF in external data memory
B:0x7F Bit address 127 or 2FH.7
C Address 0xD7 (PSW.7), memory type B:
20 Chapter 2. Microcontroller Architectures
Memory type support and flexible digital pattern processing for extremely
fast variable access
Function inlining eliminating call/return overhead
Inline assembly for accessing all microcontroller and MAC instructions
The ARM7 and ARM9 cores are easy to use, cost-effective, and support modern
object-oriented programming techniques. They include a 2-level interrupt system
with a normal interrupt (IRQ) and a fast interrupt (FIQ) vector. To minimize
interrupt overhead, typical ARM7/ARM9 microcontrollers provide a vectored
interrupt controller. The microcontroller operating modes, separate stack spaces,
and Software Interrupt (SVC) features produce efficient use of Real-Time
Operating Systems.
The ARM7 and ARM9 core provides thirteen general-purpose registers (R0–
R12), the stack pointer (SP) R13, the link register (LR) R14, which holds return
addresses on function calls, the program counter (PC) R15, and a program status
register (PSR). Shadow registers, available in various operating modes, are
similar to register banks and reduce interrupt latency.
22 Chapter 2. Microcontroller Architectures
R1
ARM7 and ARM9 Operation Modes
R2
R8 R8
R9 R9
R10 R10
R11 R11
R12 R12
R15 = PC
With 4GB of linear, unified memory space, the Cortex-Mx processors provide
bit-banding features and supports big and little endian configuration. Predefined
memory types are available, while some memory regions have additional
attributes. Code can be located in the SRAM, external RAM, but preferably in
the Code region. Peripheral registers are mapped into the memory space. Code
density is improved by the Thumb or Thumb2 instruction set, depending on the
processor version.
General-purpose registers rank from R0 to R12. R13 (SP) is banked, with only
one copy of the R13 (MSP, PSP) being visible at a time. Special registers are
available, but are not used for normal data processing. Some of the 16-bit
Thumb instructions can access R0-R7 (low) registers only. There is no FIQ;
however, nested interrupts and interrupt priority handling is implemented via the
Nested Vector Interrupt Controller (NVIC), greatly reducing interrupt latency.
24 Chapter 2. Microcontroller Architectures
R0
R1
R2
R3
Low Registers
R4
R5
R6 General-Purpose Registers
R7
R8
R9
R11
R12
R13 = PSP R13 = MSP Process Stack Pointer (PSP), Main Stack Pointer (MSP): (banked)
PRIMASK
BASEPRI
Cortex-Mx Highlights
Nested Vectored Interrupt Controller optimizes multiple external
interrupts (up to 240 + 1 NMI, with at least eight priority levels)
R0-R3, R12, LR, PSR, and PC are pushed automatically to the stack at
interrupt entry and popped back at interrupt exit points
Only one instruction set (Thumb2), assuring software upward
compatibility with the entire ARM roadmap
Several Extreme Low-Power Modes with an attached Wake-Up Interrupt
Controller (WIC)
Getting Started: Creating Applications with µVision 25
Code Comparison
The following short but representative code examples show the impressive
individual strengths of the different microcontroller architectures.
void main (void) { void main (void) { void main (void) { void main (void) {
if (P0_0) { if (P0_0) { if (IOP & 1) { if (GPIOA->ODR) {
; JNB P0_0,?C0002 ; JNB P0_0,?C0001 ; LDR R0,=0xE0028000 ; STR R0,[R1,#0xc]
; LDR R0,[R0,#0x0] ; LDR R0,[R2,#0]
; MOV R1,#0x1 ; CBZ R0,|L1.242|
; TST R0,R1
; BEQ L_1
; RET ; RET ; BX LR ; BX LR
} } } }
MicroLIB The compiler offers a MicroLIB to be used for further reducing the
code size of an application. MicroLIB is tailored for deeply
embedded systems, but is not fully ANSI compliant.
Do not use MicroLIB when execution speed is your primary goal.
Optimize for Speed To optimize an application for maximum execution speed, under
Options for Target select the following toolchain:
In the dialog pageTarget enable Code Generation - Use
Cross-Module Optimization
In the dialog page C/C++ select Optimization: Level 3 (-O3),
enable Optimize for Time, and disable Split Load and Store
Multiple
32 Chapter 2. Microcontroller Architectures
MicroLIB The compiler offers a MicroLIB to be used for further reducing the
code size of an application. MicroLIB is tailored for deeply
embedded systems, but is not fully ANSI compliant.
Do not use MicroLIB when execution speed is your primary goal.
Optimize for Speed To optimize an application for maximum execution speed, under
Options for Target select the following toolchain:
In the dialog pageTarget enable Code Generation - Use Cross-
Module Optimization
In the dialog page C/C++ select Optimization: Level 3 (-O3),
enable Optimize for Time, and disable Split Load and Store
Multiple
Sleep mode features To optimize power consumption of an application you may use the
WFI instruction to send the processor into Sleep Mode until the next
interrupt is received. In C programs, use the intrinsic function __wfi()
to insert this instruction into your code.
Enhance struct pointer Thumb2 instructions encode a limited displacement for memory
access, by placing scalars access. When a struct is accessed via a pointer, scalar variables
at the beginning and at the beginning of a struct can be directly accessed. Arrays
arrays as sub-sequent always require address calculations. Therefore, it is more efficient to
struct members. place scalar variables at the beginning of a struct.
Getting Started: Creating Applications with µVision 33
µVision IDE
The µVision IDE is a window-based software development platform combining a
robust editor, Project Manager, and Make Utility tool. µVision supports all the
Keil tools including C/C++ Compiler, Macro Assembler, Linker, Library
Manager, and Object-HEX Converter. µVision helps expedite the development
process by providing:
µVision Debugger
The µVision Debugger is completely integrated into the µVision IDE. It
provides the following features:
Target Mode1 connects the µVision Debugger to real hardware. Several target
drivers are available that interface to a:
ULINK JTAG/OCDS Adapter that connects to on-chip debugging systems
Monitor that may be integrated with user hardware or that is available on
many evaluation boards
Emulator that connects to the microcontroller pins of the target hardware
In-System Debugger that is part of the user application program and
provides basic test functions
ULINKPro Adapter a high-speed debug and trace unit connecting to
on-chip debugging systems via JTAG/SWD/SWV, and offering Cortex-M3
ETM Instruction Trace capabilities
1
Some target drivers have hardware restrictions that limit or eliminate features of the µVision
Debugger while debugging the target hardware.
Getting Started: Creating Applications with µVision 37
Assembler
An assembler allows you to write programs using microcontroller instructions. It
is used where utmost speed, small code size, and exact hardware control is
essential. The Keil Assemblers translate symbolic assembler language
mnemonics into executable machine code while supporting source-level
symbolic debugging. In addition, they offer powerful capabilities like macro
processing.
The assembler translates assembly source files into re-locatable object modules
and can optionally create listing files with symbol table and cross-reference
details. Complete line number, symbol, and type information is written to the
generated object files. This information enables the debugger to display the
program variables exactly. Line numbers are used for source-level debugging
with the µVision Debugger or other third-party debugging tools.
C/C++ Compiler
The ARM C/C++ compiler is designed to generate fast and compact code for the
ARM7, ARM9 and Cortex-Mx processor architectures; while the Keil ANSI C
compilers target the 8051, C166, XE166, and XC2000 architectures. They can
generate object code that matches the efficiency and speed of assembly
programming. Using a high-level language like C/C++ offers many advantages
over assembly language programming:
Object-HEX Converter
The object-hex converter creates Intel HEX files from absolute object modules
that have been created by the linker. Intel HEX files are ASCII files containing a
hexadecimal representation of your application program. They are loaded easily
into a device program for writing to ROM, EPROM, FLASH, or other
programmable memory. Intel HEX files can be manipulated easily to include
checksum or CRC data.
Getting Started: Creating Applications with µVision 39
Linker/Locator
The linker/locator combines object modules into a single, executable program. It
resolves external and public references and assigns absolute addresses to re-
locatable program segments. The linker includes the appropriate run-time library
modules automatically and processes the object modules created by the Compiler
and Assembler. You can invoke the linker from the command line or from
within the µVision IDE. To accommodate most applications, the default linker
directives have been chosen carefully and need no additional options. However,
it is easy to specify additional custom settings for any application.
Library Manager
The library manager creates and maintains libraries of object modules (created by
the C/C++ Compiler and Assembler). Library files provide a convenient way to
combine and reference a large number of modules that may be used by the linker.
The linker includes libraries to resolve external variables and functions used in
applications. Modules from libraries are extracted and added to programs only if
required. Modules, containing routines that are not invoked by your program
specifically, are not included in the final output. Object modules extracted by the
linker from a library are processed exactly like other object modules.
You can build library files (instead of executable programs) using the µVision
Project Manager. To do so, check the Create Library check box in the
Options for Target — Output dialog. Alternatively, you may invoke the
library manager from the Command Window.
40 Chapter 4. RTX RTOS Kernel
Software Concepts
There are two basic design concepts for embedded applications:
This software concept requires only one stack area and is very well suited for
devices with limited memory. Architectures that provide several interrupt levels
allow complex low-level ISR functions. Time-critical jobs may execute in higher
interrupt levels.
Getting Started: Creating Applications with µVision 41
RTOS Design
The RTOS design, due to its very nature, allows several tasks to execute within
sequential time slices. A preemptive RTOS provides task priority levels, in
which high priority tasks interrupt the execution of low priority tasks. Most
RTOS systems offer inter-task communication and time delay functions
supporting the design of complex applications.
The ARM based architectures are designed for RTOS usage. An RTOS is almost
mandatory on ARM7, ARM9, and Cortex-Mx based systems that have several
interrupt sources. ARM devices provide a separate ISR stack, and hence, each
task needs no additional stack for ISR execution (as required on 8051 and
C166/XE166/XC2000 devices).
42 Chapter 4. RTX RTOS Kernel
A preemptive RTOS supports multiple task priorities. Tasks with the same
priority are executed in sequence; tasks with a higher priority suspend tasks with
a lower priority. An ISR always interrupts task execution and may exchange data
with other tasks.
The RTOS also solves many other challenges specific to embedded applications.
It helps you to maintain memory resources and data communication facilities,
and allows you to split a complex application into simpler jobs.
Keil provides several different RTOS systems for the various microcontroller
architectures:
RTX Introduction
Many microcontroller applications require simultaneous execution of multiple
jobs or tasks. For such applications, an RTOS allows flexible scheduling of
system resources (CPU, memory, etc.) to several tasks.
With RTX, you write and compile programs using standard C. Only a few
deviations from standard C are required in order to specify the task ID and
priority. RTX-166 programs require the inclusion of the RTX166.H or
RTX166T.H header file also. RTX_CONFIG.C is required on ARM devices.
By selecting the operating system through the dialog Options for Target –
Target, the linker, L166, included in µVision, links the appropriate RTX-166
library file.
main (void) {
counter = 0;
Program execution starts with job0, as an RTOS task function. The RTX
function os_tsk_create marks job1 as ready for execution. The task functions
job0 and job1 are simple counting loops. After its time slot has been consumed,
RTX suspends the execution of job0 and begins execution of job1. As soon as
its time slot is consumed, the system continues with job0.
44 Chapter 4. RTX RTOS Kernel
This following program is similar to the previous example with the exception that
job0 is suspended with os_dly_wait after counter0 has been incremented.
RTX waits three timer ticks until job0 is ready for execution again. During this
time, job1 is executed. This function also calls os_dly_wait with 5 ticks time
delay. The result: counter0 is incremented every three ticks and counter1 is
incremented every five timer ticks.
1
For non-ARM devices the syntax is: void job0 (void) __task {…}.
2
Within RTX Tiny time delays are created with the function os_wait (K_TMO, …).
Getting Started: Creating Applications with µVision 45
while (1) {
counter0++; // Increment counter 0
os_dly_wait (3); // Wait 3 timer ticks
}
}
while (1) {
i0++;
if (i0 > 1000000) { // when i1 reaches 1000000
i0 = 0; // clear i1
os_evt_set (1, id1); // set event '1' on job1
}
}
}
1
RTX Tiny does not offer task priorities. Instead, RTX Tiny has one event flag per task, called
signal, and uses the function os_wait (K_SIG, …) to wait for this signal flag.
Getting Started: Creating Applications with µVision 47
Mailbox Communication
A mailbox is a FIFO (first in – first out) buffer for transferring messages between
task functions. Mailbox functions accept pointer values, typically referencing
memory buffers. However, by using appropriate type casts, you may pass any
integer 32-bit data type.
while (1) {
res = os_mbx_wait (v_mail, (void **) &v, 0xFFFF); // receive mail
if (res == OS_R_OK || s == OS_R_MBX) { // check status
printf ("\nReceived v=%d res=%d", v, res); // use when correct
}
}
}
The task job0 uses a mailbox to send information to job1. When job1 runs
with a higher priority than job0, the mail is instantly delivered. The mailbox
buffers up to 20 messages when job1 runs with the same or lower priority than
job0.
1
When creating high-priority tasks using a mailbox, initialize the mailbox before it might be used
by a high-priority task.
48 Chapter 4. RTX RTOS Kernel
Semaphores
Semaphores are utilized to synchronize tasks within an application. Although
they have a simple set of calls to the operating system, they are the classic
solution in preventing race conditions. However, they do not resolve resource
deadlocks. RTX ensures that atomic operations used with semaphores are not
interrupted.
Binary Semaphores
while(1) {
do_func_A();
os_sem_send(semA); // free the semaphore
}
}
while(1) {
os_sem_wait(semA, 0xFFFF); // wait for the semaphore
do_func_B();
}
}
In this case the semaphore is used to ensure the execution of do_func_A() prior
to executing do_func_B().
Getting Started: Creating Applications with µVision 49
Use a multiplex to limit the number of tasks that can access a critical section of
code. For example, a routine to access memory resources and that supports a
limited number of calls only.
os_sem mplxSema; // declare the semaphore
while(1) {
os_sem_wait (mplxSema); // acquire a token
processBuffer();
os_sem_send (mplxSema); // free the token
}
}
In this example, we initialize the multiplex semaphore with five tokens. Before a
task can call processBuffer(), it must acquire a semaphore token. Once the
function has completed, it returns the token to the semaphore. If more than five
calls attempt to invoke processBuffer(), the sixth must wait until one of the five
running tasks returns its token. Thus, the multiplex semaphore ensures that a
maximum of five calls can use processBuffer() simultaneously.
RTX ensures that interrupts execute correctly and leaves the machine in a well-
defined state. Interrupt service routines, also known as interrupt handlers, are
used to service hardware devices and transitions between operation modes, such
as system calls, system timers, disk I/O, power signals, keystrokes, watchdogs;
other interrupts transfer data using UART or Ethernet.
Functions that begin with os_ can be called from a task but not from an
interrupt service routine
Functions that begin with isr_ can be called from an IRQ interrupt service
routine but not from a task. Never use them from FIQ.
Never enable any IRQ interrupt that calls isr_ functions before the kernel has
been started
Avoid nesting IRQ functions on ARM7/ARM9 targets
Use short IRQ functions to send signals and messages to RTOS tasks
Interrupt functions are added to applications the same way as in non-RTX
projects
By default, interrupts are globally enabled at startup
Another important concept is the interrupt latency, which is defined as the period
between the generation and servicing of that interrupt. This is especially
important in systems that need to control machinery in real time, and therefore
require low interrupt latency. RTX ensures that a subroutine will finish its
execution in an agreed maximum length of time and that the interrupt latency
does not exceed a predefined maximum length of time.
The general logic of an ISR looks like the following code example. The interrupt
function ext0_int sends an event to process_task and exits. The task
process_task processes the external interrupt event. In this example,
process_task is simple and only counts the number of interrupt events.
Getting Started: Creating Applications with µVision 51
OS_TID pr_task;
int num_ints;
while(1) {
os_evt_wait_or (EVT_KEY, 0xFFFF);
num_ints++;
}
}
enableYourInterrupt ();
pr_task = os_tsk_create (process_task, 100); // create task with prio
os_tsk_delete_self ();
}
RTX provides thread-safe and fully reentrant1 allocation functions for fixed sized
memory pools. These functions have a deterministic execution time that is
1
Variable length memory allocation functions are not reentrant! Disable/enable system timer
interrupts using tsk_lock() and tsk_unlock() during the execution of malloc() and free().
52 Chapter 4. RTX RTOS Kernel
independent of the pool usage. Built-in memory allocation routines enable you
to dynamically use the system memory by creating memory pools and use fixed
sized blocks from the memory pool. The memory pool needs to be properly
initialized to the size of the object.
#include <rtl.h>
os_tsk_delete_self ();
}
os_tsk_delete_self ();
}
To send a message object of a variable size and use the variable size memory
block, you must use the memory allocation functions, which can be found in
stdlib.h.
Getting Started: Creating Applications with µVision 53
ARM7/ARM9 Cortex-Mx
max Code Space 4.2 KBytes 4.0 KBytes 4.0 KBytes
Hardware Needs 1 on-chip timer SysTick timer 1 on-chip timer
Context Switch < 7 µsec @ 60 MHz < 4 µsec @ 72 MHz < 15 µsec @ 20 MHz
Interrupt Lockout 3.1 µsec @ 60 MHz not disabled by RTX 0.2 µsec @ 20 MHz
54 Chapter 4. RTX RTOS Kernel
µVision windows can be re-arranged, tiled, and attached to other screen areas
or windows respectively
It is possible to drag and drop windows, objects, and variables
A Context Menu, invoked through the right mouse button, is provided for
most objects
You can use keyboard shortcuts and define your own shortcuts
You can use the abundant features of a modern editor
Menu items and Toolbar buttons are grayed out when not available in the
current context
Graphical symbols are used to resemble options, to mark unsaved changes, or
reveal objects not included into the project
Status Bars display context-driven information
You can associate µVision to third-party tools
1
The screenshots presented in the next chapters have been taken from different example programs
and several microcontroller architectures to resemble the main feature, sometimes the special
feature, of that topic. The same window, dialog, or tab category will look slightly different for
other microcontroller architectures.
56 Chapter 5. Using µVision
1
Any window can be moved to any other part of the µVision screen, or even outside of µVision to
any other physical screen, with the exception of the objects related to the Text Editor.
Getting Started: Creating Applications with µVision 57
The Project Windows area is that part of the screen in which, by default, the
Project Window, Functions Window, Books Window, and Registers Window are
displayed.
Within the Editor Windows area, you are able to change the source code, view
performance and analysis information, and check the disassembly code.
If, for any reason, you do not see a particular window and have tried
displaying/hiding it several times, please invoke the default layout of µVision
through the Window – Reset Current Layout Menu.
58 Chapter 5. Using µVision
Positioning Windows
The µVision windows may be placed onto any area of the screen, even outside of
the µVision frame, or to another physical screen.
Click and hold the Title Bar1 of a window with the left mouse button
Drag the window to the preferred area, or onto the preferred control, and
release the mouse button
Please note, source code files cannot be moved outside of the Editor Windows2.
Invoke the Context Menu of the window’s Title Bar to change the docking
attribute of a window object. In some cases, you must perform this action before
you can drag and drop the window.
µVision displays docking helper controls3, emphasizing the area where the
window will be attached. The new docking area is represented by the section
highlighted in blue. Snap the window to the Multiple Document Interface (MDI)
or to a Windows area by moving the mouse over the preferred control.
1
You may click the page/object name to drag and drop the object.
2
Source code files stay in the Text Editor’s window.
3
Controls indicate the area of the new window position. The new position is highlighted.
Getting Started: Creating Applications with µVision 59
µVision Modes
µVision operates in two modes: Build Mode and Debug Mode. Screen settings,
Toolbar settings, and project options are stored in the context of the mode. The
File Toolbar is enabled in all modes, while the Debug Toolbar and Build
Toolbar display in their respective mode only. Buttons, icons, and menus are
enabled if relevant for a specific mode.
The standard working mode is Build Mode. In this mode you write your
application, configure the project, set preferences, select the target hardware and
the device; you will compile, link, and assemble the programs, correct the errors,
and set general settings valid for the entire application.
In Debug Mode, you can also change some general options and edit source code
files, but these changes will only be effective after you have switched back to
Build Mode, and rebuild your application. Changes to debug settings are
effective immediately.
Menus
The Menu bar provides access to most µVision commands including file
operations, editor operations, project maintenance, development tool settings,
program debugging, window selection and manipulation, and on-line help.
File Menu
The File Menu includes commands that open, save, print, and close source files.
The Device Database and License Manager dialogs are accessed from this
menu.
Edit Menu
The Edit Menu includes commands for editing the source code; undo, redo, cut,
copy, paste, and indentation, bookmark functions, various find and replace
commands, source outlining functions, and advanced editor functions. Editor
configuration settings are also accessed from this menu.
60 Chapter 5. Using µVision
View Menu
The View Menu includes commands to
display/hide a variety of windows. You can
also enable/disable the Status Bar. The
Periodic Window Update option is useful
in Debug Mode to force the screens to
periodically refresh. If this option has not
been selected, you can manually update the
screens via the Toolbox.
Project Menu
The Project Menu includes commands to
open, save, and close project files. You can
Export your project to a previous version of
µVision, Manage project components, or
Build the project. In addition, you can set
Options for the project, group, and file. You
can manage multiple projects through the
Multi-Project Workspace… Menu.
Flash Menu
The Flash Menu includes commands you
can use to configure, erase, and program
Flash memory for your embedded target
system.
Getting Started: Creating Applications with µVision 61
Debug Menu
The Debug Menu includes commands that
start and stop a debug session, reset the CPU,
run and halt the program, and single-step in
high-level and assembly code. In addition,
commands are available to manage
breakpoints, view RTOS Kernel information,
and invoke execution profiling. You can
modify the memory map and manage
debugger functions and settings.
Tools Menu
Configure and run PC-Lint or set up your
own tool shortcuts to third party utilities.
SVCS Menu
The SVCS Menu allows you to configure
and integrate your project development with
third-party version control systems.
Help Menu
The Help Menu includes commands to start
the on-line help system, to list information
about on-chip peripherals, to access the
knowledgebase, to contact the Technical
Support team, to check for product updates,
and to display product version information.
62 Chapter 5. Using µVision
Peripherals Menu
The Peripherals Menu includes dialogs to
display and change on-chip peripheral settings.
The content of this menu is tailored to show the
specific microcontroller options selected for your
application. Dialogs are typically available for
System Configuration, Interrupts, UARTs, I2C,
Timer/Counters, General Purpose I/O, CAN,
Pulse-Width Modulators, Real-Time Clocks,
and Watchdog Timers. This menu is active in
Debug Mode only.
Window Menu
The Window Menu includes
commands to split, select, and
close various windows in the
Text Editor.
Restore the default layout through Reset View to Defaults at any time.
Currently open source code windows are listed at the bottom of the Window
Menu.
Getting Started: Creating Applications with µVision 63
The File Toolbar contains buttons for commands used to edit source files, to
configure µVision, and to set the project specific options
The Build Toolbar contains buttons for commands used to build the project
The Debug Toolbar contains buttons for commands used in the debugger
The File Toolbar is always available, while the Build Toolbar and Debug
Toolbar will display in their context. In both modes, Build Mode and Debug
Mode, you have the option to display or hide the applicable Toolbars.
File Toolbar
Paste – inserts text from the clipboard to the current cursor position
Indent – moves the lines of the highlighted text one tab stop to the right
Unindent – moves all highlighted text lines one tab stop to the left
Remove Comment – converts the selected text lines back to code lines
Build Toolbar
Build – builds and links those files of the project that have changed or
whose dependencies have changed
Target – drop-down box to select your target system (in the Toolbar
example above: Simulator)
Target Options – dialog to define tool and target settings. Set device,
target, compiler, linker, assembler, and debug options here. You can also
configure your flash device from here.
Debug Toolbar
Step One Line – steps to the next instruction or into procedure calls
Step Over – steps over a single instruction and over procedure calls
Run to Line – runs the program until the current cursor line
Additional Icons
Print – opens the printer dialog
File – Source file; you can modify these files; default options are used
File – Source file; you can modify these files; file options have been
changed and are different from the default options
Application, Container
Variable
Parameter
Function
Getting Started: Creating Applications with µVision 69
Project Windows
Project Windows display information about the
current project. The tabs at the bottom of this area
provide access to:
Double-click a function to
jump to its definition.
Invoke its Context Menu
to toggle the displaying
mode of this window or
scan the files.
Editor Windows
The Editor Windows are used to:
Editor Configuration
Configure Editor settings,
colors and fonts, user
defined keywords, shortcut
keys, and templates
through the Configuration
dialog.
Double-click the
tiling line to remove
the fragmentation.
Double-click a file’s
tab to close the file.
Getting Started: Creating Applications with µVision 73
Output Windows
By default, the Output Windows1 are displayed at the bottom of the µVision
screen and include:
The Build Output Window includes errors and warnings from the compiler,
assembler, and linker. Double-click a message to jump to the location of the
source code that triggered the message. Press F1 for on-line help.
The Command Window allows you to enter commands and review
debugger responses. Hints are provided on the Status Bar of that window.
Press F1 for on-line help.
The Find in Files Window allows you to double-click a result to locate the
source code that triggered the message
The Serial and UART windows display I/O information of your peripherals
The Call Stack Window enables you to follow the program call tree
The Locals Window displays information about local variables of the
current function
The Watch windows provide a convenient way to personalize a set of
variables you would like to trace. Objects, structures, unions, and arrays may
be monitored in detail.
The Symbols Window is a handy option to locate object definitions. You
can drag and drop these items into other areas of µVision.
The Memory windows enable you to examine values in memory areas.
Define your preferred address to view data.
The Source Browser Window offers a fast way to find occurrences and
definitions of objects. Enter your search criteria to narrow the output.
1
Since almost all objects can be moved to their own window frame, the terminology ‘page’ and
‘window’ is interchangeably used in this book.
74 Chapter 5. Using µVision
Peripheral Dialogs and Windows allow you to review and modify the status of
on-chip peripherals. These dialogs are dependent on the target system you
selected at the beginning of your project and thus the options provided will vary.
On-line Help
µVision includes many pages of on-line manuals and context-sensitive help. The
main help system is available from the Help Menu.
µVision includes an advanced editor, project manager, and make utility, which
work together to ease your development efforts, decreases the learning curve, and
helps you to get started with creating embedded applications quickly.
The section provides a step-by-step tutorial that shows you how to create an
embedded project using the µVision IDE.
Select the preferred folder and enter the file name for the new project. µVision
creates a new, empty project file with the specified name. The project contains a
default target and file group name, which you can view on the Project Window.
You may invoke this screen through the Project – Select Device for Target…
Menu in order to change target later.
1
For some devices, µVision requires additional parameters you must enter manually. Please read
the device description in the Select Device dialog carefully, as it may contain extra instructions for
the device configuration.
2
If you do not know the actual device you will finally use, µVision allows you to change the device
settings for a target after project creation.
Getting Started: Creating Applications with µVision 77
The startup code files are delivered with embedded comments used by the
configuration wizard to provide you with a GUI interface for startup
configuration.
1
The startup code’s default settings provide a good starting point for most single-chip
applications. However, changes to the startup code may be required.
2
Library and add-on projects need no startup code.
78 Chapter 6. Creating Embedded Programs
Components,
Environments and
Books1 dialog to modify
the settings of the exiting
manuals or add your own
manuals to the list of
books.
This action opens an empty Editor Window to enter your source code. µVision
enables color syntax highlighting based on the file extension (after you have
saved the file). To use this feature immediately, save the empty file with the
desired extension prior to starting coding.
Save the new source file using the button on the File Toolbar or use the
File – Save Menu
1
Most microcontroller manuals are part of the toolset, or are available on the Keil Development
Tools CD-ROM.
Getting Started: Creating Applications with µVision 79
A Target is a defined set of build options that assemble, compile, and link the
included files in a specific way for a specific platform.
Multiple file groups may be added to a target and multiple files may be attached
to the same file group.
You can define multiple targets for the same project as well.
You should customize the name of targets and groups to match your application
structure and internal naming conventions. It is a good practice to create a
separate file group for microcontroller configuration files.
Double-click the
desired item, or
Highlight the item
and press F2
Move Down - move a target, group, or source file down the list
Instead of using the Move Up or Move Down buttons, you may drag and drop the
source files within the Project Window to re-arrange the order of the files.
Getting Started: Creating Applications with µVision 81
Normally, you do not have to make changes to the default settings in the Target
and Output dialog.
The options available in the Options for Target dialogs depend on the
microcontroller device selected. Of course, the available tabs and pages will
change in accordance with the device selected and with the target.
When switching between devices, the menu options are available as soon as the
OK button in the Device Selection dialog has been clicked.
82 Chapter 6. Creating Embedded Programs
The following table lists the project options that are configurable on each page of
the Target Options dialog.
Invoke the Context Menu of a file group and select Options for Group to
specify the properties, compiler options, and assembler options for that file
group
Invoke the Context Menu of a source file and select Options for File to
specify the properties, compiler, or assembler options for that file
Treat Target options similar to general options. They are valid for the entire
project and for that target. Some options can be defined at the group level and on
individual files. File-level options will supersede group-level options, which in
turn, supersede the options set at the target level.
Red dots on the icon’s left side are an indication that the options of
that item differ from the general target options
Getting Started: Creating Applications with µVision 83
Keil startup files contain assembler code with options you can adjust to your
particular target system. Most startup files have embedded commands for the
µVision Configuration Wizard, which provides an intuitive, graphical, and
convenient interface to edit the startup code.
Simply click the desired value to change data. Alternatively, you can use
the Text Editor to directly edit the assembly source file.
Keil startup files provide a good starting point for most single-chip applications.
However, you must adapt their configuration for your target hardware. Target-
specific settings, like the microcontroller PLL clock and BUS system, have to be
configured manually.
84 Chapter 6. Creating Embedded Programs
Build Target – compiles and assembles those files that have changed,
then links the project
Rebuild – compiles and assembles all files, regardless whether they have
changed or not, then links the project
While assembling, compiling, and linking, µVision displays errors and warnings
in the Build Output Window.
Highlight an error or
warning and press F1 to
get help regarding that
particular message.
Double-click the message
to jump to the source line
that caused the error or
warning.
Select the desired HEX format through the drop-down control to generate
formatted HEX files, which are required on some Flash programming utilities.
86 Chapter 6. Creating Embedded Programs
By combining µVision projects, which logically depend on each other, into one
Multi-Project, you increase the overview, consistency, and transparency of your
embedded system application design. µVision supports you in grouping various
stand-alone projects into one project overview.
Removing or deleting a
project from this list will
not physically delete the
project files, or the
respective project from the
storage location.
Activating a Multi-Project
To switch to another project, right click
the project name you wish to activate,
and click Set as Active Project.
1
Only existing projects can be maintained and added to a Multi-Project. You have to create the
stand-alone project prior to managing it in the Multi-Project environment.
2
Projects can have identical names as long as they reside in different folders.
88 Chapter 6. Creating Embedded Programs
Use the Batch Build1 command from the Build Toolbar or from the Project –
Batch Build Menu to build, re-build, or clean the Project Targets.
Batch Build – opens the window which lets you select the targets and
actions
The Build button compiles and assembles those files that have changed and links
the selected targets.
The Rebuild button compiles or assembles all files and links the selected targets.
The Clean button removes the object files for the selected targets.
1
Batch Build can be used in a Multi-Project setup only.
Getting Started: Creating Applications with µVision 89
Chapter 7. Debugging
The µVision Debugger can be configured as a Simulator1 or as a Target
Debugger2. Go to the Debug tab of the Options for Target dialog to switch
between the two debug modes and to configure each mode.
Third-party tool developers may use the Keil Advanced GDI to interface µVision
to their own hardware debuggers.
No matter whether you choose to debug with the Simulator or with a target
debugger, the µVision IDE implements a single user interface that is easy to
learn and master.
1
The Simulator offers more capabilities and features than those available when debugging on
target hardware. The Simulator runs entirely on the PC and is not limited by hardware
restrictions.
2
Programs run on your target hardware. You can debug your application with restrictions.
90 Chapter 7. Debugging
To debug programs
using the Simulator,
check
Use Simulator on the
left side of the Debug
dialog.
To debug programs
running on target
hardware, check
Use <Hardware
Debugger> on the right
side of the Debug
dialog.
Control Description
Settings Opens the configuration dialog for the simulation driver or the
Advanced GDI target driver
Load Application at Startup Loads the application program when you start the debugger
Limit Speed to Real-Time Limits simulation speed to real-time such that the simulation
does not run faster than the target hardware
Run to main() Halts program execution at the main C function. When not set,
the program will stop at an implicit breakpoint ahead of the main
function
Initialization File Specifies a command script file which is read and executed
when you start the debugger, before program execution is
started
Breakpoints Restores breakpoint settings from the prior debug session
Watchpoints & PA Restores watchpoints and Performance Analyzer settings from
the prior debug session
Memory Display Restores memory display settings from the prior debug session
Toolbox Restores toolbox buttons from the prior debug session
CPU DLL Specifies the instruction set DLL for the simulator. Do not
modify this setting.
Driver DLL Specifies the instruction set DLL for the target debugger. Do not
modify this setting.
Dialog DLL Specifies the peripheral dialog DLL for the simulator or target
debugger. Do not modify this setting.
Getting Started: Creating Applications with µVision 91
Simulation
µVision simulates up to 4 GB of memory from which specific areas can be
mapped for reading, writing, executing, or a combination of these. In most cases,
µVision can deduce the correct memory map from the program object module.
Any illegal memory access is automatically trapped and reported.
This screenshot below shows some of the key windows available in Debug
Mode.
Getting Started: Creating Applications with µVision 93
Debug Mode
Most editor features are also available while debugging. The Find command can
be used to locate source text and source code can be modified. Much of the
Debugger interface is identical to the Text Editor interface.
Executing Code
µVision provides several ways to run your programs. You can
Instruct the program to run directly to the main C function. Set this option in
the Debug tab of the Options for Target dialog.
Select debugger commands from the Debug Menu or the Debug Toolbar
Enter debugger commands in the Command Window
Execute debugger commands from an initialization file
Single-Stepping
To step through the program and into function calls use the Step
command from the Debug Toolbar or Debug Menu. Alternatively,
you enter TSTEP in the Command Window, or press F11.
To step through the program and over function calls use the Step Over
command from the Debug Toolbar or Debug Menu. Enter PSTEP in
the Command Window, or press F10.
To step out of the current function use the Step Out command from the
Debug Toolbar or Debug Menu. Enter OSTEP in the Command
Window, or press Ctrl+F11.
Memory Window
Monitor memory areas through four distinct Memory Windows.
Memory Commands
The following memory commands can be entered in the Command Window.
Command Description
ASM Displays or sets the current assembly address and allows you to enter
assembly instructions. When instructions are entered, the resulting op-
code is stored in code memory. You may use the in-line assembler to
correct mistakes or to make temporary changes to the target program.
DISPLAY Displays a range of memory in the Memory Window (if it is open) or in the
Command Window. Memory areas are displayed in HEX and in ASCII.
ENTER Allows you to change the contents of memory starting at a specified
address
EVALUATE Calculates the specified expression and outputs the result in decimal,
octal, HEX, and ASCII format
UNASSEMBLE Disassembles code memory and displays it in the Disassembly Window
98 Chapter 7. Debugging
Use Bookmarks to set reminders and markers in your source code. Define the
critical spots easily and navigate quickly between bookmarks using the bookmark
navigation commands. You can also define a bookmark and a breakpoint on the
same line of code concurrently.
Breakpoints Window
Invoke the Breakpoints
Window from the
Debug Menu.
Modify existing
breakpoints and add new
breakpoints via this
dialog. Enable/disable
breakpoints using the
checkbox in the
Current Breakpoints list. Double-click on an existing breakpoint to modify its
definition.
When a Command has been specified for a breakpoint, µVision executes the
command and continues to execute your target program. The command specified
can be a µVision debug function or signal function. To halt program execution
in a µVision function, set the _break_ system variable. For more information,
refer to System Variables in the on-line help.
The Count value specifies the number of times the breakpoint expression is true
before the breakpoint is triggered.
Breakpoint Commands
The following breakpoint commands can be entered in the Command Windows.
Command Description
BREAKSET Sets a breakpoint for the specified expression. Breakpoints are program
addresses or expressions that, when true, halt execution of your target
program or execute a specified command.
BREAKDISABLE Disables a previously defined breakpoint
BREAKENABLE Enables a previously defined breakpoint that is disabled
BREAKKILL Removes a previously defined breakpoint
BREAKLIST Lists all breakpoints
You may also set execution breakpoints while editing or debugging using buttons
on the File Toolbar.
Watchpoints
Define watchpoints to observe
variables, objects, and memory
areas affected by your target
program. Watchpoints can be
defined in two Watch pages.
The Locals Window contains
items of the currently executed
function. Items are added
automatically to the Locals
Window.
Modify local variables and watchpoint values by double-clicking the value you
want to change, or click on the value and press F2. Remove a watchpoint by
selecting it and press the Del key.
Watchpoint Commands
The following watchpoint commands can be entered in the Command Window.
Command Description
WATCHSET Defines a watchpoint expression to display in a Watch Window
WATCHKILL Deletes all defined watchpoint expressions in any Watch Window
102 Chapter 7. Debugging
The serial output can be assigned to a PC COM port using the ASSIGN
Debugger command.
You can copy the content of the window to the clipboard or save it to a file.
Where applicable, you can use the Toolbox1 features to interact with the
program.
1
You can add, remove, and change Toolbox buttons at any time. Use the Command Line in the
Command Window for this purpose.
Getting Started: Creating Applications with µVision 103
Execution Profiler
The Execution Profiler in µVision records the amount of time and the number
of times each assembler instruction and high-level statement in your program
executes.
The amount of time and the number of calls, which are displayed in the
Disassembly Window and in the Editor Window alike, are cumulative values.
Enable the Execution Profiler through the Debug – Execution Profiling Menu.
Invoke the Context Menu of the Disassembly Window to switch between the
time and calls.
When you locate program hotspots (with the Performance Analyzer), the
Execution Profiler makes it easy to find real performance bottlenecks.
104 Chapter 7. Debugging
Code Coverage
The Code Coverage
Window marks the code
that has been executed, and
groups the information
based on modules and
functions.
Code Coverage data can be saved to a file. You can even include a complete
CPU instruction listing in this report. To make use of all these features, examine
the COVERAGE command in the Command Window.
Performance Analyzer
The µVision Performance
Analyzer displays the
execution time recorded
for functions in your
application program.
Use this information to determine where your program spends most of its time
and what parts need further investigation.
Logic Analyzer
The Logic Analyzer
displays values of
variables or virtual
registers and shows the
changes on a time axis.
The Logic Analyzer window contains several buttons and displays several fields
to analyze data in detail. Move the mouse pointer to the desired location and
wait one second to get additional information, which pops-up automatically.
Control Description
Setup… Define your variables and their settings through the Logic Analyzer Setup dialog
Export… Saves the currently recorded signals to a tab-delimited file
Min Time Displays the start time of the signal recording buffer
Max Time Displays the end time of the signal recording buffer
Range Displays the time range of the current display
Grid Displays the time range of a grid line
Zoom Changes the time range displayed. Zoom All shows the content of the buffer
recording the signals. Zoom Sel zooms the display to the current selection (hold
Shift and drag the mouse to mark a section).
Show Opens the Editor or Disassembly Window at the code that caused the signal
transition. It will also stop the program from executing.
Setup Configures the range of a signal. The Auto button configures the minimum and
Min/Max maximum values based on the values from the current recording. The Undo button
restores the settings prior to using Auto.
Getting Started: Creating Applications with µVision 107
System Viewer
Peripheral Registers are memory mapped registers
that a processor can write to and read from to
control a peripheral device. µVision provides an
advanced method for viewing and debugging
these peripheral registers.
Symbols Window
The Symbols Window displays information from the Debugger in an ordered
and grouped manner and can be called via the Debug Toolbar or from the
View—Symbol Window Menu. This functionality includes objects:
Use this functionality to find items quickly. Drag and drop the objects to any
other window of µVision.
# matches a digit (0 - 9)
Browse Window
The Browse Window enables you to search for objects in the code. This feature
can be used in Debug and Build Mode. Nevertheless, the browse information is
only available after compilation. You have to set the option Options for Target
– Output – Browser Information to signal to the compiler to include browse
information into the object file. Launch this window via the File Toolbar or
View – Source Browser Window.
Enable or disable the Filter on buttons, enter your search criteria in the Symbol
field and narrow the result through the File Outline drop-down. You can sort the
results by clicking the header controls. Click an item to browse the occurrences
and locate its usages. Double-click a line in the Definition and References page
to jump to the code line.
Invoke the Context Menu while pointing at an item. Dependent on the object
class you will get different options. For functions, you can invoke the callers
graph and the call graph.
110 Chapter 7. Debugging
Toolbox
The Toolbox contains user-configurable buttons that
execute debugger commands or user-defined functions.
Click on a Toolbox button to execute the associated
command. Toolbox buttons may be clicked at any time,
even while the program executes.
Where:
button_label is the name that displays in the Toolbox
command is the command that executes when the button is pressed
The following examples show the commands used to create the buttons in the
Toolbox shown above:
DEFINE BUTTON "Decimal Output", "radix=0x0A"
DEFINE BUTTON "My Status Info", "MyStatus ()" /* call debug function */
DEFINE BUTTON "Analog1 0..3V", "analog0 ()" /* call signal function */
Remove a Toolbox button with the KILL BUTTON3 command. The button number
required in this statement is shown on the left side of the button. For example:
KILL BUTTON 5 /* resembles to: “Remove the ‘Stop Analog1’ button” */
1
The printf() command defined in the last example introduces nested strings. The double quote (")
and backslash (\) characters of the format string must be escaped with \ to avoid syntax errors.
2
Use this command to redefine the meaning of a button or change the description.
3
The Update Windows button in the Toolbox is created automatically and cannot be removed.
When pressed, this button updates the contents of several Debugger windows.
Getting Started: Creating Applications with µVision 111
Double-click any line in the Instruction Trace Window to jump to or open the
Disassembly Window. Use the predefined Filter options to view the instruction
tree in the preferred mode.
This functionality is
available for the
Simulator and while
debugging the target
hardware. The window’s
look and feel might vary,
since it depends on the
driver settings of the
debugging environment.
The following device families are supported by the Keil ULINK adapters:
The µVision Debugger interfaces to the target hardware through the following
drivers, which are provided by Keil:
251 Monitor
In addition, many third-party vendors offer µVision drivers for their hardware,
for example:
Control Description
Settings Opens the configuration dialog for the simulation driver or the
Advanced GDI target driver
Load Application at Startup Loads the application program when you start the debugger
Limit Speed to Real-Time Limit simulation speed to real-time such that the simulation does
not run faster than the target hardware
Run to main() Program execution halts at the main C function. When not set,
the program will stop at an implicit breakpoint ahead of the main
function
Initialization File Specifies a command script file which is read and executed
when you start the debugger, before program execution is
started
Breakpoints Restores breakpoint settings from the prior debug session
Watchpoints & PA Restores watchpoints and Performance Analyzer settings from
the prior debug session
Memory Display Restores memory display settings from the prior debug session
Toolbox Restores toolbox buttons from the prior debug session
CPU DLL Specifies the instruction set DLL for the simulator. Do not
modify this setting.
Driver DLL Specifies the instruction set DLL for the target debugger. Do not
modify this setting.
Dialog DLL Specifies the peripheral dialog DLL for the simulator or target
debugger. Do not modify this setting.
114 Chapter 8. Using Target Hardware
Select Use Target Driver for Flash Programming to use a target adapter, like
the Keil ULINK USB-JTAG Adapter, SEGGER J-Link, EPM900 Emulator, or
Silabs adapter to program your system’s Flash memory.
Choose Target Options – from the Build Toolbar and select the
Utilities tab
Alternatively, you can use the Project – Options for Target Menu to open the
Utilities dialog.
Project-specific items, like the path for the generated HEX file, output file name,
device name, or clock frequency can be used in the Arguments field.
1
The µVision Device Database provides the correct configuration for memory Flash of many
microcontroller devices.
116 Chapter 8. Using Target Hardware
Before using the Debugger on target hardware, you have to configure the
µVision IDE to use the ULINK adapter, or any other external tool suited for
Flash programming.
The µVision Debugger can display memory contents and variables in several
familiar formats. Memory and variables are updated periodically, providing an
instant view of the current program status, even during program execution. It is
possible to set breakpoints that trigger on accessing a specific variable.
The Keil ULINK adapter family supports Flash device programming with
configurable programming algorithms. You can choose from preconfigured
programming algorithms, or customize the algorithms according to your needs.
External Flash memory programming is supported for many target systems as
well.
1
The ULINK adapters support a wide variety of devices and protocols, and support your target
hardware port pin characteristics.
Getting Started: Creating Applications with µVision 117
Debug Settings
Trace Settings (for Cortex-Mx devices only)
Flash Download
Connect the ULINK adapter to your PC. Only then, the ULINK configuration is
possible in µVision.
Click Target Options from the Build Toolbar and select the Debug tab,
or open the dialog from the Project – Options for Target – Debug
Menu
Click the Settings button to open the Target Driver Setup dialog.
118 Chapter 8. Using Target Hardware
Click Target Options from the Build Toolbar and select the Utilities
tab, or open the dialog from the Project – Options for Target Menu
To configure µVision for a specific driver, select Use Target Driver for Flash
Programming and choose the appropriate driver from the drop-down control.
Use the Settings button to open the driver-specific Flash Download Setup
dialog.
Programming Algorithms
The ULINK driver allows
you to specify the
programming algorithm
used to program Flash
memory.
If the Flash device you use is not listed, you may define new algorithms. Do this
for a new Flash device, which is currently not directly supported by Keil. You
may use the algorithms found in any \FLASH\ folder as a template for new
algorithms.
The programming algorithms included in your kit are stored in these folders:
BUS Configuration
Typically, the BUS system has to be configured before a device with external
Flash memory can be programmed. If you use the ULINK USB-JTAG adapter,
you may create an initialization file that uses predefined debug functions, like
_WBYTE and _WDWORD, to write to memory and configure the BUS. For
example:
_WDWORD(0xFFE00000, 0x20003CE3); // BCFG0: Flash Bus Configuration
_WDWORD(0xE002C014, 0x0E6001E4); // PINSEL2: CS0, OE, WE, BLS0..3
Example programs1 are stored in the \EXAMPLES\ folder, where each program
resides in a separate subfolder along with its project files. Thus, you can re-build
the examples and evaluate the features of µVision quickly.
While there are numerous example programs for you to examine, this manual
describes and demonstrates only four:
We advise you to try out the various functions of µVision while in Debug Mode.
Please test the features described in preceding chapters. In particular, get
familiar with the navigation, invoke the Context Menu of various objects, drag
and drop windows to other screen areas or other physical screens, and create and
save personalized layouts. Invoke the Performance Analyzer, Logic Analyzer,
Code Coverage, Symbols Window, and drag and drop items from one window
to another window. Single-step through the code, get familiar with the
Disassembly Window, and inspect how it works in conjunction with the
Register Window, Output Window, and Serial Window.
1
Example programs are license free.
Getting Started: Creating Applications with µVision 123
This small application helps you to confirm that you can compile, link, and
debug an application. You may perform these operations from the command
line, using batch files, or from µVision using the provided project file.
Select the Project – Open Project Menu and open HELLO.UVPROJ from the
...\EXAMPLES\HELLO\ folder.
Alternatively, you may drag and drop the HELLO.UVPROJ file into the µVision
application, or simply double-click the file.
1
Since µVision simulates the target hardware required for this program, you actually do not need
target hardware or an evaluation board.
124 Chapter 9. Example Programs
Click the Run button of the Debug Toolbar or choose Debug – Run to
start the “Hello” program. “Hello World” is printed to the Serial
Window and the program enters into an endless loop.
Click the Stop button to halt the program. Alternatively, press the Esc
key while in the Command Line of the Command Window
Single-step through the program using the Step buttons. The current
instruction, which will execute next, is marked with a yellow arrow. The
yellow arrow moves each time you step.
126 Chapter 9. Example Programs
While debugging, µVision displays the following default screen layout. If you
re-arrange the layout, µVision saves the layout automatically and provides this
layout next time you invoke the debugger. However, you cannot explicitly recall
the changed layout, unless you saved it through the Window – Debug Restore
Views… Menu.
Take the opportunity to get familiar with the new look and feel, and the
navigation features. See how the content of registers and memory areas can be
changed. Display the values in the different representations. We recommend
taking some time and using this simple example to explore the µVision
capabilities.
Getting Started: Creating Applications with µVision 127
The “Measure” program1 records data received from digital ports and A/D inputs.
A timer, which can be configured between 1 millisecond and 60 minutes,
controls the sample rate and interval. The current time and all data from the
input channels are measured and saved to a RAM buffer.
Please find your preferred “Measure” program in one of the following locations:
1
Since µVision simulates the hardware required for this program, you do not actually need target
hardware or an evaluation board.
128 Chapter 9. Example Programs
A project may contain one or more targets, a feature that allows you to build
different versions of your program. The “Measure” project contains several
targets for different test environments including the simulator and evaluation
boards. Select the model with the Simulator target. The following files comprise
the source code:
MEASURE.C This file contains the main C function and the interrupt
service routine for the timer. The main function initializes all
peripherals and performs command processing. The interrupt
routine manages the real-time clock and sampling.
MCOMMAND.C This file processes the display, time, and interval commands.
These functions are called from the main C function. The
display command lists the analog values in floating-point
format to give a voltage between 0.00V and 3.00V.
Use the Translate File command to compile the selected file in the
Project Workspace
Use the Build Target command to compile files that have changed
since the last build and link them
Use Rebuild All Target Files command to compile and link all files in
the project
Select the Build Target command to compile and link the source files of the
“Measure” project. µVision displays a message in the Command Window
when the build process has finished.
Getting Started: Creating Applications with µVision 129
Source Browser
The “Measure” project is configured to generate complete browser and debug
information.
Use the Source Browse command from the File Toolbar or View
Menu to view information about program variables and other objects
Use the Start/Stop Debug Session command from the Debug Toolbar
or Debug Menu to start the µVision debugger
Use the Trace Windows command from the Debug Toolbar or from the
View – Trace – Instruction Trace Window Menu to view executed
instructions stored in the trace buffer
Invoke the Context Menu of the Disassembly Window to review the options
offered.
Using Breakpoints
µVision supports execution, access, and complex breakpoints. The following
example shows how to create a breakpoint that is triggered when the value 3 is
written to current.time.sec.
Watching Variables
The µVision Debugger provides two Watch Windows to which you can add
variables, structures, and arrays for easy reference. The Watch Window updates
at the end of each execution command. Enable the View – Periodic Window
Update Menu to refresh the content of this window during program execution.
Remove a variable from the Watch Window by selecting the line and press the
Del key or use the Context Menu. Individual elements of structures and arrays
cannot be removed singly.
Getting Started: Creating Applications with µVision 135
1
The additional signals used in this screenshot are not integrated into the Measure example.
138 Chapter 9. Example Programs
Serial UART Window, where you can change the current time and the hours
of operation
Toolbox, where you can click the “Push for Walk” button to cross the street
Watch Window and I/O Port dialog, where you can watch the state of the
traffic light and the start/stop pedestrian lights
The following table specifies the location of the “Traffic” project files for the
various architectures.
1
Since µVision simulates the hardware required for this program, you do not need any target
hardware, an evaluation board, or a traffic light.
Getting Started: Creating Applications with µVision 139
Of course, you may always edit these files in their original source form by
clicking on the Text Editor tab.
The “Traffic” program is designed to accept commands from the on-chip serial
port, which is completely simulated within µVision, and to display output on a
traffic light, which is connected to I/O port pins.
Use the serial commands listed in the following table. These commands are plain
ASCII text. Each command must be terminated with a carriage return.
The “Blinky” program is a board-specific application, and thus, since the boards
are different, the program may show other board-specific features. Refer to the
board manual for detailed information.
Use the Rebuild command of the Build Toolbar to compile and link all
project files, or use the Project – Rebuild all target files Menu
After you have configured the µVision IDE, the Flash – Download Menu uses
the specified adapter for Flash programming.
Click Start/Stop Debug Session from the Debug Toolbar, or open the
Debug – Start/Stop Debug Session Menu, to start debugging your
application
Step One Line – use the step commands to debug the application on
target hardware
Glossary
ASCII
American Standard Code for Information Interchange
This is a set of codes used by computers to represent digits, characters,
punctuation, and other special symbols. The first 128 characters are
standardized. The remaining 128 are defined by the implementation.
Assembler
A computer program to create object code by translating assembly
instruction – mnemonics into opcodes, and by resolving symbolic names for
memory locations and other entities. Programs written in assembly
language and translated by an assembler can be loaded into memory and
executed.
CAN
Controller Area Network
Is a bus standard, designed specifically for automotive applications,
meanwhile also used in other industries. It allows microcontrollers and
devices to communicate with each other without a host computer.
CMSIS
Cortex Microcontroller Software Interface Standard
A vendor-independent hardware abstraction layer for the Cortex-Mx
processors. It enables consistent, scalable, and simple software interfaces to
the processor for interfacing peripherals, real-time operating systems, and
middleware, simplifying software re-use, and reducing the time to market
for new devices.
Compiler
A program that translates source code from a high-level programming
language, such as C/C++, to a lower level language, for example, assembly
language or machine code. A compiler is likely to perform many or all of
the following operations: lexical analysis, preprocessing, parsing, semantic
analysis, code generation, and code optimization. µVision implements
C/C++ compilers.
Getting Started: Creating Applications with µVision 147
CRC
Cyclic Redundancy Check
Is a type of function to detect accidental alteration of data during
transmission or storage.
Debugger
A computer program to test software. Debuggers offer sophisticated
functions such as running a program step-by-step (single-stepping),
stopping, pausing the program to examine the current state at some kind of
event through breakpoints, and tracking the values of variables.
FPGA
Field-Programmable Gate Array
A semiconductor device that can be configured by the customer after
manufacturing.
GPIO
General Purpose Input/Output
An interface available on microcontroller devices to interact digitally with
the outside world. GPIOs are often arranged into groups, typically of 8, 16,
or 32 pins. The GPIO port pins can be configured individually as input or
output.
ICE
In-Circuit-Emulator
A hardware device used to debug software of an embedded system. It
provides hardware-level run-control and breakpoint features. Some ICEs
offer a trace buffer that stores the most recent microcontroller events.
Include file
A text file that is incorporated into a source file using the #include
preprocessor directive.
Instruction set
An instruction set, or instruction set architecture (ISA), is the part of the
microcontroller architecture related to programming, including the native
data types, instructions, registers, addressing modes, memory architecture,
interrupt and exception handling, and external I/O. An ISA includes a
specification of the set of opcodes – the native commands implemented by
a particular microcontroller.
148 Glossary
JTAG
Joint Test Action Group
The common name used for the IEEE 1149.1 standard called Standard Test
Access Port and Boundary-Scan Architecture. JTAG is often used as a
microcontroller debug or probing port and allows data transfer out of and
into device memory.
Library
Is a file, which stores a number of possibly related object modules. The
linker can extract modules from libraries to use them in building an object
file.
LIN
Local Interconnect Network
Is a vehicle bus standard or computer networking bus-system used within
current automotive network architectures. The LIN bus is a small and slow
network system that is used as a cheap sub-network of a CAN bus.
Linker
Is a program that combines libraries and objects, generated by a compiler,
into a single executable program.
Lint
A tool to check C/C++ code for bugs, glitches, inconsistency, portability,
and whether the code is MISRA compliant.
Macro
Defines a rule or pattern that specifies how a certain input sequence should
be mapped to an output sequence.
MDI
An application that allows the user to open more than one document from
the same application without having to purposely launch another instance of
the application.
Memory model
Is a definition that specifies which memory areas are used for function
arguments and local variables.
Getting Started: Creating Applications with µVision 149
MISRA
Motor Industry Software Reliability Association
A forum that provides software development standards for the C/C++
programming language, focusing on code safety, portability , and reliability
in the context of embedded systems.
Monitor
Is a program for 8051 and C166 devices. It can be loaded into your target
microcontroller to aid in debugging and rapid product development through
rapid software downloading.
Object
A memory area that can be examined. Usually used when referring to the
memory area associated with a variable or function.
Object file
Created by the compiler, this file contains an organized collection of
objects, which are sequences of instructions in a machine code format, but
might also contain data for use at runtime: relocation information, stack
unwinding information, comments, names of variables and functions for
linking, and debugging information.
OCDS
On Chip Debug Support
A debug port that provides hardware emulation features for the Infineon
166 devices.
Opcode
An operation code is that portion of a machine language instruction that
specifies the operation to be performed. Their specification and format are
laid out in the instruction set architecture of the processor.
Simulation
Is the imitation of a real thing or process. In µVision, simulation is used to
create embedded applications without using ‘real’ hardware. You can
represent key characteristics and behaviors of the selected system, perform
optimization, safety engineering, testing, and debugging.
Stack
An area of memory, indirectly accessed by a stack pointer, that shrinks and
expands dynamically, and holds local function data. Items in the stack are
removed on a LIFO (last-in, first-out) basis.
150 Glossary
Token
Is a fundamental symbol that represents a name or entity in a programming
language.
Thumb, Thumb2
An instruction set for ARM and Cortex devices. See instruction set.
UART
Universal Asynchronous Receiver/Transmitter
Is an individual IC, or part of an IC, used for serial communications.
Getting Started: Creating Applications with µVision 151
Index
Cortex-Mx ................................ 15
µ ARM7/ARM9
Advantages ............................... 16
µVision
Coding Hints ............................ 31
Concepts................................... 55
Highlights ................................. 22
Debugger .................................. 35
Microcontrollers ....................... 21
Debugger Modes ...................... 36
Tool Support ............................ 23
Device Database ...................... 35
Assembler..................................... 37
features ..................................... 34
Assistance..................................... 13
IDE ........................................... 34
Operating Modes...................... 59
B
8 Batch-Build .................................. 88
Bookmarks ................................... 98
8051
Breakpoints .................................. 98
Advantages............................... 15
Commands ............................. 100
Classic ...................................... 17
Managing ................................. 99
Coding Hints ............................ 29
Types ........................................ 99
Extended .................................. 17
Build Toolbar ............................... 65
Highlights................................. 18
Building a project ......................... 84
Memory Types ................... 17, 19
Tool Support ............................ 18
C
A C/C++ Compiler........................... 38
C166, XE166, XC2000
Adding books ............................... 78
Advantages ............................... 16
Adding source files ...................... 79
Coding Hints ............................ 30
Adding targets, groups, files ........ 78
Highlights ................................. 20
Additional Icons ........................... 67
Memory Types ......................... 20
Advantages
Tool Support ............................ 21
8051 ......................................... 15
Code comparison
ARM7/ARM9 .......................... 16
I/O Access ................................ 26
C166, XE166, XC2000 ............ 16
Pointer Access .......................... 27
Cortex-Mx................................ 16
Code coverage ............................ 104
Architectures ................................ 14
Code, generating optimal ............. 28
16-bit ........................................ 14
Coding Hints
32-bit ........................................ 14
8051.......................................... 29
8-bit .......................................... 14
152
I Creating .................................... 86
Managing ................................. 86
I/O access comparison ................. 26
Infineon C166, XE166, XC2000 . 20
O
Installation ................................... 11
Object-HEX converter ................. 38
K On-line Help ................................. 74
Options ......................................... 81
Keil Tools ...................................... 9
Kernel information ..................... 141
P
W
T
Watchpoints................................ 101
Target Hardware ........................ 112
Commands ............................. 101
Target options .............................. 81
Who should Read this Book ........... 3
Targets ......................................... 79
Window
Testing ......................................... 89
Breakpoints .............................. 99
Tool options ................................. 81
Browse ................................... 109
Getting Started: Creating Applications with µVision 155