This action might not be possible to undo. Are you sure you want to continue?
with µVision2 and 166/ST10 Microcontroller Development Tools
User’ Guide 03.99 s
ii
Keil Software. 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’ personal use, without written s permission. Copyright © 1997-1999 Keil Elektronik GmbH and Keil Software, Inc. All rights reserved.
Keil C166™ and µVision™ are trademarks of Keil Elektronik GmbH. 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 166 and ST10 microcontrollers.
Every effort was made to ensure accuracy in this manual and to give appropriate credit to persons, companies, and trademarks referenced herein.
Getting Started
iii
Preface
This manual is an introduction to the Keil Software development tools for the Siemens 166 and ST Microelectronics ST10 family of microcontrollers. It introduces new users and interested readers to our product line. With nothing more than this book, you should be able to successfully run and use our tools. This user’ guide contains the following chapters. s “Chapter 1. Introduction” gives an overview of this user’ guide and discusses the s different products that we offer for the 166 and ST10 microcontroller family. “Chapter 2. Installation” describes how to install the software and how to setup an operating environment for the tools. “Chapter 3. Development Tools” describes the major features of the µVision2 IDE with integrated debugger, the C compiler, assembler, and utilities. “Chapter 4. Creating Applications” describes how to create projects, edit source files, compile and fix syntax errors, and generate executeable code. “Chapter 5. Testing Programs” describes how you use the µVision2 debugger to simulate and test your entire application. “Chapter 6. µVision2 Debug Functions” discusses built-in, user, and signal functions that extended the debug capabilities or generate I/O signals. “Chapter 7. Sample Programs” shows how to use the Keil 166 development tools. “Chapter 8. Using on-chip Peripherals” shows how to access the on-chip 166/ST10 peripherals within the C166 compiler. “Chapter 10. CPU and C Startup Code” provides information on setting up the 166/ST10 CPU for your application. “Chapter 11. Using Monitor-166” discusses how to initialize the monitor and install it on your target hardware. “Chapter 12. Command Reference” briefly describes the commands and controls available in the Keil 166 development tools.
iv
Preface
Document Conventions
This document uses the following conventions:
Examples README.TXT Description
Bold capital text is used for the names of executable programs, data files, source files, environment variables, and commands you enter at the command prompt. This text usually represents commands that you must type in literally. For example:
CLS
DIR
L166.EXE
Note that you are not required to enter these commands using all capital letters.
Courier
Text in this typeface is used to represent information that displays on screen or prints at the printer. This typeface is also used within the text when discussing or describing command line items.
Variables
Text in italics represents 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. Ellipses (… ) are used to indicate an item that may be repeated. Vertical ellipses are used in source code listings to indicate that a fragment of the program is omitted. For example:
Elements that repeat… Omitted code : :
Void main (void) { : : while (1);
Optional arguments in command lines and optional fields are indicated by double brackets. For example:
¤ Optional Items¥
C166 TEST.C PRINT ¤ (filename)¥
{ opt1 | opt2 } Text contained within braces, separated by a vertical bar represents a group of items from which one must be chosen. The braces enclose all of the choices and the vertical bars separate the choices. One item in the list must be selected. Text in this sans serif typeface represents actual keys on the keyboard. For example, “ Press Enter to continue.” Move the mouse until the mouse pointer rests on the item desired. Quickly press and release a mouse button while pointing at the item to be selected. Press the left mouse button while on a selected item. Then, hold the button down while moving the mouse. When the item to be selected is at the desired position, release the button. Click the mouse button twice in rapid succession.
Keys
Point Click Drag
Double-Click
Getting Started
v
Contents
Chapter 1. Introduction .................................................................................. 1
166/ST10 Microcontroller Family ............................................................................2 Manual Topics .........................................................................................................3 Changes to the Documentation .................................................................................3 Evaluation Kits and Production Kits.........................................................................4 Types of Users..........................................................................................................4 Requesting Assistance ..............................................................................................5 Product Overview.....................................................................................................8
Chapter 2. Installation................................................................................... 11
System Requirements .............................................................................................11 Installation Details .................................................................................................11 Folder Structure .....................................................................................................12
Chapter 3. Development Tools...................................................................... 13
µVision2 Integrated Development Environment .....................................................13 C166 Optimizing C Cross Compiler.......................................................................20 A166 Macro Assembler..........................................................................................28 L166 Linker/Locator ..............................................................................................30 LIB166 Library Manager........................................................................................34 OH166 Object-HEX Converter ...............................................................................34
Chapter 4. Creating Applications ................................................................. 35
Create a Project ......................................................................................................35 Project Targets and File Groups .............................................................................42 Overview of Configuration Dialogs ........................................................................43 µVision2 Utilities ...................................................................................................44 Writing Optimum Code..........................................................................................48 Applications without external RAM Devices ..........................................................55 Tips and Tricks ......................................................................................................56
Chapter 5. Testing Programs........................................................................ 67
µVision2 Debugger ................................................................................................67 Debug Commands ..................................................................................................80 Expressions ............................................................................................................82
Chapter 6. µVision2 Debug Functions .......................................................... 97
Creating Functions .................................................................................................97 Invoking Functions ................................................................................................99 Function Classes ....................................................................................................99 Differences Between Debug Functions and C .......................................................110
Chapter 7. Sample Programs .......................................................................111
HELLO: Your First 166 C Program.....................................................................112 MEASURE: A Remote Measurement System ......................................................117
vi
Contents
Chapter 8. Using on-chip Peripherals.......................................................... 127
DPP Registers ...................................................................................................... 129 Interrupts ............................................................................................................. 131 Peripheral Event Controller ................................................................................. 134 Parallel Port I/O................................................................................................... 138 General Purpose Timers....................................................................................... 140 Serial Interface .................................................................................................... 142 Watchdog Timer .................................................................................................. 145 Pulse Width Modulation ...................................................................................... 146 A/D Converter ..................................................................................................... 149 Power Reduction Modes....................................................................................... 150
Chapter 10. CPU and C Startup Code ........................................................ 153
Selecting the Memory Model ............................................................................... 153 Configuring the Startup Code .............................................................................. 153
Chapter 11. Using Monitor-166................................................................... 155
µVision2 Monitor Driver ..................................................................................... 157 Target Options when Using Monitor-166 ............................................................. 159 Monitor-166 Configuration .................................................................................. 160 Trouble Shooting ................................................................................................. 160
Chapter 12. Command Reference................................................................ 163
µVision 2 Command Line Invocation................................................................... 163 A166 Macro Assembler Directives ....................................................................... 164 C166 Optimizing C Cross Compiler Directives .................................................... 166 L166 Linker/Locator Directives ........................................................................... 168 LIB166 Library Manager Commands................................................................... 170 OH166 Object-HEX Converter Commands .......................................................... 171
Index ............................................................................................................. 172
Introduction Thank you for allowing Keil Software to provide you with software development tools for the 166 and ST10 family of microprocessors. RTX-166 real-time operating system: simplifies the design of complex. you can generate embedded applications for the C161. 8xC166. and debug your target program. L166 Linker/Locator: combines relocatable object modules created by the compiler and assembler into the final absolute object module. The Keil Software 166 development tools listed below are the programs you use to compile your C code. NOTE Throughout this manual we refer to these tools as the 166 development tools. However. they are not limited to just the 8xC166 devices. and Program Debugging in one powerful environment. With the Keil tools. OH166 Object-HEX Converter: creates Intel HEX files from absolute object modules. LIB166 Library Manager: combines object modules into a library which may be used by the linker. Each of these programs is described in more detail in “Chapter 3. link your program together. They are designed for the professional software developer. C165. but any level of programmer can use them to get the most out of the 166 hardware. A166 Macro Assembler: creates relocatable object modules from your 8xC166 or C167 assembler source code. Development Tools” on page 13. C167 and ST10 microcontrollers as well as future derivatives. create HEX files. Source Code Editing. ¢ 1 µVision2 for Windows™ Integrated Development Environment: combines Project Management. C164. . C166 ANSI Optimizing C Cross Compiler: creates relocatable object modules from your C source code. ¢ ¢ ¢ ¢ ¢ ¢ The tools are combined into the kits described in “Product Overview” on page 8. C163.Getting Started 1 Chapter 1. assemble your assembler source files. timecritical software projects.
down-grade of the C167 CPU. Variants with Flash memory available.2 Chapter 1. Variants with on-chip Flash memory and CAN interface are available. The 166/ST10 microcontroller family constantly grows. interrupts and I/O pins. Basic Device Code C161 (several Variants) C163 C164 C165 8xC166 C167 (several Variants) ST10-272 max. The following list provides only a brief overview. A flexible memory interface lets you expand the capabilities of the 166 using standard peripherals and memory devices in either 8-bit or 16-bit configurations. version with high speed CPU and on-chip MAC (DSP) coprocessor unit. the 166 CPU s. less I/O. and a rich set of timers. Flash memory. Overview of various 166 and ST10 derivatives The 166/ST10 family covers today 30+ different CPU variants with extensive onchip peripheral and I/O. watchdogs and clock drivers. Many derivatives are available and several are available from multiple sources (Siemens and ST Microelectronics). The high-end 166 CPU with extensive peripherals and I/O capabilities. less on-chip RAM. . with special capture/compare unit for high-speed signal generation and event capturing. The original 166 CPU. core is destined to see service well into the next century. variants with on-chip OTP memory available. CPU Clock 16 MHz 25 MHz 20 MHz 25 MHz 20 MHz 25 MHz Description low-cost controller. As a 16-bit. Also included are power management features. no A/D converter. data memory. 50 MHz This list represents the devices available in January 1999. Many variants offer A/D converters. down-grade of the C165 CPU. Introduction 166/ST10 Microcontroller Family 1 The 166/ST10 family of microcontrollers has been available since the early 1990’ With a wide variety of outstanding features and peripherals. the 166 family has no equal. CAN interface. Announcements for 1999: several new devices and improving of the CPU speed. Some variants have on-chip Flash program and data memory. no extended instruction set and limited to 256 KB memory space. A typical 166/ST10 family member contains the 8xC166 or C167 CPU core. The memory interface allows a mixture of 8 / 16-bit multiplexed / non-multiplex bus systems including chip select pins on up to five memory areas. code memory. high-performance embedded processor. and some versatile peripheral functions.
Sample Programs” on page 111). Create full applications using the µVision2 integrated development environment (see “Chapter 4. Install the software on your system (see “Chapter 2. Access the on-chip peripherals and special features of the 166 variants using the C166 compiler (see “Chapter 8.Getting Started 3 Manual Topics This manual discusses a number of topics including how to: ¢ 1 Select the best tool kit for your application (see “Product Overview” on page 8).TXT files. you may do so by installing the software (refer to “Chapter 2. Using on-chip Peripherals” on page 127). These files are located in the folders UV2 and C166\HLP. . Testing Programs” on page 67). Installation” on page 11) and running the sample programs (refer to “Chapter 7. Sample Programs” on page 111). Take the time to read this file to determine if there are any changes that may impact your installation. Creating Applications” on page 35). Installation” on page 11). Run the included sample programs (see “Chapter 7. Changes to the Documentation Last minute changes and corrections to the software and manuals are listed in the RELEASE. ¢ ¢ ¢ ¢ ¢ ¢ NOTE If you want to get started immediately. Overview and features of the 166 development tools (see “Chapter 3. Debug programs and simulate target hardware using the µVision2 debugger (see “Chapter 5. Development Tools” on page 13).
com under the update section. and sample programs. The included software provides you with the latest development tool technology. Introduction Evaluation Kits and Production Kits 1 Keil Software provides two types of kits in which our tools are delivered. and introduces the sample programs. take the time to read this manual. Even if you are only an evaluation user. manuals. The EK166 Evaluation Kit includes evaluation versions of our 166 tools along with this user’ guide. The 166 Production Kits (discussed in “Product Overview” on page 8) include the unlimited versions of our 166 tools along with this user’ guide and the full s manual set. The evaluation package includes evaluation tools that are limited to 4 Kbytes along with several sample programs that provide real-world applications created for the 166/ST10 microcontroller family. Types of Users This manual addresses three types of users: evaluation users. The tools in the evaluation kit let you generate applications s up to 4 Kbytes in size. The production kits also include 1 year of free technical support and product updates. . Evaluation Users are those users who have not yet purchased the software but have requested the evaluation package to get a better feel for what the tools do and how they perform. They provide a quick tutorial and help new or inexperienced users quickly get started. Updates are available on world wide web www. The software included with a product upgrade contains the latest development tools and sample programs. take the time to review the sample programs described in this manual.keil. provides you with an overview of the development tools. new users. You may use this kit to evaluate the effectiveness of our 166 tools and to generate small target applications. If you are new to the 166 or the tools. and experienced users. It explains how to install the software. New Users are those users who are purchasing 166 development tools for the first time.4 Chapter 1. Experienced Users are those users who have previously used the Keil 166 development tools and are now upgrading to the latest version.
compiler. NOTE You can always get technical support. 4. 1 . We prefer that you send the problem via email. application notes. The more descriptive your example. Read the sections in this manual that pertains to the job or task you are trying to accomplish. 1. and sample programs from our world wide web site www. 3.com to make sure that you have the latest software version. or another development tool. the faster we can find a solution. after following these steps. If you have suggestions or comments regarding any of the printed manuals accompanying this product.Getting Started 5 Requesting Assistance At Keil Software. linker.keil. do the following before calling technical support. you are still experiencing problems. library manager. 2. Try to be as detailed as possible when describing the problem you are having. product updates. we are dedicated to providing you with the best embedded development tools and documentation available. report them to our technical support group. Isolate the problem to determine if it is a problem with the assembler. If you contact us by fax. please contact us. Please try to avoid sending complete applications or long listings as this slows down our response to you. If. make sure that your problem can be duplicated with the µVision2 simulator. Please include your product serial number and version number. If you think you have discovered a problem with the software. Make sure you are using the most current version of the software and utilities. be sure to include your name and telephone numbers (voice and fax) where we can reach you.com. please email it to us. Further isolate software problems by reducing your code to a few lines. If possible. Check out the update section on. If you have a one-page code example demonstrating the problem.
Create a project to select the 166/ST10 device and the tool settings. Test linked application. a rich-featured editor with interactive error correction. 3. The compiler and assembler process source files and creates relocatable object files. Correct errors in source files. Introduction Software Development Cycle 1 When you use the Keil Software tools. option setup. C167 and ST10 derivatives.6 Chapter 1. . 5. and links your embedded application and provides a single focal point for you development efforts. the project development cycle is roughly the same as it is for any other software development project. assembles. make facility. µVision2 IDE with Editor & Make C166 ANSI C Compiler A166 Macro Assembler ANSI C Standard Library LIB166 Library Manager RTX166 Real-Time Operating System L166 Linker/Locater Emulator & PROM Programmer µVision2 IDE The µVision2 IDE combines project management. and on-line help. In addition. 2. 166 Compiler & Assembler Source files are created by the µVision2 IDE and are passed to the C166 compiler or A166 assembler. 1. The Keil A166 macro assembler supports the complete instruction sets of the 8xC166. Create source files in C or assembly. 4. The Keil C166 compiler is a full ANSI implementation of the C programming language. Build your application with the project manager. All standard features of the C language are supported. µVision2 Debugger high-speed CPU/Peripheral Simulation Monitor-166 Target Debugger Advanced GDI interface for Emulators & Target Debuggers You use µVision2 to create your source files and organize them into a project that defines your target application. numerous features for direct support of the 166 environment have been added. µVision2 automatically compiles. The development cycle described above may be best illustrated by a block diagram of the complete 166 tool set.
Via the integrated device database you can configure the µVision2 debugger to the attributes and peripherals of 166/ST10 device you are using. When the linker processes a library. For testing the software in a real hardware. All the code in an absolute object file resides at fixed memory locations. . An absolute object file or module contains no relocatable code. symbolic debugging on your target hardware. reliable program debugging. programming. ordered program collections of object modules that the linker may process at a later time. With Monitor-166. The RTX166 real-time kernel simplifies the system design. 1 L166 Linker/Locator Object files and library files are processed by the linker into an absolute object module. only those object modules in the library that are necessary to create the program are used. Monitor-166 The µVision2 Debugger supports target debugging using Monitor-166. µVision2 lets you perform source-level. µVision2 Debugger The µVision2 symbolic. source-level debugger is ideally suited for fast. The monitor program is a program that resides in the memory of your target hardware and communicates with µVision2 using the serial port of the 166 and a COM port of your PC. RTX166 Real-Time Operating System The RTX166 real-time operating system is a multitasking kernel for the 166 family. you may connect the µVision2 Debugger with Monitor-166 or you can use the Advanced GDI interface to attach the debugger front-end to a target system. The absolute object file may be used to program EPROM or other memory devices. The absolute object module may also be used with the µVision2 Debugger or with an in-circuit emulator for the program test.Getting Started 7 LIB166 Library Manager Object files created by the compiler and assembler may be used by the LIB166 library manager to create object libraries which are specially formatted. The debugger contains a high-speed simulator that let you simulate an entire 166 system including on-chip peripherals and external hardware.
C165. The kit includes everything you need to create embedded applications and can be configured for all 166/ST10 derivatives. The kernel is fully integrated into the C166 compiler and is easy to use. CA166 Compiler Kit The CA166 Compiler Kit is the best choice for developers who need a C compiler but not a debugging system. The CA166 package contains only the µVision IDE. C163. We bundle our software development tools into different packages or tool kits. The µVision2 Debugger features are not available in CA166. A166 Assembler Kit The A166 Assembler Kit includes an assembler and all the utilities you need to create embedded applications. . Product Overview Keil Software provides the premier development tools for the Siemens 166 and ST Microelectronics ST10 microcontrollers. 8xC166. PK166 Professional Developer’ Kit s The PK166 Professional Developer’ Kit includes everything the professional s developer needs to create and debug sophisticated embedded applications for the Siemens C161. Task description tables and operating system consistency are automatically controlled by the L166 linker/locator. Other 166/ST10 family members are not supported. and C167 as well as the ST Microelectronics ST10 series of microcontrollers. It can be configured for all 166/ST10 derivatives. The “Comparison Chart” on page 9 shows the full extent of the Keil Software 166 development tools. Introduction 1 and debugging of complex applications where fast reaction to time critical events is essential.8 Chapter 1. Each kit and its contents are described below. s PK161 Professional Developer’ Kit s The PK161 Professional Developer’ Kit is a reduced version of PK166 and can s be used only for the Siemens C161 derivatives. C164. The professional developer’ kit can be configured for all 166/ST10 derivatives.
it does not include support for other 166/ST10 devices. RTX166 Full provides a superset of the features found in RTX166 Tiny and includes CAN communication protocol interface routines. . 1 Comparison Chart The following table provides a check list of the features found in each package. Use this cross reference to select the kit that best suits your needs.Getting Started 9 RTX166 Real-Time Operating System (FR166) The RTX166 Real-Time Operating Systems is a real-time kernel for the 166 family of microcontrollers. Tools are listed along the top and part numbers for specific kits are listed along the side. Support µVision2 Project Management & Editor A166 Assembler C166 Compiler L166 Linker/Locator LIB166 Library Manager µVision2 Debugger/Simulator RTX166 Tiny RTX166 Full PK166 CA166 A166 PK161† FR166 ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü ü † PK161 supports only C161 derivatives.
Introduction 1 .10 Chapter 1.
NOTE Your PC should automatically launch the CD Viewer when you insert the CD. run the program KEIL\SETUP\SETUP. Windows-98. 20 MB free disk space. Windows NT 4. Installation This chapter explains how to setup an operating environment and how to install the software on your hard disk. To install the 166 development tools: ¢ ¢ Insert the Keil Development Tools CD-ROM. For our Windows-based tools. Make a copy of the installation diskette for backup purposes. you must have the following: ¢ ¢ ¢ ¢ PC with Pentium. If not. Installation Details All of our products come with an installation program that allows easy installation of our software. you must do the following: ¢ ¢ Verify that your computer system meets the minimum requirements.Getting Started 11 Chapter 2. Select Install Software from the Keil CD Viewer menu and follow the instructions displayed by the setup program. Pentium-II or compatible processor. Before starting the installation program. 2 System Requirements There are minimum hardware and software requirements that must be satisfied to ensure that the compiler and utilities function properly. or higher 16 MB RAM minimum.0. .EXE from the CD to install the software. Windows 95.
Sample applications. The default base folder is: C:\KEIL. Your installation may vary depending on the products you purchased. 2 Folder C:\KEIL\C166\ASM C:\KEIL\C166\BIN C:\KEIL\C166\CAN C:\KEIL\C166\EXAMPLES C:\KEIL\C166\RTX166 C:\KEIL\C166\RTX_TINY C:\KEIL\C166\INC C:\KEIL\C166\LIB C:\KEIL\C166\MONITOR C:\KEIL\UV2 Description Assembler SFR definition files and template source file. C compiler library files. RTX166 Full CAN example programs. . Within this users guide we refer to the default folder structure. startup code.12 Chapter 2. you have to adjust the pathnames to match with your installation. Target Monitor files and Monitor configuration for user hardware. Executable files of the 166 toolchain. If you have installed your software on a different folder. RTX166 Full files. The following table lists the structure of a complete installation that includes the entire line of 166 development tools. and source of I/O routines. Installation Folder Structure The setup program copies the development tools into sub-folders of the base folder. C compiler include files. RTX166 Tiny files. Generic µVision2 files.
True integrated source-level Debugger with high-speed CPU and peripheral simulator. and object-HEX converter. Device Database for pre-configuring the development tool setting.Getting Started 13 Chapter 3. project manager. µVision2 helps expedite the development process of your embedded applications by providing the following: ¢ ¢ ¢ ¢ 3 Full-featured source code editor. µVision2 Integrated Development Environment µVision2 is a standard Windows application. They are easy to use and are guaranteed to help you achieve your design goals. Dialogs for all development tool settings. . compiling. linker/locator. We have designed our tools to help you quickly and successfully complete your job. µVision2 supports all of the Keil tools for the 166 including the C compiler. Advanced GDI interface for software debugging in the target hardware and for connection to Monitor-166. Integrated make facility for assembling. Project manager for creating and maintaining your projects. and make facility. s ¢ ¢ ¢ ¢ NOTE The µVision2 debugging features are only available in the PK166 and PK161 tool kits. Development Tools This chapter discusses the features and advantages of the 166 development tools available from Keil Software. macro assembler. and linking your embedded applications. Links to development tools manuals. µVision2 is an integrated software development platform that combines a robust editor. device datasheets & user’ guides.
File Menu and File Commands Toolbar File Menu New Shortcut Description Ctrl+N Create a new source or text file . and on-line help. and information displays. program debugging. project maintenance. 3 Menu Commands. Toolbars and Shortcuts The menu bar provides you with menus for editor operations. a tool bar where you can rapidly select command buttons. dialog boxes.14 Chapter 3. Several commands can be reached also with keyboard shortcuts. Development Tools About the Environment The µVision2 screen provides you with a menu bar for command entry. The following tables give you an overview of the µVision2 commands. window selection and manipulation. With the toolbar buttons you can rapidly execute operations. µVision2 lets you simultaneously open and view multiple source files. development tool option settings. and windows for source files.
9 Exit Shortcut Description Ctrl+O Open an existing file Close the active file Ctrl+S Create a new source or text file Save all open source and text files Save and rename the active file Maintain the µVision2 device database Setup the printer Ctrl+P Print the active file Display pages in print view Open the most recent used source or text files Quit µVision2 and prompt for saving files 3 Edit Menu and Editor Commands Toolbar Edit Menu Shortcut Description Home Move cursor to beginning of line End Move cursor to end of line Ctrl+Home Move cursor to beginning of file Ctrl+End Move cursor to end of file Ctrl+ç Ctrl+è Undo Redo Cut Copy Paste Find Move cursor one word left Move cursor one word rigth Ctrl+A Select all text in the current file Ctrl+Z Undo last operation Ctrl+Shift+Z Redo last undo command Ctrl+X Cut selected text to clipboard Ctrl+Y Cut text in the current line to clipboard Ctrl+C Copy selected text to clipboard Ctrl+V Paste text from clipboard Ctrl+F Search text in the active file F3 Repeat search text forward Shift+F3 Repeat search text backward Ctrl+F3 Search word under cursor Ctrl+] Find matching brace.Getting Started 15 Toolbar File Menu Open Close Save Save as… Device Database Print Setup… Print Print Preview 1 . or bracket Find in Files… Replace Search text in several files Ctrl+H Replace specific text Indent selected text right one tab stop Indent selected text left one tab stop Ctrl+F2 Toggle bookmark at current line F2 Move cursor to next bookmark Shift+F2 Move cursor to previous bookmark .. parenthesis.
Development Tools Toolbar Edit Menu Shortcut Description Clear all bookmarks in active file Select Text Commands In µVision2 you can select text by holding down Shift and pressing the key that moves the cursor. For example. and Ctrl+Shift+è selects the text from the current cursor position to the beginning of the next word. and then click Move the pointer to the left of the lines until it changes to a right-pointing arrow. Ctrl+è moves the cursor to the next word. With the mouse you can select text as follows: 3 Select Text Any amount of text A word A line of text Multiple lines of text A vertical block of text With the Mouse Drag over the text Double-click the word Move the pointer to the left of the line until it changes to a right-pointing arrow.16 Chapter 3. and then drag View Menu Toolbar View Menu Status Bar File Toolbar Build Toolbar Debug Toolbar Project Window Output Window Source Browser Disassembly Window Watch & Call Stack Window Memory Window Code Coverage Window Performance Analyzer Window Symbol Window Serial Window #1 Serial Window #2 Toolbox Periodic Window Update Workbook Mode Options… Shortcut Description Show or hide the status bar Show or hide the File toolbar Show or hide the Build toolbar Show or hide the Debug toolbar Show or hide the Project window Show or hide the Output window Open the Source Browser window Show or hide the Disassembly window Show or hide the Watch & Call Stack window Show or hide the Memory window Show or hide the Code Coverage window Show or hide the Performance Analyzer window Show or hide the Symbol window Show or hide the Serial window #1 Show or hide the Serial window #2 Show or hide the Toolbox Updates debug windows while running the program Show workbook frame with windows tabs Select Colors & Fonts and Editor options . and then drag up or down Hold down the ALT key.
Group or File Change options for current Target Select current Target File Extensions Build Target Rebuild Target Translate… Stop Build 1 . Files Select Device for Target Options… Shortcut Description Create a new project Open an existing project Close current project Maintain Targets. 9 Select file extensions for different file types F7 Translate modified files and build application Re-translate all source files and build application Ctrl+F7 Translate current file Stop current build process Open the most recent used project files 3 Debug Menu and Debug Commands Toolbar Debug Menu Start/Stop Debugging Reset CPU Go Step Step over Step out of current function Stop Running View Trace Records Breakpoints… Shortcut Description Ctrl+F5 Start or stop µVision2 Debug Mode Set CPU to reset state F5 Run (execute) until the next active breakpoint F11 Execute a single-step into a function F10 Execute a single-step over a function Ctrl+F11 Execute a step out of the current function ESC Stop program execution Enable trace recording for instruction review Review previous executed instructions Open Breakpoint dialog Toggle breakpoint on current line Kill all breakpoints in the program Enable/disable breakpoint on the current line Disable all breakpoints in the program Show next executeable statement/instruction Enable/Disable Trace Recording Memory Map… Performance Analyzer… Inline Assembly… Function Editor… Open memory map dialog Open setup dialog for the Performance Analyzer Stop current build process Edit debug functions and debug INI file .. File Groups and Files of a proejct Select a CPU from the Device Database Alt+F7 Change tool options for Target.Getting Started 17 Project Menu and Project Commands Toolbar Project Menu New Project … Open Project … Close Project… Targets. Groups.
The menu is extended once you have added customer programs with the option Customize Tools Menu… Toolbar Tools Menu Shortcut Description Configure compiler and linker paths Configure PC-Lint from Gimpel Software Run PC-Lint current editor file Run PC-Lint across the C source files of your project Add user programs to the Tools Menu 3 Target Environment PC-Lint Options Lint Lint all C Source Files Customize Tools Menu… Window Menu Toolbar Window Menu Cascade Tile Horizontally Tile Vertically Arrange Icons Split 1 . these dialogs depend on the CPU selected from the device database [ Interrupt … Watchdog ] Tools Menu The tools menu allows you to run custom programs. 9 Shortcut Description Arrange Windows so they overlap Arrange Windows so they no overlap Arrange Windows so they no overlap Arrange Icons at the bottom of the window Split the active window into panes Activate the selected window Help Menu Toolbar Help Menu Help topics About µVision Shortcut Description Open on-line help Display version numbers and license information . Development Tools Toolbar Debug Menu Shortcut Description Open dialogs for on-chip peripherals.18 Chapter 3..
¢ In both operating modes you can use the source editor of µVision2 to modify your source code. The Debug Mode is described in “Chapter 5. The features of the Build Mode are described in ”Chapter 4.Getting Started 19 µVision2 has two operating modes: ¢ Build Mode: allows you to translate all the application files and to generate executable programs. Creating Applications” on page 35. Debug Mode: provides you with a powerful debugger for testing your application. Testing Programs” on page 67. 3 .
because of the comfortable modular program construction techniques. ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ C166 Language Extensions The C166 compiler is an ANSI compliant C compiler and includes all aspects of the C programming language that are specified by the ANSI standard. rudimentary knowledge of the memory structure of the 166/ST10 CPU is desirable (but not necessary). This leads to better program structure. A number . The Keil C166 is not a universal C compiler adapted for the 166. and can be easily obtained for most systems. The Keil C166 Compiler implements the ANSI standard for the C language. The language C is a very portable language (based on the ANSI standard) that enjoys wide popular support. Keywords and operational functions can be used that more nearly resemble the human thought process.20 Chapter 3. The C run-time library contains many standard routines such as: formatted output. The ability to combine variable selection with specific operations improves program readability. Use of a high-level language such as C has many advantages over assembly language programming: ¢ 3 Knowledge of the processor instruction set is not required. Programs get a formal structure and can be divided into separate functions. Existing program parts can be more easily included into new programs. the Keil C166 Cross Compiler offers a way to program in C which truly matches assembly programming in terms of code efficiency and speed. Details like register allocation and addressing of the various memory types and data types is managed by the compiler. Programming and program test time is drastically reduced which increases your efficiency. Development Tools C166 Optimizing C Cross Compiler For 166/ST10 microcontroller applications. This means that existing program investments can be quickly adapted to other processors as needed. numeric conversions and floating point arithmetic. It is a dedicated C compiler that generates extremely fast and compact code.
and arrays.7E+308 Address of objects 0 or 1 0 to 65535 Data Types for SFR access: The sbit and sfr data types are included to allow access to the special function registers that are available on the 166. variables can be combined into structures. Reentrant Functions. Pointers. Interrupt Functions. unions. the declaration: sfr P2 = 0xFFC0. The following sections briefly describe these extensions. 3 Data Types The C166 compiler supports the data types listed in the following table. declares the variable P2 and assigns it the special function register address of 0xFFC0. Memory Models. Real-Time Operating Systems. In addition to these scalar types.40E+38 ±1.176E-38 to ±3. For example. This is the address of PORT 2 on the C167. Data Type bit signed char unsigned char signed int unsigned int signed long unsigned long float double pointer sbit sfr Size 1 bit 1 byte 1 byte 2 bytes 2 bytes 4 bytes 4 bytes 4 bytes 8 bytes 2 / 4 bytes 1 bit 2 bytes Range of values 0 or 1 -128 to +127 0 to 255 -32768 to +32767 0 to 65535 -2147483648 to +2147483647 0 to 4294967295 ±1.Getting Started 21 of extensions to the C programming language are provided to support the facilities of the 166 microprocessor.7E-308 to ±1. . The C166 compiler includes extensions for: ¢ ¢ ¢ ¢ ¢ ¢ ¢ Data Types. Memory Types.
16 KB for system area in SDATA group. Accessing the integrated RAM (on-chip RAM = idata) is considerably faster than accessing off-chip (near. 32 bit address calculation supports objects with unlimited size. 16 KB for constants in NCONST group. far is the optimum memory type on the 80C166 CPU for accessing the 256KB address space of this CPU. extern float near x. . 16 bit address calculation allows access to: ¢ ¢ ¢ 16 KB for variables in NDATA group. 16 bit address calculation allows full access to the whole address space. bit-addressable on-chip RAM of the 166. Development Tools Memory Types The C166 compiler explicitly supports the architecture of all 166/ST10 derivatives completely. sbit flag0 = flags^0. extern unsigned int xhuge vector[50][100]. Together with the L166 directive DPPUSE you can have even up to 64KB NDATA/NCONST group. unsigned char sdata pec_buffer [100]. 16 bit address calculation supports objects which size up to 64 KB. If far is applied to a function a CALLS (segmented call) instruction is generated to this function.22 Chapter 3. 32 bit pointer. If near is applied to a function a CALLA or CALLR (16 bit call) is generated to this function. It has full access to all hardware components of the 166 system. huge is the optimum memory type on the newer 166 derivatives like the C167 for accessing the 16MB address space 32 bit pointer. SYSTEM area (address space 0C000h-0FFFFh). z. Therefore it is useful to place often-used variables into on-chip memory. 32 bit pointer. or xhuge) memory. y. and to locate larger and less often accessed data elements into the far or huge memory. huge. idata bdata sdata far on-chip RAM of the 166. static unsigned long far array [100]. 3 Memory Type near 166/ST10 Address Space 16 bit pointer. char bdata flags. supports mixed bit and byte accesses (limited to 256 bytes). far. Each variable can be explicitly assigned to various memory types. huge xhuge Examples of Variable Declarations with Memory Type: The following examples illustrate the use of the memory type within variable declarations: char idata var1. fastest access to variables. The size of a single object (array or structure) is limited to 16 KB. this can be used for the definition of PEC addressable objects.
A far pointer can access all objects in the 16MB address space. If you want to use a pointer to access the whole 16MB address space you must define a xhuge pointer. if for example the memory type near is used in the LARGE memory model. A near pointer allows the accessing of all objects which are user stack based or defined in the near. would define var1 to exist in near memory. whereby the size of a single object is limited to 16KB. If the HLARGE memory model is selected the var1 would have been placed into huge memory. huge and xhuge can also be applied to pointers. With xhuge very large objects with unlimited size can be accessed. Note Pointer arithmetic on huge pointers modifies only the 16-bit offset of the pointer. Memory Models C166 supports seven memory models. the default memory model SMALL. The memory model determines the default memory type to be used for variable or function declarations without explicit memory type. With an explicit memory type the limits of the memory model in used can be by-passed. idata or bdata area. With the exception of the TINY model. The default memory type depends on the memory model. . far. the default or implicit memory type is selected. sdata. In the same way the access to variables can be speed-up. Default Memory Type For… Variables Functions near near far huge near far huge near (up to 64KB code size) near (up to 64KB code size) near (up to 64KB code size) near (up to 64KB code size) far (unlimited code size) far (unlimited code size) far (unlimited code size) 3 Memory Model TINY SMALL COMPACT HCOMPACT (not for 8xC166 CPU) MEDIUM LARGE HLARGE (not for 8xC166 CPU) Pointer The memory type near. The memory type huge allows to access objects up to 64KB size. For instance if a definition is made as char var1[10]. the 166/ST10 operates always in the SEGMENTED mode.Getting Started 23 If the memory type is omitted in a variable declaration.
void near func1 (void). int (far *fp2) (void). char xhuge *xf_ptr. 3 Registerbanks C166 supports up to 128 logical register banks. Pointer Size 16/32 bit 16 bit 32 bit 32 bit 32 bit 16 bit 32 bit Declaration of the Pointer char *ptr. Areas for PEC data can be define with the memory type sdata or must be explicitly located to SEGMENT 0 of the 166/ST10 memory. Development Tools Examples for using the memory type together with Pointers: Variable Declaration char c. Refer to “Interrupt” on page 131 for example of an interrupt function. int near nc. unsigned long far l. . Such support allows the system programmer to create efficient effective interrupt procedures.) int near *np. The user need only be concerned with the interrupt and necessary register bank switch over operation. (Pointer size depends from the memory model in use. This allows that the main program and one or more interrupt service routines can call simultaneously the same function. in a general and high level manner. long far *lp. The code generated by C166 including all library functions is fully reentrant and independent from the register bank currently selected. char huge *hc_ptr. The C166 compiler generates only the code necessary to effect the most expedient handling. void (near *fp1) (void). PEC Support The Peripheral Event Controller (PEC) can be directly programmed in the C166 source. float xhuge xf.24 Chapter 3. int far func2 (void). Refer to “Peripheral Event Controller” on page 134 for an example of using the PEC. Interrupt Functions The C166 compiler gives you complete control over all aspects of interrupt and register bank usage. Register banks can be used for example in connection with interrupt procedures. char huge hc.
R5 Description 3 LSB in R4. R5 R4 to R7 R4 R4. R5 R4. Return value bit (unsigned) char (unsigned) int (unsigned) long float double near * far * or huge * Register R4.Getting Started 25 Parameter Passing Up to five parameters can be passed via CPU registers. MSB in R5 32 bit IEEE format. exponent and sign in R7 Offset in R4. The user has the choice of eight OPTIMIZE levels. The return of function values takes place in fixed CPU registers. In addition the type of code generation can be influenced with OPTIMIZE (SIZE) and OPTIMIZE (SPEED). the user stack is used for parameters. All optimizations executed by C166 are summarized below: General Optimizations ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ ¢ Constant Folding Jump Optimizing Dead Code Elimination Register Variables Parameter Passing Via Registers Global And Local Common Sub-expression Elimination Strength Reduction Loop Rotation Dead Code Elimination Common Tail Merging . The user stack holds also automatic variables and is accessed via the R0 register (user stack pointer). exponent and sign in R5 64 bit IEEE format. In this way the interface to assembler subroutines is very easy.0 RL4 R4 R4. as listed in the table below. This yields an efficient parameter passing which compares to assembler programming. Selector in R5 Code Optimizing C166 optimizes the generated code with modern optimization techniques. If all five registers are used for parameters.
0 ERROR(S) 3 Control directives can also be entered via the #pragma directive. at the beginning of the C source file. in response to the various C language statements and other directives. directive information. and a symbol table. and so on to allow detailed program debugging and analysis with the µVision2 Debugger or emulators.00 C166 COMPILATION COMPLETE. Example >C166 MODULE. an assembly listing. you may invoke the compiler also within a DOS box by typing C166 on the command line. The C166 compiler produces object files in OMF-166 format.LST) DEBUG SYMBOLS C166 COMPILER V4. function names. Sample Program The following example shows some functional capabilities of C166. The compilation phase also produces a listing file that contains source code. However. Additionally the name of the C source file to compile is specified on the invocation line as well as any optional control parameters to affect the way the compiler functions. 0 WARNING(S). the compiler can emit all the necessary information such as. the C166 compiler will be called from the µVision2 IDE when you build your project.C COMPACT PRINT (E:M. Development Tools 166/ST10 Specific Optimizations ¢ ¢ ¢ Peephole Optimization NOP and DPP Load Optimization Case/Switch Optimization Program Invocation Typically. An example for a listing file created by the C166 compiler is shown on the next page. For a list of available C166 directives refer to “C166 Optimizing C Cross Compiler Directives” on page 166.26 Chapter 3. Additionally and optionally. variable names. line numbers. .
C166 COMPILER V4. buf[c] != 0. 1 1 1 1 1 1 1 1 /* Initialize the Serial Interface 0 */ void init_serial (void) { p310 = 1. COMPILATION OF MODULE SAMPLE OBJECT MODULE PLACED IN SAMPLE. SAMPLE 12/01/99 10:31:08 PAGE 1 27 C166 produces a listing file with line numbers as well as the time and date of the compilation. /* convert to capital } printf (“%s\n”.h> 1 1 1 /* Convert to Upper Character */ unsigned char toupper (unsigned char c) { if (c < ‘a’ || c > ‘z’) return ©. UNINITIALIZED --------------------------------------------------. /* echo input line P0 = 0.Assembly Code the C166 CODE directive. while (1) { P0 = P2. 3 */ */ */ */ */ */ 1 1 1 1 1 2 2 2 2 3 3 2 2 2 1 If errors or possible sources of errors exist an error or warning message is displayed. /* set Port 3.OBJ COMPILER INVOKED BY: C:\KEIL\C166\BIN\C166.10 output latch (TxD) dp310 = 1.10 direction control register */ /* Port 3.RL4 : : : : MODULE INFORMATION: INITIALIZED CODE SIZE = 130 NEAR-CONST SIZE = 4 FAR-CONST SIZE = -----NEAR-DATA SIZE = -----FAR-DATA SIZE = -----IDATA-DATA SIZE = -----SDATA-DATA SIZE = -----BDATA-DATA SIZE = -----BIT SIZE = -----INIT’L SIZE = -----END OF MODULE INFORMATION.EXE SAMPLE. Information about compiler invocation and the object file generated is printed.h> #include <stdio. buf[10].C CODE DEBUG stmt level 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 source /* register definitions for 80166 CPU */ /* standard i/o definitions */ #include <reg166. dp310 = DP3^10. FUNCTION toupper (BEGIN Enable under µVision2 Options for Target – Listing . /* reset Port 3. This gives you an assembly listing file with embedded source line numbers. init_serial (). sizeof (buf)).10 output latch */ /* Port 3. /* set Port 3.R8 0002 C085 MOVBZ R5. /* output hardware switch from Port2 */ */ */ */ */ gets (buf. /* delete receive interrupt flag S0BG = 0x40.Variable ‘c’ assigned to Register ‘R8’ --.11 direction control (RxD input) S0TIC = 0x80.Getting Started C166 COMPILER V4. /* set baudrate to 9600 baud S0CON = 0x8011. /* Port 3.10 direction control (TxD output) dp311 = 0. /* set serial mode } /* Echo Upper Characters */ main () { unsigned char c. buf). SOURCE LINE # 6 0000 F048 MOV R4. /* set transmit interrupt flag S0RIC = 0x00. else return (c & ~0x20). c++) { buf[c] = toupper (buf[c]). A memory overview provides information about the occupied 166/ST10 memory areas. dp311 = DP3^11. SOURCE LINE # 5 .00. The number of errors and warnings in the .---.11 direction control register */ The listing contains a line number before each source line and the instruction nesting { } level. /* clear Output Port to signal ready } } ASSEMBLY LISTING OF GENERATED OBJECT CODE RMASK = @0x0030) . } sbit sbit sbit p310 = P3^10. /* get input line for (c = 0.00.
small code size and exact hardware control is essential. Listing File On the following page is an example listing file generated by the assembler. Even line numbers of the source file are available to enable source level debugging for assembler programs with the µVision2 Debugger or emulators. this allows an exact display of program variables. since common sequences need only be developed once. Functional Overview A166 translates an assembler source file into a relocatable object module. A166 translates symbolic assembler language mnemonics into executable machine code. like string manipulation or number processing. The Macro Processing Language (MPL) is a string replacement facility. Development Tools program are included at the end of the listing. The A166 macro facility saves development and maintenance time. Conditional assembly of sections of code can help you to achieve the most compact code possible or to generate different applications out of one assembly source file. . These MPL processor functions perform many useful operations.28 Chapter 3. ¢ Another powerful feature of A166 macro assembler is conditional assembly depending on command line directives or assembler symbols. A166 contains two macro processors: ¢ Standard Macros are simple to use and enable you to define and to use macros in your 166/ST10 assembly programs. A166 allows you to define each instruction in a 166/ST10 program and is used where utmost speed. optionally with symbol table and cross reference. 0 WARNING(S). A166 generates a listing file. The standard macros are used in many assemblers. C166 COMPILATION COMPLETE. It is fully compatible with Intel ASM86 and has several predefined macro processor functions. 3 Source-Level Debugging A166 generates complete symbol and type information. 0 ERROR(S) A166 Macro Assembler A166 is a macro assembler for the 166/ST10 microcontroller family.
.-----. . TYPE ---WORD WORD LIT : : VALUE I ATTRIBUTES SECTION 12# 50 SFR 21 22 SFR 10 6# : : ---FFC6H A FE06H A "NEAR" : : Enable under µVision2 Options for Target – Listing – Cross Reference to get a detailed listing of all symbols used in the assembler source file.OBJ INVOKED BY: C:\KEIL\C166\BIN\A166. . timerstart ASSUME DPP3:SYSTEM ?PR?SERINIT SERINIT proc section code NEAR 0000 0002 0004 0006 000A 000E 0012 0016 AFE2 AFE3 BEE3 E7B68000 E7B70000 E65A4000 E6D81180 CB00 0018 001C 0020 0024 0028 002C 0030 E6A00000 E6A10000 E6200000 E6210000 E6A14000 E6A04F00 CB00 0032 0036 003A 003E 0042 E6A00000 E6A10000 F2F442FE F2F540FE CB00 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 3 A166 is procedure oriented. . . .#000H S0BG .#004FH RET timerstart endp NEAR If errors or possible sources of errors exist an error or warning message is displayed.T2 RET timerstop endp ?PR?SERINIT ends end NEAR A166 MACRO ASSEMBLER SAMPLE 24/01/99 15:44:45 PAGE 2 XREF SYMBOL TABLE LISTING ---. .Getting Started A166 MACRO ASSEMBLER SAMPLE 24/01/99 15:44:45 PAGE 1 29 A166 produces a listing file with line numbers as well as the time and date of the translation. OUTPUT LATCH (TXD) DIR-CONTROL (TXD OUTPUT) DIR-CONTROL (RXD INPUT) TRANSMIT INTERRUPT FLAG RECEIVE INTERRUPT FLAG 9600 BAUD SET SERIAL MODE timerstart proc MOV T2CON. .#0 MOV T3CON. DP3.A66 SET(SMALL) XREF DEBUG LOC OBJ LINE 1 2 3 SOURCE $SEGMENTED $IF MEDIUM OR LARGE Model LIT 'FAR' $ELSE Model LIT 'NEAR' $ENDIF PUBLIC SERINIT. .#0040H S0CON.#080H S0RIC.#0 MOV T3.10 DP3. A166 MACRO ASSEMBLER V4. .#0 MOV R4. . . MODEL.#8011H endp . .#0 MOV T2. .#0040H MOV T2CON.******************************* BSET BSET BCLR MOVB MOVB MOV MOV RET SERINIT P3.------N A M E ?PR?SERINIT.#0 MOV T3CON. The listing contains a source line number and the object code generated by each source line. . . . . . Information about assembler invocation and the object file generated is printed. .T3 MOV R5.00 OBJECT MODULE PLACED IN SAMPLE.*** INIT SERIAL INTERFACE 0 *** .EXE SAMPLE. . timerstop proc MOV T2CON. . : : . All CPU instructions need to be placed with PROC / ENDP statements. .10 DP3. timerstop. . DPP3 . .******************************* .#0 MOV T3CON. .----.11 S0TIC. . . .
Development Tools The number of errors and warnings in the program are included at the end of the listing. ?XD?MYPROG%XDATA (0x20000) in this dialog field will insert the L166 SECTIONS directive which locates the section with the name ?XD?MYPROG and the memory class XDATA to address 0x20000: SECTIONS (?XD?MYPROG%XDATA (0x20000)) . L166 automatically selects the appropriate run-time libraries and links only the library modules that are required. The modules to be combined may have been written in C or assembler. Exact placing of a section is also possible.. L166 locates all sections with the class name FCODE to this memory region. For example. The class name refers to the different memory areas: for example the class NCODE contains code which must be directed to ROM space. CLASSES (FCODE (0x10000 – 0x1FFFF. During the link/locate process all sections with the same class name are located to a specific memory area. 0x40000 – 0x5FFFF)) Above is an example for an L166 CLASSES directive. the class NDATA contains variable sections which must be directed to RAM space. In doing so the external and public references are resolved and the relocatable program parts are assigned to absolute addresses.0x1FFFF and 0x40000 – 0x5FFFF for the FCODE class (= far code). This instructs L166 to use the address spaces 0x10000 . The µVision2 IDE delivers the correct settings for L166 CLASSES directive from the selected CPU and specifications under Options – Target for external memory and on-chip memory components. : : : Chapter 3. You can enter address ranges for user defined memory classes under Options – L166 Locate – Users Classes. which is usually ROM space. 0 WARNING(S). enter in µVision2 dialog Options – L166 Locate – User Sections the address specification for individual sections. 3 Address Management The C166 compiler assigns each code and data section to a specific class name.30 : ASSEMBLY COMPLETE. 0 ERROR(S) L166 Linker/Locator The L166 linker/locator combines several program modules into one executable 166/167 program.
Getting Started 31 Map File On the following page is an example listing file generated by L166. 3 .
EXE SAMPLE. L166 displays the invocation line. All interrupt procedures with assigned trap numbers are listed.00.M66) with date and time of the link/locate run. VALUE TYPE REP LENGTH TGR SYMBOL NAME ======================================================== 0003AH GLOBAL LABEL ----main 00022H PUBLIC LABEL ----init_serial 00004H PUBLIC LABEL ----toupper 00004H 00008H 00004H 00004H 00018H 00020H --: : BLOCK SYMBOL LINE LINE LINE LINE BLOCKEND : : LVL=0 REG --------LVL=0 : : 001EH ------------: : --------------: : toupper c #5 #6 #7 #8 : : A complete list of all debug symbols is printed. Development Tools 10:32:02 PAGE 1 L166 produces a MAP file (extension . Warning messages and error messages are listed at the end of the MAP file. GROUP NAME TYPE TGR GRP CLASS SECTION NAME ============================================================================= NCODE CODE --1 NCODE ?PR?SAMPLE NCODE ?PR?printf NCODE ?PR?GETS : : : : : : PUBLIC SYMBOLS OF MODULE: SAMPLE (SAMPLE) The Group list shows the group. class and section names used in the application program.00 : : 22/01/99 Chapter 3. These may point to . INVOKED BY: C:\KEIL\C166\BIN\L166.--. CPU type.00 L166 LINKER/LOCATER V4.--* INTVECTOR TABLE * 00004H 00085H 00082H CODE WORD --1 PUBL NCODE ?PR?SAMPLE 00086H 0044FH 003CAH CODE WORD --1 PRIV NCODE ?PR?printf 00450H 004BDH 0006EH CODE WORD --1 PUBL NCODE ?PR?GETS : : : : : : : : GROUP LIST OF MODULE: SAMPLE (SAMPLE) The memory map contains the usage of the physical 80C166 memory. Each input module and the library modules included in the application are listed.LIB (?C_STARTUP) COMMENT TYPE 128: A166 V4.OBJ (SAMPLE) COMMENT TYPE 128: C166 V4. VALUE PUBLIC SYMBOL NAME REP TGR CLASS SECTION NAME ============================================================================= 00608H ?C_CLRMEMSECSTART VAR -----00606H ?C_INITSECSTART VAR -----00000H ?C_PAGEDPP1 CONST -----00001H ?C_PAGEDPP2 CONST -----: : : : : : : : SYMBOL TABLE OF MODULE: SAMPLE (SAMPLE) All public symbols together with their values are listed.00 C:\KEIL\C166\LIB\C166S.00 C:\KEIL\C166\LIB\C166S. 3 INTERRUPT PROCEDURES OF MODULE: SAMPLE (SAMPLE) INTERRUPT PROCEDURE INT INTERRUPT NAME ===================================================== C_STARTUP 0 RESET MEMORY MAP OF MODULE: SAMPLE (SAMPLE) START STOP LENGHT TYPE ALIGN TGR GRP COMB CLASS SECTION NAME ============================================================================== 00000H 00003H 00004H ------.32 L166 LINKER/LOCATER V4.OBJ CPU TYPE: C166 CPU MODE: SEGMENTED MEMORY MODEL: SMALL INPUT MODULES INCLUDED: SAMPLE. memory model.LIB (PRINTF) COMMENT TYPE 128: A166 V4. and CPU mode.
Getting Started possible problems encountered during the link/locate run. 0 WARNING(S). 33 L166 RUN COMPLETE. 0 ERROR(S) 3 .
libraries provide a good vehicle for distributing a large number of useful functions and routines without the need to distribute source code. the build time is shortened since these modules do not require re-compilation for each project. You may also call LIB166 from a DOS box. you may merge them into a library. Additionally. There are a number of benefits to using a library. A library file is a formatted collection of object modules (created by the C compiler and assembler). Library files provide a convenient method of combining and referencing a large number of object modules which may be accessed by the L166 linker/locator. For example. They can be easily loaded into a device programmer for programming EPROMS. and FLASH memory utilities that you may use over and over again. Development Tools LIB166 Library Manager The LIB166 library manager lets you create and maintain library files. Intel HEX files are ASCII files that contain a hexadecimal representation of your application program. Library routines that are not specifically invoked by your program are not included in the final output.34 Chapter 3. Security. the ANSI C library is provided as a set of library files. To build a library with the µVision2 project manager enable Options for Target – Output – Create Library. Unused bytes are filled with a specified byte value. Libraries are used by the L166 linker when linking and locating the final application. 3 OH166 Object-HEX Converter The OH166 object-HEX converter creates Intel HEX files from absolute object modules which are created by the L166 linker/locator. Refer to “LIB166 Library Manager Commands” on page 170 for command list. The linker extracts the modules from the library and processes them exactly as it does other object modules. Once these routines are written and debugged. CAN. . speed. You may also create HEX files to program FLASH memory devices. The data records in these files are sorted in ascending order. It is easy to build your own library of useful routines like serial I/O. Modules in the library are extracted and added to the program only if they are required. Both HEX-86 (1 MB address range) and HEX-386 (16 MB address range) file formats are supported. and minimized disk space are only a few of the reasons to use a library. Since the library contains only the object modules.
Build project and create a HEX file for PROM programming. Refer to “Product Overview” on page 8 for a description of the kits that are available. This includes output file options. For larger applications. Creating Applications To make it easy for you to evaluate and become familiar with our 166 product line. . Add and configure the startup code for the 166/ST10 device Set tool options for target hardware. Refer to the “Release Notes” for more information on the limitations of the evaluation tools.Getting Started 35 Chapter 4. we provide an evaluation version with sample programs and limited versions of our tools. Also discussed are options for generating and maintaining projects. This chapter describes the Build Mode of µVision2 and shows you how to use the user interface to create a sample program. Create a new source file and add this source file to the project. you need to purchase one of our development kits. The sample programs are also included with our standard product kits. and the features of the µVision2 project manager. NOTE The Keil C166 evaluation tools are limited in functionality and the code size of the application you can create. The description is a step-by-step tutorial that shows you how to create a simple µVision2 project. the configuration of the C166 compiler for optimum code quality. create a project file and select a CPU from the device database. 4 Create a Project µVision2 includes a project manager which makes it easy to design applications for the 166 family. You need to perform the following steps to create a new project: ¢ ¢ ¢ ¢ ¢ Start µVision2.
Please carefully read the information provided under Description in this dialog. This opens a standard Windows dialog that asks you for the new project file name. To create a new project file select from the µVision2 menu Project – New Project… . This selection sets necessary tool options for the C167CR-LM device and simplifies in this way the tool configuration. You can see these names in the Project Window – Files.e. since it might have additional instructions for the device configuration. Now use from the menu Project – Select Device for Target and select a CPU for your project. the µVision2 environment needs additional parameters that you have to enter manually. i.UV2 which contains a default target and file group name. µVision2 creates a new project file with the name PROJECT1. Then select this folder and enter the file name for the new project. . You can simply use the icon Create New Folder in this dialog to get a new empty folder. The Select Device dialog box shows the µVision2 device database. We suggest that you use a separate folder for each project.36 Chapter 4. Project1. We are using for our examples the Siemens C167CR-LM CPU. Creating Applications Start µVision2 and Create a Project File µVision2 is a standard Windows application and started by clicking on the program icon. 4 NOTE On some devices. Just select the microcontroller you use.
C you have just created.C. This opens an empty editor window where you can enter your source code. you can select the file group in the Project Window – Files page and click with the right mouse key to open a local menu. For example. µVision2 enables the C color syntax highlighting when you save your file with the dialog File – Save As… under a filename with the extension *. The option Add Files opens the standard files dialog.C. We are saving our example file under the name MAIN.Getting Started 37 Once you have selected a CPU from the device database you can open the user manuals for that device in the Project Window – Books page. 4 Once you have created your source file you can add this file to your project. Select the file MAIN. These user manuals are part of the Keil Development Tools CD-ROM that should be present in your CD drive. Create New Source Files You may create a new source file with the menu option File – New. . µVision2 offers several ways to add source files to a project.
you should use the START167.A66 file to your project. Another file that aids you in program debugging is TRAPS. you should copy the START167. In the same dialog box you can use the Add Files to Group… button to add the START167. Also TRAPS. Since you need to modify that file to match your target hardware. Only the 8xC166 CPU variants are initialized with the STARTUP. It is a good practice to create a new file group for the CPU configuration files. Groups.38 Chapter 4. . For most 166 / ST10 derivatives.C can be copied from the folder C:\KEIL\C166\LIB to your project folder and added in the same way. With Project – Targets.A66 file as startup code.A66 file from the folder C:\KEIL\C166\LIB to your project folder. Files… you can open a dialog box where you add a group named System Files to your target.C. a 166/ST10 program requires a CPU initialization code that needs to match the configuration of your hardware design. Creating Applications Add and Configure the Startup Code 4 Typically.A66 file. This file contains service routines for the various CPU hardware traps (interrupts) which are called on hardware or software failures.
CPU and C Startup Code” on page 153.Getting Started 39 The Project Window – Files lists all items of your project. It is very important that the settings in the startup code match the settings of the Options – Target dialog. Then you configure the startup code as described in “Chapter 10.A66 in the editor with a double click on the file name in the project window. Open START167. . This dialog is discussed in the following. 4 The µVision2 Project Window – Files should now show the above file structure.
allows you to optimize the memory model settings. specifies the C166 compiler memory model. In the Target tab you specify all relevant parameters of your target hardware and the on-chip components of the device you have selected. 4 The following table describes the options of the Target dialog: Dialog Item Clock Description specifies the internal CPU clock of your device. in most cases this value is not identical with the XTAL frequency. Allocate On-chip … Memory Model Data Threshold Near Memory . The dialog Options for Target opens via the toolbar icon. For starting new applications the default SMALL is a good choice. Most 166 designs are using the on-chip PLL to generate the CPU clock.40 Chapter 4. Make sure that the dialog settings are identical with the START167. Creating Applications Set Tool Options for Target µVision2 lets you set options for your target hardware. Check your hardware design carefully to determine the correct value.A66 settings. The following the settings for our example are shown. Refer to “ Memory Models and Memory Types” on page 48 for a discussion of the various memory models. specifies the usage of the on-chip components which are typically enabled in the CPU startup code. Refer to “ Data Threshold” on page 50 for more information.
RAM denotes the memory areas where variables are stored. µVision2 will display errors and warning messages in the Output Window – Build page. otherwise your application has no memory for constants and program code. You may translate all source files and line the application with a click on the Build Target toolbar icon. However you have to specify ROM in this dialog. For more information. When you build an application with syntax errors. the program will run in RAM space. it is required to create an Intel HEX file to download the software into an EPROM programmer or simulator. 41 Build Project and Create a HEX File Typical. The FLASH Fill Byte. µVision2 creates HEX files with each build process when Create HEX file under Options for Target – Output is enabled. ROM refers to areas that store constants and program code (typical EPROM or Flash memory). the tool settings under Options – Target are all you need to start a new application. Refer to “Chapter 5. Start and End values direct the OH166 utility to generate a sorted HEX files. A double click on a message line opens the source file on the correct location in a µVision2 editor window.Getting Started External Memory here you specify all external memory areas of the target hardware. When using the Monitor-166. Testing Programs” on page 67 for a discussion of the µVision2 debugging features. sorted files are required for some Flash programming utilities. refer to “ Target Options when Using Monitor-166” on page 159. After you have tested your application. 4 Once you have successfully generated your application you can start debugging. . You may start your PROM programming utility after the make process when you specify the program under the option Run User Program #1.
We have already used file groups in our example to separate the CPU related files from other source files. µVision2 maintains a file dependency list and knows all include files used within a source file. This is useful for grouping files into functional blocks or for identifying engineers in your software team. Groups. Files Groups let you group associated files together in a project. You may need one target for testing and another target for a release version of your application. regardless of modifications. Each target allows individual tool settings within the same project file. We have already used this dialog to add the system configuration files. Creating Applications 4 Now you can modify existing source code or add new source files to the project. The Project – Targets. . Even the tool options are saved in the file dependency list. Files… dialog allows you to create project targets and file groups. Project Targets and File Groups By using different Project Targets µVision2 lets you create several programs from a single project. so that µVision2 rebuilds files only when needed. The Build Target toolbar button translates only modified or new source files and generates the executable file.42 Chapter 4. all source files are translated. An example project structure is shown below. With these technique it is easily possible to maintain complex projects with several 100 files in µVision2. With the Rebuild Target command.
Set C166 compiler specific tool options like code optimization or variable allocation. to In the build toolbar you can quickly change the current target to build. Specify all listing files generated by the tool chain. L166 Misc Debug Properties . The following table describes the options of the Target dialog. Via the local menu in the Project Window – Files you may set different options for a file group or even a single file. Refer to “ Other C166 Compiler Directives” on page 53 for information. You need to reserve some memory locations when you are using Monitor-166 for debugging. in this case you get only the related dialog pages. With the context help button you get help on most dialog items. You can move file positions with Drag & Drop. Typical you will enable Use Memory Layout from Target Dialog as show below to get automatic settings. Define the output files of the tool chain and allows you to start user programs after the build process. Define the location of memory classes and sections. You may select a target or group name and Click to rename it. Refer to page 74 for more information. Refer to “ Locate Sections to Absolute Memory Locations” on page 60 and “ User Classes” on page 61 for more information on this dialog. The local menu opens with a right mouse Click and allows you for each item: • set tool options to • add files to a group to • remove the item to • open the file. Set assembler specific tool options like macro processing. See page 56 for more information.Getting Started 43 The Project Windows shows all groups and the related files. Other linker related settings like Warning or memory Reserve directive. Files are built and linked in the same order as shown in this window. File information and special options for files and groups refer to “ File and Group Specific Options – Properties Dialog” on page 62. Settings for the µVision2 Debugger. See page 40 for details. 4 Overview of Configuration Dialogs The options dialog lets you set all the tool options. Dialog Page Target Output Listing C166 A166 L166 Locate Description Specify the hardware of your application. For more informatino refer to “ Target Options when Using Monitor-166 “ on page 159 for more information.
44 Chapter 4. These utilities are discussed in the following section. The search results are displayed in the Find in Files page of the Output window. Use View – Source Browser to open the Browse window. the compiler includes browser information into the object files. If Options for Target – Output – Browser Information is enabled when you build the target program. Creating Applications 4 µVision2 Utilities µVision2 contains many powerful functions that help you during your software project. Source Browser The Source Browser displays information about program symbols in your program. . Find in Files The Edit – Find in Files dialog performs a global text search in all specified files. A double click in the Find in Files page positions the editor to the text line with matching string.
… with an underline. … that contain one digit in any position. … with an underline. . followed by a digit. followed by any character. followed by ABC. Click on the list item to sort the information. Mask * *#* _a$#* _*ABC Matches symbol names … Matches any symbol. memory space and the number of uses.Getting Started 45 4 The Browse window lists the symbol name. specify the memory type for data and function symbols. select the definition type of the symbol select the file where information should be listed for. You can filter the browse information using the options described in the following table: Browse Options Symbol Description specify a mask that is used to match symbol names. ending with zero or more characters. _ab1 or _a10value. Filter on File Outline Memory Spaces The following table provides a few examples of symbol name masks. This is the default mask in the Symbol Browser. type. class. The mask may consist of alphanumeric characters plus mask characters: # matches a digit (0 – 9) $ matches any character * matches zero or more characters. followed by the letter a. followed by zero or more characters. For example.
46 Chapter 4. Select the item that you want to search for and open the local menu with a right mouse click or use the following keyboard shortcuts: Shortcut F12 Shift+F12 Ctrl+Num+ Ctrl+Num– Description Goto Definition. The Definitions and References view gives you additional information with the following symbols: Symbol [D] [R] [r] [w] [r/w] [&] Description Definition Reference read access write access read/write access address reference 4 You may use the browser information within an editor window. but without path specification (PROJECT1. Creating Applications The local menu in the Browse window opens with a right mouse Click and allows you to open the editor on the selected reference. A key sequence is a combination of a Key Code and a File Code.UV2) filename without extension and path specification (PROJECT1) .UV2) filename with extension. For functions you can also view the Call and Callers graph. place cursor to a symbol reference Goto Next Reference or Definition Goto Previous Reference or Definition Tools Menu Via the Tools menu. You may add custom programs to the Tools menu with the dialog Tools – Customize Tools Menu… . you run external programs. Using a key sequence in the Parameters Line you may pass arguments from the µVision2 project manager to these user programs. The available Key Codes and File Codes are listed in the tables below: Key Code $ # % @ Specifies the path selected with the File Code folder name of the file specified in the file code (C:\MYPROJECT) filename with complete path specification (C:\MYPROJECT\PROJECT1. place cursor to the symbol definition Goto Reference. With this dialog you configure the parameters of the user applications.
UV2) µVision2 executable program file (C:\KEIL\UV2\UV2. #. or non-sense C code. The PC-Lint messages are redirected to the Build – Output Window.EXE) application HEX file (PROJECT1. typical the executeable file for debugging (PROJECT1) Running PC-Lint PC-Lint from Gimpel Software checks the syntax and semantics of C programs across all modules of your application. (MEASURE. After the setting the PC-Lint options. %. ##. erroneous. you may Lint your source code. A double click on a Lint message line locates the editor to the source file position. To get correct output in the Build page. PC-Lint flags possible bugs and inconsistencies and locates unclear. or @@ For example @@ gives a single @ in the user program command line.H86) linker output file. 4 . Tools – Lint All C Source Files runs PC-Lint across all C source files of your project. use $$. %%. You need to install PCLint on your PC and specify various parameters with the dialog Tools – PC Lint Options. or @ in the user program command line.C) name of the current project file (PROJECT1. you need to use the configuration file that is located in the folder KEIL\C166\BIN. PC-Lint may considerably reduce the debugging effort of your target application.Getting Started To use $. The example shows a typical PC-Lint configuration. File Code F P X H L 47 Specifies the file name inserted in the user program line current in focus editor file. Tools – Lint … runs PC-Lint on the current in focus editor file.
The following table allows you to determine the memory model that best fits your application. ST10-262) and SEGMENTED CPU mode. C163. since it contains also other PC-Lint options required for the Keil C166 compiler. Memory Models and Memory Types The most significant impact on code size and execution speed has the memory model. C165.LNT contains already these lines. Writing Optimum Code 4 Many configuration parameters have influence on the code quality of your 166 application. C167. This is typical for all new applications. ST10-272. The . To bypass the 64KB variable limitation. for most applications the default tool setting generates very good code. Refer to “Memory Models” on page 23 for detailed information. The program will not work since C run-time library functions cannot access huge or xhuge variables in this memory models. The code optimization techniques are described in this section.48 Chapter 4. Tips for SMALL and MEDIUM Memory Model Even if your application exceeds the 64KB data/constant limit you may still use the SMALL or MEDIUM memory model. The memory model influences variable access and CALL/RET instructions. PC-Lint needs the following option lines in the configuration file: -hsb_3 -format="*** LINT: %(%f(%l) %)%t %n: %m" -width(0. The memory model is selected in the Options for Target – Target dialog page. Total Code Size of the Application less than 64 KB more than 64KB Data and Constant Size of the Application less then 64KB more than 64KB SMALL MEDIUM HCOMPACT HLARGE This table is valid for devices with extended instruction set (i. like printf or scanf. the address of such variables cannot be passed to C run-time library functions. Although. C161. colom below // Change message output format // Don't break lines The configuration file C:\KEIL\C166\BIN\CO-KC166. It is strongly recommended to use this configuration file.10) // 3 lines output. you should be aware of the parameters which improve code density and execution speed. you may direct some variables to huge or xhuge memory. However.e. C164. Creating Applications To get correct results in the Build – Output Window.
void main (void) { t. 1. 1. The following shows and example: struct test { int bit0: int bit1: int bit2: int value1: int value2: }.bit0 = 1.bit1) t. Another alternative is. // this structure contains some // fields with size 1 bit struct test bdata t. For more information refer to “Data Threshold” on page 50. 4.Getting Started 49 HCOMPACT and HLARGE memory model does not have this limitation and should be used instead. 4 Bit-field Structures C166 accesses bit-field struct members with size 1 bit directly with CPU BIT instructions if the struct is located in the bdata space. Tips for HCOMPACT and HLARGE Memory Model You may apply near memory type to optimize variable accesses in this memory model. This generates 16-bit addressing instead of 32-bit addressing. You can also enter a Data Threshold in the Options for Target – Target dialog to locate such bit-field structures automatically to the bdata space. This is why you should use HCOMPACT instead of COMPACT or HLARGE instead of LARGE when you select a memory model. 9. 1. } // locate to bit-addressable space // generates BSET instruction // uses JB and BMOV instructions .bit2 = t. NOTE The far memory type is provided for compatibility to the 8xC166 CPU and support of existing C166 code.bit0. if (t. Refer also to “Data Threshold” later in this section. The C166 compiler HOLD directive may direct variables below a specified size automatically to optional memory areas. since this memory type has an object size limit of 64KB and generates better code for near pointer cast operations. that you copy variables to near memory and pass the address of the near variable to the C library function. For new designs you should use huge instead of far. Frequently used variables should be located in the 166 on-chip memory with the idata memory type.
you should use the same data threshold setting for the application using this library. the C166 compiler might have different memory type settings for this variable. With the application wide register optimization. A problem may arise when a module with an extern variable definition is translated with a different data threshold setting than the module defining this variable. Objects that require more then 6 Bytes are located in the far or huge area. This entry generates directly the C166 HOLD directive. the C166 compiler knows the registers used by external functions. If the LARGE. 4 Global Register Optimization The Keil 166 tools provide support for application wide register optimization which is enabled in the Options for Target – C166 dialog with Global Register Coloring. Creating Applications Data Threshold In the Options for Target – Target dialog you may enter a Data Threshold to specify the default memory type for small objects. Other variables without memory type are in huge. To improve . Registers that are not altered in external functions can be used to hold register variables. When you create libraries with global variables or accesses to extern application variables.50 Chapter 4. HCOMPACT memory model is used together with the default near. 6 all variable definitions without explicit memory type which occupied not more then 6 bytes are place in the near area. you may specify explicit memory types. This is typically the XRAM space in a 166 device. HLARGE or COMPACT. As an alternative. The code generated by the C compiler needs less data and code space and executes faster. In this case. Other variables without explicit memory space are in the huge space. Examples: Locates variables with size < 10 Bytes to sdata space. Locates variables with size < 2 Bytes to idata. bit-field structs with single bit members to bdata and variables with size < 6 Bytes to near. NOTE The C166 HOLD directive should be identical for all modules in an application.
In the following example the function func1 calls the external function func2. Therefore func1 can use some CPU register without saving it. Due to the global register optimization. 4 .Getting Started 51 the register allocation. the µVision2 build process makes automatically iterative re-translations of C source files. func2 is using not all the CPU registers. the C166 compiler is aware of this situation and can take advantage of it.
[R0] . j < 100. R9. MOV val.#099 JMPR cc_SLT. a++) { MOV R12.#099 JMPR cc_SLT.#0 .#063H cc_SLT.52 Chapter 4.---.[R0+#02H] R8.Variable 'a' assigned to 'R12' ?C0004: c += (b + 1).---. CALL func1 } CMPI1 R3. s+2 .R4 . CALL func1 } CMPI1 R13.R5 . PUSH R13 for (j = 0.---.#0 . { Without Global Register Optimization char *func1 (void) int a.#0 . j < 100.#1 ADD R1.b.---.Variable 'j' assigned to 'R3' ?C0010: func1 (). char *s. j++) { MOV R3. a < 100.#4 b = c = 0.---.?C0010 } RET Code Size: 60 Bytes Code Size: 86 Bytes . s for (j = 0. s MOV [R0+#02H].---.?C0004 val = c.?C0004 val.#0 .R4 } CMPI1 R12. MOV R4. MOV R9.R1 return (s).R4 MOV R7.---.R14 R5. { PUSH R13 PUSH R14 PUSH R15 SUB R0.#0 .Variable 'b' assigned to 'R2' for (a = 0.#0 . MOV return (s). MOV R1.Variable 's' assigned to 'R6/R7' b = strlen (s). s .---.R4 s = func2 ().R5 MOV R8. Creating Applications With Global Register Optimization char *func1 (void) int a.R4 s = func2 (). { 4 b = c = 0.R2 ADD R4. MOV R4. j++) { MOV R13. s+2 . a++) { MOV R13.[R0] strlen R15. MOV MOV RET } void func0 (void) { int j. c. a < 100.R4 CALL strlen MOV R2.Variable 'c' assigned to 'R1' MOV R2.Variable 'c' assigned to 'R14' MOV R15.R7 RET } void func0 (void) int j. char *s.b.?C0010 } POP R13 RET (s). s+2 b = strlen MOV MOV CALL MOV } CMPI1 JMPR val = c.R15 ADD R4.#063H JMPR cc_SLT.Variable 'a' assigned to 'R13' ?C0004: c += (b + 1).#1 ADD R14.Variable 'b' assigned to 'R15' for (a = 0. CALL func2 MOV [R0].R6 MOV R5.#0 . c. MOV R4. CALL func2 MOV R6.[R0+#02H] R4.#0 .---. MOV R14.R5 .R4 R13.Variable 'j' assigned to 'R3' ?C0010: func1 ().
If the compiler detects common code sequences. Typical you will not alter the default. With “ Favor Code Size” . it will replace one code sequence by a jump instruction to the other equivalent code sequence. Also some intrinsic sequences (like struct copy) are replace by a library call. the C166 compiler inserts for some C operations (like long shift) loops instead of a faster replacement code. You can translate the C modules in an application with different compiler settings.Getting Started 53 Other C166 Compiler Directives There are several other C166 directives that improve the code quality. While analyzing the code. the compiler also tries to replace sequences with cheaper instructions. enables the “ Global Register Optimization” Refer to page 50 for details. You can optimize for execution speed or code size. Since the compiler inserts JMP instructions. the execution speed of the optimized code might be slower. These directives are enabled in the Options – C166 dialog page. . With the highest level “ Common Tail Merging” the compiler analyzes the code and 7: tries to locate common heads and tails. specifies C166 OPTIMIZE level. You may check the code quality of different compiler settings in the listing file. 4 The following table describes the options of the C166 dialog page: Dialog Item Define Undefine Code Optimization Level Description outputs the C166 DEFINE directive to enter preprocessor symbols. is only available in the Group and File Options dialog and allows you to remove DEFINE symbols that are specified at the higher target or group level. Code Optimization Emphasis Global Register Coloring . Typical this level is interesting to optimize the code density.
This is exemplified in following code example: Program with ‘ int’data type char array[100]. Creating Applications Dialog Item Use Static Memory for Non-register Automatics Alias Checking on Pointer Accesses Keep Variables in Order Treat ‘ char’as ‘ unsigned char’ Save DPP on Interrupt Entry Description instructs C166 to use static memory locations for function automatics (not parameters) which cannot be allocated in CPU registers. instructs C166 to treat all variables declared with plain char as unsigned char variables. allows you to enter special C166 directives. The default setting saves temporary results to the System Stack. When this option is disabled. k < 10. If a CPU register holds a variable it gets reused. For this reason. This directive should not be used for the 8xC166 CPU and when you are sure that your assembler code does not alter the DPP registers in any way. directs the C compiler to save temporary results and saved-by-callee variables to the User Stack. The code generated is not longer reentrant. but the size is limited. this is always fast on-chip RAM it is faster. The C run-time libraries and the RTX166 operating system never modifies these registers when you are generating code with extended instruction set (MOD167 directive used). k++) array[k] = 0. char test (int i) int k. } { . when this option is disabled. 4 Double-Precision Floating-Point Save Temporary Variables to User Stack Misc Controls Compiler Control String Data Types The 166/ST10 CPU is a 16-bit microcontroller. instructs C166 not to save DPP registers on interrupt entries. even when a pointer write could modify that variable. C166 ignores pointer write operations during the optimization phase. This option does not influence code quality. displays the C166 compiler invocation string. but code size and execution speed can be improved. k++) array[k] = 0. k < 10. } { for (k = 0. You may need such options when you are using very new 166/ST10 devices with chip bugs. tells the C166 compiler to order the variables in memory according their definition in the C source file. to enter compiler FIXxxx directives. C166 uses single precision floating point arithmetic even if the double keyword is used the C source file. this is typical for all new applications. Operations that use 16-bit types (like int and unsigned int) are more efficient than operations that use char or long types. Allows you can verify the compiler options currently for your source files. This option does not influence code quality. char test (char i) char k.54 Chapter 4. { Program with ‘ char’data type char array[100]. since the CPU can access static variables faster. } return (array[I]). it is typically better to use the int or unsigned int data type for all automatic and parameter variables in your application instead of char or unsigned char. } return (array[i]). { for (k = 0.
---.---.[R8+#array] Applications without external RAM Devices For single-chip applications or hardware with no external RAM devices the User Stack and the System Stack size needs to be reduced in the CPU startup file. $SET (STK_SIZE = 2) USTSZ EQU 80H .RL4 RET MOVB RET RL4.RL6 MOVB [R4+#array].Variable 'k' assigned to 'R6' MOVB RL5.#00H .A66 file as shown below: ?C_USERSTACK SECTION SECTION DATA PUBLIC 'IDATA' DATA PUBLIC 'SDATA' or ?C_USERSTACK Also you need to change the line: MOV R0. for 64 words system stack size .#DPP2:?C_USERSTKTOP to MOV .#0AH JMPR cc_SLT.#00H .?C0004 Generated Code: 28 Bytes . The USERSTACKDPP3 should be applied when DPP0.R8 MOVBS R4. 4 The C166 directive USERSTACKDPP3 changes the assumption made by the C166 compiler regarding the access of the User Stack area. DPP1 and DPP2 are used to access the NCONST class.#00H ?C0004: MOVBS R4.#09H JMPR cc_SLT.Variable 'i' assigned to 'R8' MOV R6. The default User Stack is allocated in the NDATA memory class and accessed with DPP2. The following values in the startup files are good choices when only on-chip RAM is available in a system.Variable 'i' assigned to 'R8' MOVB RL6.RL5 CMPI1 R6.#01H CMPB RL6. the ?C_USERSTACK section definition must be modified in the STARTUP.---.RL5 ADDB RL6.#DPP2:?C_USERSTKTOP R0.Variable 'k' assigned to 'RL6' MOVB RL5. for 128 bytes user stack size. Refer to “Configuring the Startup Code” on page 153 for more information.#00H ?C0004: MOVB [R6+#array].A66 or START167.Getting Started 55 Generated Code: 18 Bytes . If USERSTACKDPP3 is used. You enter this directive under Misc Controls in the Options for Target – C166 dialog.---.?C0004 MOV R4.
4 2. Check carefully if all settings are copied correctly to the new µVision2 project file.56 Chapter 4. Once you have done that. Also the dScope Debugger settings cannot be copied to the µVision2 project file. This menu option is only available. This command imports the old µVision1 linker settings into the L166. But. NOTE It is not possible to make a 100% conversion from µVision1 project files since µVision2 differs in may aspects from the previous version. Create a new µVision2 project file and select a CPU from the device database as described on page 36. you should enable Use Memory Layout from Target Dialog in the Options for Target – L166 Locate dialog and remove the settings for User Classes and User Sections in this dialog. You will not need the following features very often. for example user translator. Some µVision1 project settings. we recommend that you are using the µVision2 Options for Target – Target dialog to define the memory structure of your target hardware. Creating Applications Tips and Tricks The following section discusses advanced techniques you may use with the µVision2 project manager. . Then you can Drag & Drop files into the new file groups. library module lists and special compiler and linker controls like the C166 PECDEF and L166 OBJECTCONTROLS directive are not converted to the µVision2 project. 3. It is important to create the new µVision2 project file in the existing µVision1 project folder. After you have imported your µVision1 check carefully if the tool settings are converted correct. if the file list of the new µVision2 project file is empty. but readers of this section get a better feeling for the µVision2 capabilities. 4. Import Project Files from µVision Version 1 You can import project files from µVision1 with the following procedure: 1. 5. Select the old µVision1 project file that exists in the project folder in the dialog Project – Import µVision1 Project. You may now create file groups in the new µVision2 project as described under “Project Targets and File Groups” on page 42.
or @ in the user program command line.UV2) µVision2 executable program file (C:\KEIL\UV2\UV2. typical the executeable file for debugging (PROJECT1) 4 . A key sequence is a combination of a Key Code and a File Code. ##.UV2) filename without extension and path specification (PROJECT1) To use $.UV2) filename with extension. but without path specification (PROJECT1.H86) linker output file. #. or @@ For example @@ gives a single @ in the user program command line. File Code P X H L Specifies the file name inserted in the user program line name of the current project file (PROJECT1.Getting Started 57 Start External Tools after the Build Process The Options for Target – Output dialog allows to enter up to two users programs that are started after a successful build process. Using a key sequence you may pass arguments from the µVision2 project manager to these user programs. use $$. The available Key Codes and File Codes are listed in the tables below: Key Code $ # % @ Specifies the path selected with the File Code folder name of the file specified in the file code (C:\MYPROJECT) filename with complete path specification (C:\MYPROJECT\PROJECT1.EXE) application HEX file (PROJECT1. %%. %.
When you use a separate folder for the object files of each project target. there are some custom devices and there will be future devices which are currently not part of this database. Specify the on-chip memory as External Memory in the Options for Target – Target dialog. The Options for Target – Listing dialog provides the same functionality for all listing files with the Select Folder for List Files button.58 Chapter 4. ¢ . You should enclose the key sequence with quotes (“”) if you use folder names with special characters.e. The User program #2 will get only the name of the linker output file PROJECT1 and as a parameter -p the path specification to the project C:\MYPROJECT. space. The C167 (all s Variants) is used for devices with extended instruction set. #. Therefore most likely you will need to select this device. ~. The CPU setting in the Options box defines the basic the tool settings. a Build Target command will just retranslate the modified files. The C166 (all Variants) device supports all CPU’ with no extended instruction set. Even when you change your project target.e. i. However. You may enter a new CPU into the µVision2 device database. µVision2 has still valid object files of the previous build process. The parameters are described in the following table. Specify a Separate Folder for Listing and Object Files You can direct the output files of the tools to different folders: ¢ 4 ¢ The Options for Target – Output dialog lets you Select a Folder for Objects. Use a CPU that is not in the µVision2 Device Database The µVision2 device database contains all 166 / ST10 standard products.H86. C:\MYPROJECT\PROJECT1. All new devices are based on the extended instruction set. Creating Applications In the example above the User Program #1 is called with the Hex Output file and the full path specification i. If you need to work with an unlisted CPU you have two alternatives: ¢ Select a device listed under the rubric Generic. Open the dialog File – Device Database and select a CPU that comes close to the device you want to use and modify the parameters.
the part is split automatically into two sections. Default CPU clock used when you select the device. but NOFIXDPP is more generic since no DPP register assumptions are made. µVision2 will call the LIB166 Library Manager instead of the L166 Linker/Locater. ¢ . the entries in the L166 Locate and L166 Misc options page are ignored. Create a Library File Select Create Library in the dialog Options for Target – Output. if you plan to use your code on different 166/ST10 directives.Getting Started 59 Parameter IRAM (range) XRAM (range) IROM (range) Specifies … Address location of the on-chip IRAM. if the library is designed for a target application with one of the following configurations: ¢ 4 More than 16KB ROM or 16KB ROM are set for Target – Near Memory. The User Stack is set to the memory class SDATA or IDATA as described under “Applications without external RAM Devices” on page 55. The start address must be 0. Since the code in the Library will be not linked and located. The directive NOFIXDPP should be entered under Options – C166 – Misc. You may use the C166 directive USERSTACKDPP3 instead of NOFIXDPP. Leave this variables unchanged when adding a new device to the database. Address location of the on-chip XRAM. ICAN (range) CLOCK (val) MOD167 Other Option variables specify CPU data books and µVision2 Debugging DLLs. Also the CPU and memory settings in the Target page are not relevant. The range specifies the physical ROM size. Address location of the on-chip (flash) ROM. In this case the L166 DPPUSE directive will be applied. Use the extended instruction set. This directive requires that the C166 compiler made no default assumptions for the DPP registers. Address location of the on-chip CAN module. Read the section “Data Threshold” on page 50 and check if you need to enter a Target – Data Threshold value in the options dialog. Select a CPU listed under the rubric Generic in the device database. if the size is more than 32KB.
#pragma NOINIT // disable zero initialization for alarm_control struct alarm_st huge alarm_control. unsigned char status. µVision2 allows you to specify the base address of any section under Options for Target – L166 Locate – Users Sections. : : struct alarm_st { unsigned int alarm_number. it is required to locate sections to specific memory addresses. : : The C166 compiler generates an object file for ALMCTRL. In the following example. Files… dialog. unsigned char enable flag. }.C and this module contains only the declaration for this structure. Groups. Copy tool settings from an existing target to the current target in following way: 1. . Select the target with the tool settings you want to copy with Set as Current Target. Creating Applications Copy Tool Settings to a New Target Select Copy all Settings from Current Target when you add a new target in the Project – Targets. Add the again removed target with Copy all Settings from Current Target enabled. Locate Sections to Absolute Memory Locations 4 Sometimes. Use Remove Target to delete the current target. This structure is defined in a source file named ALMCTRL.C and includes a section for variables in the huge memory area. the structure called alarm_control should be located at address 0x128000. 3. The variable alarm_control is the located in the section ?HD?ALMCTRL. 2. unsigned int time_delay.60 Chapter 4.
You can use the C166 directive RENAMECLASS to rename the standard C166 HDATA memory class to NVRAM for several modules. User Classes User classes are useful when you need to locate many variables from different source modules to special memory areas. : Source Module 2: #pragma RENAMECLASS (HDATA=NVRAM) : : #pragma NOINIT static float huge value3. In the following example we have a nonvolatile RAM starting at address 0x100000. : . µVision2 allows you to specify the base address of any section under Options for Target – L166 Locate – Users Classes.Getting Started 61 4 In this example L166 will locate the section named ?HD?ALMCTRL of the class HDATA0 at address 0x128000 in the physical memory. long huge value4. With #pragma NOINIT the variable zero initialization is disabled. Source Module 1: #pragma RENAMECLASS (HDATA=NVRAM) : : #pragma NOINIT int huge value1. static int huge value2.
regardless of modifications in the source file. when you are using the project file for several different hardware systems. The dialog pages have tri-state controls.0x107FFF. This is useful when a file contains __DATE__ and __TIME__ macros that are used to stored version information in the application program. click with the right mouse key and choose Options for … . Always Build . If a selection is gray or contains <default> the setting from the higher group or target level is active. Enable this option to re-translate a source module with every build process. File and Group Specific Options – Properties Dialog µVision2 allows you to set file and group specific options via the local menu in the Project Window – Files page as follows: select a file or group.62 Chapter 4. µVision2 will not translate and not link the selected item into the current targets. Disable this option to exclude the group or source file in this target. If this option is not set. This is useful for configuration files. The following table describes the options of the Properties dialog page: Dialog Item Path. Type. Creating Applications 4 In this example L166 will locate the user class section named NVRAM in the physical memory address range 0x100000 . Size Last Change Include in Target Build Description Outputs information about the file selected. Then you can review information or set special options for the item selected.
Getting Started
63
Dialog Item
Generate Assembler SRC File Assemble SRC File
Description
Instructs the C166 compiler to generate an assembler source file from this C module. Typical this option is used when the C source file contains #pragma asm / endasm sections. Use this option together with the Generate Assembler SRC File to translate the assembler source code generated by C166 into an object file that can be linked to the application. Instructs L166 to link only PUBLIC symbols from that module. Typical this option when you want to use entry or variable addresses from a different application. It refers in the most cases to an absolute object file which may be part of the project. Specify an exit code when the build process should be stop on translator messages. By default, µVision2 translates all files in a build process regardless of error or warning messages. Allows you to always include specific modules from a Library. Refer to “ Include Always specific Library Modules” on page 64 for more information. This line is required if your project contains files that need a different translator. Refer to “ Use a Custom Translator” on page 64 for more information.
Link Publics Only
Stop on Exit Code
Select Modules to Always Include Custom Arguments
4
In this example we have specified for FILE1.C that the build process is stopped when there are translator warnings and that this file is translated with each build process regardless of modifications.
Translate a C Module with asm/endasm Sections
If you use within your C source module assembler statements, the C166 compiler requires you to generate an assembler source file and translate this assembler
64
Chapter 4. Creating Applications
source file. In this case enable the options Generate Assembler SRC File and Assembler SRC File in the properties dialog. NOTE Check if you can use build-in intrinsic functions to replace the assembler code. In general it better to avoid assembler code sections since you C source code will not be portable to other platforms. The C166 compiler offers you many intrinsic functions that allow you to access all special peripherals. Typically it is not required to insert assembler instructions into C source code.
Include Always specific Library Modules
4
The Properties dialog page allows you to specify library modules that should be always included in a project. This is sometimes required when you generate a boot portion of an application that should contain generic routines that are used from program parts that are reloaded later. In this case add the library that contains the desired object modules, open the Options – Properties dialog via the local menu in the Project Window – Files and Select Modules to Always Include. Just enable the modules you want to include in any case into your target application.
Use a Custom Translator
If you add a file with unknown file extension to a project, µVision2 requires you to specify the file type for this file. You may select Custom File and use a custom translator to process this file. The custom translator is specified along with its command line in the Custom Arguments line of the Options – Properties dialog. Typical the custom translator will generate a source file from the custom file. You need to add this source file to your project to and use A166 or C166 to generate an object file that can be linked to your application.
Getting Started
65
4
In this example we have specified for CUSTOM.PRE that the program C:\UTILITIES\PRETRANS.EXE is used with the parameter –X to translate the file. Note that we have used also the Always Build option to ensure that the file is translated with every build process.
File Extensions
The dialog Project – File Extensions allows you to set the default file extension for a project. You can enter several extensions when you separate them with semicolon characters. The file extensions are project specific.
Different Compiler and Assembler Settings
Via the local menu in the Project Window – Files you may set different options for a file group or even a single file. The dialog pages have tri-state controls; if an option is grayed the setting from higher level is taken. You can specify with this technique different tools for a complete file group and still change settings on a single source file within this file group.
Version and Serial Number Information
Detailed tool chain information is listed when you open Help – About. Please use this information whenever you send us problem reports.
.
or code execution access. and timers. The µVision2 Debugger offers two operating modes that are selected in the Options for Target – Debug dialog: Use Simulator allows to configure the µVision2 Debugger as software-only product that simulates most features of the 166 / ST10 microcontroller family without actually having target hardware. the simulator also provides support for the integrated peripherals of the various 166 / ST10 derivatives. like Keil Monitor 166 interface.Getting Started 67 Chapter 5. Depending on the Options for Target – Debug configuration. 5 CPU Simulation µVision2 simulates up to 16 Mbytes of memory from which areas can be mapped for read. For more information refer to “Chapter 11. You can also change the aspects of each peripheral using the controls in the dialog boxes. external I/O. The on-chip peripherals of the CPU you have selected are configured from the Device Database selection you have made when you create your project target. Testing Programs µVision2 Debugger You can use µVision2 Debugger to test the applications you develop using the C166 compiler and A166 macro assembler. You can test and debug your embedded application before the hardware is ready. OCDS debugging systems or the Keil Monitor program. . Refer to page 36 for more information about selecting a device. µVision2 simulates a wide variety of peripherals including the serial port. Using Monitor-166” on page 155. In addition to memory mapping. write. You may select and display the on-chip peripheral components using the Debug menu. The µVision2 simulator traps and reports illegal memory accesses. With the Advanced GDI interface you may connect the environment directly to emulators. Start Debugging You start the debug mode of µVision2 with the Debug – Start/Stop Debug Session command. Use Advance GDI drivers. The peripheral set is selected when you select a CPU from the device database for your target.
The µVision2 debug mode differs from the edit mode in the following aspects: ¢ The “Debug Menu and Debug Commands” described on page 17 are available. Testing Programs µVision2 will load the application program and run the startup code. The project structure or tool parameters cannot be modified. Program source text of your application is shown in the same windows. You . For example. During debugging. µVision2 opens an editor window with the source text or shows CPU instructions in the disassembly window. If the program execution stops. The next executable statement is marked with a yellow arrow. If you select the Disassembly Window as the active window all program step commands work on CPU instruction level rather than program source lines. All build commands are disabled.68 Chapter 5. µVision2 saves the editor screen layout and restores the screen layout of the last debug session. you can use the find command or correct program errors. The additional debug windows are discussed in the following. For information about the configuration of the µVision2 debugger refer to page 74. set Debug – Enable/Disable Trace Recording. In addition. ¢ Disassembly Window 5 The Disassembly window lets you view your target program as mixed source and assembly program or just assembly code. most editor features are still available. a trace history of previously executed instructions can be displayed with Debug – View Trace Records. To enable the trace history.
You may use the dialog Debug – Inline Assembly… to modify the CPU instructions. . You may already set Execution Breaks during editing of your source text. You can quickly disable or enable the breakpoints with a mouse click on the check box in the Current Breakpoints list. Breakpoints µVision2 lets you define breakpoints in several different ways.Getting Started 69 can select a text line and set or modify code breakpoints using toolbar buttons or the context menu commands. Breakpoints can be defined and modified in the following ways: ¢ With the File Toolbar buttons. Just select the code line in the Editor or Disassembly window and click on the breakpoint buttons. ¢ ¢ 5 ¢ The Breakpoint dialog lets you view and modify breakpoints. That allows you to correct mistakes or to make temporary changes to the target program you are debugging. In the Output Window – Command page you can use the BreakSet. define and modify breakpoint settings. BreakEnable. The Debug – Breakpoints… dialog lets you review. With the breakpoint commands in the local menu. A double click in the Current Breakpoints list allows you to modify the selected break definition. and BreakDisable commands. The local menu opens with a right mouse click on the code line in the Editor or Disassembly window. even before the program code is translated. BreakList. BreakKill. This dialog allows you to define also access breakpoints with different attributes. Refer to the examples below.
>. Write or both) is selected an Access Break (A) is defined that becomes active when the specified memory access occurs. . The operators (&. The conditional expression is recalculated after each CPU instruction. You can specify the size of the memory access window in bytes or object size of the expression. <=. <. an Execution Break (E) is defined that becomes active when the specified code address is reached. For more information refer to “System Variables” on page 85. &&. To halt program execution in a µVision2 function.70 Chapter 5. The command you specify here may be a µVision2 debug or signal function. = =. When a memory Access (Read. therefore the program execution speed may slow down considerably. When the expression cannot be reduced to an address a Conditional Break (C) is defined that becomes active when the specified conditional expression becomes true. ¢ ¢ When you specify a Command for a breakpoint. µVision2 executes the command and resumes executing your target program. >=. The code address must refer to the first byte of a CPU instruction. set the _break_ system variable. and !=) can be used to compare the variable values before the Access Break halts program execution or executes the Command. Testing Programs 5 You define a breakpoint by entering an Expression in the Breakpoint dialog. Expressions for an Access Break must reduce to a memory address and memory type. Depending on the expression one of the following breakpoint types is defined: ¢ When the expression is a code address.
This breakpoint is disable in the above Breakpoint dialog. The Current Breakpoints list summarizes the breakpoint type and the physical address along with the Expression. Expression: \Measure\143 Execution Break (E) that halts when the target program reaches the code line 143 in the module MEASURE. Expression: mcommand == 1 Contional Break (C) that halts program execution when the expression mcommand = = 1 becomes true. Expression: sindex == 10 Access: Write Access Break (A) that halts program execution when the value 10 is written to the variable sindex.Getting Started 71 The Count value specifies the number of times the breakpoint expression is true before the breakpoint is triggered. Since save_record is a structure with size 16 bytes this break defines an access region of 48 bytes. This breakpoint is disable in the above Breakpoint dialog. Expression: save_measurements Count: 10 5 Execution Break (E) that halts when the target program reaches the function save_measurements the 10th time. Expression: main Execution Break (E) that halts when the target program reaches the main function. Breakpoint Examples: The following description explains the definitions in the Breakpoint dialog shown above. . Expression: save_record[10] Access: Read Write Size: 3 Objects Access Break (A) that halts program execution when an read or write access occurs to save_record[10] and the following 2 objects. Expression: timer0 Command: printf ("Timer0 Interrupt occurred\n") Execution Break (E) that prints the text "Timer0 Interrupt occurred" in the Output Window – Command page when the target program reaches the timer0 function. Command and Count.
and Tstep commands. The local menu opens with a right mouse click on the code line in the Editor or Disassembly window. You add variables in three different ways: . With the Run till Cursor line command in the local menu. The target program execution resumes after the debug function MyStatus has been executed. The contents of the Watch Window are automatically updated whenever program execution stops. ¢ ¢ 5 Watch Window The Watch window lets you view and modify program variables and lists the current function call nesting. Pstep. Ostep. You can enable View – Periodic Window Update to update variable values while a target program is running. The Locals page shows all local function variables of the current function. The Watch pages display user-specify program variables. Target Program Execution µVision2 lets execute your application program in several different ways: ¢ With the Debug Toolbar buttons and the “Debug Menu and Debug Commands” as described on page 17. Testing Programs MyStatus () Execution Break (E) that executes the µVision2 debug function MyStatus when the target program reaches the function measure_display. In the Output Window – Command page you can use the Go.72 Expression: measure_display Command: Chapter 5.
¢ ¢ To remove a variable. In an editor window open the context menu with a right mouse click and use Add to Watch Window. Up to four different areas can be review in the different pages. Another mouse click enters edit mode that allows you to add variables. you can enter any expression that evaluates to a start address of the area you want to display. In the Output Window – Command page you can use the WatchSet command to enter variable names. The context menu allows you to select the output format. 5 Memory Window The Memory window displays the contents of the various memory areas. alternatively you may mark an expression before using that command. In the same way you can modify variable values. You can double click on a line to show the invocation an editor window. µVision2 automatically selects the variable name under the cursor position. click on the line and press the Delete key. This opens an edit box that allows you .Getting Started 73 ¢ Select the text <enter here> with a mouse click and wait a second. CPU Registers The CPU registers are displayed and Project Window – Regs page and can be modified in the same way as variables in the Watch Window. In the Address field of the Memory Window. To change the memory contents. double click on a value. The current function call nesting is shown in the Call Stack page.
even while running the test program. "printf (\"R15=%04XH\\n\")" NOTE The printf command defined in the last button definition shown above introduces nested strings. "radix=0x0A" "Hex Output". Toolbox The Toolbox contains user-configurable buttons. "radix=0x10" "My Status Info". The double quote (") and backslash (\) characters of the format string must be escaped with \ to avoid syntax errors.5V". 5 The following examples show the define commands used to create the buttons in the Toolbox shown above: >DEFINE >DEFINE >DEFINE >DEFINE >DEFINE BUTTON BUTTON BUTTON BUTTON BUTTON "Decimal Output".. "analog0 ()" /* call signal function */ "Show R15".74 Chapter 5. The general syntax is: >DEFINE BUTTON "button_label". command is the µVision2 command to execute when the button is pressed. To update the memory window while a target program is running enable View – Periodic Window Update. "MyStatus ()" /* call debug function */ "Analog0. "command" button_label is the name to display on the button in the Toolbox. Testing Programs to enter new memory values. The Update Windows button updates several debug windows during program execution. For example: >Kill Button 5 /* Remove Show R15 button */ NOTE The Update Windows button in the Toolbox is created automatically and cannot be removed. You may remove a Toolbox button with the KILL BUTTON command and the button number. . Toolbox buttons may be executed at any time. Toolbox buttons are define the Output Window – Command page with the DEFINE BUTTON command. Click on a Toolbox button to execute the associated command.
Enable this option to load your target application automatically when you start the µVision2 debugger. Restore breakpoint settings from the previous debug session.Getting Started 75 Set Debug Options The dialog Options for Target . The Keil Monitor-166 Driver allows you to connect a target board with the Keil Monitor. 5 The following table describes the options of the Debug dialog page: Dialog Item Use Simulator Use Keil Monitor-166 Driver Settings Load Application at Startup Go till main () Initialization File Breakpoints Toolbox Watchpoints & PA Memory Display Description Select the µVision2 Simulator as Debug engine. Restore the memory display settings from the previous debug session. Select the Advanced GDI driver to connect to your debug hardware. Process the specified file as command input when starting a debug session. Restore Watchpoint and Performance Analyzer settings from the previous debug session.Debug configures the µVision2 debugger. There are µVision2 emulator and OCDS drivers in preparation. Start program execution till the main label when you start the debugger. Opens the configuration dialog of the selected Advanced GDI driver. Restore toolbox buttons from the previous debug session. . Other dialog options are available separately for the Simulator and Advanced GDI section.
Characters you type in the Serial Window are input to the simulated CPU. The settings are taken from the device database. . s The serial output may be also assigned to a PC COM port using the ASSIGN command in the Output Window – Command page. Serial Window µVision2 provides two Serial Windows for serial input and output. 5 This lets you simulate the CPU’ UART without the need for external hardware. Please do not modify the DLL or DLL parameters. Serial data output from the simulated CPU is displayed in this window. Testing Programs Dialog Item CPU DLL Driver DLL Parameter Description Configures the internal µVision2 debug DLLs.76 Chapter 5.
Information such as invocation count. The <unspecified> address range is automatically generated. maximum time. minimum time. and average time is displayed for the selected function or address range. lines of code that have been executed are market green in the left column. Results display as bar graphs. 5 To setup the Performance Analyzer use the menu command Debug – Performance Analyzer. The percent of the total time spent in the selected address range or function.Getting Started 77 Performance Analyzer The µVision2 Performance Analyzer displays the execution time recorded for functions and address ranges you specify. Code Coverage The µVision2 debugger provides a code coverage function that marks the code that has been executed. The total number of times the selected address range or function was executed. It shows the amount of time spent executing code that is not included in the specified functions or address ranges. The maximum time spent in the selected address range or function. You can use this feature when you . You may enter the PA command in the command window to setup ranges or print results. Label min time max time avg time total time % count Description The minimum time spent in the selected address range or function. The average time spent in the selected address range or function. The total time spent in the selected address range or function. In the debug window. Each of these statistics is described in the following table.
Execute. The Code Coverage dialog provides information and statistics. For each memory range. You need to map only memory areas that are accessed without explicit variable declarations.e. Write. s When you load a target application.78 Chapter 5. you may specify the access method: Read. . or a combination. Testing Programs test your embedded application to determine the sections of code that have not yet been exercised. Typically it is not required to map additional address ranges. You can output this information in the Output Window – Command page using the COVERAGE command. You may also configure the target program’ memory map using the MAP command. µVision2 automatically maps all address ranges of your application. The dialog opens via the menu Debug – Memory Map… As your target program runs. Memory Map 5 The Memory Map dialog box lets you specify the memory areas your target program uses for data storage and program execution. i. memory mapped I/O space. µVision2 uses the memory map to verify that your program does not access invalid memory areas.
Mask * *#* _a$#* Matches symbol names … Matches any symbol. Public symbols have application-wide scope. ending with zero or more characters. local symbols or line number information defined in the currently loaded application program. specify a mask that is used to match symbol names. … that contain one digit in any position. The mask may consist of alphanumeric characters plus mask characters: # matches a digit (0 – 9) $ matches any character * matches zero or more characters. … with an underline. Current Module Mask Apply The following table provides a few examples of masks for symbol name. The scope of local symbols is limited to a module or function. followed by a digit. applies the mask and displays the update symbol list. This is the default mask in the Symbol Browser. _ab1 or _a10value. 5 You may select the symbol type and filter the information with the options in the Symbol Window: Options Mode Description select PUBLIC. select the source module where information should be displayed. CPU-specific SFR symbols are also displayed. For example.Getting Started 79 View – Symbols Window The Symbols Window displays public symbols. Lines refer to the line number information of the source text. . followed by the letter a. LOCALS or LINE. followed by any character.
Steps over instructions but does not step into procedures or functions. Memory Commands 5 The following memory commands let you display and alter memory contents. followed by zero or more characters. Starts program execution.80 Chapter 5. . followed by ABC. Enters values into a specified memory area. the WATCHSET command must be entered as WS. Program Execution Commands Program commands let you run code and step through your program one instruction at a time. Adds a watch variable to the Watch window. Specifies access parameters for memory areas. You can enter nearly all debug commands. In the following all available µVision2 debug commands are listed in categories. NOTE Use the underlined characters in the command names to enter commands. Display the contents of memory. Testing Programs Mask _*ABC Matches symbol names … … with an underline. Evaluates an expression and outputs the results. For example. Debug Commands You interact with the µVision2 debugger by entering commands from the keyboard in the Command page of the Output Window. Steps over instructions and into functions. Disassembles program memory. Command Esc GO PSTEP OSTEP TSTEP Description Stops program execution. Defines typed symbols that you may use with µVision2 debug functions. Command ASM DEFINE DISPLAY ENTER EVALUATE MAP UNASSEMBLE WATCHSET Description Assembles in-line code. Steps out of the current function.
Sets the string value for predefined variable. Setup the performance analyzer or list PA information. Displays address assignments of modules and functions of a target program. Creates log files. and closes log files for the Debug window. List code coverage statistics. 5 . They are included to make debugging easier and more convenient. Adds a breakpoint expression to the list of breakpoints. queries log status. Creates a Toolbox button. Resets CPU. and closes log files for the Serial window. Removes one or more breakpoints from the breakpoint list. Exits the µVision2 debug mode. Breakpoints can be set on read operations. queries log status.Getting Started 81 Breakpoint Commands µVision2 provides breakpoints you may use to conditionally halt the execution of your target program. Lists the current breakpoints. and HEX files. object modules. Sets the baud rate. Command BREAKDISABLE BREAKENABLE BREAKKILL BREAKLIST BREAKSET Description Disables one or more breakpoints. Saves a memory range in an Intel HEX386 file. Loads CPU drivers. Assigns a source file to a module. and number of stop bits for PC COM ports. write operations and execution operations. Displays signal function status and removes active signal functions. Command ASSIGN COVERAGE DEFINE BUTTON DIR EXIT INCLUDE KILL LOAD LOG MODE PerformanceAnalyze RESET SAVE SCOPE SET SETMODULE SIGNAL SLOG Description Assigns input and output sources for the Serial window. parity. Reads and executes the commands in a command file. Deletes µVision2 debug functions and Toolbox buttons. General Commands The following general commands do not belong in any other particular command group. Performance Analyzer or predefined variables. Generates a directory of symbol names. Enables one or more breakpoints. Creates log files. memory map assignments.
HEX constants. Testing Programs You can interactively display and change variables. or operands. Constants are fixed numeric values or character strings. A numeric expression is a number or a complex expressions that contains numbers. floating-point constants.hour time. Assign the value 12 to register R7. When you compile or assemble a program. Assigns the value 0 to index. Component Bit Addresses Constants Line Numbers Description Bit addresses reference bit-addressable data memory. Expressions Many debug commands accept numeric expressions as parameters. Program variables are those variables in your target program. Displays the member hour of the time structure. registers. System variables alter or affect the way µVision2 operates. and memory locations from the command window. octal constants. Operators Program Variables (Symbols) System Variables Type Specifications Constants The µVision2 accepts decimal constants. debug objects.82 Chapter 5. For example. character constants. -. and string constants. binary constants. You may use all operators that are available in the C programming language. and /. . Operators include +. Increments the member hour of the time structure. Line numbers reference code addresses of executable programs. *. you can type the following text commands at the command prompt: Text MDH R7 = 12 time. Type specifications let you specify the data type of an expression or subexpression. They are often called symbols or symbolic names. 5 Components of an Expression An expression may consist of any of the following components.hour++ index = 0 Effect Display the MDH register. the compiler and assembler include line number information in the generated object module. Operators may be used to combine subexpressions into a single expression.
When a number is entered that is larger than the range of a 16-bit integer . number ¤ ¤ ¥number¥ e +|For example. and Octal Constants By default. numeric constants are 16-bit values. It must be entered as 0. Base Binary: Decimal: Hexadecimal: Octal: Prefix None None 0x or 0X None Suffix Y or y T or none H or h Q.12. n Numbers may be grouped with the dollar sign character (“$”) to make them easier to read. When you enter 10. number .1e3. number number . For example: 0x1234L. numeric constants are decimal or base ten numbers. The following table shows the prefixes and suffixes that are required to enter constants in base 2 (binary). 32-bit values. 4. They may be followed with an L to make them long. In contrast with the C programming language. HEX constants must begin prefixed with a leading zero when the first digit in the constant is A-F. 0. number e¤ ¥number +|- . . n n 5 n Floating-Point Constants Floating-point constants are entered in one of the following formats. O. 1255HL. For example. q. For example. floating-point numbers must have a digit before the decimal point.12e–5. 1234L. base 8 (octal). this is the number ten and not the HEX value 10h. 1111$1111y is the same as 11111111y.12. By default.12 is not allowed. base 10 (decimal). the number is promoted automatically to a 32-bit integer. and 12.Getting Started 83 Binary. HEX. and base 16 (HEX). Decimal. or o Example 11111111Y 1234T or 1234 1234H or 0x1234 777q or 777Q or 777o Following are a few points to note about numeric constants.
Tab. bell. Alert. 'a'. '\v'. the following are all valid character constants. For example. Backspace. '\x0FE'. successive strings are not concatenated into a single string. Sequence \n \r \t \0nn \Xnnn Description Newline. '\015' Also escape sequences are supported as listed in the following table: Sequence \\ \" \' \a \b \f Description Backslash character (“ ). For example: "printf (\"hello world!\n\")" In contrast with the C programming language. For example.84 Chapter 5. '1'. "string1+" "string2" is not combined into a single string. Single quote. '\n'. . Carriage return. Testing Programs Character Constants The rules of the C programming language for character constants apply to the µVision2 debugger. double quotes for a nested string must be escaped. For example. Form feed. Octal constant. HEX constant. \” Double quote. 5 String Constants The rules of the C programming language for string constants also apply to µVision2. For example: "string\x007\n" "value of %s = %04XH\n" Nested strings may be required in some cases.
Variable $ Type unsigned long Description represents the program counter. Refer to page 68 for more information. trace information is recorded. Illegal Word Operand Access. The default setting is 16 for HEX output. _break_ unsigned int _traps_ unsigned int states unsigned long itrace unsigned int 5 radix unsigned int On-chip Peripheral Symbols µVision2 automatically defines a number of symbols depending on the CPU you have selected for your project. and their uses. NOTE: states is a read-only variable. radix may be 10 or 16. no trace recording is performed. indicates whether or not trace recording is performed during target program execution. Refer to “ Chapter 6. lets you stop executing the target program. µVision2 Debug Functions” on page 97 for more information. µVision2 halts target program execution. $ = 0x4000 sets the program counter to address 0x4000. determines the base used for numeric values displayed. The following table lists the available system variables. Special Function Registers (SFRs) µVision2 supports all special function registers of the microcontroller you have selected. When itrace is 0. current value of the CPU instruction state counter. Protected Instruction Fault. You may use $ to display and change the program counter. When you set _break_ to a non-zero value. When itrace has a non-zero value. when you set _traps_ to a non-zero value. You may use this variable in user and signal functions to halt program execution. . starts counting from 0 when your target program begins execution and increases for each instruction that is executed. µVision2 display messages for the 166 hardware traps: Undefined Opcode. the data types. Stack Underflow and Stack Overflow.Getting Started 85 System Variables System variables allow access to specific functions and may be used anywhere a program variable or other expression is used. Special function registers have an associated address and may be used in expressions. Illegal Instruction Access. There are two types of symbols that are defined: special function registers (SFRs) and CPU pin registers (VTREGs). For example.
A group of I/O pins for a port on the chip. These are read by your target program. For the C167 CPU the following VTREG symbols for the on-chip peripheral registers are available: CPU-pin Symbol AIN0 AIN1 AIN2 Description Analog input line AIN0 (floating-point value) Analog input line AIN1 (floating-point value) Analog input line AIN2 (floating-point value) . You may write 8-bit or 9-bit values to SxIN. For example. These registers allow you to simulate port I/O. The following table describes the VTREG symbols. the CPU driver simulates external interrupt 0. You can list these symbols with the DIR VTREG command. When SxTIME is 1. The input buffer of serial interface x. or VTREGs. the programmed baudrate timing is ignored and serial transmission time is instantaneous. VTREG AINx PORTx SxIN Description An analog input pin on the chip. VTREGs are not public symbols nor do they reside in a memory space of the CPU. The VTREG symbols that are actually available depend on the selected CPU. The clock frequency of the simulated CPU as defined in the Options – Target dialog. When SxTIME is 0 (the default value). The value 0xFFFF signals that the previous value is completely processed and a new value may be written. let you use the CPU’ simulated pins for input s and output. Your target program may read values you write to AINx VTREGs. Defines the baudrate timing of the serial interface x. PORT2 refers to all 8 or 16 pins of P2. They may be used in expressions. The output buffer of serial interface x. 5 SxOUT SxTIME CLOCK NOTE You may use the VTREGs to simulate external input and output including interfacing to internal peripherals like interrupts and timers. µVision2 copies 8-bit or 9-bit values (as programmed) to the SxOUT VTREG.86 Chapter 5. For example. VTREGs provide a way to specify signals coming into the CPU from a simulated piece of hardware. You may read SxIN to determine when the input buffer is ready for another character. but their values and utilization are CPU dependent. Testing Programs CPU Pin Registers (VTREGs) CPU pin registers. if you toggle bit 2 of PORT3 (on the 8051 drivers). µVision2 simulates the timing of the serial interface using the programmed baudrate.
Bit 1of EBC represents EBC1. Bit 0 of EBC represents EBC0. You must invoke the RESET command after changing the value of EA. This configuration pin is necessary for calculating the execution time of a program. PORT0H PORT0L PORT1H PORT1L PORT2 PORT3 PORT4 PORT5 PORT6 PORT7 PORT8 S0IN S0OUT S0TIME S1IN S1OUT Digital I/O lines of PORT 0H (8-bit) Digital I/O lines of PORT 0L (8-bit) Digital I/O lines of PORT 1H (8-bit) Digital I/O lines of PORT 1L (8-bit) Digital I/O lines of PORT 2 (16-bit) Digital I/O lines of PORT 3 (16-bit) Digital I/O lines of PORT 4 (8-bit) Digital/analog Input Lines of PORT 5 (16-bit) Digital I/O lines of PORT 6 (8-bit) Digital I/O lines of PORT 7 (8-bit) Digital I/O lines of PORT 8 (8-bit) Serial input for SERIAL CHANNEL 0 (9 bits) Serial output for SERIAL CHANNEL 0 (9 bits) Serial timing enable for SERIAL CHANNEL 0 Serial input for SERIAL CHANNEL 1 (9 bits) Serial output for SERIAL CHANNEL 1 (9 bits) . non-multiplexed 8-bit data bus. multiplexed 16-bit data bus. You must invoke the RESET command after changing the value of EBC. EBC may have one of the following values: Value 0 1 2 3 Description 8-bit data bus. multiplexed EBC 5 Bus configuration pins are necessary for calculating the execution time of a program. EBC0 and EBC1 are both set. External Bus Configuration after reset (2 bits).Getting Started 87 CPU-pin Symbol AIN3 AIN4 AIN5 AIN6 AIN7 AIN8 AIN9 AIN10 AIN11 AIN12 AIN13 AIN14 AIN15 EA Description Analog input line AIN3 (floating-point value) Analog input line AIN4 (floating-point value) Analog input line AIN5 (floating-point value) Analog input line AIN6 (floating-point value) Analog input line AIN7 (floating-point value) Analog input line AIN8 (floating-point value) Analog input line AIN9 (floating-point value) Analog input line AIN10 (floating-point value) Analog input line AIN11 (floating-point value) Analog input line AIN12 (floating-point value) Analog input line AIN13 (floating-point value) Analog input line AIN14 (floating-point value) Analog input line AIN15 (floating-point value) Status of the EA pin (1 bit). When EBC is 3. non-multiplexed 16-bit data bus.
e.0005 secs */ clear P1. twatch ((CLOCK / 2) / 2000). The VTREGs are the signals present on the pins. PORT2 &= ~1. First.2 */ delay for .0) to enable or disable an LED. you can use a signal function to simulate the signal.2 */ delay for .1 with a frequency of 1000Hz. Two steps are required. Simulating external hardware that responds to output from a port pin is only slightly more difficult.e. Do not confuse these VTREGs with the SFRs for each port (i. For example. write a µVision2 user or signal function to perform the desired operations. . Testing Programs CPU-pin Symbol S1TIME CLOCK Description Serial timing enable for SERIAL CHANNEL 1 Clock frequency The following examples show how VTREGs may be used to aid in simulating your target program. Suppose you use an output pin (P2. create a breakpoint that invokes the user function. } } /* /* /* /* /* /* repeat forever */ set P1. µVision2 Debug Functions” on page 97 for more information about user and signal functions. P2).0005 secs */ repeat */ 5 The following command starts this signal function: one_thou_hz () Refer to “Chapter 6. Second. the following signal function inputs a square wave on P2. signal void one_thou_hz (void) { while (1) { PORT2 |= 1. you use VTREGs in signal functions to simulate some part of your target hardware. In most cases. twatch ((XCLOCK / 2) / 2000). If you have a pulse train coming into a port pin. With µVision2. I/O Ports µVision2 defines a VTREG for each I/O port: i. The SFRs can be accessed inside the CPU memory space. The following signal function uses the PORT2 VTREG to check the output from the CPU and display a message in the Command window. it is easy to simulate input from external hardware. PORT2.88 Chapter 5.
"check_p20 ()" Now. . and S0OUT. S0IN = 'A'. When S0TIME is 0. 1. Refer to page 69 for more information about setting breakpoints. Suppose you have an external serial device that inputs specific data periodically (every second). S0IN and S0OUT represent the serial input and output streams on the CPU. the check_P20 function prints the current status of the LED. } } /* repeat forever */ /* Delay for 1 second */ /* /* /* /* Send first character */ Delay for 1 character time */ 900 is good for 9600 baud */ Send next character */ 5 /* Send final character */ /* repeat */ When this signal function runs. twatch (CLOCK / 900). Simulating serial input is just as easy as simulating digital input. it delays for 1 second. Serial Ports The on-chip serial port is controlled with: S0TIME.Getting Started signal void check_p20 (void) { if (PORT2 & 1)) { printf ("LED is ON\n"). The following command line adds a breakpoint for all writes to PORT2. twatch (CLOCK / 900). ‘ . and ‘ into A’ B’ C’ the serial input line and repeats. When S0TIME is 1. serial data displayed in the Serial window is output at the specified baudrate. S0IN = 'C'. } else { printf ("LED is OFF\n"): } } 89 /* Test P2. whenever your target program writes to PORT2. S0IN = 'B'. Serial output is simulated in a similar fashion using a user or signal function and a write access breakpoint as described above.0 */ /* 1? LED is ON */ /* 0? LED is OFF */ Now. You can create a signal function that feeds the data into the CPU’ serial port. inputs ‘ . S0IN. s signal void serial_input (void) { while (1) { twatch (CLOCK). BS WRITE PORT2. serial data is displayed in the Serial window much more quickly. you must add a breakpoint for writes to port 1. S0TIME lets you specify whether the serial port timing instantaneous (STIME = 0) or the serial port timing is relative to the specified baudrate (SxTIME = 1).
A’ Z’ a’ z’ 0’ 9’ _’ ?’ NOTE When using the ternary operator (“?:”) in µVision2 with a symbol that begins with a question mark (“?”). ‘ -’ . in your target program by simply typing their name. Symbols make the debugging process easier by allowing you to use the same names in the debugger as you use in your program. represent numeric values and addresses. or ‘ . Symbol Naming Conventions The following conventions apply to symbols.90 Chapter 5. Without debug information. n n n The case of symbols is ignored: SYMBOL is equivalent to Symbol. or symbol names. 5 The module name is derived from the name of the source file. The symbols include local variables (declared within functions). ‘ -’ . Variable names. or ‘ . ‘ . For example. the module name is MCOMMAND. Module Names A module name is the name of an object module that makes up all or part of a target program. When you load a target program module and the symbol information is loaded into the debugger. The first character of a symbol name must be: ‘ -’ . or symbols. the function names. ‘ -’ . Testing Programs Program Variables (Symbols) µVision2 lets you access variables.OBJ.C and the C compiler generates an object file called MCOMMAND. If the target program consists of a source file named MCOMMAND. A’ Z’ a’ z’ _’ ?’ Subsequent characters may be: ‘ -’ . . Source-level debugging information as well as symbolic information is stored in each module. µVision2 cannot perform source-level and symbolic debugging. and the line number information. R5 = R6 ? ?symbol : R7. you must insert a space between the ternary operator and the symbol name. You must enable Options for Target – Output – Debug Information. ‘ .
you must literalize your program symbol using the back quote character (`) to differentiate them from reserved words. Literal Symbols Often you may find that your program symbols duplicate reserved words. register names. you must prefix the variable name with the back quote character.Getting Started 91 Symbol Classification µVision2 recognizes two classes of symbols: n n Program Symbols are defined in the target program. you will actually access the R5 register. Function Name identifies the function in a module where a local symbol is defined. To access the R5 variable. data type names. When you literalize a symbol. Accessing the R5 Register >R5 = 121 Accessing the R5 Variable >`R5 = 212 5 Normally. µVision2 only searches for target program symbols. A fully qualified symbol name may include any of the following components: n n Module Name identifies the module where a symbol is defined. and VTREGs are all reserved words. Debug commands & options. Symbol Name identifies the name of the symbol. For example. Symbols may also be entered using a fully qualified name that includes the name of the module and name of the function in which the symbol is defined. Line Number identifies the address of the code generated for a particular line in the module. CPU symbols. µVision2 searches for reserved words then for target program symbols. Reserved Words are predefined in µVision2. Fully Qualified Symbols Symbols may be entered using the only name of the variable or function they reference. if you define a variable named R5 in your program and you attempt to access it. n n . system variables. When this occurs.
92
Chapter 5. Testing Programs
You may combine names as shown in the following table:
Symbol Components
\ModuleName\LineNumber \ModuleName\FunctionName \ModuleName\SymbolName \ModuleName\FunctionName\SymbolName
Full Qualified Symbol Name addresses …
… line number LineNumber in ModuleName. … FunctionName function in ModuleName. … global symbol SymbolName in ModuleName. … local symbol SymbolName in the FunctionName function in ModuleName.
Examples of fully qualified symbol names:
Full Qualified Symbol Name
\MEASURE\clear_records\idx \MEASURE\MAIN\cmdbuf \MEASURE\sindx \MEASURE\225 \MCOMMAND\82 \MEASURE\TIMER0
Identifies …
… local symbol idx in the clear_records function in the MEASURE module. … cmdbuf local symbol in the MAIN function in the MEASURE module. … sindx symbol in the MEASURE module. … line number 225 in the MEASURE module. … line number 82 in the MCOMMAND module. … the TIMER0 symbol in the MEASURE module. This symbol may be a function or a global variable.
5
Non-Qualified Symbols
When you enter a fully qualified symbol name, µVision2 determines if the symbol exists and reports an error if it does not. For symbols that are not fully qualified, µVision2 searches a number of tables until a matching symbol name is found. This search works as follows: 1. Local Variables in the Current Function in the target program. The current function is determined by the value of the program counter. 2. Global or Static Variables in the Current Module. As with the current function, the current module is determined by the value of the program counter. Symbols in the current module represent variables that were declared in the module but outside a function. This includes file-scope or static variables. 3. Symbols Created with the µVision2 DEFINE Command. These symbols are used for debugging and are not a part of the target program. 4. System Variables provide a way to monitor and change debugger characteristics. They are not a part of the target program. Refer to “System Variables” on page 85 for more information. If a global variable in your target
Getting Started
93
program shares the same name as a system variable, you may access the global variable using a literal symbol name. Refer to “Literal Symbols” on page 91 for more information. 5. Global or Public Symbols of your target program. SFRs defined by µVision2 are considered to be public symbols and are also searched. 6. CPU Driver Symbols (VTREGs) defined by the CPU driver. Refer to “CPU Pin Registers (VTREGs)” on page 86 for a description of VTREG symbols. NOTE The search order for symbols changes when creating user or signal functions. µVision2 first searches the table of symbols defined in the user or signal function. Then, the above list is searched. Refer to “Chapter 6. µVision2 Debug Functions” on page 97 for more information about user and signal functions.
Line Numbers
Line numbers enable source-level debugging and are produced by the compiler or assembler. The line number specifies the physical address in the source module of the associated program code. Since a line number represents a code address, µVision2 lets you use in an expression. The syntax for a line number is shown in the following table.
Line Number Symbol
\LineNumber \ModuleName\LineNumber
5
Code Address …
… for line number LineNumber in the current module. … for line number LineNumber in ModuleName.
Example
\measure\108 \143 /* Line 108 in module "MEASURE" */ /* Line 143 in the current module */
94
Chapter 5. Testing Programs
Bit Addresses
Bit addresses represent bits in the memory. This includes bits in special function registers. The syntax for a bit address is expression . bit_position Examples
R6.2 0xFD00.15 /* Bit 2 of register R6 */ /* Value of the 166 bit space */
Type Specifications
µVision2 automatically performs implicit type casting in an expression. You may explicitly cast expressions to specific data types. Type casting follows the conventions used in the C programming language. Example:
(unsigned int) 31.2 /* gives unsigned int 31 from the float value */
Operators
5
µVision2 supports all operators of the C programming language. The operators have the same meaning as their C equivalents.
Differences Between µVision2 and C
There are a number of differences between expressions in µVision2 and expressions in the C programming language:
n
µVision2 does not differentiate between uppercase and lowercase characters for symbolic names and command names. µVision2 does not support converting an expression to a typed pointer like char * or int *. Pointer types are obtained from the symbol information in the target program. They cannot be created. Function calls entered in the µVision2 Output Window – Command page refer to debug functions. You cannot invoke functions in your target from the command line. Refer to “Chapter 6. µVision2 Debug Functions” on page 97 for more information. µVision2 does not support structure assignments.
n
n
n
Z@..4' /* Simple constant */ /* Output */ /* Output in several number bases */ Register >R1 0x000A >R1 = --R7 /* Interrogate value of register R1 */ /* Address from ACC = 0xE0.. . array[15] of char Program Variable Examples .... 00 CE 39 . 5 Address Utilization Examples >&\measure\main\cmdbuf[0] + 10 0x23026 >_RBYTE (0x233DA) 0x76 /* Address calculation */ /* Read byte from code address 0x233DA */ /* Reply */ Symbol Output Examples >dir \measure\main /* Output symbols from main() in module MEASURE */ R14 idx .. .D. ... . ... uint /* Output */ R13 i .. main starts at 0x233DA */ /* Same as before */ 76 E6 E6 E6 E2 B7 28 F8 00 00 3C 7A 04 00 F6 40 76 E6 E6 CA E3 5A CE 00 00 40 44 CE = main.66 E3 FF F7 E6 .v.9..f...E6 F8 18 44 CA /* Get address of main() from MEASURE. ..*< 00 BB D8 .... The MEASURE example program were used for all examples..BF 88 E6 A8 40 .....Getting Started 95 Expression Examples The following expressions were entered in the Command page of the Output Window..... ..E6 D8 11 80 E6 .C */ /* Reply.. . ....(<. uint 0x0002301C cmdbuf . mem type = D: */ /* Set R1 and R7 equal to value R7-1 */ Function Symbol >main 0x00233DA >&main 0x00233DA >d main 0x0233DA: 0x0233EA: 0x0233FA: 0x02340A: /* 04 00 00 39 Display: address . All applicable output is included with each example. Constant >0x1234 0x1234 >EVAL 0x1234 4660T 11064Q 1234H '. uint 0x0002301C cmdbuf . uint /* Output */ R13 i . .@.D. . . array[15] of char Program Counter Examples >$ = main /* Set program counter to main() */ >dir /* points to local mem sym. from main() */ R14 idx .z@.. mem type = C: */ B6 80 00 v. 2A 3C F6 ..
96 >cmdbuf 0x0002301C >cmdbuf[0] 0x00 >i 0x00 >idx 0x0000 >idx = DPP2 >idx 0x0008 Chapter 5.hour = DPP3 >save_record[0].time.min = getint ("enter integer: ").hour 0x03 /* Address of a record */ /* Change struct element of records */ /* Interrogation */ µVision2 Debug Function Invocation Examples >printf ("uVision2 is coming!\n") /* String constant within printf() uVision2 is coming! /* Output >_WBYTE(0x20000. _RBYTE(0x20001) /* Read & Write Memory Byte > /* example useful in debug functions >interval.time. */ */ */ */ Fully Qualified Symbol Examples >--\measure\main\idx 0xFFFF /* Auto INC/DEC valid for qualified symbol */ . Testing Programs /* Interrogate address from cmdbuf */ /* Output of address due to aggregate type (Array)*/ /* Output contents of first array element */ /* Output contents from i */ /* Output contents from idx */ /* Set contents from index equal to register DPP2 */ /* Output contents from idx */ Line Number Examples >\163 0x000230DA >\MCOMMAND\91 0x000231F6 /* Address of the line number #104 */ /* Reply */ /* A line number of module "MCOMMAND" */ Operator Examples >--R5 0xFE >mdisplay 0 >mdisplay = 1 >mdisplay 1 /* Auto-decrement also for CPU registers */ /* Output a PUBLIC bit variable */ /* Change */ /* Check result */ 5 Structure Examples >save_record[0] 0x002100A >save_record[0].
n For a complete description of the “Differences Between Debug Functions and C” refer to page 110. case. µVision2 debug functions utilize a subset of the C programming language. else. while. and goto may be used in debug functions. 6 Creating Functions µVision2 has a built-in debug function editor which opens with Debug – Function Editor. log memory contents to a file. break. do. You may create functions that generate external interrupts. Local scalar variables are declared in debug functions in the same way they are declared in ANSI C.Getting Started 97 Chapter 6. and input serial data to the on-chip serial port. update analog input values periodically. Arrays are not allowed in debug functions. . switch. µVision2 debug functions aids you in debugging of your application and are entered or with the Function Editor or on µVision2 command level. You may use functions to extend the capabilities of the µVision2 debugger. continue. All of these statements operate in µVision2 debug functions as they do in ANSI C. When you start the function editor. The debug function editor works in the same way as the build-in µVision2 editor and allows you to enter and compile debug functions. The basic capabilities and restrictions are as follows: n Flow control statements if. the editor asks for a file name or opens the file specified under Options for Target – Debug – Initialization File. NOTE Do note confuse µVision2 debug functions with functions of your target program. µVision2 Debug Functions This chapter discusses a powerful aspect of the µVision2: debug functions.
send current editor content to the µVision2 command interpreter.Initialization File.INI MYFUNCS.INI. µVision2 Debug Functions Options Open New Save Save As Compile Description open an existing file with µVision2 debug functions or commands. create a new file save the editor content to file. >INCLUDE MYFUNCS. shows a list of all errors.INI will be processed. the contents of MYFUNCS.98 Chapter 6. this locates the cursor to the erroneous line in the editor window. Functions that are no longer needed may be deleted using the KILL command. . Every time you start the µVision2 debugger. µVision2 reads and interprets the contents of MYFUNCS.INI may contain debug commands and function definitions. if you type the following command in the command window. 6 Compile Errors Once you have created a file with µVision2 debug functions. This compiles all debug functions. Choose an error. For example. You may enter this file also under Options for Target – Debug . you may use the INCLUDE command to read and process the contents of the text file. specify a file for saving the debug functions.
and built-in functions. For example. For example. and signal functions available. A maximum of 64 signal functions may be active simultaneously. Signal functions run in the background during your target program’ execution. and Signal Functions. . they are entered into the internal table of user or signal functions. User Functions. Predefined functions cannot be removed or redefined. signals can be applied on the input lines of the CPU under simulation. to execute debug commands from user and signal functions. signal. to run the printf built-in function to print “Hello World. User Functions extend the capabilities of µVision2 and can process the same expressions allowed at the command level. Signal Functions simulate the behavior of a complex signal generator and lets you create various input signals to your target application. You may use the predefined function exec. user. DIR SIGNAL displays the names of all signal functions. n n 6 As functions are defined.Getting Started 99 Invoking Functions To invoke or run a debug function you must type the name of the function and any required parameters in the command window. n Predefined Functions perform useful tasks like waiting for a period of time or printing a message. DIR FUNC displays the names of all user. Function Classes µVision2 supports the following three classes of functions: Predefined Functions.” enter the following text in the command window: >printf ("Hello World\n") The µVision2 debugger responds by printing the text “Hello World” in the Command page of the Output Window. You may use the DIR command to list the predefined. s Signal functions are coupled via CPU states counter which has a resolution of instruction state. DIR BFUNC displays the names of all built-in functions. DIR UFUNC displays the names of all user functions.
µVision2 Debug Functions Predefined Functions µVision2 includes a number of predefined debug functions that are always available for use. ulong val) (address. uchar val) (address. The command_string may contain several commands separated by semicolons. float val) (address. void exec (“command_string”) The exec function lets you invoke µVision2 debug commands from within your user and signal functions..100 Chapter 6. . double val) Description Execute Debug Command Ask the user for a double number Ask the user for a int number Ask the user for a long number fill memory with constant value works like the ANSI C printf function return a random number in the range -32768 to +32767 Delay execution of signal function for specified number of CPU states Read char on specified memory address Read int on specified memory address Read long on specified memory address Read float on specified memory address Read double on specified memory address Write char on specified memory address Write int on specified memory address Write long on specified memory address Write float on specified memory address Write double on specified memory address 6 double void void void void void The predefined functions are described below. They cannot be redefined or deleted.) .. Return void double int long void void int void uchar uint ulong float Name exec getdbl getint getlong memset printf rand twatch _RBYTE _RWORD _RDWORD _RFLOAT _RDOUBLE _WBYTE _WWORD _WDWORD _WFLOAT _WDOUBLE Parameter (“ command_string” ) (“ prompt_string” ) (“ prompt_string” ) (“ prompt_string” ) (start_addr. Predefined functions are provided to assist the user and signal functions you create. uint val) (address. len) (“ string” . (int seed) (ulong states) (address) (address) (address) (address) (address) (address. The following table lists all predefined µVision2 debug functions. value.
EVAL R7") >exec ("BS timer0") >exec ("BK *") double getdbl (“prompt_string”). 'a'. 0x1000) /* Fill 0x20000 to 0x20FFF with "a" */ 6 void printf (“format_string”. int getint (“prompt_string”). Following arguments may be expressions or strings.) The prinf function works like the ANSI C library function. returns the value of the number entered. Example >exec ("DIR PUBLIC. If no entry is made.. The first argument is a format string. The conventional ANSI C formatting specifications apply to printf. upon entry. rand(0)) random number = 64D6H >printf ("%s for %d\n". "uVision2". uchar value.. Example >age = getint ("Enter Your Age") void memset (start address. rand(0)) random number = 1014H >printf ("random number = %04XH\n". the value 0 is returned. Example >MEMSET (0x20000. long getlong (“prompt_string”) This functions prompts you to enter a number and. Example >printf ("random number = %04XH\n". (ulong) -1) 4294967295 . 166) uVision2 for 166 >printf ("%lu\n".Getting Started 101 The command_string is passed to the command interpreter and must be a valid debug command. . ulong length) The memset function sets the memory specified with start address and length to the specified value.
µVision2 updates the state counter while executing your target program. 6 signal void int0_signal (void) { while (1) { PORT3 |= 0x04. Example The following signal function toggles the INT0 input (P3.2) high again */ for 1 second */ NOTE The twatch function may be called only from within a signal function. /* pull twatch (CLOCK). /* pull PORT3 |= 0x04. /* wait } } INT0(P3. The random number generator is reinitialized each time a non-zero value is passed in the seed argument. /* pull PORT3 &= ~0x04. You may use the rand function to delay for a random number of clock cycles or to generate random data to feed into a particular algorithm or input routine. Calls outside a signal function are not allowed and result in an error message. . Example >rand (0x1234) 0x3B98 >rand (0) 0x64BD /* Initialize random generator with 0x1234 */ /* No initialization */ void twatch (long states) The twatch function may be used in a signal function to delay continued execution for the specified number of CPU states.102 Chapter 6.2) high */ INT0(P3.2) low and generate interrupt */ INT0(P3. µVision2 Debug Functions int rand (int seed) The rand function returns a random number in the range -32768 to +32767.2) every second.
uchar value).5 at 0xE000 */ /* write the long value 12345678 at 0x1000 */ 6 . uint _RWORD (address). ulong _RDWORD (address). double value) These functions write a value to the specified memory address. Example >_WBYTE (0x20000. _WFLOAT (addr.Getting Started 103 uchar _RBYTE (address). ulong value). _WWORD (addr. float _RFLOAT (address). _WDWORD (addr. 12345678) /* write the byte 0x33 at 0x20000 */ /* write the float value 1. double _RDOUBLE (address) These functions return the content of the specified memory address. 1. _WDOUBLE (addr. Example >_RBYTE (0x20000) >_RFLOAT (0xE000) >_RDWORD (0x1000) /* return the character at 0x20000 */ /* return the float value at 0xE000 */ /* return the long value at 0x1000 */ _WBYTE (addr.5) >_RDWORD (0x1000. float value. 0x55) >_RFLOAT (0xE000. uint value).
} . uchar. Example The following example shows a user function that displays the contents of the registers R0 through R7. You may enter user functions directly in the function editor or you may use the INCLUDE command to load a file that contains one or more user functions. R4. printf (" R4 R8 R9 R10 R11 R12\n"). Each argument must have a type and a name.MyRegs() ----------\n"). The function definition is complete when the number of open braces is balanced with the number of the closing braces (“}”).104 Chapter 6. FUNC void MyRegs (void) { printf ("---------. R11. is the name of the function. µVision2 Debug Functions User Functions User functions are functions you create to use with the µVision2 debugger. ulong. User functions begin with FUNC keyword and are defined as follows: FUNC return_type fname (parameter_list) { statements } return_type is the type of the value returned by the function and may be: bit. use void for the parameter_list. R10. If no return type is specified the type int is assumed. printf (" %04X %04X %04X %04X %04X %04X\n". For more information about “Creating Functions” refer to page 97. uint. You may use void if the function does not return a value. float. R12). is the open curly brace. int. long. NOTE µVision2 provides a number of system variables you may use in your user functions. void. char. Refer to “System Variables” on page 85 for more information. R8. printf ("------------------------------\n"). If no arguments are passed to the function. R9. Multiple arguments are separated by commas. statements { are instructions the function carries out. fname 6 parameter_list is the list of arguments that are passed to the function.
the MyRegs function displays the contents of the registers and appears similar to the following: ---------. Functions with a void return type must not return a value. n n n 6 .Getting Started 105 To invoke this function. MyRegs() When invoked. Functions with a non-void return type must return a value. User functions may not invoke signal functions or the twatch function. The value of a local object is undefined until a value is assigned to it. type the following in the command window. Note that µVision2 does not check each return path for a valid return value. Remove user functions using the KILL FUNC command.MyRegs() ---------R4 R8 R9 R10 R11 R12 B02C 8000 0001 0000 0000 0000 ------------------------------ Restrictions n µVision2 checks user functions to ensure they return values that correspond to the function return type.
Signal functions help you simulate and test serial I/O.000 CPU states. like signal inputs and pulses.000. a signal function must call the twatch function at some point to delay and let µVision2 run your target program. Signal functions execute in the background while µVision2 simulates your target program. Refer to “System Variables” on page 85 for more information. and other repetitive external events. twatch (1000000). µVision2 Debug Functions Signal Functions A Signal function let you repeat operations. 6 parameter_list is the list of arguments that are passed to the function. in the background while µVision2 executes your target program. NOTE µVision2 provides a number of system variables you may use in your signal functions. use void for the parameter_list. } } { . Signal functions begin with the SIGNAL keyword and are defined as follows: SIGNAL void fname (parameter_list) { statements } fname is the name of the function. port communications. For more information about “Creating Functions” refer to page 97. Each argument must have a type and a name. is the open curly brace. The function definition is complete when the number of open braces is balanced with the number of the closing braces (“}”). Multiple arguments are separated by commas. µVision2 reports an error for signal functions that never call twatch. Therefore. If no arguments are passed to the function. Example The following example shows a signal function that puts the character ‘ into the A’ serial input buffer once every 1. statements { are instructions the function carries out.106 Chapter 6. analog I/O. SIGNAL void StuffS0in (void) while (1) { S0IN = 'A'.
µVision2 may enter an infinite loop. A signal function may be invoked by a user function. delays for 1. A signal function that is running is executing statements inside the function. When a signal function invokes the twatch function. View the state of active signal functions with the command SIGNAL STATE. Signal functions may only be activated once. Execution continues at the statement after twatch. When you invoke a signal function. and repeats. A signal function that is idle is delayed while it waits for the number of CPU states specified in a call to twatch to expire. type the following in the command window. A signal function may invoke other predefined functions and user functions. After the user program has executed the specified number of CPU states.000 CPU states. µVision2 adds that function to the queue and marks it as running. A signal function must call the twatch function at least once. Managing Signal Functions µVision2 maintains a queue for active signal functions. StuffS0in() When invoked. A signal function may either be either idle or running. the StuffS0in signal function puts and ASCII character ‘ in the A’ serial input buffer. the signal function becomes running. 6 . A signal function may have a maximum of eight function parameters. it goes in the idle state for the number of CPU states passed to twatch.000. a warning is displayed. Restrictions The following restrictions apply to signal functions: n n n n n n The return type of a signal function must be void. Since you cannot use Ctrl+C to abort a signal function.Getting Started 107 To invoke this function. A signal function may not invoke another signal function. Signal functions that never call twatch do not allow the target program time to execute. Remove active signal functions form the queue with the command SIGNAL KILL. if the function is already in the queue.
When 200. µVision2 Debug Functions If a signal function exits. The function increases and decreases the input voltage by 0. signal void analog0 (float limit) float volts. This signal function repeats indefinitely. limit).0) { ain0 = volts.\n". you can infer that analog0 executed the twatch function (on line 8 of analog0) and is waiting for the specified number of CPU states to elapse. analog0 continues execution until the next call to twatch in line 8 or line 14. /* increase voltage */ } volts = limit.000000) ENTERED /* Start of 'ANALOG()' */ The SIGNAL STATE command to displays the current state of the analog0: >SIGNAL STATE 1 idle Signal = ANALOG0 (line 8) µVision2 lists the internal function number. while (volts >= 0. /* analog input-0 */ twatch (200000). . while (volts <= limit) { ain0 = volts. /* 200000 states Time-Break */ volts -= 0. Since the status of the signal function is idle. the status of the signal function: idle or running.1. { 6 printf ("Analog0 (%f) entered.0) ANALOG0 (5. /* decrease voltage */ } } } The signal function analog0 can then be invoked as follows: >ANALOG0 (5. it is automatically removed from the queue of active signal functions. Analog Example The following example shows a signal function that varies the input to analog input 0 on a C167. twatch (200000).000 states for each voltage step. because of a return statement. the function name and the line number that is executing. delaying 200.5 volts from 0V and an upper limit that is specified as the signal function’ only s argument. while (1) { /* forever */ volts = 0. /* 200000 states Time-Break */ volts += 0.1.000 states pass.108 Chapter 6.
Getting Started 109 The following command removes the analog0 signal function from the queue of active signal functions. >SIGNAL KILL ANALOG0 6 .
µVision2 has no preprocessor. { /* . func test (pa1. n µVision2 does not differentiate between uppercase and lowercase. #include. You may define symbols with the DEFINE command and use them like you would use a global variable. */ } { /* ANSI type. Preprocessor directives like #define.. Structures. Pointers and structures may not be returned. int pa2) /* . The old K&R format is not supported. variables may not be initialized when they are declared. µVision2 functions may only return scalar variable types.. For example. µVision2 functions cannot be called recursively. During function execution. µVision2 Debug Functions Differences Between Debug Functions and C There are a number of differences between ANSI C and the subset of features support in µVision2 debug user and signal functions. */ } /* Old K&R style is */ /* not supported */ . In µVision2. arrays.. and #ifdef are not supported. This applies to the function return type as well as the function parameters. Explicit assignment statements must be used to initialize variables. and pointers are not allowed. µVision2 functions may only be invoked directly using the function name. Scalar variables must be declared within a function definition. The names of objects and control statements may be written in either uppercase or lowercase. pa2) int pa1. func test (int pa1. µVision2 supports the new ANSI style of function declaration for functions with a parameter list.. µVision2 recognizes recursive calls and aborts function execution if one is detected. Indirect function calls via pointers are not supported. µVision2 does not support global declarations.110 Chapter 6. pa2. the following ANSI style function is acceptable. correct */ n n n n n 6 n n n The following K&R style function is not acceptable. µVision2 functions only support scalar variable types.
You may use the µVision2 editor to correct these. Demonstrates round-robin multitasking using RTX-166 Tiny. Demonstrates an RTX-166 Tiny application that uses signals. Additionally.module project with µVision2. You can use the sample programs to learn how to use our tools. Simple addition and subtraction calculator that shows how to build a multi. Each sample program is stored in a separate folder along with project files that help you quickly build and evaluate each sample program. MEASURE RTX_EX1 RTX_EX2 SIEVE TRAFFIC WHETS 7 To begin using one of the sample projects. Try this first when you begin using µVision2. you can copy the code from our samples for your own use. Shows how to control a traffic light using the RTX-166 Tiny real-time executive. The sample programs are found in the C:\KEIL\C166\EXAMPLES\ folder.Getting Started 111 Chapter 7. Refer to “ HELLO: Your First 166 C Program” on page 112 for more information about this sample program. Example BADCODE CSAMPLE DHRY HELLO Description Program with syntax errors and warnings. Data acquisition system that collects analog and digital signals. Benchmark program that calculates the whetstones factor for the target CPU. Hello World program. Dhrystone benchmark. Benchmark that calculates prime numbers. The following table lists the sample programs and their folder names. The following sections in this chapter describe how to use the tools to build the following sample programs: ¢ ¢ HELLO: Your First C51 Program MEASURE: A Remote Measurement System . use the µVision2 menu Project – Open Project and load the project file. Refer to “ MEASURE: A Remote Measurement System” on page 117 for more information about this sample program. It prints Hello World on the serial interface and helps you confirm that the development tools work correctly. Calculates the dhrystones factor for the target CPU. The sample programs are ready for you to run. Sample Programs This section describes the sample programs that are included in our tool kits.
Double click on HELLO. The hardware for HELLO is based on the standard C167 CPU. using batch files. You do not actually need a target CPU because µVision2 lets you simulate the hardware required for this program. select Open Project from the Project menu and open HELLO. and debug an application. A project file has been created for HELLO. or from µVision for Windows using the provided project file.UV2 from the folder … \C166\EXAMPLES\HELLO.C You can now edit HELLO. HELLO does nothing more than print the text “Hello World” to the serial port. HELLO Project File In µVision. This small application helps you confirm that you can compile. The entire program is contained in a single source file HELLO. Sample Programs HELLO: Your First 166 C Program The HELLO sample program is located in C:\KEIL\C166\EXAMPLES\HELLO\ .C. 7 Editing HELLO.C in the Files page of the Project Window. µVision2 loads and displays the contents of HELLO. link. You can perform these operations from the DOS command line. To load this project. The only on-chip peripheral used is the serial port. applications are maintained in a project file.112 Chapter 7. .C.C in an editor window.
. use the Build Target command from the Project menu or the Build toolbar.Getting Started 113 Compiling and Linking HELLO When you are ready to compile and link your project. The status of the build process is listed in the Build page of the Output Window. 7 NOTE You should encounter no errors when you use µVision2 with the provided sample projects. µVision2 begins to translate and link the source files and creates an absolute object module that you can load into the µVision2 debugger for testing.
114 Chapter 7. use the Start/Stop Debug Session command from the Debug menu or toolbar. . µVision2 initializes the debugger and starts program execution till the main function. Sample Programs Testing HELLO Once the HELLO program is compiled and linked. Stop Running HELLO with the Halt command from the Debug menu or the toolbar. The following screen displays.” it begins executing an endless loop. In µVision2. you can test it with the µVision2 debugger. You may also type ESC in the Command page of the Output window. The HELLO program executes and displays the text “Hello World” in the serial window. 7 Open Serial Window #1 that displays the serial output of the application with the Serial Window #1 command from the View menu or the Debug toolbar. Run HELLO with the Go command from the Debug menu or toolbar. After HELLO outputs “Hello World.
You may stop debugging at any time with Start/Stop Debug Session 7 .Getting Started 115 During debugging µVision2 will show the following output: Single-Stepping and Breakpoints Use the Insert/Remove Breakpoints command from the toolbar or the local editor menu that opens with a right mouse click and set a breakpoint at the beginning of the main function. You can single-step through the HELLO program using the Step buttons in the debug toolbar. Use the Reset CPU command from the Debug menu or toolbar. µVision2 will stop the program at the breakpoint. The current instruction is marked with a yellow arrow. The arrow moves each time you step Place the mouse cursor over a variable to view their value. If you have halted HELLO start program execution with Run.
7 . Sample Programs command.116 Chapter 7.
The sample interval can be configured from 1 millisecond to 60 minutes.UV2 in the folder C:\KEIL\C166\EXAMPLES\MEASURE.C. use Open Project from the Project menu and select MEASURE. The function of the source files is described below. The project contains several targets for different test environments. double-click on the filename. The three application related source files that are located in the Main Files group. To load this project file. Each measurement saves the current time and all of the input channels to a RAM buffer. A timer controls the sample rate. and MEASURE.C.Getting Started 117 MEASURE: A Remote Measurement System The MEASURE sample program is located in the \C166\EXAMPLES\MEASURE\ folder. For debugging with the simulator select the target Small Model in the Build toolbar.C. This implementation records data from one 16-bit digital port and four A/D inputs. MEASURE is composed of three source files: GETLINE. You do not actually need a target CPU because µVision2 lets you simulate all the hardware required for this program. Hardware Requirements The hardware for MEASURE is based on the C167 CPU. 7 . MEASURE Project File The project file for the MEASURE sample program is called MEASURE. The Files page in the Project Window shows the source files that compose the MEASURE project. This microcontroller provides analog and digital input capability. Port 2 is used for the digital inputs and AN0 through AN3 are used for the analog inputs. To open a source file. MCOMMAND.UV2. MEASURE runs a remote measurement system that collects analog and digital data like a data acquisition systems found in a weather stations and process control applications.
The timer interrupt routine. contains the command-line editor for characters received from the serial port.118 Chapter 7. .00V. you can use a terminal simulation to communicate with the C167 CPU. manages the real-time clock and the measurement sampling of the system. time. processes the display.C contains the main C function for the measurement system and the interrupt routine for timer 0. Once the project is build. The main function initializes all peripherals of the C167 and performs command processing for the system. If you have actual target hardware.C GETLINE. use the Source Browse command from the View menu or the toolbar. For more information refer to “Source Browser” on page 44. To view the information. timer0. These functions are called from main. you can use µVision2 to simulate the hardware. You can also use the serial window in µVision2 to provide serial input. MCOMMAND. Sample Programs MEASURE. Browse Symbols 7 The MEASURE project is configured to generate full browse and debug information. Testing MEASURE The MEASURE sample program is designed to accept commands from the onchip serial port. If you do not have target hardware.C Compiling and Linking MEASURE When you are ready to compile and link MEASURE. and interval commands. you are ready to browse the symbol information or begin testing the MEASURE program. The display command lists the analog values in floating-point format to give a voltage between 0. use the Build Target command from the Project menu or the toolbar.00V and 5. µVision2 begins to compile and link the source files in MEASURE and displays a message when the build is finished.
Getting Started
119
Once the MEASURE program is build, you can test it. Use the Start/Stop Debug Session command from the Debug menu to start the µVision2 debugger.
Remote Measurement System Commands
The serial commands that MEASURE supports are listed in the following table. These commands are composed of ASCII text characters. All commands must be terminated with a carriage return. You can enter these commands in the Serial Window #1 during debugging.
Command
Clear Display Time Interval
Serial Text
C D T hh:mm:ss I mm:ss.ttt
Description
Clears the measurement record buffer. Displays the current time and input values. Sets the current time in 24-hour format. Sets the interval time for the measurement samples. The interval time must be between 0:00.001 (for 1ms) and 60:00.000 (for 60 minutes). Starts the measurement recording. After receiving the start command, MEASURE samples all data inputs at the specified interval. Displays the recorded measurements. You may specify the number of most recent samples to display with the read command. If no count is specified, the read command transmits all recorded measurements. You can read measurements on the fly if the interval time is more than 1 second. Otherwise, the recording must be stopped. Quits the measurement recording.
Start
S
Read
R [count]
Quit
Q
7
120
Chapter 7. Sample Programs
View Program Code
µVision2 lets you view the program code in the Disassembly Window that opens with the View menu or the toolbar button. The Disassembly Window shows intermixed source and assembly lines. You may change the view mode or use other commands from the local menu that opens with the right mouse button.
View Memory Contents
µVision2 displays memory in various formats. The Memory Window opens via the View menu or the toolbar button. You can enter the address of four different memory areas in the pages. The local menu allows you to modify the memory contents or select different output formats.
7
Program Execution
Before you begin simulating MEASURE, open the Serial Window #1 that displays the serial output with the View menu or the Debug toolbar. You may disable other windows if your screen is not large enough.
Getting Started
121
You can use the Step toolbar buttons on assembler instructions or source code lines. If the Disassembly Window is active, you single step at assembly instruction basis. If an editor window with source code is active, you single step at source code level. The StepInto toolbar button lets you single-step through your application and into function calls. StepOver executes a function call as single entity and is not interrupt unless a breakpoint occurs. On occasion, you may accidentally step into a function unnecessarily. You can use StepOut to complete execution of that function and return to the statement immediately following the function call. A yellow arrow marks the current assembly or high-level statement. You may use the you may accidentally step into a function unnecessarily. You can use StepOut to complete execution of that function and return to the statement immediately following the function call. The toolbar or local menu command Run till Cursor Line lets you use the current cursor line as temporary breakpoint. With Insert/Remove Breakpoints command you can set or remove breakpoints on high-level source lines or assembler statements.
Call Stack
µVision2 internally tracks function nesting as the program executes. The Call Stack page of the Watch Window shows the current function nesting. A double click on a line displays the source code that called the selected function.
7
Click on the Define button to set the breakpoint. If Enable/Disable Trace Recording is set you can view the CPU instructions that were executed be reaching the breakpoint. current.sec.sec==3. Enter as expression Select the Write check box (this option specifies that the break condition is tested only when the expression is written to). 7 Open the Breakpoints dialog from the Debug menu. The example shows how to stop when the value 3 is written to current. You may want to halt program execution when a variable contains a certain value. Sample Programs Trace Recording It is common during debugging to reach a breakpoint where you require information like register values and other circumstances that led to the breakpoint.122 Chapter 7. The Regs page of the Project Window shows the CPU register contents for the selected instruction. .time.time. Breakpoints Dialog µVision2 also supports complex breakpoints as discussed on page 69.
Getting Started 123 To test the breakpoint condition perform the following steps: Reset CPU. Structures and arrays open on demand when you click on the [+] symbol. and arrays. You can enter WatchSet in the Output Window – Command page. ¢ ¢ 7 The Watch Window updates at the end of each execution command. structures. Watch Variables You may constantly view the contents of variables. In the same way you can modify variable values. The Locals page shows all local symbols of the current function. You enable may enable Periodic Window Update in the View menu to update the watch window during program execution. Open the Watch Window from the View menu or with the toolbar. If program execution is halted begin executing the MEASURE program. The program counter line in the debug window marks the line in which the breakpoint occurred. Select a variable name in an Editor Window and open the local menu with a right mouse click and use the command Add to Watch Window. click on the line and press the Delete key. The Watch #1 and Watch #2 pages allow you to enter any program variables as described in the following: ¢ Select the text <enter here> with a mouse click and wait a second. After a few seconds. Another mouse click enters edit mode that allows you to add variables. µVision2 halts execution. . Display lines are indented to reflect the nesting level. To remove a variable.
The dialogs show the current status of the peripherals and you may directly change the input values. Serial Ports. A/D Converter. Sample Programs View and Modify On-Chip Peripherals µVision2 provides several ways to view and modify the on-chip peripherals used in your target program. Open the Serial Window #1 and enter the ‘ command for the MEASURE d’ application. 7 . If program execution is halted begin executing the MEASURE program. You may directly view the results of the example below when you perform the following steps: Reset CPU and kill all defined breakpoints. MEASURE shows the values from I/O Port2 and A/D input 0 – 3.124 Chapter 7. Timers. and chip-specific peripherals. For the MEASURE application you may open I/O Ports:Port2 and A/D Converter. Interrupts. These dialogs can be opened from the Debug menu. The Serial Window shows the following output: You may now use the following procedures to supply input to the I/O pins: Using Peripheral Dialog Boxes µVision2 provides dialogs for: I/O Ports.
In the Command page of the Output Window. For example: PORT2=0xDA00 AIN1=3. set analog input AIN1 to 3. 7 Using the Performance Analyzer µVision2 lets you perform timing analysis of your applications using the integrated performance analyzer. To change the inputs. change the values of the Pins or Analog Input Channels.Getting Started 125 Each of these dialogs lists the related SFR symbols and shows the current status of the peripherals. Using User and Signal Functions You may combine the use of VTREG symbols defined by the CPU driver and µVision2 user and signal functions to create a sophisticated method of providing external input to your target programs. The signal function is included in the MEASURE example and may be quickly invoked with the Toolbox button Analog0. Using VTREG Symbols You may use the “CPU Pin Registers (VTREGs)” described on page 86 to change input signals. halt program execution and open the Setup Performance Analyzer dialog with the Debug menu. you may make assignments to the VTREG symbols just like variables and registers.. . The “Analog Example” on page 108 shows a signal function that provides input to AIN0.5V and changes constantly the voltage on the input AIN0.3 set digital input PORT2 to 0xDA00. To prepare for timing analysis.3 volts.
126 Chapter 7. If program execution is halted begin executing the MEASURE program. Refer to page 77 for more information. 7 . The bar graph shows the percent of the time spent executing code in each range. Perform the following steps to see the performance analyzer in action: Open the Performance Analyzer using the View menu or toolbar. Select the Serial Window #1 and type the commands S Enter D Enter The Performance Analyzer shows a bar graph for each range. Reset CPU and kill all breakpoints. Click on the range to see detailed timing statistics. Sample Programs You may specify the function names dialog box available from the Setup menu.
Topic “ Header Files” “ DPP Registers” “ Interrupt” “ Peripheral Event Controller” “ Parallel Port I/O” “ General Purpose Timers” “ Serial Interface” “ Watchdog Timer” “ Pulse Width Modulation” “ A/D Converter” “ Power Reduction Modes” 129 131 134 138 140 142 145 146 149 150 Page 128 NOTE The code examples presented here were tested with the C167CR microcontroller. The code examples in this chapter only present one or two methods of using each peripheral. Using on-chip Peripherals There are a number of techniques you must know to create programs that utilize the various on-chip peripherals and features of the 8xC166 and C167 family. 8 .Getting Started 127 Chapter 8. It is a simple procedure to convert them to work with your particular device. Be aware that there are more configuration options than are presented in this text. The on-chip peripherals of the C167 are quite sophisticated and offer numerous configuration options. You may use the code examples provided here to quickly get started working with the 166. Many of these are described in this chapter. Make sure that the on-chip peripherals you attempt to use actually exist in your device.
h> The REG167.H REG161.H REG164. sfr DP4 = 0xFFCA. The Keil development tools provide include files or header files that define these registers. It is easy to create your own custom header files for new chips or for you own projects. sfr DP6 = 0xFFCE. The CAN. /* I/O Ports */ sfr DP0L = 0xF100. sfr DP8 = 0xFFD6. Using on-chip Peripherals Header Files and Startup Code The on-chip peripherals of the 166/ST10 are accessed using the special function registers located in the system area of the on-chip memory.A66 START167. .H header file supports these peripherals. sfr DP1H = 0xF106. The following excerpt from that file shows the definitions for the parallel I/O ports.A66 START167. sfr DP1L = 0xF104. sfr DP7 = 0xFFD2. It defines the special function registers for the Siemens C167 device series. sfr DP3 = 0xFFC6.H REG163.H include file is located in the folder C:\KEIL\C166\INC. Many of the example programs presented in this chapter begin with: #include <reg167.H 8 8xC166 / ST10x166 C161 C163 / ST10x163 C164 C165 / ST10x165 C167 / ST10x167 Many devices include CAN peripherals.A66 START167.H REG165.A66 START167. sfr DP0H = 0xF102. The following table gives you an overview of the 166/ST10 derivatives currently available and the required startup and SFR definition files. Derivatives Instruction Set Standard 166 Enhanced 167 Enhanced 167 Enhanced 167 Enhanced 167 Enhanced 167 Startup File STARTUP. You must include the provided header files or you may create and include your own header files to access the on-chip peripherals. sfr DP2 = 0xFFC2.A66 Include File REG166.128 Chapter 8.A66 START167.H REG167.
NOTES The DPP3 register is also used when generating 166 code to speed-up memory and string copy and compare functions. The access the NDATA group (variables defined with near). The access the SDATA or SYSTEM group (variables defined with sdata. DPP registers are allocated according to the following table. The DPP registers contain the base address for four different data pages. 8 . NOTE Except for the TINY memory model. the C166 Compiler always uses the segmented mode of the 166/ST10. By default. and xhuge objects code for the 8xC166 is generated. For CPU with extended instruction set. if two far or huge objects are accessed. Except the 8xC166 CPU. huge and xhuge objects with EXTP and EXTS instructions instead of using the DPP0 register. This is faster than full 32-bit memory accesses.DPP3) to efficiently access memory with 16-bit near addresses. If you specify more than 16KB for RAM or ROM. the C166 compiler uses the four DPP registers (DPP0 . Typically. When C166 is invoked with the MOD167 directive the DPP registers are never altered by C code or the run-time library. DPP1 DPP2 DPP3 In µVision2. huge. With DPPUSE the NDATA and NCONST groups can be expanded to a total of 64 Kbytes. µVision2 inserts the C166 NOFIXDPP and the L166 DPPUSE directive.Near Memory the size for RAM (= NDATA group) and ROM (= NCONST group).Getting Started 129 DPP Registers In the segmented mode of the 166. This has the advantage that the CPU instructions require only 16-bit address fields for memory accessing. all 166/ST10 microcontrollers are using the extended instruction set which offer EXTS and EXTP instructions to overwrite the DPP addressing mode. DPP Register DPP0 By default. DPPUSE reassigns the DPP registers for NDATA and NCONST. you may specify under Options – Target . The access the NCONST group (variables defined with const near). the 166 microcontroller family uses 16KB pages to access data. the compiler accesses far. idata or bdata). used in C programs To access far.
[R2] . load R1 with memory location (DPP1*4000H) + 0010H The EXTS and EXTP instructions overwrite the DPP addressing mode. load R1 with memory location 0x108042 R3 contains 5: use page address in R3 for next two instructions load R4 with location (4*0x4000+0x180) = 0x14180 load R5 with location (4*0x4000+0x180+2) = 0x14182 . MOV R5. thus the CPU ignores the DPP contents and uses the base address given by the EXTP instruction instead. . the CPU uses linear 24-bit addresses.[R2+#2] . A far pointer contains a 14-bit offset and a 10-bit page address.0x8042 . Only during the debugging phase you need to know about DPP registers and EXTP / EXTS CPU instructions when you view pointer values or assembly code. In EXTS code sequences. For example. The top tow bits of a 16-bit near address indicate the DPP which holds the base address for the 14-bit offset. you need to calculate the physical memory address for near and far pointer values as shown in the above examples. Only during debugging.[R2] . The same address calculations are performed for indirect addressing modes: . Using on-chip Peripherals When using the C166 near addressing. The huge and xhuge pointer values are representing directly physical memory addresses. the instruction accesses the address: 8*0x4000 + 0x0042H = 0x20042. EXTP R3. MOV R4. the CPU gets a 14-bit offset and a 2-bit DPP selector. R2 contains the value 0x4010H which indicates DPP1: MOV R1. Therefore the different CPU address calculations are totally transparent to the C programmer.0x8042 . if DPP2 = 8.130 Chapter 8. the assembler instructions below will use the DPP2 to form the physical address. An EXTP instruction sequence specifies a 10-bit page address. However. R2 contains 0x180. the upper 8-bits are specified by the EXTS instruction. This is exemplified in the following code example: EXTS MOV 0x10. MOV R1. 8 The C166 compiler and the L166 Linker/Locater handles all the CPU addressing modes for you. load R1 with memory location (DPP2*0x4000) + 0x0042 If DPP2 contains 2.#2 . use segment address 0x10 for the next instruction .#1 R1. the base will be 2*0x4000 = 0x8000. You are faced with the 14-bit offset / 2-bit DPP selector format when near pointer values are displayed. the lower 16-bits are given by the executed instructions. since the top two bits of the instruction address 8042H are 10 indicating that DPP2 holds the base address for the 14-bit offset 0042H. Thus R1 will be loaded with the content of the memory address 0x8042.
and so on. you may define RBANK1 for interrupt priority level 1 (ILVL 1). The linker automatically reserves space for the register bank and the compiler automatically switches register bank contexts inside the interrupt routine. RBANK2 for ILVL 2. For example. /* re-start transmit */ } 8 The following listing shows the code generated by the C166 compiler for the above interrupt routine. is the interrupt vector definition. 1 2 3 4 5 6 7 void serial_TX_irq (void) interrupt S0TINT=42 using rbank1 1 1 1 1 1 1 { if (tx_in != tx_out) /* buffer not empty? */ S0TBUF = tx_buf [tx_out++]. void isr (void) interrupt S0TINT=42 using RBANK1 The rbank is a symbolic register bank name you define for a new register bank. Interrupt routines are declared as follows: void function (void) interrupt vector ¤ using rbank¥ function vector rbank is the name of the interrupt function. You may use the same register bank for interrupt routines which cannot interrupt each other. . is the register bank name.Getting Started 131 Interrupts The C166 compiler lets you write interrupt service routines in C. /* transmit next character */ else tx_restart = 1. Note that the register bank context is swapped on entry to the interrupt routine and is restored on exit. void isr (void) interrupt 42 using RBANK1 ¢ The vector is a symbolic name followed by the trap number it references. The compiler generates very efficient entry and exit code and accommodates register bank switching. Typical interrupt routines are define as follows: ¢ The vector is only a trap number without any symbolic name. The following example code shows the interrupt code for the serial transmit interrupt routine.
Interrupt Control Register Layout Reserved 15 14 13 12 11 10 9 8 xxIR 7 xxIE 6 5 4 ILVL 3 2 GLVL 1 0 . SOURCE LINE # 3 0010 F3F80002 R 0014 43F80202 R 0018 2D0B 001A 001E 0022 0024 0028 002A 002E 0030 RL4. When IEN is set to 0.ONES R4. interrupts are disabled. Interrupt Control Registers The C167 provides interrupt services for nearly every on-chip peripheral.tx_out RL4. Interrupts are globally enabled and disabled using the IEN bit of the PSW.#rbank1 . SOURCE LINE # 6 F3FA0002 R MOVB 258F0002 R SUBB C0A4 MOVBZ F4840000 R MOVB C084 MOVBZ F6F4B0FE MOV 0D01 JMPR ?C0001: R BSET ?C0002: POP POP RETI 0030 0F00 0032 0032 FC08 0034 FC03 0036 FB88 tx_restart . Using on-chip Peripherals . Therefore you should compare the assembler code generated by C166 for simple interrupt functions with and without using attribute.?C0001 . All interrupt control registers of the C167 have the same format as shown in the following figure. *** Restore Register Bank *** CP DPP3 NOTE If interrupt routines are small. 8 Interrupts are individually controlled through the interrupt control register for each interrupt source.tx_out tx_out.?C0002 . SOURCE LINE # 1 0000 0004 0006 000A 000E C6030300 CC00 F6F00000 R C60800C0 R CC00 SCXT NOP MOV SCXT NOP MOVB CMPB JMPR DPP3.R0 CP.[R4+#tx_buf] R4. SOURCE LINE # 4 RL5. interrupts are enabled. When IEN is set to 1.RL5 RL4.RL4 S0TBUF.tx_in cc_Z.#03H rbank1. SOURCE LINE # 7 . *** Switch to rbank1 *** .132 Chapter 8. it may be more efficient to exclude the using attribute and allow the compiler to push the registers used onto the stack.R4 cc_UC.
These fields are described in the following table. It may be a number from 0 to 15. It may be set by software to trigger an interrupt service routine. A value of 1 indicates that an interrupt is pending while a value of 0 indicates that no interrupt is pending. This bit is written by hardware when the interrupt occurs and is cleared automatically by the hardware when the interrupt service routine exits. Higher numbers represent higher priority levels. If set to 1. Note that an ILVL of 0 never gets serviced! However. the interrupt is disabled. /* Interrupt Enabled. #define IC_IE(x) #define IC_ILVL(x) #define IC_GLVL(x) (((x) == 0) ? 0x0000 : 0x0040) (((x) << 2) & 0x003C)) ((x) & 0x0003) T3IC = IC_IE(1) | IC_ILVL(1) | IC_GLVL(0). xxIE ILVL GLVL NOTE The ILVL and GLVL fields may not be the same for more than one interrupt source. The interrupt priority level defines the priority level of the interrupt request. Higher numbers represent higher priority levels. Level 1 */ 8 . The following code exemplifies the setup of the interrupt control registers. See “ Idle Mode” on page 150 for more information. you may define C macros to initialize the fields for the interrupt. priority level 0 may be used to awaken the CPU from IDLE mode. The interrupt enable bit enables or disables an individual interrupt source. The group level defines the order in which simultaneous interrupts with the same priority level are services. Since all interrupt control registers share the same format.Getting Started 133 Bits 15-8 are unused while bits 7-0 contain four fields that control different aspects of the interrupt. Each enabled interrupt source must have its own unique combination of ILVL and GLVL. The group level may be from 0 to 3. Field xxIR Description The interrupt request flag indicates whether or not an interrupt request is pending. the interrupt is enabled. If set to 0.
PEC transfers may occur only in page 0— the first 64K address space (0x000000-0x00FFFF). Initialize the Interrupt Control Register for the interrupt source. the PEC works just like direct memory access (DMA) controllers. Basically. PEC Control Register The PEC control register provides three fields that let you select whether bytes or words are moved (BWT field). Initialize the Destination Pointer. 8 3. For example. you can program the PEC to… ¢ ¢ ¢ Read data from the A/D converter and store it in a buffer. Using on-chip Peripherals Peripheral Event Controller The 166 devices provide an 8-channel peripheral event controller or PEC that you can program to automatically move data (8-bit bytes or 16-bit words) when an interrupt occurs. The number of uses for the PEC is virtually unlimited. destination pointer. The benefit of using the PEC is that the memory transfers are fast (only 1 CPU cycle) and the setup required is trivial. 4. 1. a source pointer register (SRCP0-SRCP7). Transfer data from a static buffer out to the serial port. or neither pointer are incremented after the move (INC field). and a destination pointer register (DSTP0-DSTP7). Each of these steps is described in detail in the following sections. Periodically read A/D input values and output them to the serial port. Initialize the PEC Control Register. whether the source pointer. Initialize the Source Pointer. The PEC can read from and write to the special function registers of the CPU as well as to internal RAM. and the number of . 2. There are 4 steps you must follow to properly initialize and use the PEC. Each PEC channel includes a PEC control register (PECC0-PECC7). But. it is easier to program and it works much faster.134 Chapter 8.
/* Destination is the serial output */ Assigns the value 0xFEB0 to the destination pointer for PEC channel 0. the following line of code: DSTP0 = (unsigned int) &S0TBUF. These fields are described in the following table. NOTE Use the _sof_ intrinsic library routine to obtain the page 0 offset of variables used with the PEC source and destination pointers. that number of moves are made.Getting Started 135 times to move the data (COUNT field). BWT COUNT Source and Destination Pointers The source and destination pointers are initialized directly in the C source code. The address is a 16-bit address that corresponds to the lower 64K of the C167. This address is the address of the S0TBUF register (which is the serial 0 transmit buffer). When COUNT is a non-zero value. PEC Control Register Layout Reserved 15 14 13 12 11 10 INC 9 BWT 8 7 6 5 COUNT 4 3 2 1 0 Bits 15-11 of each PEC control register are unused. Bits 10-0 contain three fields that control several aspects of the interrupt and PEC channel. 0 1: Destination pointer (DSTPx) is incremented by 1 (BWT=1) or by 2 (BWT=0). Selects the number of transfers. Incrementing both pointers is not supported. . the interrupt service routine is invoked instead of a PEC transfer. continuous moves are made. Selects whether bytes (when 1) or words (when 0) are transferred. When COUNT is 0. Valid values are: 0 0: Neither pointer is modified. When COUNT is 0xFF. The following line of code: SRCP0 = _sof_ (string1). Either the source pointer or the destination pointer may be incremented. For example. The layout of the control register is shown in the following figure. 1 0: Source pointer (SRCPx) is incremented by 1 (BWT=1) or by 2 (BWT=0). /* Source is STRING1 */ 8 Assigns the address of string1 to the source pointer for PEC channel 0. Field INC Description The INC field selects the pointer that is incremented after the PEC transfer.
The interrupt control registers of the C167 use the format shown in the following figure when the PEC is enabled. At most. you may define C macros to setup the fields. Bits 7-0 contain three fields that control several aspects of the interrupt and PEC channel. PEC Channel 0 */ S0TIC = IC_IE(1) | IC_PEC(0). The interrupt enable bit enables or disables an individual interrupt source. The following code exemplifies the setup of the interrupt control register for PEC channel transfers. 8 interrupts can use the PEC (since there are only 8 PEC channels). #define IC_IE(x) #define IC_PEC(x) (((x) == 0) ? 0x0000 : 0x0040) (((x) & 0x0007) | 0x0038) /* Interrupt Enabled. Interrupt Control Register Layout for PEC Reserved 15 14 13 12 11 10 9 8 xxIR 7 xxIE 6 1 5 1 4 1 3 PEC Channel 2 1 0 Bits 15-8 of each interrupt control register are unused. the interrupt is disabled. xxIE PEC Channel Since all interrupt control registers share the same format for the PEC. A value of 1 indicates that an interrupt is pending while a value of 0 indicates that no interrupt is pending. If set to 0. 8 . The PEC channel defines which PEC channel is used for the interrupt source.136 Chapter 8. These fields are described in the following table. Using on-chip Peripherals Channel Selection A PEC channel is selected for a particular interrupt source through the interrupt control register. It may be set by software to trigger an interrupt service routine. This bit is written by hardware when the interrupt occurs and is cleared automatically by the hardware when the interrupt service routine exits. Field xxIR Description The interrupt request flag indicates whether or not an interrupt request is pending. the interrupt is enabled. If set to 1.
SRCP0 = _sof_ (string1). S0TIC = 0x00F8. /* Serial TX IRQ = Level 14. /* This function initializes PEC Channel 0 to move the data from */ /* STRING1 to the serial transmit buffer. */ void serial_TX_irq (void) interrupt S0TINT = 42 serial_PEC0_setup (). while (1) } } { .1). DSTP0 = (unsigned int) &S0TBUF. Priority 0 (PEC 0) */ serial_PEC0_setup ().Getting Started 137 PEC Example Program The following example program shows how to program PEC channel 0 for data transfers to the serial port transmit buffer. /* Set TXD for output */ DP3 &= ~0x0800. This interrupt function resets the PEC 0 transfer and the string is sent again.h> #pragma PECDEF (0) /* Reserve space for PEC channel 0 pointers */ const char string1 [] = "0123456789\n". #include <reg167. /* Set TXD high */ S0CON = 0x8011. IEN = 1. Inc Src Ptr */ | ((sizeof (string1) / sizeof (string1 [0])) . /* Enable interrupts */ } 8 void main (void) { serial_setup (19200).h> #include <intrins. /* Set RXD for input */ P3 |= 0x0400. } /* Source is STRING1 */ /* Destination is the serial output */ /* The Serial TX interrupt just resets PEC 0 and transfers another */ /* copy of STRING 1. */ void serial_PEC0_setup (void) { PECC0 = 0x0500 /* Move Bytes. It transmits the string “0123456789\n” out the serial port and then generates a transmit interrupt (serial_TX_IRQ). DP3 |= 0x0400. } { /* The setup routine for the serial port also initialized the PEC 0 */ /* transfer and sets a TX interrupt request */ void serial_setup (unsigned int baud) { /* Calculate reload value for baudrate generator */ S0BG = (20000000UL / (32UL * (unsigned long) baud)) -1.
Mux’ 16-bit bus: d.7: P5. Port P0L Direction I/O Width Alternate Use 8 bits Mux’ 16-bit bus: d.5: P4.138 Chapter 8. Mux’ 8-bit bus: d.4-P1H. Non-Mux’ 8-bit bus: d.15: P3. Non-Mux’ 16-bit bus: d. Mux’ 16-bit bus: d. Non-Mux’ 16-bit bus: d.12: P3.4: P3. Mux’ 8-bit bus: d.3: P3.6: P4.15: A0-A7 & D0-D7 A0-A7 & D0-D7 D0-D7 D0-D7 A8-A15 & D8-D15 A8-A15 D8-D15 Available for user I/O Available for user I/O Available for user I/O A0-A7 A0-A7 Available for user I/O Available for user I/O A8-A15 A8-A15 Compare/Capture I/O Compare/Capture I/O Timer 6 Output CAPIN Timer 3 Output Timer 3 Ext. However. Up/Down Timer 6 Input Timer 5 Input Timer 4 Ext. Many may be used for general purpose I/O.15: P4.0-P2.10: P5.14: P3.1: P3.13: P3. Mux’ 8-bit bus: d.2: P3. some ports have alternate uses that may prevent their generic use by your application. Non-Mux’ 16-bit bus: d.5: P3.11: P3.15: P5. Non-Mux’ 16-bit bus: d.6: P3. 0 Receive /BHE or /WRH SSC Master Clock Output Not Implemented System Clock Output A16-A23 CAN2_RxD CAN1_RxD CAN1_TxD CAN2_TxD A/D Analog Inputs Timer 6 Ext. Up/Down P0H I/O 8 bits P1L I/O 8 bits P1H I/O 8 bits P2 P3 I/O I/O 16 bits 15 bits 8 P4 I/O 8 bits P5 I 16 bits . Up/Down Timer 4 Input Timer 3 Input Timer 2 Input Serial Chan. Non-Mux’ 8-bit bus: d.4: P4. Mux’ 16-bit bus: d. Up/Down Timer 5 Ext.14: P5. Mux’ 8-bit bus: d. P1H. Non-Mux’ 8-bit bus: d. 0 Transmit Serial Chan.13: P5. Using on-chip Peripherals Parallel Port I/O The C167 provides a number of parallel I/O ports you may use for your target application.7: P3. Up/Down Timer 2 Ext.11: P5. Non-Mux’ 8-bit bus: d.12: P5.10: P3.7: P4.0-P5.0-P4.7: P2.
7: CS0-CS4 Output External Master Hold Req. Port 6. /* Write new value to P7 */ } } } .7: P7.3: P7.7-P7.0-P7. i <<= 1) { P7 = i. Port 3. Direction Port Register Control Register P0L P0H P1L P1H P2 P3 P4 P6 P7 P8 DP0L DP0H DP1L DP1H DP2 DP3 DP4 DP6 DP7 DP8 ODP6 ODP7 ODP8 ODP2 ODP3 Write a 1 to a push-pull/ open-drain control register bit to configure the corresponding port bit or pin as an open-drain output.7-P7.5: P6. The following example program shows how to output values to Port 7 in open-drain configuration.Getting Started 139 Port P6 Direction I/O Width Alternate Use 8 bits P6. Port 7.4: P6.7: P8.0 for open-drain */ 8 while (1) { for (i = 0x01. DP7 = 0xFF. #include <reg167.6: P6. Push-Pull/Open-Drain Control Register Write a 1 to a direction control register bit to configure the corresponding port bit or pin as an output. /* Setup P7. The pins of Port 2. i <= 0x80. and Port 8 may be programmed for push-pull operation or open-drain operation via control registers. Intput Hold Acknowledge Output Bus Request Output PWM Outputs 0-3 Compare/Capture I/O Compare/Capture I/O P7 P8 I/O I/O 8 bits 8 bits Most ports have data direction registers you must properly initialize to specify whether each port pin is an input or an output.h> void main (void) { unsigned int i.0-P6.4-P7.0 for output */ /* Setup P7. The following table specifies the names for these registers. Write a 0 to configure the port bit or pin as a push-pull output. ODP7 = 0xFF.0-P8. Write a 0 to configure the port bit or pin as an input.
The timer3_setup function initializes the timer and the timer3_delay function delays for the specified number of timer ticks. GPT2 timer 5 interrupt control register. GPT1 timer 2 register. GPT1 timer 3 register. GPT1 timer 4 control register. GPT2 timer 5 register. GPT2 timer 5 control register. gated timer mode. GPT2 timer 6 register. GPT1 timer 3 interrupt control register. T3. GPT1 timer 3 control register. GPT1 timer 4 register. The timer tick interrupt increments the timer_tick variable once for each interrupt. . GPT2 timer 6 control register. This example program toggles a bit on Port 7 every 0. GPT2 CAPREL interrupt control register. GPT1 timer 4 interrupt control register. Using on-chip Peripherals General Purpose Timers The C167 has two groups (GPT1 and GPT2) of general purpose timers/counters.100 seconds. Each timer in each group may operate independently in a number of different modes including timer mode. Register CAPREL CRIC T2 T3 T4 T5 T6 T2IC T3IC T4IC T5IC T6IC T2CON T3CON T4CON T5CON T6CON Description GPT2 capture/reload register. and capture mode. GPT1 timer 2 control register.. GPT2 timer 6 interrupt control register. counter mode. GPT1 contains 3 timers/counters (T2. reload mode. and T4) and GPT2 contains 2 timers/counters (T5 and T6).140 Chapter 8. The following table lists the special function registers used to program the general purpose timers. GPT1 timer 2 interrupt control register. 8 The following example program shows how to use Timer 3 to generate a 1000Hz timer tick interrupt for timing purposes.
} { 141 void timer3_setup (unsigned int ticks_per_sec) unsigned int reload. T2 = reload. while (1) { timer3_delay (100).0 */ . P7 |= 0x01. ODP7 = 0x01.start_tick) > ticks) break. P7 &= ~0x01. Level 1 */ Start Timer */ Enable Interrupts / void timer3_delay (unsigned long ticks) unsigned long start_tick.Getting Started #include <reg167. timer3_delay (100).5MHz. frequency /= 2. T3R = 1.h> #include <intrins. { /* start un-interruptable code */ /* end un-interruptable code */ while (1) { _atomic_ (0). Timer Mode. _endatomic_ ().10 seconds */ off P7.0 for open-drain */ /* Setup timer for 1000Hz operation */ /* /* /* /* Wait Turn Wait Turn 0. prescale++) { if ((frequency / ticks_per_sec) <= 65535) break. _endatomic_ ().h> static unsigned long volatile timer_tick = 0UL. T2CON = 0x0027.0 */ 0. } /* 2. } } 8 void main (void) { DP7 = 0x01. unsigned int prescale. static void timer3_irq (void) interrupt T3INT = 35 timer_tick++. } } /* Setup P7.0 for output */ /* Setup P7.10 seconds */ on P7. start_tick = timer_tick_copy. { for (prescale = 0. Count Down */ /* /* /* /* /* /* Setup T2 for reload operation on any T3OTL */ Reload for T3 */ Start T3 with proper reload */ Timer 3 interrupt enabled. T3CON = 0x0080. T3 = reload. T3CON |= prescale. } reload = frequency / ticks_per_sec. T3IC = 0x0044. prescale < 8. unsigned long frequency = 2500000. timer3_setup (1000). unsigned long timer_tick_copy. _atomic_ (0). /* end un-interruptable code */ if ((timer_tick_copy . IEN = 1. /* start un-interruptable code */ timer_tick_copy = timer_tick.
Serial port 0 receive interrupt control register. This also lets the printf and scanf library functions work with the interrupt-driven I/O routines in this example. the library routines for putchar and _getkey have been replaced with ones that use the interrupt-driven serial I/O routines. Serial port 0 error interrupt control register. You may also create interrupt routines to handle these operations. Interrupt routines in this example s handle transmit interrupts (serial_TX_irq) and receive interrupts (serial_RX_irq) using 256-byte circular buffers.142 Chapter 8.11 for transmit and receive respectively. 8 The following example program shows how to perform interrupt-driven serial I/O using the C167’ asynchronous serial channel. Serial port 0 control register. there is a baudrate reload register and a control register that you must properly configure before serial port 0 will function. Serial port 0 receive buffer. Using on-chip Peripherals Serial Interface The C167 includes a standard RS-232 compatible serial port (ASC0) you may use with your application programs. and error conditions. You must properly configure these port pins for input and output to use the serial port. Register S0BG S0CON S0EIC S0RBUF S0TBIC S0TBUF SORIC SOTIC Description Serial port 0 baud rate generator reload register. Additionally. Serial port 0 transmit interrupt control register. You may poll the interrupt control registers to determine when a character has been receive or when the next character may be sent. receive. . Additionally. The C167 uses port pins P3. Serial port 0 transmit buffer interrupt control register. Routines are provided to transmit (serial_TX) and receive (serial_RX) characters and to initialize the serial channel (serial_setup). There are separate transmit and receive buffers you write outgoing data to and read incoming data from.10 and P3. The following table lists the special function registers used to program serial port 0. The C167 provides full interrupt control for the serial port transmit. Serial port 0 transmit buffer.
/* Disable serial transmit interrupt lvl 2*/ tx_restart = 1.1. /* Note: variables that are modified in interrupts are volatile! */ static unsigned char volatile rx_in = 0. return (rx_buf [rx_out++]). . /* clear re-start flag */ S0TIR = 1. static bit volatile tx_restart = 0. { } char _getkeyserial_RX (void) { while (rx_in == rx_out). /* RX buffer next in index */ static unsigned char rx_out = 0.h> static unsigned char volatile rx_buf [sizeof (unsigned char) * 256]. else tx_restart = 1. static unsigned char tx_buf [sizeof (unsigned char) * 256]. static unsigned char volatile tx_out = 0. */ tx_restart = 0..h> #include <intrins. void serial_TX_irq (void) interrupt if (tx_in != tx_out) S0TBUF = tx_buf [tx_out++]. /* RX buffer next out index */ static unsigned char tx_in = 0. } /* substitute function for _getkey */ void serial_setup (unsigned int baud) { /* Calculate reload value for baudrate generator */ S0BG = (20000000UL / (32UL * (unsigned long) baud)) . /* end un-interruptable code */ if (tx_restart) { /* if transmits must be restarted. /* enable interrupt */ return (c). /* Set restart flag */ } 8 void main (void) { serial_setup (19200). /* Set TXD for output */ DP3 &= ~0x0800. /* put the character in the buffer */ _endatomic_ (). /* enable transmit request */ } S0TIE = 1. /* buffer full? */ _atomic_ (0). S0RIC = 0x0044. /* start un-interruptable code */ tx_buf [tx_in++] = c. /* Set TXD high */ S0CON = 0x8011. /* Set RXD for input */ P3 |= 0x0400..Getting Started #include <reg167. /* put received character in buffer */ } char putchar (char c) /* substitute function for putchar */ /* wait while buffer is full */ while (((unsigned char)(tx_in + 1)) == tx_out). DP3 |= 0x0400. /* Enable serial receive interrupt lvl 1 */ S0TIC = 0x0008. } /* TX buffer next in index */ /* TX buffer next out index */ /* NZ for transmit restart */ 143 S0TINT = 42 { /* buffer not empty? */ /* transmit the next character */ /* transmit must be re-started */ void serial_RX_irq (void) interrupt S0RINT = 43 { rx_buf [rx_in++] = S0RBUF.
144 IEN = 1. while (1) char c. printf ("\nYou typed the character %c. Chapter 8.\n". { c = getchar (). Using on-chip Peripherals /* Enable interrupts */ printf ("Serial I/O Initialized\n"). c). } } 8 .
h> #include <intrins.. WATCHDOG: Disable Hardware Watchdog . --. the C startup code disables the watchdog for you.Getting Started 145 Watchdog Timer The C167 includes a 16-bit watchdog timer for recovery from hardware or software failures. Your application must periodically reset the watchdog timer using the _srvwdt_ intrinsic C library function. the watchdog timer overflows and resets the CPU. The watchdog timer configuration register WDTCON lets you specify the reload value for upper byte of the timer as well as the clock divisor (2 or 128).h> void main (void) { WDTCON = 0x8001. The following example code shows how to initialize the watchdog timer and how to reset it.1------------Divide by 2 */ while (1) { /* Applicaiton Code */ _srvwdt_ (). it resets the CPU and starts executing your program from the beginning exactly as if a hardware reset occurred. /* Setup the watchdog timer */ /* 80.. However.------------Set the reload value to 0x80 */ /* . If the watchdog timer overflows. } } /* Reset the watchdog timer */ NOTE The watchdog timer is enabled after a software reset.Set WATCHDOG = 1 to enable the Hardware watchdog $SET (WATCHDOG = 1) . if your application uses the watchdog timer. Look for the following section in the startup code and set the WATCHDOG variable to 1. or watchdog reset. . #include <reg167. By default. 8 . The watchdog timer counts up until it overflows or until it is reset by the SRVWDT instruction. make sure the startup code (found in START167. hardware reset.. If your program does not reset the watchdog timer frequently enough or if your program crashes.A66) properly enables it. Your application must disable the watchdog timer if it is not used.
setting P7. After reset.000 is 1. The C167 provides 4 independent PWM channels. . You may set a port latch to invert the PWM signal on that port pin. Each channel has a 16-bit up/down counter. the following pulse widths generate the specified duty cycles.000 MHz and the PWM counter is driven with no divisor and the period register (PPx) contains 19999. 8 The pulse width register (PWx) contains the count at which the PWM signal is “on”. a 16-bit period register. the counter counts from 0 to 19999 (20. Dimmer switches use this technology to control the amount of the AC sine wave that reaches the light bulb.146 Chapter 8. the Port 7 latches are cleared to 0 and the PWM signals go directly to the port pins. If the clock frequency is 20. Register PPx PWx PTx PWMCON0 PWMCON1 PWMIC Description PWM period register for channel x. 20. the output is “on” or 1. PWM control register 0. When the PWM counter contains a value that is greater than the pulse width register.000 (1. PWM pulse width register for channel x.000. PWM control register 1. When the PWM counter contains a value that is less than the pulse width register. There are 2 common control registers and a common interrupt control register. PWM interrupt control register. and a 16-bit pulse width register. PWM counter register for channel x.000 kHz).000 counts). Using on-chip Peripherals Pulse Width Modulation Pulse width modulation (PWM) is a method of varying the width of a pulse to control the duty cycle of a signal.000 divided by 20. the output is “off” or 0. the PWM counter (PTx) counts up from 0 until it reaches the defined period and then resets to 0. In the standard PWM generation mode. The clock for each of the PWM counters is the CPU clock with no divisor or with a divisor of 64.0 inverts the PWM channel 0 output signal. The PWM output signals are XORed with the outputs of their respective Port 7 latches. If the period is setup for 19999 (20000 counts). For example. The PWM signals are output on Port 7 pins 0 to 3.
channel = 0 */ /* Set PWM period */ /* Set 0% duty cycle */ /* Channel 0 & 1 are independent */ /* Set PWM period */ /* Set 0% duty cycle */ /* Channel 0 & 1 are independent */ /* Set PWM period */ /* Set 0% duty cycle */ /* Stardard mode (non-single shot) */ /* Set PWM period */ /* Set 0% duty cycle */ /* Stardard mode (non-single shot) */ 8 PWMCON1 |= (0x0001 << channel).channel for open-drain */ /* P1.0% 87. The following example code shows functions to initialize the PWM (PWM_setup) and how to set the pulse width (PWM_pulse_width). PB01 = 0. break.0% 50. PW3 = period + 1. break. PW1 = period + 1. &= ~(0x0100 << channel). PS2 = 0. break. case 3: PP3 = period.5% 0. break.0% 25.channel for output */ /* Setup P7.h> void PWM_setup (unsigned char channel.0% † For a period of 20.000 counts. &= ~(0x0010 << channel). ODP7 |= (1 << channel). case 2: PP2 = period. /* /* /* /* Start the PTx counter */ PTx clocked with CLKCPU */ Disable interrupts */ Clear interrupt request */ period) { /* Setup P7.Getting Started 147 Pulse Width 0 2500 5000 10000 15000 17500 20000 Duty Cycle† 100. #include <reg167. &= ~(0x1000 << channel). P7 &= ~(1 << channel). PW0 = period + 1. PW2 = period + 1. } PWMCON0 PWMCON0 PWMCON0 PWMCON0 |= (0x0001 << channel).5% 75. /* Enable channel output */ PWMCON1 &= ~(0x0010 << channel). case 1: PP1 = period.0% 12. unsigned int if (channel > 3) return. PS3 = 0. PB01 = 0. DP7 |= (1 << channel). /* Setup edge aligned mode */ } . switch (channel) { case 0: PP0 = period.
case 2: PW2 = width. Using on-chip Peripherals void PWM_pulse_width (unsigned char channel. case 1: PW1 = width.148 Chapter 8.1). /* 100% duty cycle (ON from 0 to 19999) */ /* 0% duty cycle */ /* 50% duty cycle */ /* 25% duty cycle */ 8 . 0). (0. 20000 . while (1) { PWM_pulse_width PWM_pulse_width PWM_pulse_width PWM_pulse_width } } /* 20MHz/20000 = 1kHz (1ms pulse width) */ (0. break. 15000). } } unsigned int width) { void main (void) { PWM_setup (0. break. (0. case 3: PW3 = width. switch (channel) { case 0: PW0 = width. break. 10000). 20000). (0. break.
{ 8 /* Loop thru ADC channels */ /* Print channel */ /* Print ADC input */ while (1) { for (i = 0.. the C167 A/D converter can generate interrupts for end-of-conversion and overwrite conditions and can even be used to trigger a PEC data transfer. (unsigned) i. A/D converter interrupt control register (for overrun errors and channel injection). i++) { printf ("ADC Channel %u = %u\n".----------------. } /* Select channel to convert */ /* Begin conversion */ /* Wait while the ADC is converting */ /* Return the result */ void read_adc_channels (void) unsigned char i.. #include <reg167. i < 16.Conversion Clock = TCC = 96 * TCL */ /* B. Register ADCON ADDAT ADDAT2 ADCIC ADEIC Description A/D converter control register. } } } . return (ADDAT & 0x03FF).. ADST = 1. In addition. A/D converter result register. The on-chip A/D converter may be configured for a number of conversion modes including single or continuous conversions on one or more analog input channels. The following example code shows how to initialize the A/D converter for single channel single conversion mode and read the data for that channel.----------------. Analog inputs may range from the voltages present on the VAREF and VAGND pins. (unsigned) ADC_read (i)). A/D converter interrupt control register (for end-of-conversion)..Getting Started 149 A/D Converter The C167 A/D converter provides 16 channels of 10-bit analog to digital conversion.h> unsigned int ADC_read (unsigned char channel) { ADCON = 0xB000. while (ADBSY == 1). /* B.Sample Clock = 8 * TCC */ ADCON |= channel & 0x000F. Voltages presented to the input pins on Port 5 are converted to digital values and may be read from the A/D result register. A/D converter channel injection result register.
h> void main (void) while (1) { task_a (). the CPU begins executing the code following the IDLE instruction. task_b (): task_c (): _idle_ (). terminates Idle Mode.150 Chapter 8. After the RETI instruction of the interrupt that terminates Idle Mode. This applies only to those interrupts whose individual interrupt enable flags were set before Idle Mode was entered. regardless of IEN. To enter Idle Mode. 8 Power Down Mode Power Down Mode halts both the CPU and peripherals. All peripherals including the watchdog timer continue to operate normally. Using on-chip Peripherals Power Reduction Modes The C167 offers two different power saving modes you may invoke using a single instruction: Idle Mode and Power Down Mode.h> void main (void) task_a (). your program must execute the IDLE instruction. #include <intrins. It is canceled only by a hardware reset. your program must pull the NMI pin low using external hardware and execute the PWRDN instruction using the _pwrdn_ intrinsic library function. } } { /* Enter IDLE Mode */ Any interrupt condition. When any reset or interrupt condition occurs. To enter Power Down Mode. Power consumption can be greatly decreased in idle mode. Idle Mode Idle Mode halts the CPU but lets peripherals continue operating. task_b (): { . Idle Mode is canceled. You may do this directly in C using the _idle_ intrinsic library function. #include <intrins.
the PWRDN instruction is ignored and the 166 does not go into Power Down Mode. 8 .Wait for reset */ 151 If the NMI pin is not held low. } /* Enter POWER DOWN Mode . only a hardware reset will restart the CPU and peripherals.Getting Started task_c (): _pwrdn_ (). Once Power Down Mode is entered.
.
A66 SET (SMALL) Configuring the Startup Code The STARTUP. MEDIUM.DPP3 and CP for memory and registerbank accesses. The START167.A66 file contains the startup code for all other 166 derivatives. . 11 Selecting the Memory Model When you assemble the startup code outside of µVision2. Initialize the ADDRSELx and BUSCONx SFRs. Reserve and initialize the hardware stack and stack overflow and underflow SFRs. Reserve and initialize the user stack area and user stack pointer (R0). These source files are located in the \C166\LIB directory. 2.A66 and START167. Clear data memory. 8. Transfer control to the main C function. or HLARGE. Initialize the SYSCON and BUSCON SFRs. The startup code executes immediately upon reset of the target system. 3.A66 files contain definitions at the beginning which are used for the chip hardware configuration and for the C run-time system. 7. 5.Getting Started 153 Chapter 10. 4. you must tell the assembler which memory model you use. if you use the SMALL memory model. An overview of the groups of configuration statements is provided below. The STARTUP. CPU and C Startup Code Your target program must initialize the CPU to match the configuration of your hardware design. You do this with the SET command and the memory model: TINY. SMALL. Set DPP0 . LARGE. use the following command line to assemble the startup code: A166 START167. It optionally performs the following operations: 1. Initialize variables that are explicitly initialized in the C source code. COMPACT. For example. 6. HCOMPACT.A66 file contains the startup code for an 8xC166 target program. You should copy either of these files to your project directory and make changes to match your hardware configuration.
DPPUSE INIT_VARS SSTSZ STK_SIZE 8 USTSZ WATCHDOG NOTE Siemens offers a configuration and programming utility called DAVE. STK_SIZE: Maximum System Stack Size selection initialization value. CPU clock control registers. This configures the chip parameters like basic bus characteristics. Allow re-assignment of DPP registers. Default: 1 to support the L166 DPPUSE directive. chip select configuration. This free utility helps you configure the CPU and create C source code to use the on-chip peripherals of the various 166 derivatives. This is also the reset value. To disable the memory zero initialization enter “ $SET (CLR_MEMORY = 1)” this reduces the code size of the startup code. and on-chip peripheral enable registers (available only on some devices). Default: initialize variables. To disable the variable initialization enter “ $SET (INIT_VARS = 0)” this reduces the code size of the . SYSCON2 SYSCON3 BUSCONn ADDRESSn RANGEn C Compiler Run-Time Configuration Name CLR_MEMORY Description Memory Zero Initialization of RAM areas. . . startup code. SRAM. CPU and C Startup Code Hardware Configuration Name SYSCON Description CPU system control register. reduces the code size of the startup code. Set STK_SIZE to the following values for other stack sizes: 0 for 256 words system stack. These registers define the starting address. 2 for 64 words system stack. The user stack is used for automatic variables. Default: disable the hardware watchdog. range.154 Chapter 10. 4 for 512 words system stack (not for 166) 7 for user defined size of the system stack Set the actual stack space for the user stack. Hardware Watchdog control. Default value is 0 for 256 words stack size. Variable Initialization of explicit initialized variables (The variables are to be defined static or declared at file level). and bus characteristics for different memory devices (like FLASH. and I/O) accessed via the chip select outputs. Power-down control registers. The USTSZ variable allows you to set the size for the user stack. if you have selected 7 for the STK_SIZE. power-down modes. Set the actual stack space for the system stack. EPROM. system clock parameters. Default: enable the memory zero initialization of RAM area. 3 for 32 words system stack. To disable the DPP re-assignment enter “ $SET (DPPUSE = 0)” this . and so on. 1 for 128 words system stack. Initialization registers for BUSCON0-BUSCON4. To enable the watchdog enter “ $SET (WATCHDOG = 1)” .
This mode does not use any of the on-chip peripherals. This is typical the best mode to start working with the Monitor. to stop program execution with the uVision2 HALT toolbar command. the Monitor inserts TRAP instructions at all breakpoint locations. The Monitor communicates with the 166/ST10 build-in UART ASC0. The Monitor requires that the program you are debugging is located in RAM space. The serial interface requires and additional interrupt. since the serial interrupt is not available. the Monitor program will be downloaded into RAM of the target system. You may break program execution with a switch connect to the NMI pin of the CPU. Simulated Serial Mode This configuration uses a simulated serial interface and does not require the 166/ST10 on-chip UART. The Keil Monitor-166 may be configured in three different operating modes: 11 Bootstrap Mode In bootstrap mode. Using Monitor-166 The Keil Monitor-166 allows you to connect your 166/ST10 hardware to the uVision2 Debugger. You may use two unused I/O pins of the 166/ST10 to establish the communication between uVision2 and your target hardware. but has the restrictions that you cannot use the uVision2 HALT toolbar command. You can use the powerful debugging interface to test application programs in your target hardware. This operation is completely transparent. To set breakpoints in your code. . since it auto-adjust baudrates and does not require to burn any EPROM's. UART Mode In this configuration the Monitor program will be direct programmed to (Flash) EPROM's.Getting Started 155 Chapter 11. but may have side effects when calculating program checksums. Compared to the Bootstrap mode. The Monitor program requires two interrupt vectors: the NMI interrupt is used for breakpoints. you save the time to download the Monitor program at system startup. It also communicates via the UART ASC0 (or ASC1 for 8xC166 CPU) and requires exact configuration of the baudrate.
RECEIVE DATA and SIGNAL GROUND from the RS232 or V. However. The asynchronous serial port (ASC0) is used to transfer the program code. PIN connections of various computer systems . You target board does not require a monitor ROM. The bootstrap loader is used by the Keil Monitor to download itself and your program for debugging. and a stop bit.4 is low at the end of the hardware reset. This procedure is similar for other 166 derivatives. Once the zero byte is received. Additional 10 words stack space in the user program to be tested. 5 Kbytes of-chip code memory loaded with Monitor-166 software (ROM or RAM in Bootstrap Mode).156 Chapter 11. Serial Transmission Line Monitor-166 requires only the signals TRANSMIT DATA. For example. The zero byte must contain 1 start bit. in most cases. to enable transmit and receive data. 8 All other hardware components can be used by the application. Using Monitor-166 Bootstrap Loader Many derivatives of the 166 include a bootstrap loader (BSL) that uses the serial port to download code to the on-chip RAM. some additional connections are necessary in the serial connectors. Software trap used for breakpoints (usually NMI trap). 256 bytes off-chip data memory (RAM).24 line. eight zero bits. the BSL initialized the ASC0 interface with the appropriate baudrate and transmits an identification byte on TXD0. Only RAM devices are required for testing your programs. the C167 device enters BSL mode when port pin P0L. After entering BSL mode. Hardware and Software Requirements The following requirements must be met for Monitor-166 to operate correctly: ¢ ¢ ¢ ¢ ¢ ¢ Siemens 161/163/164/165/166/167 CPU or ST10 variant Serial interface for communication with the PC. the C167 waits to receive a zero byte on the RXD0 line.
11 µVision2 Monitor Driver µVision2 interfaces to target systems when you select Use: Keil Monitor-166 Driver in the dialog Options – Debug. Refer to “Set Debug Options” on page 75 for more information about the Debug dialog. Click on Settings to opens the dialog Monitor Driver Settings that allows you to configure various parameters such as COM port and baudrate. . connect pin 7 to pin 8 and pin 1 to pin 4 and pin 6.Getting Started 157 25 Pin Connector Signal Name RxD TxD Gnd 9 Pin Connector Description receive data transmit data signal ground Pin 3 2 7 Signal Name RxD TxD Gnd Pin 2 3 5 Description receive data transmit data signal ground In addition to the above pins.
It contains also required configuration settings. You should disable this option to debug self-modifying code. When enabled µVision2 duplicates the program code on the PC and never reloads the code from your target system. In any case a high to low transition at the NMI# pin terminates a running application. when access or conditional breakpoints are set. Single step execution is at least 1000 times slower. you can terminate a running application program with the Stop toolbar button or the ESC key in the Command page. it is not allowed to reset the global Interrupt Enable Flag IE (bit in PSW) in your application. Call Stack and Code Coverage features are not available with Monitor-166. It is not possible to use Debug – Memory Map to change the memory mapping of the target system. In addition. When you single step trough code. The Performance Analyzer. µVision2 will reload the data regions. enables the memory cache for data regions. even when SFR cache is enabled.158 Chapter 11. Cache SFR space Restrictions of µVision2 when using Monitor-166 The memory mapping of a CPU board with Monitor-166 is selected with hardware components and the Monitor configuration file. If you have problems with your target hardware. the serial interface is not longer available for the user program. When Serial interrupt or NMI is enabled. You may use cut and paste to copy the settings into other Options dialog pages. However. the Monitor driver implements several data caches. Description PC Port Settings Stop Program Execution with Cache Options Ignore Code Modifications Cache Memory To speed up the screen updates. Using Monitor-166 The following table describes the Monitor Driver Settings page: Dialog Item Monitor Configuration Description List available Monitor configurations. To support this. enables the memory cache for the SFR space of the CPU. Provides you with a quick description of you target hardware. the application is executed in single steps and not in real time. try the Baudrate 9600. Select the PC COM port and the baudrate you want to use. You may add user configurations as described under “ Monitor-166 Configuration” on page 160. You should disable this option to view changes on IO ports or peripherals when debugging is stopped. Breakpoint Options are handled directly by Monitor-166. even when memory cache is enabled. When you single step trough code. µVision2 will reload the SFR regions. 8 . You should disable this option to view changes on IO ports or peripherals when debugging is stopped. Select the Monitor configuration for your target hardware.
Therefore the ROM entries in the dialog Options – Target – External Memory should refer to the RAM areas where you want to store the program code during debugging.Getting Started 159 Target Options when Using Monitor-166 When you are using Monitor-166. the complete target application need to be stored in RAM space. This is required. . 11 In the page Options – L166 Misc you should enter under Reserve the memory regions used by your Monitor configuration. For more information refer to “Monitor-166 Configuration” on page. The required address ranges for preconfigured Monitor variants can be found under Options – Debug – Settings – Description. since the Monitor changes the program code to set breakpoints in your application.
This error might occur because your program re-initializes the serial interface or changes the PORT direction register for I/O lines used by the serial interface.UV2 C:\KEIL\C166\MONITOR\U User configuration files for all other CPU variants.TXT. check if the Write Configuration Control bit _WRCFG matches your hardware. like 161/163/164/165 SER167\USER 167.INC. In BOOTSTRAP mode. If the Monitor stops working during the C startup code of your application your are most likely using different settings in the CPU parameter section. This error also occurs when you single step in the serial I/O routines of your application. Using Monitor-166 Monitor-166 Configuration The Monitor-166 can be adapted to different hardware configurations. You try to download code into ROM space or non-existing memory. The configuration works with a µVision2 project file and is described in the file C:\KEIL\C166\MONITOR\README. CANNOT WRITE TO ROM AREA CANNOT WRITE BREAKPOINT . Check carefully if the settings of the STARTUP. 8 During operation the Monitor might report the following errors: Error Text BAD SERIAL TRANSMISSION Description uVision2 has lost the serial connection to the Monitor program.INC. Check carefully the settings in the file CONFIG.A66 or START167. To configure a new Monitor variant. create a new folder under C:\KEIL\C166\MONITOR and copy all files from USER166 or USER167 Trouble Shooting If the Monitor does start correctly it is typically a problem of the CPU startup or Monitor code and data locations.A66 file match the settings in the CONFIG. The following table describes the µVision2 project files used for the Monitor configuration: Folder and Project File Description C:\KEIL\C166\MONITOR\U User configuration files for 8xC166 CPU and ST10-166. uVision2 check if the Monitor is downloaded correctly.160 Chapter 11. You try to set a breakpoint in ROM space or non-existing memory. If the Monitor does not start. SER166\USER 166.UV2 and 167 CPU type and ST10 C:\KEIL\C166\MONITOR\ … Other folders may contain pre-configured monitor variants for different boards.
You try to execute invalid program code.Getting Started 161 Error Text CANNOT WRITE BREAKPOINT VECTOR INVALID OPCODE Description The Monitor program cannot install the interrupt vectors for the NMI trap or Serial interface. 11 . This error occurs when the RAM at address 0 cannot be accessed.
.
Commands and directives are listed in a tabular format along with a description. µVision2 will exit after debugging is completed with the EXIT command or stop debug session. µVision2 project files have the extension . The command line syntax is as follows: UV2 ¤ projectfile¥ ¤ command¥ projectfile is the name of a project file. Command Reference This chapter briefly describes the commands and directives for the Keil 166/ST10 development tools.UV2 –o"listmake. Open the project and set the specified target as current target. If no projectfile is specify. Example: UV2 PROJECT1. You can use this command together with a Debug Initialization File to execute automated test procedures.UV2 –t"C167CR Board" –b builds the target “ C167CR Board” as defined in the PROJECT1. If the –t command option is not given µVision2 uses the target which was set as current target in the last project session.Getting Started 163 Chapter 12. Example: UV2 PROJECT1. is one of the following commands. Re-translate the project and exit after the build process is complete.UV2 file. 11 µVision 2 Command Line Invocation The µVision2 IDE can directly execute operations on a project when it is called from a command line. copy output of the Output Window – Build page to the specified file.UV2.prn" –r command Command -b -d -r -t targetname -o outputfile . Description Build the project and exit after the build process is complete. If no command is specified µVision2 opens the projectfile in interactive Build Mode. µVision2 opens the last project file used. This option can be used in combination with other µVision2 commands. NOTE Underlined characters denote the abbreviation for the particular command or directive. Start µVision2 Debugging Mode.
Set the output format of the macro processor function %EVAL to decimal format. Outputs error messages to filename. NOPRINT REGUSE RESET (symbol. Do not list the following symbol definitions in the symbol table.164 Chapter 12. Generates a full listing of macro expansions in listing file. directives A166 Directive CASE COND. Define the mode of CPU operation. Do not recognize the predefined special function registers. Enable the extended instruction set for 161/163/164/165/167. is the name of a file which contains a complete command line for the assembler including a sourcefile and directives. The listing file is saved as filename if specified. Excludes line number information from the object file. Disables standard macro processing. … ) RESTORE SAVE SEGMENTED. NOSEGMENTED 8 . Defines register usage of assembler functions for the C optimizer. Description Enable case sensitive symbol names. Assigns a value of 0000h to the specified symbols. NOOBJECT PAGELENGTH(n) PAGEWIDTH(n) PRINT¤ (filename)¥ . Disables MPL macro processing. Sets maximum number of characters in each line of listing file. NOCOND DATE(date) DEBUG ERRORPRINT¤ (filename)¥ EXPDECNUM EXTMAC INCLUDE(filename) GEN NOGEN NOLINES NOLIST NOMPL NOMACRO NOMOD166 MOD167 NOSYMBOLS NOSYMLIST OBJECT¤ (filename)¥ . Enables or disables object file output. Sets maximum number of lines in each page of listing file. LIST and SYMLIST. Excludes the symbol table from the listing file. Stores current control setting for GEN. Enable or disable skipped sections to appear in the listing file. Includes the contents of filename in the assembly. are control parameters described in the following table. The object file is saved as filename if specified. Includes debugging symbol information in the object file. Enable extended ST10 MAC instructions. Command Reference A166 Macro Assembler Directives Invocation: sourcefile commandfile A166 sourcefile ¤directives¥ A166 @commandfile is the name of an assembler source file. Restore control setting from SAVE stack. Places date string in header (9 characters maximum). Excludes the assembler source code from the listing file. List only the original source text in listing file. Enables or disables listing file output.
Includes title in the listing file header. NOTYPE USEDEXTONLY XREF Description Assigns a value of 0FFFFh to the specified symbols. 11 .Getting Started 165 A166 Directive SET (symbol. … ) TABS (number) TITLE(title) TYPE. Specifies the tab setting. Includes a symbol cross reference report in the listing file. Prevent A166 from generating external definitions for unused external identifiers. Defines whether type information is included in object file or not.
NOASMEXPAND BROWSE BYTEALIGN CODE COMPACT DEBUG DEFINE DYNAMICUSRSTK EXTINS FIXxxx FLOAT64 HCOMPACT HLARGE HOLD INCDIR INIT. Defines preprocessor names on the command line.166 Chapter 12. Specifies size limits for default placing of objects without explicit memory types. Do not save the DPP registers in interrupt functions. NOINIT 8 LARGE LISTINCLUDE MEDIUM MOD167 NOALIAS NODPPSAVE NOCOND NOEXTEND NOFIXDPP NOFRAME . Assume pointers to byte-aligned structures. Enabled double-precision floating-point numbers. Description Merge assembler source text into the SRC file. Generate code with fixes for chip bugs. Generate code without DPP register assumptions. Break EXT instruction sequences at C source line numbers. Enables dynamic modification of the user stack by a real-time OS. Command Reference C166 Optimizing C Cross Compiler Directives Invocation: where sourcefile commandfile C166 sourcefile ¤directives¥ C166 @commandfile is the name of a C source file. Includes debugging information in the object file. are control parameters described in the following table. Generate browse information. Selects the HLARGE memory model. Disables 166 extensions and processes only ANSI C constructs. Enable or disable macro text expansion for assembler source text sections. Suppress prolog and epilog for interrupt service routines directives C166 Directive ASM / ENDASM ASMEXPAND. Selects the COMPACT memory model. Selects the LARGE memory model. Disable alias checking for pointer access optimization. is the name of a file which contains a complete command line for the compiler including a sourcefile and directives. Selects the MEDIUM memory model. Specify additional path names for include files. Includes an assembly listing in the listing file. Enable or disabled zero initialization of variables. Excludes skipped conditional code from the listing file. Enable the extended instruction set for 161/163/164/165/167. Includes the contents of include files in the listing file. Selects the HCOMPACT memory model.
NOOBJECT OPTIMIZE ORDER PACK PAGELENGTH(n) PAGEWIDTH(n) PECDEF PREPRINT¤ (filename)¥ PREPRINTONLY¤ (file)¥ PRINT¤ (filename)¥ .Getting Started 167 C166 Directive OBJECT¤ (filename)¥ . Selects the SMALL memory model. Rename predefined class names in the object file. The object file is saved as filename if specified. Change a Warning to an Error or disable a warning. Specifies the level of optimization performed by the compiler. Produce a preprocessor listing and stop compilation. Treat plain char as unsigned char. Reserve PEC channels. 11 . Creates an assembly source file instead of an object file. Selects the TINY memory model. Sets maximum number of lines in each page of listing file. Assume user stack area in IDATA or SDATA memory class. Locates variables in memory in the same order in which they are declared in the source file. Allocate automatic variables to static memory addresses. Includes a list of the symbols used in the listing file. Controls the types and severity of warnings generated. Enables or disables listing file output. Save temporary results and saved-by-callee variables to user stack. Specifies the name of the generated file to contain register usage information. Generate BYTE aligned structures with word elements. Save temporary results and variables to system stack. The preprocessor listing file is saved as filename if specified. NOPRINT REGFILE(filename) RENAMECLASS SAVESYS SAVEUSR SMALL SRC STATIC SYMBOLS TINY UNSINGEDCHAR USERSTACKDPP3 WARNING WARNINGLEVEL(n) Description Enables or disables object file output. Sets maximum number of characters in each line of listing file. The listing file is saved as filename if specified. Produce a preprocessor listing file with all macros expanded.
You may use a command file to make linking your application easier or to include more input files or directives than fit on the command line. Define physical class address ranges and class locating order. Command Reference L166 Linker/Locator Directives The L166 Linker/Locator links your 166 object modules. Excludes memory map information from the listing file. Disable case sensitivity of the linker. Invoke the linker using either of the following command lines: L166 @commandfile L166 inputlist ¤ outputfile¥ ¤ TO directives¥ where inputlist is a comma-separated list of the object files and libraries the linker includes in the final absolute object module. Locate C initialization data sections to specified address range. is the name of a file which contains a complete command line for the linker. Specifies a module name for the object file. Remove the interrupt vector table in the output file. Excludes comment information from the listing file and the object file. Re-assign DPP registers for NCONST and NDATA groups. and directives. locates them at absolute addresses. outputfile commandfile directives L166 Directive ASSIGN CINITTAB CLASSES DISABLEWARNING DPPUSE GROUPS IXREF 8 LINKONLY NAME NOCASE NOCOMMENTS NODEFAULTLIBRARY NOLINES NOMAP NOPUBLICS NOSYMBOLS NOTYPES NOVECTAB . Excludes type information from the object file. Excludes line number information from the listing file and object file. are linker control parameters described in the following table. is the name of the absolute object module the linker creates.168 Chapter 12. Excludes modules from the run-time libraries. Suppress located process for incremental linkage. Define physical group addresses and group locating order. Include a cross reference report in the listing file. and creates an absolute object module you may use for debugging or creating an Intel HEX file. Disable report of specified warning numbers. Excludes local symbol information in listing and object file. Description Define public symbols on the command line. The command file includes an inputlist. outputfile (if desired). Excludes public symbol information in listing and object file.
NOLINES. Define physical register bank addresses and locating order. NOSYMBOLS. Define physical section addresses and section locating order. See NOCOMMENTS. and PURGE. Specifies the name of the listing file. NOLINES. Change the length of sections. See NOCOMMENTS. NOSYMBOLS. Reserve physical 166/ST10 memory areas. NOPUBLICS. Subcontrols must be specified in parentheses. Includes support for the RTX166 Tiny real-time kernel. Specifies the name of the register usage information file.Getting Started 169 L166 Directive OBJECTCONTROLS Description Excludes specific debugging information from the object file. Includes support for the RTX166 Full real-time kernel. Specify a start address for the interrupt vector table. Excludes specific debugging information from the listing file. NOPUBLICS. Sets maximum number of lines in each page of listing file. Sets maximum number of characters in each line of listing file. Subcontrols must be specified in parentheses. Excludes all debugging information from the listing file and the object file. Controls the types and severity of warnings generated. and PURGE. PAGELENGTH(n) PAGEWIDTH(n) PRINT PRINTCONTROLS 11 PURGE REGBANK REGFILE(filename) RESERVE RTX166 RTX166TINY SECSIZE SECTIONS VECTAB WARNINGLEVEL(n) .
You may use a command file to generate a large library with at once. Removes an object module from the library file.LST) that contains the module names stored in the MYLIB.OBJ object module in MYLIB. FILE2. Command Reference LIB166 Library Manager Commands The LIB166 Library Manager lets you create and maintain library files of your 166 object modules.OBJ to that library.LST PUBLICS generates a listing file (named MYLIB. For example. is the name of a file which contains a complete command line for the library manager. LIB166 REPLACE GOODCODE.LIB TO MYLIB.LIB. commandfile LIB166 Command Description ADD Adds an object module to the library file. Generates a complete new library and adds object modules.LIB replaces the GOODCODE. LIB166 DELETE MYLIB. For example. The command file includes a single command that is executed by LIB166. LIB166 ADD GOODCODE. For example. LIB166 EXTRACT MYLIB.OBJ TO MYLIB.LIB. Note that Replace will add GOODCODE. LIB166 TRANSFER FILE1.LIB. Creates a new library file.OBJ copies the GOODCODE module to the object file GOOD. The PUBLICS directive specifies that public symbols are also included in the listing.LIB deletes the existing library MYLIB.OBJ to the library if it does not exists.LIB.LIB (GOODCODE) removes the GOODCODE module from MYLIB.LIB. Extracts an object module from the library file.LIB creates a new library file named MYLIB. re-creates it and adds the object modules FILE1. For example. Replaces an existing object module to the library file.OBJ. For example.OBJ object module to MYLIB. CREATE DELETE EXTRACT EXIT HELP LIST 8 REPLACE TRANSFER . Lists the module and public symbol information stored in the library file.OBJ and FILE2.OBJ IN MYLIB.170 Chapter 12.LIB (GOODCODE) TO GOOD. For example. LIB166 LIST MYLIB. If no command is specified LIB166 enters an interactive command mode. LIB166 CREATE MYLIB. For example. Displays help information for the library manager. Exits the library manager interactive mode. Invoke the library manager using the following command: LIB166 ¤ command¥ LIB166 @commandfile command is one of the following commands.LIB adds the GOODCODE.OBJ.LIB library file.OBJ TO MYLIB.
The default range is 0x000000 to 0xFFFFFF. By default. Unused bytes in the RANGE are filled with the fillbyte specified with the FLASH directive.Getting Started 171 OH166 Object-HEX Converter Commands The OH166 object-HEX converter creates Intel HEX files from absolute object modules. The HEX file is sorted in ascending order. specifies an offset (offset) added to the addresses from the absfile. The sorted HEX file can be downloaded to FLASH devices. H167 RANGE start end OFFSET FLASH The following command line creates a HEX file named MYCODE.HEX from the absolute object module MYCODE. This address must be entered in C hexadecimal notation. OH166 MYCODE H167 . This address must be entered in C hexadecimal notation. specifies the ending address of the range. for example: 0x010000. specifies the address range of data in the absfile to convert and store in the HEX file. Invoke the HEX converter using the following command: OH166 absfile ¤ H167¥ RANGE(start-end)¥ OFFSET(offset)¥ FLASH(fillbyte)¥ ¤ ¤ ¤ where absfile 11 is the name of an absolute object file that the L166 linker/locator generated. for example: 0xFFFFFF. specifies that an Intel HEX-386 file is created. OH166 creates a standard Intel HEX-86 file. specifies the starting address of the range. Records in the HEX file are written in HEX-386 format.
36 Command line parameters 163 Debug Options 75 Menu Commands 14 Options 40 Shortcuts 14 Toolbars 14 Toolbox 74 1 166 Devices 166 microcontroller family 2 2 C A A/D converter Example program A166 A166 macro assembler Commands Directives Access Break ADCIC register ADCON register Add command LIB166 library manager ADDAT register ADDAT2 register 149 149 8 28 164 164 70 149 149 170 149 149 C run-time configuration C startup code C166 C compiler C166 compiler Commands Directives Language Extensions Memory Models CA166 CAPREL register case Changes to the documentation Character constant escape sequence 154 153 20 166 166 20 23 8 140 97 3 84 .13. use of Bootstrap loader Braces.172 Index Index $ $ system variable 85 Additional items. document conventions ADEIC register Analog/Digital converter ANSI C Assembler Instructions Assembler kit Assign directive L166 linker/locator Assistance iv 149 149 110 68 8 168 5 _ _break_ system variable _getkey library routine _idle_ library routine _pwrdn_ library routine _sof_ library routine _srvwdt_ library routine 85 142 150 150 135 145 B Binary constants Bit addresses Bit-fields Bold capital text. use of break Breakpoint Commands Breakpoints Access Break Conditional Execution Break Build Process Build Project 83 94 49 iv 156 iv 97 81 69 70 70 70 57 41 µ µVision2 Debugger 67 µVision2 IDE 6.
72 67 67 83 170 6 13 58 134 164 166 168 170 171 12 68 iv 134 97 iv 3 iv . document conventions iv Classes directive L166 linker/locator 168 Classes of symbols 91 Code Coverage 77 Command reference 163 A166 macro assembler 164 C166 compiler 166 L166 linker/locator 168 LIB166 library manager 170 OH166 hex converter 171 Comparison chart 9 Compiler kit 8 conditional assembly 28 Conditional Break 70 Configuration C run-time 154 CPU 153 DAVE utility 154 Hardware 154 Memory model 153 Run-time 154 tool options 43 Constant Expressions 82 Constants 82 Binary 83 Character 84 Decimal 83 Floating-point 83 HEX 83 Octal 83 String 84 continue 97 Control Directives #pragma 26 Copy Tool Settings 60 Correct syntax errors 41 Counters 140 Courier typeface. use of iv CPU driver symbols 85 CPU initialization 153 CPU pin register See VTREG CPU registers 73 CPU Registers 73 CPU Simulation 67 Create a Library Create a Project File Create command LIB166 library manager Create HEX File Creating header files CRIC register Custom Translator cycles system variable 59 36 170 41 128 140 64 85 11 D Data Threshold Data Types DAVE utility Debug Comamnds Program Execution Debug Commands Memory Debug Functions Debug Menu Debug Mode Debugger Decimal constants Delete command LIB166 library manager Development cycle Development tools Device Database Direct memory access controllers Directives A166 macro assembler C166 compiler L166 linker/locator LIB166 library manager OH166 hex converter Directory structure Disassembly Window Displayed text. use of 50 54 154 80 17.Getting Started 173 Character constants 84 Choices.68.80 80 97 17. document conventions DMA do Document conventions Documentation changes Double brackets.
174 Index DPP registers dScope functions 129 110 E Edit Menu Editor Commands EK166 evaluation kit Ellipses.90 86 95 82 55. document conventions Files Groups Find in Files float Predefined function Floating-point constants Folder for Listing Files Folder for Object Files FR166 Fully qualified symbols Function classes Predefined functions Signal functions User functions Function Classes Functions µVision2 Debug Functions Classes Creating Invoking Predefined Signal User 9 14 65 14 43.90 82.90 85 85 82.62 iv 42 44 100 83 58 58 9 91 99 99 99 99 97 99 97 99 100 106 104 G General commands General purpose timers Example program getfloat 81 140 140 .94 82 85 82.94 82. use of Ellipses. use of else Escape sequence Evaluation board Evaluation kit Evaluation users Example program A/D converter General purpose timers Idle mode Interrupt functions Parallel port I/O PEC Peripheral event controller Power down mode Pulse width modulation PWM Serial interface Watchdog timer Examples of expressions exec Function description Predefined function Execution Break Exit command LIB166 library manager Experienced users Expression components Bit addresses Constants CPU driver symbols Line numbers Operators Program variables SFRs Special function registers Symbols System variables 15 15 4 iv iv 97 84 155 4 4 149 140 150 131 139 137 137 150 147 147 142 145 95 100 100 70 170 4 82 82.85 Type specifications Variables VTREGs Expression examples Expressions External RAM Extract command LIB166 library manager 82.59 170 F Feature check list File Commands File Extensions File Menu File specific Options Filename. vertical.94 82.93 82.
62 Layout Layout for PEC Interrupt enable flag Interrupt functions Example program Interrupt group level Interrupt priority level Interrupt request flag Introduction Italicized text.64 93 170 58 91 I I/O ports IDLE instruction Idle mode Example program IEN register if 97 Import µVision1 Projects Include specific Library Modules Installing the software Instructions IDLE PWRDN RETI SRVWDT Interrupt control registers 88. use of itrace system variable 132 136 133 131 131 133 133 133 1 iv 85 11 K Key names. document conventions Kit comparison iv 9 H Hardware configuration Hardware requirements HCOMPACT Memory Model Header files Help Help command LIB166 library manager Help Menu HEX constants HEX File HLARGE Memory Model 154 11 49 128 5 170 18 83 41 49 L L166 linker/locator Assign directive Classes directive Commands Directives Ixref directive Name directive Nocomments directive Nodefaultlibrary directive Last minute changes LIB166 library manager Add command Commands Create command Delete command Exit command Extract command Help command List command Replace command Transfer mmand Library Line numbers List command LIB166 library manager Listing Files Literal 30 168 168 168 168 168 168 168 168 3 34 170 170 170 170 170 170 170 170 170 170 63.138 150 150 150 132.Getting Started 175 Function description Predefined function getint Predefined function getlong Predefined function Getting help Getting started immediately Global Register Optimization goto GPT1 GPT2 Group specific Options for Groups 101 100 100 100 5 3 50 97 140 140 43.150 56 64 11 150 150 150 145 132 .
48 22 73 101 100 90 157 155 160 156 28 OH166 hex converter Command-line example Commands Omitted text.62 43.101 100 100 N Naming conventions for symbols New Project New users NMI pin Non-qualified symbols 90 36 4 150 92 O Object Files Octal constants 58 83 .60 M Macro Processing Language Macros standard macros Manual topics MEDIUM Memory Model Memory Map Memory model Memory Model COMPACT HCOMPACT HLARGE LARGE MEDIUM SMALL TINY Memory Models Memory Type Memory Types Memory Window memset Function description Predefined function Module names Monitor Driver Monitor-166 Configuration Serial Transmission Line MPL 28 28 3 48 78 153 40. document conventions Options for Files for Groups Output Window 34 171 171 iv 94 48 iv 43. document conventions Operators Optimum Code Optional items.176 Index Literal symbols Locate Sections 91 43.62 41 P Parallel port Example program Part numbers PC-Lint PEC Control register layout Example program Interrupt control register layout Performance Analyzer Peripheral event controller Control register layout Example program Interrupt control register layout PK161 PK166 Pointer Port I/O Ports Power down mode Example program Power reduction modes PPx register Predefined functions exec float getfloat getint getlong 138 139 8 47 134 135 137 136 77 134 135 137 136 8 8 23 138 88 150 150 150 146 100 100 100 100.48 23 23 23 23 23 23 23 23 40.
document conventions iv printf Function description 101 Predefined function 100 printf library routine 142 Product link 8 Production kit 4 Professional Developer’ Kit s 8 Program counter system variable 85 Project Commands 17 Project Menu 17 Project Targets 42 PSW register 132 PTx register 146 Pulse width modulation 146 Example program 147 putchar library routine 142 PWM 146 Example program 147 PWMCON0 register 146 PWMCON1 register 146 PWMIC register 146 PWRDN instruction 150 PWx register 146 Q Qualified symbols 91 R radix system variable rand Function description Predefined function Real-time operating system REG167.101 printf 100.102 Printed text.Getting Started 177 memset 100.101 rand 100.H header file Register banks Registers ADCIC ADCON ADDAT 85 102 100 9 128 131 149 149 149 ADDAT2 ADEIC CAPREL CRIC IEN PPx PSW PTx PWMCON0 PWMCON1 PWMIC PWx S0BG S0CON S0EIC S0RBUF S0RIC S0TBIC S0TBUF S0TIC T2 T2CON T2IC T3 T3CON T3IC T4 T4CON T4IC T5 T5CON T5IC T6 T6CON T6IC WDTCON Replace command LIB166 library manager Requesting assistance Requirements RETI instruction RS-232 RS-232 ports RTX166 Run Program 149 149 140 140 132.102 twatch 100.150 146 132 146 146 146 146 146 142 142 142 142 142 142 142 142 140 140 140 140 140 140 140 140 140 140 140 140 140 140 140 145 170 5 11 150 142 89 9 72 11 .
A66 153 String constants 84 switch 97 Symbol expressions Symbols Classification CPU driver Fully qualified Literals Module names Naming conventions Non-qualified Qualified names SFRs Special function registers System variables VTREGs Symbols Window Syntax errors System variables $ 85 _break_ cycles itrace Program counter radix 90 91 85 91 91 90 90 92 91 85 85 85 86 79 41 85 85 85 85 85 85 T T2 register T2CON register T2IC register T3 register T3CON register T3IC register T4 register T4CON register T4IC register T5 register T5CON register T5IC register T6 register T6CON register T6IC register Target hardware Target Tool Settings Technical support Timer 2 Timer 3 Timer 4 140 140 140 140 140 140 140 140 140 140 140 140 140 140 140 155 60 5 140 140 140 .145.178 Index S S0BG register 142 S0CON register 142 S0EIC register 142 S0RBUF register 142 S0RIC register 142 S0TBIC register 142 S0TBUF register 142 S0TIC register 142 Sans serif typeface. use of iv Saving power 150 scanf library routine 142 Select Text 16 Serial interface 142 Example program 142 Serial ports 89 Serial Window 76 SETUP program 11 SFRs 85 Siemens DAVE utility 154 Signal functions 106 Simulating I/O ports 88 Simulating serial ports 89 Simulation 67 Simulator 67 Single Step Program 72 Single-board computers 155 SMALL Memory Model 48 Software development cycle 6 Software requirements 11 Source Browser 44 Special function registers 85 SRVWDT instruction 145 ST10 Devices 2 Start µVision2 36 Start Debugging 67 Start External Tools 57 START167.153 START167.153 Memory model 153 STARTUP.A66 file 145 Startup code 128.A66 38.
Getting Started 179 Timer 5 Timer 6 Timers Tool Information tool options Tools Menu Topics Transfer command LIB166 library manager Translate asm/endasm sections twatch Function description Predefined function Type specifications Types of users 140 140 140 65 43 18.46 3 170 63 102 100 94 4 V VAGND pin VAREF pin Variable expressions Variable values Variables. document conventions Vertical bar. use of View memory contents View Menu VTREGs 149 149 90 72 iv iv iv 73 16 86 11 W Watch Window Watchdog timer Example program WDTCON register while Window Menu Windows-based tool requirements Write Optimum Code 72 145 145 145 97 18 11 48 U UART User Classes User functions Users Using Monitor Utilities 76 61 104 4 155 44 . use of Vertical ellipses.
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.