Sudan Academy of Sciences ( SAS) Atomic Energy Council

Design and building of home made 8051 Microcontroller Emulator

By Abdclmoncim Elobeid Hussein iVI.Sc. in Electronics Engineering University of Khartoum ( 2002)

A Thesis Submitted to the Sudan Academy of Sciences In Fulfillment of the Requirements for Doctor of Philosophy Degree Ph.D. in Electronics Engineering

Supervisor Dr.Abd Elrasol Gabar Elzobaidi

September 2009 Sudan Academy of Sciences (SAS)

Examination committee

Name

External examiner Dr. Sid Ahmed Ibrahim

Internal examiner Dr. P'arouk Idris llabbani

Supervisor Dr. Abdelrasoul Gabar Hlzobaidi Dedication

ll'or wfwm tfwy tfiougfit we are of their concern ^L&J all uu iao uu ^ i « J&Jl (J ic -llLa t-Lu 5 ^jrti Ua]|j ac-LiU , A . O \ JjjLill

SbVI jl nr.J jj— VAJ ^1 JJ^UI SbV ^JJ^^I J>\jd\ j CjL^ajjJ]

.Lpj.1 .As*-* ialJLi j I^JIJJILU 3JJJJ vb byj ISjAi^a ^jjSjJl ^aJLxJl S^a.j (j^ia ^.l.^l.nl <_U*Jl IJtA J.Je»S ^JJjjjfUVI J»lj-iH

^ j J n-> j ijj jc SjLc- Clllj% ajjjl Lai .dljj l-t")!! (jiaxJ £-a (-^*-LJl j_c V JJ o>—% ojSI-ll) dib Ajj^aJl CJlAaaJt dial Vina ) 4 .aS'i j»£jkloll

iati C_>jxl-tll jLj-a. £

.^jlaJl SjSlill J- . jlll <• iu?i«ll «_1 axubJl ^Jc <4_al.lklu>l j£-aJ 1 >ji>i

J—jl (J}* «JJ J «J «, iji nail <-_) a ml ->It ^ifi. JLi^l jj Vi« i H Ijj <_JJ|JA!I £-»UJJJ| £<* a > A i_J ajoibJl AjLuol Aft Jul (Jj^»"n I—l3tj*ll.1> j -llialt .^1%"ujall

jj «J ^ Ull 4JSJJ.H j£l jill 4jk-aj> Ai'jlj Cilfljjll (jlfi .hjtaj>\t

^a)j—j l^lwv 4J&yajf 4JJ ajjilVI »Jjl aJ ^ AJSJJ J^'j^ ^-^J A^al_)j (jj_^iaj j»>-%1niolt

S^l_Ji L^aiUa A^jJA ijfrV^S VJ L^W^J jLaj ft^c liliiS . J^ai OXJ LJlSfc ^JiLI

J__JS jjfjl.^iail ^aUjJl ijajJl SjSlill AjLp3 AJIJJ AJJ^J (_llku IJA l-lS>a .lillij jc-ajuU

kllll-S o 3_jjbj ^-1 a—li Jl SjSlill Sj4.Ua .4laa.JJ

.(JjJ-llI ^Viall J>?.a^ i—lSljaJl ^aljjjJl jl LaJUa l^-\jjn j$-»J

Jl >ji Jjl ^ ci«x]l IJUb jli t JJ aiaSlI AjLaC Col ^Irati j»Al gjijull

^—Sc. (dll—iMajjiil^j-al «VI ^ji-iwil gtJlii^ .ili

^uukll t^ri.tilt i $.lja.VI tjLuiV 4 jiill tjiijaJl nJjjMSlI <£jAji)l (£A ^.I-^IMI/ill ^alijJ

^—^IjVI J-a «J Javil "ajJ j£l ia^li^J Lk JL>J| jS^aj ^yjil <• «jihati l_l j»»il->ll ^a (J^a\jjl)j

. jiJJ j»J jJa^Jlj * ijS «jl i^-full t'll i-s ajj (jLt t->'inall ^aUjj A-a^-ail

3—uibvlt ^. a J ual jSll J uiLuull frLu-all ^,\^*iiaj lilj-ail ^UJJ J^^W J£^3>-^ d—^yik ^—US J? »>-» ijl Ji«y V i J (jJka. jl a^vmall (j^i ^ ' 'J'^oti j a (—J—UaJ j 4jA.jliJl SjSlJll ^-3

L_I j uilaJl ^ lc ,\t Villi JJ j'»•!».i JJ jiaj I Jl Li jbkjl jirsll a ^ jnll t"i\jJoft

^ S Sj—j i%il ^ jjjll (a a (.\ SJJJSI (Ji-al jp (J^*i l-Ub C_lSlj-all gt-aljjj (JA1*J ^»JJ <_kuia-ajl • I. tjiXnil C-ljillicit

11 ABSTRACT

This research targeted design and build of a simple lab made emulator fur the 8051 microcontroller to assist student and researcher in their projects. This will be achieved by thorough understanding of the software and the hardware of the development tool which will enliance the user knowledge rather limn considering them as black boxes and unaware of their capabilities and their limitations. Regarding the hardware this work preferred to use the same the developer wanted to build with little modification. While the software is a program loaded in the microcontroller itself responsible (making use of flash microcontrollers) for communication with the host computer terminal, and monitoring the user program which is loaded in the external memory by the program. Any terminal program on the host computer can be used to carry out communication with monitor program provided that a carriage return should be pressed after monitor power up to let the monitor adjust its baud rate accordingly. This feature makes the monitor program so simple and familiar to the user. For simplicity the software is enhanced with flash programming and erasing subroutine which can allow the user to store his program there if he put a flash ROM in his hardware and he can make it as start up program which will run automatically after start up. Also many programs can be loaded in the flash as long as its capacity is capable Definitely this requires configuring flash start and end in the source before compiling it. This flash feature allows the development liardware to be as final board and hence a debugable one as long us monitor program resides inside the microcontroller.

Considering the debugging stage as the most crucial step in the development cycle, this work tried to find some suitable and simple solutions that can enhance knowledge. As a result some commands on the user program like uploading, downloading, displaying, jumping, selecting among others, running, editing, clearing and communicating with the host PC can be carried out efficiently. But unfortunately some significant commands on the user program like tracing, pausing and single stepping were not met. It is worth mentioning tliat the monitor program is using the serial port for communication with the host PC, so the user has to be careful not to change any register

iii involved in serial communication in his program. Also the user program is loaded in the external memory and the user is required to add some I/O ports if he needs this design as last setup. Tracing and single stepping could be accomplished if some host PC emulation program is developed and this monitor program is modified to carry out more intelligent communication with the new host PC environment.

iv ACKNOWLEDGEMENTS

I gratefully acknowledge Coskim HARMANSAH and Mehmel BAYBURT for their advice and supervision which represents the backbone of this research and so to this thesis. It is a pleasure to convey my gratitude to them all in my humble acknowledgment.

In the first place 1 would like to record my gratitude to Coskun HARMAN§AH for his supervision, advice, and guidance from the early stage of this research as well as giving me extraordinary experiences through out the work. Many thanks go in particular to Serdar AKDURAK I am much indebted to AKDURAK for his valuable advice in science discussion and supervision I gratefully thank them for their constructive comments on this thesis.

I would like to thank Pcrihau UNAK and Meral KRAI, for giving me the opportunity to work on Electronic l.ab equipment in Institute of Nuclear Science in Ege University in Izmir. To Mehmet Bayburt, thank for his technical assitances during work I had in Izmir.

I would also like to thank M. Muslim SAC; and Onui KAHVECi for their collobration and their willingness to share their bright thoughts with me, which were very fruitful for shaping up my ideas and research.

It is a pleasure to express my gratitude wholeheartedly to Siileyman ERKUT, Giingor POLAT and their family for their kind hospitality during my stay in Izmir. I would like to express special thanks to Siileyman ERK.UT for his indispensable help dealing with travel funds, administration and buieaucratic matters during my stay in Izmir.

I cannot end without thanking my family, on whose constant encouragement and love I have relied throughout my time during this work. Words fail me to express my appreciation to my wile Sehna whose dedication, love and persistent confidence in me, has taken the load off my shoulder.

v Finally, 1 would like to thank everybody who was important to the successful realization of this thesis, as well as expressing my apology that I could not mention personally one by one. 1 am grateful in every possible way and hope to keep up our collaboration in the future.

vi Table of contents

Dedication 1

Arabic abstract ii Abstract tv

Acknowledgement v

Table of contents vii

List of figures xi

List of tables xiii

Abbreviations xiv

Chapter One: Introduction I

1.1 Background I

1.2 Problem statement 2

1.3 Objectives 2

1.4Melhodology / -

1.5 Research outlines 4

Chapter Two: 8051 Microcontroller 6

2.1 8051 Microcontroller Review 6

2.1.1 Why embedded systems 7

2.1.2 Why 8051 microcontroller 7

2.1.3 8051 Important features 8 2.1.4 8051 Programming 9 2.1.5 8051 Related processors 9 2.2 Memory Organization 1°

2.2.1 External Code Memory 11

2.2.2 External RAM Data memory II

2.2 3 Internal Memory 12

2.2.3.1 Register Banks (O0h to IFh) 12

2.2.3.2 Bit Addressable RAM (20h to 2F) 13

2.2.3.3 General Purpose RAM (30h to 7Fh 14

2.2.4 SFR Registers 14

vii 2.2.4.1 Program Status Word (PSW) register 16

2.2.4.2 Power Control (PCON) register 17

2.2.4.3 rimer/Counter Mode Control (TMOD) register 18

2.2.4.4 Serial Control (SCON) register 19

2.2.4.5 Interrupt Enable (IE) register 2 1

2.2.4 6 Interrupt Priority (IP) register 2 1

2.2.4.7 Timer /Counter 1 Control (TI CON) register 2 2

2.2.4.8 Timer/ Counter2 Control (T2C0N) register 2 3

2.3 8051 Addressing modes 2 5

2.3.1 Direct addressing 2 5

2.3.2 Indirect addressing 2 5

2.3.3 Indexed addressing 2 5

2.3.4 Register instruction 2 5

2.3.5 Register specific instruction 2 5

2.3.6 Immediate constants 2 5

2.4 Circuit I lardwarc 26

Chapter Three: Development Tool 31

3.1 Creating a New Project 32

3.2 Building the Project 37

3.3 Debugging the Project 37

3.4 CPU Simulation 39

Chapter Four: Emulation Concept 40

4.1 Writing Microcontroller Code 40

4.2 Translating the Code 41

4.3 Debugging the Code 41

4.3 I Simulators 4 2

4.3.2 Monitors 4 3

4.3.3 Emulators 4 3

4.3.3.1 Emulation control logic and emulation Memory 4 3

4.3.4.3.2 The emulation device 4 4

4.3.3.3 The pinout adaptor 4 4

viii 4.4 Programming Microcontrollers 45

4 4.1 Out -of - Circuit Programming 4 5

4.4.2 In System Programming 4 5

4.5 Emulation Technical Approaches 46

4.5.1 Base unit and probecard 4 6

4.5.2 board Module 4 7

4.5.3 Dedicated emulators 4 7

4.5.4 Emulators Using Microcontrollers 4 7

Chapter Five: Debugging Strategies 49

5.1 Integrated Development Environment IDE Simulator 50

5.2 In System Debugging 51

5.3 Software JSD Techniques 51

5.3.1 Terminal Based General - Purpose Monitor 5 1

5.3.2 Terminal Based On-Chip MSC Monitor Program 5 3

5.3.3 IDE-Based Monitor MON51 5 4

5.3.4 IDE-Based Monitor ISD51 5 5

5.4 Hardware ISD Techniques 5 6

5.4.1 In-Circuit Emulator 5 6

5.4.2 Built- In Debug Module (BDM) 5 7

Chapter Six: Software Developed 58

6.1 Monitor Program 58

6.1.1 Initialization parameters and interrupt vectors 6 4

6.1.2 Serial I/O subroutines 6 5

6.1.3 Main menu and monitor user commands 6 6

6.1.4 Memory Management Subroutines 6 8

6.1.5 Power On and Initialization 6 9

6.1.6 Multiplication and Division 7 0

6.1.7 Multi- Sequence and Compressed Data Processing 7 0

6.2 Pre-design Stage (Structuring and Modularity) 7 2

6.3 Post-design Stage (Maintenance and Modification) 7 2

6.4 Program Development 77

ix 6.4.1 Creating the project 7 7

6.4.2 Building the project 8 3

6.4.3 Debugging the project 8 3

Chapter Seven: Results and Discussion 8 5

Chapter Eight: Conclusion and Recommendations 9 1

References 9 3

Appendix A 9 4

x List of figures

2.1 8051 block diagram 6

2.2 8051 chip using external memory 10

2.3 8051 memory organization 11

2.4 Organization of the 8051 internal memory 14

2.5 Special Function Register layout 15

2.6 Circuit diagram of the 8051 board 28

2.7a Top layer (component side) PCB 29

2.7b Bottom layer (solder side) PCB 29

2.8a Top layout (component side) of the board 30

2.8b Bottom layout (solder side) of the board 30

3.1 Development tool features debugging The Code 32

3.2 Open new project debugging tools 33

3.3 Create a new folder 33

3.4 Select devices for target 34

3.5 Open a new file 35

3.6 Adding file to the project 35

3.7 Selecting file to add to the project 36

3.8 Selecting HEX tile output 36

3.9 Start debugging 38

3.10 Program execution 39

5.1 MSC Debugging Strategies Tree 49

5.2 Block diagram of an IDE simulator Concept 50

5 3 Monitor Conceptual Block Diagram 52

6.1 Parameters initialization 59

6.2 Power on segment 59

6.3 Main menu 60

6.4 a, b Initialization segment How chart 61-62

6.5 asc2hex subroutine 73

6.6 pstr subroutine 74

xi 6.7 Run routine 75-76-77

6.8 Create new project 78

6.9 Make new folder 79

6.10 Select device 79

6.11 Make new file 80

6.12 Add file to targe 81

6.13 Create hex file window 82

6.14 Building process 83

6.15 Debugging process 84

7.1 Building the project 85

7.2 Testing the project 85

7.3 Running of the Help command of the program 86

7.4 Running the displays to see the internal RAM 86

7.5 Display of the clear command running 87

76 Downloading some program 88

7.7 Running some user program 89

xii List of tables

2.1 Different 8051 microcontroller produced by Intel

2.2 Special Function Register names, symbols and addresses

2.3 Program Status Word (PSW) bits distribution

2.4 Power Control (PCON) register bits distribution

2.5 Timer/Counter Mode Control(TMOD) register bits distribution

2.6 Serial Control (SCON) register bits distribution

2.7 Interrupt Enable (IE) register bits distribution

2.8 Internipt Priority (IP) register bits distribution

2.9 Timer/counter Control (TCON) register bits distribution

2.10 Tinier/counter2 Control (T2CON) register bits distribution

xiii Abbreviations

3): Liquid Crystal Display HE: Integrated Development Environment 5C: Micro System Controller ): In system Debugging 0: Input and Output uvT: Universal Asynchronous Receiver & Transmitter ',: Micro Controller »: AG Semiconductors Company fl>: NXP Semiconductors company : Semiconductors company SC 51: Micro System Controllers 1 40S: N channel Metal Oxide Semiconductor K)S: Complementary Metal Oxide Semiconductors D: Central Processing Unit \M: Random Access Memory DM: Read Only Memory I: Kilobyte IZ: Mega Hertz ,abs: Silicon Labs ): lnter-lntegrated Circuit I: Serial Paralegal Interface 5PR0M. Electrically Erasable Programmable Read Only Memory

KB: Universal Serial Bus RVM: Pulse Width Modulation vD: Analog to Digital rl A: Digital to Analog iTC: Real Time Clock : Data Pointer plOM: Programmable Read Only Memory 0-R7: RegisterO - Register 7 PROM: Erasable Programmable Read Only Memory

xiv 5W: Program Status Word K: Special Function Registers >-P3:PortO Port.t Dc: Accumulator Stack Pointer 1: Data Pointer Low byte »H: Data Pointer High byte : Interrupt Priority Control Register : Interrupt Enable Control Register

CD: Timer/Counter Counters Mode Control Register X)N .Timer/Counter Control Register ICON: Timer /Counter 2 Control Register 10: Timer / Counter 0 I ligh byte c Timer / Counter 0 Low byte II: Tinier/Counter 1 High byte

,1: Timer /Counter I Low byte 12 Tinier / Counter 2 High byte 2: Timer / Counter 2 Low byte 2AP2H. Timer2 Capture Register High byte 2AP2L Timer2 Capture Register Low byte JON: Serial Control Register W. Serial Data Buffer JON. Power Control Register 40D: Serial Mode Control Register rtOD: Timer /Counter Mode Control Register J: Personal Computer X)N: Serial Control Register : Interrupt Enable Register : Interrupt Priority Register : Integrated Circuit EN. Program Strobe finable AL: Crystal (CD: Transmitted Data tD: Received Data

xv : Printed Circuit Board C: SI: Compiler for 8051 instructions : Assembler for 8051 instructions P: One Time Programmable DII: American Standard Code for Information Interchange ): Programmable Logic Device F:Zero Insertion Force : In-System Programming 4: Debug Board Module KG: Joint Test Action Group for boundary scan ): In-System Debugging I: Graphical User Interface [: In -Circuit Emulator : Built-in Debugger Module HN51: Monitor program for 8051

: Write JL: Address Latch Enable T: Restart .: Carriage Return : Line Feed Carry C: Escape : Most Significant Byte

B: Least Significant Byte

xvi Chapter One

Introduction

Microcontroller-based systems require knowledge in hardware, in software, and the specific application area. The hardware contains the microcontroller, some memory (optional) and input/output interfaced with external circuitry. These building blocks are found in many commercial applications, for example, main home appliances contain embedded-systems interfaced with keypad and an LCD screen.

1.1 Background

l)e\elopmenl of microcontroller-based applications code is best accomplished in a structured fashion. All major subsystems should be first identified. Program segment and subroutines should be developed and tested for each major subsystem. Prototyping (he subsystems and thoroughly evaluating the code for each subsystem usually save time and effort in the long run. Modularization of the code makes it easier to debug and modify, finally, the subroutines are combined in the end product. It is worth mentioning that the development process which is reduced into only four stages (write code, compile code, debug code and program) is incomplete as it emphasizes on the procedural stages and neglects the essential pre-design stage (structuring and modularity of code) and the pro-design stage (maintenance and modification of code). To explain the idea let us illustrate the development process briefly.

1- Writing code deals with writing the .source program for the application in assembly or (' language. This step is simple if one knows the programming language and microcontroller's architecture ami it's instruction set.

2- Compiling code deals with converting the source code into executable code for the microcontroller to execute.

.1- Debugging code deals with resolving errors and testing it with realistic input to see it produces the desired outputs. Single stepping, or tracing through the code is the optimum method to evaluate the behavior of the code microscopically

I •I- Programming is the last slop in which the code is loaded in microcontroller mentors, or external memory.

1.2 Problem statement

It is very common that in the third stage the programmer discovers errors and returns hack to the first stage to correct the errors and repeat the process. Since the third stage is very crucial in the development cycle and ambiguous, ihis studs is intended to resolve this stage by developing a simple home-made emulator for 8051 microcontroller to assist in the debugging and hence the development process. The neglect of the pre-design stage in which the program is made to be modular, structured and documented makes it impossible for the program to be maintained or modified later on. This point is important because debugging is required to make some modification.

1.3 Objectives

This research aims to produce an 8051 emulator to be used by researchers anil students to:

1- Establish rooted knowledge of emulation technique in development and troubleshooting.

2- Provide cheap and simple tool for development and troubleshooting.

3- Enhance microcontroller based instrument research and development among electronics engineers.

1.4 Methodology

The research is planned to be executed as follows:

I - 8051 Microcontroller study (theoretical and practical).

2- I heorelical suivey in the Held of emulation.

3- Real- time debugging techniques.

-I- Software development tool study.

5- Software development (communication, debugging & presentation).

6- Emulator building, testing & verification. 7- Writing the thesis.

I lie microcontroller 8051 was studied. Many experiments were carried out using assembly language and basic language. Experiments covered using input & output ports, using the counter/timer, using the serial port, measuring sink & source current of different pins, measuring the duration of signals ,and measuring the frequencies of different signal. Investigation on emulation diflerent approaches was carried using the internet. Traditional emulator working with two microcontrollers was studied thoroughly so as to avoid disadvantages in the required design. It worth mentioning that, the research deviated from what is planned in some regards. For instance, it only considered the simplicity in achieving emulation and forgets about dedicated hardware for emulation. Keal lime debugging techniques were investigated because user's program correction and monitoring is a fundamental job of emulator. Debugging strategies were studied also, and terminal monitor option was selected for this research making use Hash microcontroller features. pvision development platform was studied thoroughly, and all the features and capabilities of the tool were investigated regarding project creation, simulation and testing. Many experiment were made using the simulator which simulator all 8051 microcontroller capabilities. Particularly all sections of the software developed were tested using this tool Software developed started with a general terminal program running the host PC to communicate with the emulator. Later serial & parallel communication program with the host PC was fetched and studied thoroughly. Further more a monitor program managing emulation commands was investigated and studied in details. This program used command recognizer which calls lower orders programs called command routines. It worth mentioning that some monitor programs found in the internet were studied for comparison. Using uvision simulator the whole program was checked. In the hardware the research used special design board, which preformed the target CPU. 'Ihen the program was compiled and loaded in the microcontroller for testing & verification and showed excellent results.

3 1.5 Research outline

Beyond this preamble this chapter reviews different chapters of this thesis. Chapter 2 reviews the hardware used in the development process. It firstly presents some information about the 8051 microcontroller regarding it's block diagram, memory organization and the special function register. The use of special function registers in the software to implement serial communication with host l'(' is of is of prime importance, so it is explained in this chapter, lastly the electronic card used to test the overall code performance in the real lime is presented. In chapter 3 Kcil development tool for the 8051 microcontroller family is reviewed. It supports every level of developer form professional application engineer to a student just learning about embedded system software development. It includes C Compiler, Macro Assembler, Debugger, a Ilex Converter. Real Time Kernel, Linker and some Monitors programs all under one Integrated Development Environment (IDE). In the debugger mode the user may use the Simulator which support simulating all features of the 8051 without actually having any target hardware. This feature is used very much for testing all subroutines. The only drawback of the simulator is running not within real time framework. Chapter 4 discusses the Emulation Principles. It starts with the practical development cycle stages and the tools used in the development process. It elaborates on debugging and emulation concept. Then it gives a quick review on emulation techniques. Then it concentrates on emulation techniques with monitor program enhanced after development of On-Chip Debugging facilities and Hash memory. In chapter 5, the modern debugging strategies of Micro Systems Controller (MSC) are reviewed. These strategies range from simulation-based to In System Debugging (ISD). categorized as software and hardware strategies. Chapter 6 of this thesis deals with the Software developed. It shows a general flowchart of the program. I lien it gives a short description for all its subroutines under some headings like, initialization parameters and interrupt vectors, serial I/O subroutines, menu and monitor commands, memory management subroutines, power on and initialization subroutines, multiplication and division subroutines, multi-byte sequence and compressed data processing subroutines. Also it touches program modularity and maintainability. Also in this chapter, the steps of creating the

4 project, building it and finally testing the whole program together, using Keil development tool, is reviewed. In the appendix the source program is given. In chapter 7 results obtained using the programs were reviewed after project building. It is first tested using the development tool for different commands like help command and display internal RAM command. Also testing using the hyper-terminal were manifested after loading the IIF.X llle in the real microcontroller. Chapter 8 discusses the conclusion obtained and points out some recommendations for future work.

5 Chapter Two

8051 Microcontroller

This chapter gives a brief overview of the hardware used. It first reviews the 8051 microcontroller (uC) block diagram, the memory organization and elaborate a little bit on the special function registers, specially those used in interrupts and the serial communication. This is because their relevant peripherals are used in the process of emulation. Other peripheral and their associated special function registers, like I/O ports are left to user to use them as he likes. At the end this chapter will review the electronic circuit used to test the software developed.

2.1 8051 Microcontroller review

The 8051 is an 8-bit microcontroller originally developed by Intel. I here are currently hundreds of derivatives produced by dozens of chip nianufacturcrs.8051 family is widely used today for embedded control applications. The 8051 is an 8-bit micro-controller. The basic 8051 chip includes a number of peripheral I/O devices including two (or three)Timer / Counters, 8- bit I/O ports, and a 11 ART as shown in figure 2.1 block diagram [9].

L.L

'."nv.j

...! j f

t 1 I... -..TOT. , t if if inr

I'igurc2.l 8051 hlock diagram

6 2.1.1 Why embedded systems

Imhcdded microcontrollers tire used extensively in robotics and industry. In this application, many specific tasks might be distributed among a large number of controllers in one system. Communications between each controller and a central would enable in format ion to be processed by the central computer, or to be passed around to other controllers in the system. A special application that microcontrollers arc well suited for is data logging. Stick one of these chips out in the middle of a corn Held or up in a balloons, and monitor and record environmental parameters (temperature, humidity, rain. etc). Small size, low power consumption, and flexibility make these devices ideal for unattended data monitoring and recording. The automotive market is the most important driving force in the microcontroller market. Several microcontroller families were developed specifically for automotive applications and were subsequently modified to serve other embedded applications 118).

2.1.2 Why 8051 microcontroller

The Intel 8051 is a Harvard architecture, single chip microcontroller (pC) which was developed by Intel in 1980 for use in embedded systems. Intel's original versions were popular in the 1980s and early 1990s, but has today largely been superseded by a vast range of faster and/or functionally enhanced 8051-compatible devices manufactured by more than 20 independent manufacturers including Atmel, Infineon Technologies (formerly Siemens AG), Maxim Integrated Products (via its Dallas Semiconductor subsidiary), NXP (formerly Philips Semiconductor). Nuvoton (formerly Winbond), ST Microelectronics, Silicon Laboratories (formerly Cygnal), Texas Instruments and Cypress Semiconductor. Intel's official designation for the 8051 family of uCs is MCS. 51 11 *>|. Intel's original 8051 family was developed using NMOS technology, but later versions, identified by a letter "C" in their name, e.g. 80C5I. used CMOS technology and were less power-hungry than their NMOS predecessors - this made them eminently more suitable for battery-powered devices.

7 2.1.3 8051 Important features

It provides many Functions (CPU, RAM, ROM, l/O, interrupt logic, timer, etc.) in a single package.

8-bit data bus - It can access 8 bits of data in one operation (hence it is an 8-bit microcontroller).

16-bit address bus - It can access 2I(> memory locations - 64 kB each of RAM and ROM.

On-chip RAM - 128 ("Data Memory").

On-chip ROM - -I kB ("Program Memory").

Four byte bi-directional input/output port.

UART (serial port).

Two 16-bit Counter/timers.

I wo-level interrupt priority.

Power saving mode.

A particularly useful feature of the 8051 core is the inclusion of a boolean processing engine which allows bit-level Boolean logic operations to be carried out directly and efficiently on internal registers and RAM. This feature helped to cement the 8051's popularity in industrial control applications. Another valued feature is that it has four separate register sets, which can be used to greatly reduce interrupt latency compared to the more common method of storing interrupt context on a slack |8|. The 8051 UARTs make it simple to use the chip as a serial communications interface. External pins can be configured to connect to internal shift registers in a variety of ways, and the internal timers can also be used, allowing serial communications in a number of modes, both synchronous and asynchronous. Some modes allow communications with no external components. Once a UART - and a timer, if necessary, have been configured, the programmer needs only to write a simple interrupt routine to refill the 'send' shift register whenever the last bit is shifted out by the UART and/or empty the full 'receive' shift register (copy the data somewhere else). The main program then perforins serial reads and writes simply by reading and writing 8-bit data to

8 slacks. 8051 based microcontrollers typically include one or two UARTs, two or three timers, 128 or 256 bytes of internal data RAM (16 bytes of which are bit-addressable), up to 128 bytes of I/O, 512 bytes to 64 kB of internal program memory, and sometimes a quantity of extended data RAM (F.RAM) located in the external data space. The original 8051 core ran at 12 clock cycles per machine cycle, with most instructions executing in one or two machine cycles. With a 12 Mil/, clock frequency, the 8051 could thus execute I million one- cycle instructions per second or 500.000 two-cycle instructions per second. Enhanced 8051 cores are now commonly used which run at six, four, two, or even one clock per machine cycle, and have clock frequencies of up to 100 MHz, and are thus capable of an even greater number of instructions per second. All Sil.abs. some Dallas and a few Atmel devices have single cycle cores. Common features included in modern 8051 based microcontrollers include built- in reset timers with brown-out detection, on-chip oscillators, self-programmable flash ROM program memory, boot-loader code in ROM, EEPROM non-volatile data storage, l-C, SPI. and USB host interfaces, PWM generators, analog comparators, A/D and D/A converters, R'I'Cs, extra counters and timers, in- circuit debugging facilities, more interrupt sources, and extra power saving modes |8|.

2.1.4 8051 Programming

Several (' compilers are available for the 8051, most of which feature extensions that allow the programmer to specify where each variable should be stored in its six types of memory, and provide access to 8051 specific hardware features such as the multiple register banks and bit manipulation instructions. Other high level languages such as forth, BASIC, Pascal/Object Pascal, PL/M and Modula 2 are available for the 8051, but they are less widely used than C and assembly.

2.1.5 8051 Related processors

'I'he 8031 was a cut down version of the original Intel 8051 that did not contain any internal program memory (ROM). To use this chip external

ROM is to be added that will contain the program that the 8031 will fetch

9 and execute. Hie 8052 was an enhanced version of the original Intel 8051 that featured 256 bytes of internal RAM instead of 128 bytes, 8 kB of ROM instead of 4 kB, and a third 16-bit tinier. The 8032 had these same features except for the internal ROM program memory. The 8052 and 8032 are largely considered to be obsolete because these features and more are included in nearly all modern 8051 based microcontrollers.

2.2 Memory Organization

The 8051 device has separate address spaces for program and data memory. I here are separate memories for program storage, internal memory, registers, I/O functions, and external data memory. They each hold up to 64 kilobytes of instructions and data respectively. Its memory is organized in Intes and practically all its instruction deal with byte quantities. The logical separation of program and data memory allows the data memory to be accessed by 8-bit addresses, which can be quickly stored and manipulated by an 8-bit CPU. Nevertheless, 16-bit data memory addresses can also be generated through the Data Pointer (DPI R) register, figure 2.2 shows the external code memory and data memory connected to the 8051 chip |4J.

ADDRESS BUS (16 bit)

•< > ( xl.'lli.il Extent.)! 8051 IIA1 A CODE Ma.-liloly Mommy (KAMI (ROM) K/*4 Control tin**

DATA BUS <0-biO

l/i i Moil, HII Vi

I igure 2.2 8051 chip using external memory

I he 8051 has three very general types of memory. To effectively program the 8051 it is necessary to have a basic understanding of these memory types. They are: External Code Memory, External RAM and On-Chip Memory (internal memory), 8051 memory organization is mapped in figure 2.3.

10 TNT External 8051 chip DATA Memory (up to Internal 0000 64KB) Memory Internal SI Ks FEFF External COOK Internal Memory RAM (up to 0000 64KB)

I igure 2.3 8051 memory organization

2.2.1 External Code Memory

The executable program code is stored in external code memory. This is often in the Ibrm of an external EPROM. The code memory size is limited to 6-IKBytcs in a standard 8051. The code memory is read-only in normal operation and is programmed under special conditions e.g. it is a PROM or a flash RAM type of memory.

2.2.2 External RAM Data Memory

External RAM is memory that resides off-chip and often in the form of static RAM or Hash RAM. This is read-write memory and is available for storage of data. Up to 64KBytes of external RAM data memory is supported (in a standard 8051). Hie External Data Memory space contains all the variables, buffers and data structures that can't lit on-chip. It is principally addressed by the 16-bit Data Pointer (DPI R), although the first two general purpose register (R0. Rl) of the currently selected register bank can access a 256-byte bank of External Data Memory. The maximum size of the External Data Memory space is 64Kbytes. External data memory can only be accessed using the indirect addressing mode with the DP'f'R, R0 or Rl.

11 2.2.3 Ink-null Memory

litis refers lo any memory thai physically exists on the microcontroller itself. The 8051's on-chip memory is mapped in Figure 2.4 below. 'Ihe internal memory is shown divided into three blocks, which are generally referred to as the Lower 128, the Upper 128, and SFR [10]. The maximum size of the Internal Data Memory space is 256-byles. However, different 8051 family members integrate different amounts of on-chip memory as shown in fable 2.1 below. The register implicit, indirect and direct addressing modes can be used in different parts of the Internal Data Memory space. The Internal Data Memory space is functionally the most important data memory space. In it resides up to four banks of general purpose registers, the program stack. 128 bits of the 256-bit memory, and all the variables and data structures that are operated on directly by the program.

Lower 12S hyh'.s: OOh to t I'll Register Banks

20h lo 2Fh Bit Addressable RAM

30h to 7Fh General Purpose RAM

Upper /2.V/m'A'v. XOh to Fill Special Function Registers

Table 2.1 Different 8051 microcontroller produced by Intel

Device Internal Program tetital Data Timer/Counters Interrupt Oscillator Memory Memory (16-bit) Sources squency (MHz)

W5IAII -IK bytes ROM 128 2 5 3.5-12

0C51IJI1 •IK bytes ROM 128 2 5 0.5 - 24

87C5I •IK bytes HI'KOM 128 2 5 0.5-24

•» U'5II A 8K bytes ROM 25<» .i 7 0.5 - 33

80C58 32K bytes ROM 256 3 6 0.5 33

2.2.3.1 Register Banks (OOli to I Mi)

I he lowest 32 bytes are grouped into 4 banks of 8 registers. The 8051 uses 8 general-purpose registers RO through R7. When the instruction is

12 executed, one of the eight registers in the selected bank is accessed. Program instructions call out these registers as RO through R7. Two bits in the Program Status Word (PSW) select which register bank is in use. This allows more efficient use of code space, since register instructions are shorter than instructions that use direct addressing |I0|. All of the bytes in the Lower 128 bytes can be accessed by either direct or indirect addressing. The Upper 128 bytes can only be accessed by indirect addressing.

2.2J.2 Bit Addressable RAM (20h to 2Mi)

The 8051 supports a special feature which allows access to bit variables. Ihis is where individual memory bits in Internal RAM can be set or cleared. In all there are 128 bits numbered OOh to 7Ph. Being bit variables any one variable can have a value 0 or I. A bit variable can be set with a command such as SH IB and cleared with a command such as CLR. for instance:

Sli I'B I5h : sets the bit I5h (becomes I)

( 7/v' /5// ; clears bit 15h (becomes 0)

fhe bit addressing can also be performed on some of the SIR registers, which will be discussed later on. The Bit Memory space is used for storing bit variables and Hags. Hits can only be accessed using the bit instructions and the direct addressing mode.

1.1 AM ' :• li- l>> I... i: "Ft, General i.»u:po>e RANIaie.,. t>0 byte-.

:•. '1; — —— —....— :-ni. 60 IUIEIU.IL y~L~. p :-au •• ~ 50 ...... 4.J SFR-

«0

Iutrl ll.ll 12 RAM ' - :o .ts CD JL. C'O IFK 0 - .BiiO. 1.

0 " :B1: '.i<.: :.:FI. F' -r * 0 " .B.uJ. 1. Register Baulk 0

0 0 ?«E " -••= = - " B.-ul. Mil R*f « •;:Z 05k R«r 5 04b 3eg 4 Oih Re? i a:n Reg I . r.h Reg I OOh 0

l-iuniv 2.-t Oruuni/ation of ihe 8051 ink-mal memorv

2.2.3.3 General Purpose RAM (30h lo 7Fh)

80 Intes oi'lntemal RAM memory are available for general-purpose data storage. Access to this area of memory is fast compared to access to the main memory and special instructions with single byte operands are used. The general purpose RAM can be accessed using by direct or indirect addressing modes.

2.2.4 SFR Registers

The SI R registers are located within the Internal Memory in the address range 80h to I'l'h, as shown in figure 2.5 below. Not all locations within this range are defined. Each SIR has a very spec i lie function. SIRs include the N Port latches, timers, peripheral controls, etc. These registers can only be accessed by direct addressing. Sixteen addresses in SFR space are both byte- and bit- addressable. The Special Function Register space contains all the on-chip peripheral I/O registers as well as particular registers that need program access. These registers include the Slack Pointer, the PSW and the Accumulator.

r\cgi'..:ei-fv>.3p|>eJ Pons

•iailicj^ea tlicrt en;: in OH •> 311

Po/t Pins .£OC'.m''.|:cltC

;ctc.i S.-OI i

ton K..-.0

figure 2.5 Special lunction Register layout

The standard SOS I has four 8 bit I/O ports: PO, PI, P2 and P3. All four ports in the 80C5I are bidirectional. I'aeh consists of a latch (Special Function Registers PO through P3), an output ilriver. and an input buffer. The output drivers of Ports 0 and 2, and the input buffers of Port I), are used in accesses to external memory. In such application. Port 0 outputs the low byte of the external memory address, lime-multiplexed with the hue being written or read, while Port 2 outputs the high byte of the external memory address when the address is 16 bits wide. Otherwise, the Port 2 pins continue to emit the P2 SFR content. All the Port 3 pins are multifunctional. They are not only port pins, but also serve the functions of various special features. I.isl of all special function registers and their addresses is shown in fable 2.2 below

15 table 2.2 Special I unction Register Nantes. symbols and addresses

.__ .... ._ l^jili—.1?— Ace.. . AeeuniulatDL ^register »_ 1*S\\' l'«'M'!!!!' -iW."A \V«»rd .... !T1< ...... !>J«a.lK>!!««.l2l?iJ«a_ ... !>i'!.-... .!,"": H\'c... _. .JSb._ i>!'H ... ._..JiiKhHytc ._ _.H! \*m _. .. _.!'J_ ... !•!«!._._ _ -_V«iL _i'2 aoJl M. Ml

... "I".. . iiiraH .L'rJyrti' VsmM. ... !l: JnitrryiH <•:!»!>!?!«. *i!!U!(>L _a«l__ !M. !'ii!UT'(;oiinter Mode (JojilroL .

' '!'.">•'.'. *VlJ»'V*< .L**.»ll!l.,>i .m. \2( ON Tlnwr/«'«'yv!'2i.:«,.«iL':».>! .!!!" |Wtj^ritt.

... i'l'. ...

JU! !'i»»sr/r^iM!.»y!.L«i

. .111 li^HeT/0>U.»M].].•^»!iiiliiV:•.... m.. I! !.2 .n!nsr^»J!s?jiij|hBj!c_. !L? .._ J«AI'?!! C2 Capture UegJIigj. L»YJe . . K(.'A!'?.L [Li'2 CL'Wuic Reg. Jaw I»vie„ i:A!>. SCON ...... JJsda!.OS>ir«l ._ siuJ!:...... ^naLOalaJJulTcr .-mm..... _. J'^erConlrol _ l?!l._

2.2.4.1 Program Status Word (PSW) register

The Program Status Wort! (PSW) register configures register banks and user defined Hag. fable 2.3 below shows bits distribution in the bit addressable register PSW 11()|.

16 I able 2.1 Program Stains Word (PSW) bits distribution

l'SW7 I'SWl) PSW5 PSW-4 PSW.? PSW2 PSWI PSWU

CY AC It) RSI RSO OV - p

etpi psw inil, 0 ;value/br/>sw (which re}> bank to use)

IIIOV psw, ///».vir /'///'/ initialize program stains word

The first line initializes psw inil variuhle by zero while (ho second line configures PSW by zero making all Hags disabled, and selecting register bank /ero by making register bank selectors (RSO and RSI) zero.

selh psw. 5 ;sel /lag sinee there is display

jnb psw.5, pintl6h ;olherwise jump if no previous display

Here PSW.5 (10 llagt) available lor user) is used to signal previous letter display to continue displaying small characters. It has to be stated that PSW.5 (user defined (lag) is used several time for different tasks.

2.2.4.2 Power ('ontrol (PCON) register

The Power Control (PCON) register configures power consumption mode of the chip whether it is IDLE or in POWER DOWN mode, fable 2.4 below shows different bits distribution in the non bit addressable register PCON |I0|. table 2.1 Power < 'onirol (PCON) register bits distribution

P( C)N7 ('()N() ('ON5 ( ()NI CON? CON2 ('ON 1 CONO

SMOI) -- - (ill CIO PI) 11)1.

IIIOV /Htm, IMxtSO ;coiifi}>iire peon for fast baud (doubled)

17 II is clear Ilial power saving mode is not enabled and only SMOD is enabled which impl} baud rale doubling. Power saving is enabled when battery powered electronic circuits is implemented lor example in data loggers when used in remote areas.

2.2.4.3 Timer/Counter Mode Control (TMOD) register

The 80C51 has two 16-bit Timer/Counter registers. timcrO and timer I. Doth can be configured to operate either as timers or event counters. This is defined by Timer/Counter Mode Control TMOI.) special function register. In this program timerO and timer I are used lo measure the baud-rate of the host PC to start communication with the PC. After measuring the baud-rate and calculating the baud-constant using the following equation

band const 256 - (crystal (12 * 16 * baud-rale))

Timer/Counter Low Byte (II.) and Timer/Counter High Byte (I'll) are loaded with the baud-constant calculated to establish automatic reloading 110|.

<•//• a .clear A

IIIOV till, a .clear timer!) low byte

IIIOV tht). a .clear limerO high byte

mov ill. a .clear timer I low byte

IIIOV l/il. a ;clear timerl high byte

The upper five lines initialize 1'1.0,'f 110. II. I and II11 with zeros to start measuring the baud rale for example.

IIIOV a. ill) .•move tiinerO low byte to A

IIIOV rl). a .move A content lo rO

IIIOV a. l/iO ;movc limerO high byte to A

IIHIV rl. a ;move A content to rl

The upper four lines load (he measurement result into rO and rl.

IIIOV till, a ;move the reload value to till

18 mov ill. a ;mo\e the reload value to til

The tipper two lines reload time I with some value to start counting down.

The Timer/Counter Mode Control register (TMOD) configures timer/counter. Table 2.5 below shows bits distribution in the non bit addressable register TMOI).

I able 2.5 Timer/Counter Mode ( onlrol( I'MOD) register bits distribution

TMOD7 "MOIM) MOD5 MODI 1 MOD'S MO 1)2 MODI I'fvfODO

GATI: (7! Ml Ml) li.Vli: (7T Ml MO

Timer//1 Timei7/()

IIIOV tinod. Ii0x2l .set timer III for H hit auto-reload and limeiilOJiir 10 hit auto reload mode

2.2.4.4 Serial Control (SCON) register

The Serial Control (SCON) register configures the serial port. Table 2.6 below shows the different bits distribution in the bit addressable register SCON 110|.

I'able(2.6) Serial Control (SCON) register bits distribution

SCON 7 SCON<> SCON5 iC< )N4 SCON.3 CON2 SCONI JCONO

SMO SMI SM2 Kl-N ins RH8 II Rl

Our program configure the SCON twice, once at the begining of autohaud subroutine.

mov scon, 110x42 -.configure scon for Shit var-baud, receive disabled

fhe second at the end of autohaud subroutine to set the new baud-rate

Mov scon. 110x52 .configure serial port control

Now REN is enabled for receiving data through the serial port cin: jnh ri. cin :loop if receive interrupt flag not set

clr ri ;clear receive interrupt flag

I1) In the first line the program loop until receive interrupt is high; when it is high, it clear it in the second line and continue cin subroutine processing. coul: jnb //', caul .display it

clr ti .clear transmit interrupt

In the first line the program loop until receive interrupt is high; when it is high, it clear it in the second line and continue coul subroutine processing. The serial port receive and transmit registers both access the serial buffer SBUF. Writing to SBUF loads the transmit register, and reading SBUF accesses a physically separate receive register. cin: jnb ri. cin .loop if receive interrupt flag not set

clr ri .clear receive interrupt flag

mov a. sbuf .put serial buffer into A

ret .return

In cin subroutine sbujcontent (which is coming from the serial port) is moved to A for further processing. coiit: jnb ti. cout .display it

clr ti .clear transmit interrupt

mov shut, a :put A into serial buffer lo send

ret .return while in cout subroutine A content is moved to sbufio be sent by the serial port.

It has to be stated that the program developed has very limited use of special function register and only when very necessary so as to spare them for the user program developed by the developer. Also the register used should not be modified in the user program to avoid eon diet. This means the baud rate specified should he kept. The resources used for example like the serial port should not be used by the developer as it is specified for communication with the host PC at a certain baud rate.

20 2.2.4.5 Interrupt Enable (IE) register

The 80C51 provides 6 interrupt sources as follows:.

External interruptO (IE0)

External interrupl (IEI)

TimerO overflow interrupt (TEO)

Timer I overflow interrupt (TF1)

Timer2 overflow interrupt (TE2)

Serial port interrupts (Rl or TI)

These interrupt are enabled by the bit addressable. Interrupt Enable (IE) register as shown in Table 2.7 below [10].

Table 2.7 Interrupt Enable (IK) register bits distribution

IE bit No. IB7 11-6 11-5 II-4 113 1122 ii:i

Interrupt Name ; - - n 2 Rl or T TP I ii: i no IKO

Enable Signal KA - KT2 l-S i:ii I:XI irro •:xo

*EA= Enable All

** All bits arc set by the programmer.

clr a .clear A

mov ie, a ;reset interrupt enable register

The above two lines disable all the interrupts by putting zeros in all IE bits

2.2.4.6 Interrupt Priority (IP) register

All interrupts are internally prioritized as follows INTO. TEO, IN'I'I, TF1 and lastly the serial port interrupt (Rl or TI). But any interrupt source can be individually programmed to one of two priority levels to achcivc some kind of flexibility. These interrupt are prioritized by the bit addressable Interrupt Priority (IP) register as shown in Table 2.8 below [10].

21 table 2.S Interrupt I'rioiilv (II') register bils distribution

II' bit No. 11*7 Il'o Il'5 ii'-i IIM ll'2 IIM 11*0

IciTiipls hit name 1-2 priority K lor II 1 priority 1:1 priority 10 priority ;() priority enable enable enable enable enable - - >ril) enable

IlilsMllllol - - t* r> I'S I'll l»XI HX) l'XO

Since all interrupts are already prioritized by hardware as mentioned above, there might be no need for making some priority changes by software.

clr a :clear A

niov //>, a ;re\cl interrupt priority register

The above two lines enable the hardware priority as they clear all IP bits

2.2.4.7 Timci7( 'ounterl Control (IX ON) register

The External Interrupts INTO and IN'l'l (1F.0 and WW) can each be either level-activated or edge-activated, depending on bits I TO and I'll in register ICON. The Hags that actually generate these interrupts are bits IF.O and 1H1 in ICON. When an external interrupt is generated, the llag that generated it is cleared by the hardware when the service routine is vectored. TimerO and timer 1 overflow interrupt (I TO and IT I) are both activated by run bit-command TRO and IR1 in register I'CON. The flags that are generated are bits TFO and IT I in register ICON |10|. These interrupt are enabled by bit addressable Interrupt Finable (III) register as shown in fable 2.9 below.

I able 12.')) I iniei i-uunler ( ontiol t I ('ON) register bits distribution

'let>N hit No. ICON7 ()N(> ICON5 K'ON-l ICON? ICON2 'I'CON 1 TCON0

InliTiiipls bit III IT inn ITU 1II) run II. 1 flag 11:1 edge or 11:0 flag 1:0 edge or inline Overflow Dill overflow emit level level

Hap llag triggered riggered

Hit SMIIIXII III IKI 1 ID IKI) II 1 III MO 110 * Kun command signals arc enabled by programmer (software)

* Edge or level signals are determined by programmer (software)

* Overflow flags are set by hardware when there is overflow and is cleared by hardware when interrupt service starts.

* Edge flags arc set by hardware when there is interrupt and is cleared by hardware when interrupt service starts.

Our program for example command timer I to start timing by the following line when it is measuring baud rate

setb //•/ ;now we're timing it

It also cheeks whether timer I ovelllows by the following line

aulob2c:jb If I, auiobl :clieek for timeout while waiting

It starts limerO at a certain condition by the following line

vi7/> trO .start liming last -I bits

It stops limerO for some reason by the following instruction

• I : ! i i • ;I op t. i iih.- 1 0

2.2.4.8 Tiinoi7('ounter2 Control (T2CON) register

Timer/eounler2 is not available in all 8051 microcontrollers particularly old ones. It is found in 8052 chips. It offers a third timer/counter beside timer/counterO and timer/counter I. All timer2 configuration bits are within T2CON register as shown in fable 2.10 below 110|.

I able 2.10 rimcr.Vuimter2 Control ( I 2CON) register bits distribution

h'on t)ii n.i l.'l ON7 i;roNi. IJl'ON> .H ONI 21'«)N2 JMONI T2CONO

I'll lumie 1 line i \i i la.' < Koeeiu- ll.ilr.nill 1 xt llaj' Slail oi ('oimlci line i» reload

eiialilo lliif. meillnu CIJ-lllIC Ol rliK-k eloek stop HI Inner

Iclil.hl)

llas>

till h>nilnil II -J 1X12 IUI K ICI K .XI N2 TR2 iv r C1VKI.

Reside timer2 configuration 12CON contains other bits as follows

23 *

*EXEN2 bit determine capturing or reloading occurs by a signal at timer external input (I'2MX).

* I (IK bit determine serial transmission clock (whether timer I or Iimer2).

*R('I.K bit determine serial receiving clock (whether timer I or timer2).

*l XI 2 bit determine whether capturing or reloading is due to T2 or T2EX.

It has to be mentioned that the program developed used timcrO and timer I overflow interrupts lo measure the host computer baud rate during jiowcron subroutine only. Also it uses serial port interrupt during communication with the host, lo use any of the interrupts in the 80C5I family, (he following steps must be considered.

1. Set the I-A (enable all) bit in the Hi register to I.

2. Set the corresponding individual interrupt enable bil (EXO, 1:10. EX I, ET1, l-S and li I 2) in the Hi register to I.

3. f inter overflow interrupt (lit), III and 11'2) have to be started by bits in IXX >N (TRO and IRI) and T2CON (TR2) while serial port interrupt (RI or Ti) and external interrupt (Hit) and Hi I) do not need starting.

4. External interrupt (110 and IE I) have to defined whether they arc edge triggered or level triggered within ICON by bits (110 and ffl).

5. Begin the interrupt service routine at the corresponding vector address of that interrupt.

6. Serial port interrupt Hags (Rl or TI) has lo be cleared (bits in SCON) by software after the transmit or receive operation, while external interrupt flags (11-0 and IE I) in ICON and timer overflow interrupt flags (TEO, TE1 and TE2) (within IX ON and T2CON) are cleared by hardware when the interrupt routine is serviced.

7. Interrupts priority may be modified by bits (PXO, 1T0, 1WI, IT1. PS and 8. Timer overflow interrupt (TEO. II'1 and TE2) are delected by flags within ICON andT2CON.

«>. External interrupt (IEO ami III) are detected by flags within ICON.

10. Serial port interrupt (Rl or 11) is detected by flag within SCON.

2.3 8051 Addressing modes

All members of the 8051 family executes the same instruction set which is optimized for 8-bit. It provides a variety of addressing modes for different memory types. Ureif definitions of these modes are as follows |8|:

2.3.1 Direct addressing:

'The address of the operand is specified by an 8-bil Held in the instruction (only for internal RAM and SERs).

2.3.2 Indirect addressing:

1 he address of the operand is specified by a register. Used for both internal and external memories. RO or Rl arc used for addressing.

2.3.3 Indexed addressing:

The address of the operand is specified by DPTR or PC. It is used only for program area for reading look-up table.

2.3.4 Register instruction:

Contents of RO through R7 in the current register bank can be accessed by these instructions.

2.3.5 Register-specific instruction:

Contents of certain register like Ace and DPTR are accessed by these instructions.

2.3.6 Immediate constants:

The value following the opcode (//constant) is operated with the Acc or DPTR.

25 It worth mentioning that the programming instructions deals with arithmetic operations, logical operations, data transfer operations. Boolean operations, jumping and calling operations. Details information are available in instruction set.

2.4 Circuit Hardware

The hardware used is a simple circuit consisting of an 8051 microcontroller beside some necessary items as shown in Tig 2.6 below. The different items are as follows:

1. 8051 microcontroller, dell tied by UI.

2. 7411( 'TOO dual input NAND gates, defined by U2 (for making RAM like R( )M containing the code as the PSEN is active when fetching the opcode).

3. 7411( I 573 octal D latch, defined by 11.3. I his is for latching the lower address byte to the memories as lower address byte and data are multiplexed on porlO.

4. 27C512 normal or 301 512 Hash ROM. defined by U4 (pin compatible ICs, even different si/e are also possible, depending on user program size).

5. 6264 static RAM (64Kbit), defined by D5 (pin compatible ICs, even different size are also possible, depending on user data size).

6. 24COI IIC protocol Ef PROM, defined by U6.

7. PCI 8583 real lime clock, defined by 117.

8. 74 I IC'f 10 triple NAND gate, defined byU8 (for decoding and Hash writing).

9. 7805 voltage regulator, defined by 110.

10. 11.006MHz. XI Al for the microcontroller.

11. 32.768 KHz for real time clock.

12. BC857and BC847 transistors for buffering TXD and RXD signal to the serial port, defined Ql and Q2.

13. Some resistors, capacitors, diodes and connectors.

The schematic drawing of the circuit is shown in figure 2.6 on the next page. While the circuit is built.on a double side Printed Circuit Board (PCB). The 26 component side and the solder side arc shown in Figure 2.7a, Figure 2.7b while the layout of the components side is shown in Figure 2.8a while the layout of the solder side is shown in Figure 2.8b below.

27 Figure 2.6 Circuit diagram of the 8051 board

28 Figure 2.7a lop layer (component side) IV B

Figure 2.7b Bottom layer (solder side) PCB

29 32.76BkHz f D311 — Ul B0C32 at U5 62296 J3 0.1

12pF G PCF8583 RX

..LI

TV 3k8' Ta&i.:: n CZ12'»C0'. 1N100? O-UDKrt 74HCT673 11095

U2\. PCB051 filitrr" JP2 22quLi25iD L |X2 xi 1 33pF

Figure 2.8a I op layout (component side) of the board

8MN11 Sr830 mi £1 3K3 r::::i to I-1 001 n exe [ZD 6&31—J 1.0 It tr oat F .....

1.0 B 001 [ZD 001 001 CZD luOl

figure 2.8b Bottom layout (solder side) of the board

30 Chapter Three

Development Tool

uVision is a standard Windows; application and an integrated software

development platform that combines a robust editor, project manager, and make facility.

uVision supports all of the Keil tools for the 8051 including the C compiler, macro assembler, linker/locator, and objeel-HKX converter. uVisiou helps expedite the development process of embedded applications by providing the following [5]:

Full-featured source code editor.

Device Database for pre-conllguring the development tool setting.

Integrated make facility for assembling, compiling, and linking your embedded applications, and Dialogs for all development tool settings.

True integrated .source-level Debugger with high-speed CPU and peripheral

Simulator.

Links lo development tools manuals, device datasheets & user's guides.

Using Keil Software tools, the project development cycle is roughly the same as it is for any other software development project [5j.

\. CtevWe a pvotacA Vo seAce\ \\\e W>5>\ vtastae vmi\ \Y»e tool settings.

2. Create source Files in assembly or C. .1 )hri)()y

5. Test linked, aoplicauon.

The development . cle described above may be best illustrated by different software of

Keil development tool features as shown in Figure 3.1. The uVision screen provides the

user with it menu bar for command entry, a tool bar where the user can rapidly select

command buttons, and windows for source files, dialog boxes, and information displays.

jiVision lets the user simultaneously open and view multiple source files. The menu bar

provides the user with menus for editor operations, project maintenance, development

tool option settings, program debugging, window selection and manipulation, and on•

line help. The Watch window lets the user view and modifies program variables and lists

.31 the current function call nesting. The contents of the Watch Window are automatically updated whenever program execution stops. The user can enable View "Periodic

Window Update" lo update variable values while a target program is running. The

Memory window displays the contents of the various memory areas. Up to four different areas can be review in the different pages. The context menu allows the user to select the output format |5|.

fl* k*>3» E«HW COW &%JC" ttcO "3h a c p j «t * «s: a ;»I si 8 h fr* t: | * it«\M vv'&tM: jll , Work• T^S. 1 -IS DQ02Q9K PWOOIWI Pioiect H 000209E0 CMO space WiiMOW 531 ) •11 OHM 3.« uuntf ( • II ATIUIURO RI«» III d- i II aan?03rt M.4.M • ID IIUU2U31C lour hhiU |! 131II) i 54s 1 *iitpi«y • I: -9 00020W1 RCR» waiU («di«?i*i') : 8 01030400 NOT »«4«tir* dt*i>'.*y (dttrwit) - -7 00112052c oeroiioo I I I Ntlli« IMplrty • ii pun-.t ( ".i. use l mruiMl.i OTOONIL) JI OiFDOO.L.OIIN: wklU (adi«»loy)i 'iWUtimil JO UlHllK>.l.tllU2ll. PuiiimeiaiM l>:*ln*.f ('".t.Lt.it l!«.jui nlil to (adi&Ploy): at.xtfl.9 - 1; : B&oarEio JB OIFMIO.I.O«02O: Wafc/V I....I. »KLTN (Mdovplwyl: NILINI iiiii Ca« ffi203i? MIISFEIO JB HiP|HII.I.NT«?O: Sracfc ' aAiiaitiB IB niFCinn/".niO?o!i2 •.asm. ill.play (i.lr.nt); ICT'.'irMh M.F7IIIU0 MIIV U7.*>JftQUIU I 2007

I 0 j start aoAKsr^aoit

i Memory Display cmr»

MVIitKIA. It' VO 00 I

>Ml:on oo 30 oo « I004101C- 00 11)04102:.. 00 00 (_ >OOU02£; 00 00 00 00 00 00 00 G 19041037. 00 00 00 IT 00 oo oo T >9041O4Ompiuiw*. ni00t 0ii0n 0on0 0ty0i 0iu0i 0»H0 iwOOi 0 | • |. F.U«LL^'.>'J.LI«>/L».L.L*,\F<•£»*/ »A04t\< *.04[ J»^f.lli«tiifM^U«Ti» 00 tr 00 00 00 00)»• 0/0 <

I igure .1.1 Development tool features

3.1 Creating a new project

pVision includes a project manager which makes it easy to design

applications for the 8051 family. The user need to perform the following steps to create

a new project:

Create tt new design project. Select New Project from the Project pull-down menu as

shown in Figure 3.2 below |5).

.32 BP

J

Figure 3.2 ()pen new project The user will prompted to ehose a name for his new project. It is preferred that the user, create a separate folder as shown in Figure 3.3 below, where all the files of his project will he stored. The user should choose a name and click Save.

Create New Protect

Save tn: |, )EST "3 © d* 11»

5j];lest1 Uv2

F::e name: | Teitl' Save

3 Cancel

figure 3.3 Create a new Colder Hie following window will appear, where the user will be asked to select a device for Target 'Target 1': as shown in Figure 3.4 below [5| I !

figure 3.4 Select devices tor target from the list at the left. The Select Device dialog box shows the uVision device database. The user should select the microcontroller he wants to use. When the user clicks OK to continue, a new pop-up window will appear. It will ask whether the user would like to copy the standard 8051 startup code to the project folder. The user should select Yes when prompted to add the start-up code to the project folder. The STAUTUP.ASl file is the startup code for most 8051 CPU variants. The startup code clears the data memory and initializes hardware and reentrant stack pointers. In addition, some X051 derivatives require a CPU initialization code that needs to match the configuration of hardware design. Then using the file menu the user can open a new file as shown in figure 3.5 below or he may open an old one. If the file is new the user should print his code in the window and save it with .asm or .(.' extention.

34 m

i"-: IF. t.^c: Let-, j 'i.^-e jj JC-OS I-CS . tisv |lM rM •i-fl ...

o;c:: ".*.<..• H.os = J5I6H.J,.- .... •••iiijp 1 1

Ml

r

figure i5 open a new file Now lhe source code is ready, but it lias not been added to the project. To add the source code to the project, the user should right-click on Source Group I and select Add files to

Group 'Source Group /' as shown in figure 3.6 below.

US

,5; iJ= U (J ha ..-I '.A jni|!ai •»

T.M C.'J .•.V.JTaryet 1

«T~' "

j ATM ME* LO GROUP 'SOUITE CIIOUP 1'

i I

lit; 3.6 Adding tile lo (he project A pop-up window will appear. The user should select the file he created to add or any

oilier file as shown in figure 3.7 below, and then, click on Add to add the file to the group. I'ig 3.7 Selecting file to add to the project

The user should cheek Create HEX File to enable the program to create hex files. This have to be turned ON manually to generate IIKX files. The user should make sure it is turned ON, by right-clicking on target I » Options for target 'target I', then under the 'output tab, by checking the box 'generate IIKX file' as shown in Figure 3.8 below. This step is very important as the 11HX file is the compiled output of the project that is going to be transferred to the microcontroller.

Pl'tiCiii* J°rIflJBet'Jj»n!et.t.' ,

I" Gc£e Batch fit

Or. | j Defaults |

I'igure 3.8 Selecting III!X file output

36 3.2 Building the project

Before testing the source code, the user has to compile his source code, and correct eventual syntax errors. In Kfill. I DPI, this step is called 'rebuild all targets' and has this icon: lt*l. When building an application with syntax errors, uVision will display errors and warning messages in the Output Window - Build page. A double click on a message line opens the source file on the correct location in a uVision editor window. After testing the application, it is required to create an Intel HEX file to download the software into an liPROM programmer or simulator. uVision creates HEX files with each build process when Create HEX file under Options for Target - Output is enabled. The build target toolbar button translates only modified or new source files and generates the executable file. pVision maintains a file dependency list and knows all include files used within a source file. Even the tool options are saved in the file dependency list, so that pVision rebuilds files only when needed. With the Rebuild Target command, all source files are translated, regardless of modifications [5|.

3.3 Debugging the project

,pVision Debugger will lest the applications developed using the C51 compiler and A51 macro assembler. The uVision Debugger offers two operating modes that arc selected in (he Options for Target - Debug dialog: Using Simulator allows you to configure the p Vision Debugger as software-only product that simulates most features (if the 8051 microcontroller family without actually having target hardware. The user can lest and debug his embedded application before the hardware is ready. uVision simulates a wide variety of peripherals including the serial port, external I/O, and timers. The peripheral set is selected when you select a CPU from the device database for your target. After clicking on the debug icon'-U , the user can start debugging as shown in figure 3.0 below. The user will notice that some part of the user interface will change, some new icons will appear, like the run icon circled in the following figure |5J:

37 Qfile £dit y.iew £roje« £«t»ug Fljsh Pejipherals loots £VC8 JJindow flelp

•m fe^puHS «a *

Target I 01 1 T4>.j«t; I 02 j H : Sourc* Group 1 03 04 I 05 08 0/ 08 »:::r 09 10 11 K:K;I 12 ii, ».;-:.r 13 14 15 16

JUJ I'iguie .>.') Start debugging I he user can click on Che 'Run' icon and the execution of the program will start as shown in I'igure 3.10 below. The user can see the behavior of the pin 0 or port one, but clicking on 'peripherals, I/O ports. Port 1'. The user can always stop the execution of the program by clicking on the stop button ( 'O ) and can simulate a reset by clicking on the 'reset' button Kit. The user can also control the execution of the program using the following icons: ^ ^* ^ which allows following the execution step by step. Then, when

finished with the debugging, the user can always return to the programming interface by clicking again on the debug button ('-'l ).

3X Qfi'« Id* J£i*w PioJ«ct £ebu.j Flijh jp«riph«rjlj} Jooli §VCS Jgindow fcjgle

, ;v;j .| 'l/O-Puitt Port 0 Portl 01 Timer Port J 02 Port 2 Oi 04 >:r. *: 05 lu', 0/ 00 09 10 OH ci. :i.: 12 ti:: 13 14 IS 16 .^1

I Symbols H=] test .asm

Load "C: \\electr"onTc3 Name Value

13. &SM ASSIGN jrj iUWttK.-...A7«JliU J

I -'inure 3.10 I'lounini execution

3.4 CPU Simulation

(iVision simulates up ti) 16 Mbytes of memory from which areas can be mapped lor read, write, or code execution access. The uVision simulator traps and reports illegal memory accesses. In addition to memory mapping, the simulator also provides support for the integrated peripherals of the various 8051 derivatives. The on- chip peripherals of the CPU selected are configured from the Device Database selection the user have made when he created his project target [5 j.

39 *

Chapter Four

Emulation Concept

Developing software and hardware for microcontroller-based systems involves the use of a range of tools that can include editors, assemblers, compilers, debuggers, simulators, monitors, emulators and programmers. To the newcomer microcontroller based system development is often not clear. How all these different components play together in the development cycle? And what are the differences for example between emulators and simulators? To complicate matters more, there are quite different approaches and technologies for emulation available that make it difficult for embedded system engineers to choose the right tools. Good approach for understanding the tools is the review of the development cycle which is reduced in the

following four steps 11 f> |.

1. Writing the code

2. Translating the code

3. Debugging the code from mistakes

4. Programming Hash or OTP (One Time Programmable) memory of the microcontroller

The cycling is clear coming from the nature of the process which indicates that whenever a mistake is discovered (which is always happening and several times) the whole process is repeated again. Therefore the development tools mentioned above are used in all these four steps of the process as follows:

4.1 Writing microcontroller code

Software code for a microcontroller is written in a programming language (often Assembler or C). This source code is written with standard ASCII text editor and saved as ASCII text file. Of course programming in Assembler requires learning the microcontroller specific instruction set (assemble mnemonics) and result in compact and fastest code. A higher level language like C is independent of a microcontroller

specific architecture, but requites controller specific extensions to the standard Imgunge to be able to control all of the chip's peripherals and functionality. The code yielded is

40 portable and fast to develop but the penalty is larger eode size (40% compared to assembler). This will require more space and the program will run 40% slower than assembler code. Also the programmer has to be familiar with the C language.

4.2 Translating the code

The source code needs to be translated into instructions the microcontroller can execute. The microcontroller instruction set is represented by op codes which are Unique sequence of bits (zeros and ones). These op codes are decoded by the microcontroller's instruction decoder logic and then executed. Instead of writing op eodes in bits they are commonly represented as hexadecimal numbers, where one hex number represents four bits within a byte. So it takes two hex numbers to represent eight bits (one byte). For this reason microcontroller code in machine readable form is also called hex code and the file that stores that code is called hex tile. Assemblers or C compilers translate the source code into "hex code" that represents machine instruction "op codes". To support modular programming useable libraries of codes most assemblers and compilers come with linkers and librarians. I-inkers are used to link code modules saved in different files together into a single final program. At the same time they lake care of chip's memory allocation by assigning each instruction a,memory address in such a way that different modules do not overlap, librarians help to manage anil organize a library of re usable code modules. Once the ASCII source code text file has been assembled (with an assembler) or compiled (with a compiler) and the files has been linked (with a linker), the output results a number of files that can be used for debugging the software and programming the actual microcontroller memory.

4.3 Debugging the code

A debugger is a piece of software running on the PC, which has to be tightly integrated with the emulator used to validate the code. For this reason all emulator are accompanied with their debugger software. I "Jul also some compilers include debugger, which work with certain emulator. Debugger allows the download of code to emulator memory and then control all the function of the emulator from the PC. Common debugging feature include the capability to examine and modify the microcontroller's on-chip registers, data and program memory; pausing and slopping program execution

41 at dc/incd program locations by setting break points; single stepping (execute one instruction at a time) through the code: and looking at the history of executed code. So far text editor, assembler, C compiler, linkers, librarian and debugger are mentioned. This can become a big challenge to alternate back and forth between all these programs during the debugging process (discover a bug, edit the source code, compile it again, link it again, download the modified code again to the emulator, and so on). This is where an Integrated Development Hnviroiunent (IDH) comes in. An integrated development environment puts all of the previously discussed software components under a common unified User Interlace, so that it become possible lo make a code change and get the modified code loaded into the emulator with a few mouse clicks instead of dozens. A good IDH allows for example, lo click on a syntax error message produced by the compiler and have the source code with the highlighting offending instruction pop-up for editing the text editor. One click of a button and the modified code gets translated, linked, anil downloaded to the emulator. An lDli stores the configuration setting for the project such as compiler switches and so on, so as to recreate easily the project later. When it comes to debugging code and testing applications, there are different tools that can be utilized. 'I'hey differ in development time spent and debugging features available. These are simulators, monitors and emulators. •

4.3.1 Si in ula tors

Simulators try to model the behavior of the complete microcontroller in software. Sonic simulators go even a step further and include the whole system (simulation of peripherals outside the microcontroller). No mailer how fast the host PC is, there is no simulator on the market that can actually simulate the microcontroller behavior in real-time. Simulating external event can become a time consuming exercise, as the developer have to create "stimulus" files that tell the simulator what external waveforms to expect on a particular microcontroller pin. A simulator also can not talk to the target system, so functions needed by external peripherals are so difficult lo verify, for that reason simulators are best to test algorithms that run completely within the microcontrollers (such as math routines). They are the perfect tools lo complement emulators for large development teams, where buying an emulator for each developer is financially not feasible.

4.3.2 Monitors

Monitors commonly bundle hardware boards anil in-system programmer with some software components (assemblers, linkers, debugger and code-size limited compiler). They allow very basic emulation and debugging functions. They are usually with Hash-based microcontrollers, as they allow an actual microcontroller to emulate itself. This is done by including in-system programmer to download the code into the Hash and execute it. The monitor code in the hardware board allows stopping of execution (break) and examine memory. Of course, it uses some of microcontroller's resources (interrupts, stack memory, data memory and some pins). That is why this approach is called intrusive or non-transparent emulation.

4.3.3 I'mutators

An emulator is a piece of hardware that ideally behaves exactly like the real microcontroller chip with all its integrated functionality. It is the most powerful debugging tool of all. A microcontroller's functions are emulated itt real-time and non- intrusively. An emulator by definition always works transparent or non-intrusively. This means none of microcontroller's on-chip resources or l/O pins are lost due to emulation. If emulation is non transparent, then it is not an emulator, but an evaluation board. When developing a project of medium complexity, a non-intrusive emulator will save a lot of time and effort.

All emulators contain three essential functions in different implementation forms:

I - The emulator control logic and emulation memory

2- The actual emulation device

>- The pinoul adaptor

4.3.3.1 ICiiiulatioii control logic and emulation memory

Control logic is the more difficult and expensive part of emulators, as it is required to recreate functions that might be lost due to the emulator using these

43 resources (in other words, some standard I/O pins). My recreating such functions with additional logic, emulators work truly transparent and non-intrusive. This means all the pins, all the memory, and all the peripherals functions available like with the real microcontroller. I'veu more, control logic is required to implement emulator features such as break points, external event, single stepping, loop counters and trace memory.

An emulator uses external static RAM for the emulated program memory, because ROM and Oil* (One Time Programmable) memories are not suitable due to program changes. RAM memory allows the code to be changed quickly and an "indefinite" number of times during the software debugging process. For flash based microcontroller which grantee 1000 times of reprogramming, Hash memories are used for emulation despite their limited life-time and low speed for the sake of price.

4.3.3.2 The emulation device

Emulators typically vise external RAM memory for program storing. Hence it becomes apparent that, they can not use standard sample of the emulated microcontroller for emulation purposes. They need special bond-out chips of the microcontroller to be emulated. Those bond-out chips have additional pins that allow the emulator electronics to feed the external stored program information to the microcontroller instead of the on-chip memory content in standard microcontroller. Also they control program execution (low and access on-chip registers and data memory. Instead of special bond-out chips, some emulators manufacturers program the microcontroller's complete functional model into a PIT) (Programmable Logic Device).'! he main drawback of this approach is; how accurate will the PI.l) model of the microcontroller resemble the real standard microcontroller. Anyway it works in real-time with models of less complexity and slow speed. On the positive side, such emulators can easily be reconfigured to support many different derivatives of a microcontroller family.

4.3.3.3 The pinout adaptor

A pin adaptor gives the emulator's target connector, the same "package" and pinout as the microcontroller to be emulated. Most emulators give a range of choices of

44 exchangeable pin adaptors that supports the exact derivative and package of your specific microcontroller.

4.4 Programming microcontrollers

The last step in the development cycle is programming the chip, lo carry out the job needed in the target hardware. Microcontroller programming depends on the chip version whether it contains Hash memory or OTP (One Time Programmable) memory. It is also classified according to the chip's position IN or OUT-of the target hardware as follows:

4.4.1 Out-of-C'irciiit Programming

OTP microcontrollers are typically programmed out-of-circuit. That means the chip is programmed before being soldered in the target board, for this purpose production grade programmers are needed; which arc special programming hardware similar to standalone fPROM programmers. Programming process is carried through a parallel bus of address lines, data lines, control line and 1IV programming voltage line, therefore programmer are connected to the parallel port of the driving PC and microcontroller programming utility is invoked. These programmers offer the choice of optional, high quality, expensive, zero-insertton-foree (ZIP) pin adaptors to support different packages.

4.4.2 In-Systcm Programming (ISP)

flash microcontrollers can be both in-circuit (in-system) and out-of-circuit. In-circuil programming means that, the microcontroller is already soldered into the target hardware and can be programmed via one of its communication interfaces ('HART, SIM). Ibis requires that, the signals needed for programming routed to an in- system-programming (ISP) connector. ISP connector required varies from one microcontroller lo another, so it is recommended that, before the PCI! layout is made, which ISP connector required is decided. ISP process is done via the serial port of the driving PC, therefore it is slower than out-of-circuil programming. But on the other hand, ISP has some advantages as follows 116]:

1- It programs code and data memories.

45 2- It allows upgrading the system without disassembling.

3- It allows code incryplion and protection.

4- There is no need for expensive socket adaptors.

4.5 Emulation Technical approaches

Since development of microcontrollers, not only their unit volume has been increasing over years, but also their application has been increasing too. One main problem that has arose in using microcontrollers dealt with debugging • systems incorporating these devices, since their program memory and data memory are integrated inside the chip. I'mutators are designed to solve these problems. They are used to design and run program outside the microcontroller memory to control the process and discover the bugs. I''initiator used different approaches that can be reduced in the following

4.5.1 Base unit and I'robecard

Many emulator consists of a base unit and probecard (the base unit is connected to a IV via the serial, parallel or USB port) It contains the majority of emulator electronics (emulation control logic and emulation memory), with the exception of the emulation chip it self. The emulation chip is a special bond-out version of the actual microcontroller and mounted on a separate small PCB, called the probecard. This probecard connects via a ribbon cable to the base unit, and has a pinout adaptor at the bottom, which allows the probecard to be plugged into a socket on the actual target board in place of the actual microcontroller. The advantage of partitioning the emulator into base unit and probeeard is that, one base unit can support many different derivatives of the given microcontroller architecture (for example, all 8051 devices). \\y purchasing different probecards the emulator can then be changed to support all the on-chip features and packages of the specific microcontroller derivatives. Another advantage is that the probecard can be kept relatively small, which make it easier to plug into the target in space constrained applications. I'robecard approach also minimize the physical distance of the emulation chip from the location of the final microcontroller, minimizing the impact of noise and additional capacilive and resistive

46 loading dial can become a big issue when analog peripherals need to be emulated. Motherboards and daughtereards is a similar approach under different name.

4.5.2 Debug Board Modules (lHilYI)

In this approach all of the emulator electronics and the emulation chip are combined onto one single board, large sized I'CB not housed in an enclosure. The connection to the target system is accomplished by ribbon cable. This means that, all signals of the microcontroller to be emulated arc routed via the ribbon cable that connects the target system with the emulator. This is not preferred particularly when A/I) converter signals are to be measured accurately during emulation. DBMs emulate a single specific microcontroller and cannot be modified to support other derivative of a family, on the other hand DBMs arc typically low priced than others, and their debugging capabilities arc below probecard approach.

4.5.3 Dedicated emulators

There are several forms dedicated emulators, which only supports a very narrow range of microcontroller devices (microcontrollers with identical functionality and pinoul. but different memory sizes). They take the form of DBMs that can be plugged directly into the target systems or base units and probecards with probecards not being exchangeable. They are actually built on a small single I'CB with or without an enclosure.

4.5.4 Emulators Using Microcontroller Flash Memory

With the advent of flash program memory new approach in microcontroller becomes possible. The write/ erase capability of Hash program memory, in combination with emulation support circuitry and code embedded in microcontroller; enable such microcontroller to be its own emulator. This does not work with all Hash microcontroller particularly earlier generation which lack the necessary on-chip emulation support circuitry, flash microcontrollers with the necessary on-chip emulation support circuitry can, regardless of the package, be soldered directly into the target system. This of course grantee that the chip actually sees the exact environment as the final one. This is a big advantage when it comes to emulating analog peripherals.

-17 The connection required to enable PC-based software debugging is accomplished by few digital I/O pins of the microcontroller who have additional functions created by a small piece of hardware. One common approach of the on-chip emulation interface is the JTA(i interface, found mostly on 10-bit and higher microcontroller, flash emulators do not require RAM memory to store program code, but they use lite microcontroller's Hash memory. Another advantage is that, they also double function as Hash programmer, since the program code can be downloaded into the chip's memory. Also flash emulators arc in fact one. and the same emulator can support all flash derivatives of a given microcontroller architecture. If a new device with new functionality comes out, all needed is a sample of that new device and an update of the debugger software. Therefore there is no need to buy new probecards or debug board module or dedicated emulators for each new derivative. Disadvantage of using flash emulators is that, program downloads (required after every code change) take much longer time; also the microcontroller's flash memory life-time is limited and depends on the write/erase cycles number given by the manufacturer.

48 Chapter Five

Debugging Strategies

For simple code, debugging is usually not an issue. However, as code size increases, not only does the need for debugging increases, the complexity of debugging increases as well. Debugging may further be complicated by other issues, such as the requirement of real-time debugging or the insertion or removal of debug code into the final product code. Consequently, thought must be given to the debug strategy that is used in a given application. Figure 5.1 depicts the available debugging strategies for

Micro System Controller (MSC) devices. 'I'he strategies range from simulation-based to in-system debugging. ISI) is further categorized into software-based 1SD and hardware- based ISD. The examples used in this application note focus on C and Assembly programming, but the principles can be applied lo other programming languages [19].

MSC Debugging Strategies

Simulator

Sc-ftware ISD HaiJv.aie ISD

h'liiiimil Mxiiiti'i IDt MoiiiU'i Unlit In Debug; In Circuit r.iimlator MM: MON MOX

figure 5.1 MSC Debugging Strategies Tree

-I') 5.1 Integrated Development Environment IDE simulator

1DI\ is a set of development tools integrated in a user-friendly, Graphic Use

Interface (GUI) environment. Development tools integrated into the same environmen

shorten the code development cycle and reduce code errors, which also enhances cod quality. IDHs provide tools such as editors, assemblers, compilers, linkers, projec

management, and revision control, as well as device simulators in the same environmen

|7|. Simulators enable users to simulate code execution without requiring actual targe

hardware. Users can verily algorithms and timing, and simulate peripherals, interrupts and l/O. This simulation is important because it allows the user to start cod< development and even evaluate system performance before the target hardware i: available, figure 5.2 below depicts the conceptual block diagram of an IDE simulato

for the MSG device. Users can perform disassembly, break point, memorj

watch/modify, code execution trace, or peripheral monitor. Simulators also support codt coverage tools that mark the code that has been executed. Simulators also providt

performance analyzer tools that record the execution lime for functions such that uses can profile code performance. The most common operation in simulators is codt

stepping. Simulators support single-step with step-into a target function, or step-over i

given function. The machine cycle count is accurate in the simulators, as well; therefore execution time can easily be evaluated for inefficiencies.

Piocessoi Model

oa H • Llegistei File t

Peiipheials

figure 5.2 Block diagram of an IDC simulator Concept

50 Code simulation is a low-cost approach to code development, since it does not requin

any target hardware for debugging. When the code development reaches the stage tha

requires target hardware, however, debugging in the target system. In - Systen

. Debugging (ISD) is needed.

5.2 In System Debugging

Instead of PC simulation. ISI) executes and debugs code in the actual targe

system. Ad-hoc debugging is the easiest method for 1SD. Ad-hoc debugging is simph

inserting debug code wherever needed. In Example below, for instance, two number:

(10 and 40000) of different data types arc added. An error result of 25526 will b<

stored, since the unsigned number 40000 is the same as 25536 for a 16-bit signec

number. The ad-hoc debugging method would simply add a print/ statement and inspec

the result. This style is good for simple code testing. When the code size increases

however, the number of print/ statements becomes unmanageable. Other systematic

debugging methods need to be used (I).

ml i=IOJ:

unsigned int 40000:

y=/-» k:

printf("%ii ~ %d\ %d",j,i,k):

There are two categories of In-System-Debugging as shown in Figure 5.1 software

based and hardware-based ISI). Software-based ISI) is further divided into terminal-

based and IDE-based. Terminal-based debugging includes a genera I-purpose monito

and an on-chip debugger. IDE-based debugging includes a source level monitor am

flash-enabled-1 SI). Hardware-based ISD is further categorized into In-Circuit Emulator

(ICE) and Built-in Debugger Module (BDM).

5.3 Software ISD Techniques

5.3.1 Terminal-Based General-Purpose Monitor

A terminal-based general-purpose monitor is a software monitor that reside

in code memory. The monitor program concept, as shown in Figure 5.3. acts as a

51 i- interpreter between the user code and the terminal program. The monitor allows for downloading code into the target system memory from PC terminal programs using the on-chip UART, and then performing debugging features, such as memory or special function register (SFR) read-modify, CPU status, or calling a user routine, single step, or break.

MSC Target r

MSC De^ice

PC COM port Data Metnorv RS 232

with Terminal Emulator

Monitor Code

Figure 5.3 Monitor Conceptual Block Diagram

Two techniques may be used with the monitor code. First, the user code may be downloaded together with the monitor code into the MSC Hash memory. Alternatively, because program and data memories arc separate (that is, designed with Harvard architecture), the user program can be stored in external data memory with the monitor load command. When the user issues an execution command for the downloaded code, the CPU fetches the downloaded code from external data memory. For a typical data memory access, the memory is only accessible via a MOVX instruction. External hardware is needed to enable the program fetch from data memory. The external hardware may be a simple gate or diodes/resistor, which enables the data memory access

52 when the PSEN device signal is active. The biggest advantages for using the software monitor are its simplicity and low cost. The disadvantages are:

1. Monitor debugging is only good for assembly language debugging. Since the monitor interface is only a PC terminal emulation program, source-level debugging is not supported. Source-level debugging functions such as single-step requires a symbol-table and machine code to source code relationships.

2. Monitor programs have many hardware restrictions, such as needing an external RAM memory PSEN connection and serial port baud rate setup. Greater effort is needed to adapt the monitor program for the target system.

3. The existing monitor commands may not meet the needs of the user, and modifications to the monitor may be needed. Furthermore, the source code for the monitor program may not be easily available.

4. The monitor code and monitor PC communication port arc general-purpose resources of the target system and are used for debugging purposes. Therefore, the application code must avoid using these resources during debugging, and the application code must be coded according to the monitor code coding style. For example, the interrupt vector is re-mapped from OOOOh to a higher program memory address.

5.3.2 Terminal-Based On-Chip MSC Monitor Program

Some microcontroller has an on-chip, 2kB boot loader ROM that also contains embedded debug sub-routines. Using the boot loader debug subroutines, such as autobaud, put_string, and andjuirser, gives the user the lowest debugging setup. Monitor programs are closely related to the target system hardware setup. General- purpose monitor programs (most developed in the 1980s and 1990s) support EPROM programming. The MSC devices are embedded flash memory devices. The MSC embedded debug subroutines support not only the basic debugging commands such as SSingleStep, B-Break, and Q-Continiie; they also support flash memory commands such as CP-CodePageErase, CW-CodeWrite, XP-XDataPageErase, and L-LoadFlash. For the MSCMon to translate into debug overhead, the minimum configuration is needed; Which is only 29 bytes of flash code space, as follows:

53 Sinclude (regl210. inc)

CSEG at 807FH

db OBFH; HCRO: PM1--0 RSI-1 to protect 0-100011 Flash

CSEG at OOOOH; Monitor code start

LCALL autohaud

mov R6, iihigh greet

mov R7, iilow greet

kail jnitstring

LIMP andj?arser

greet: dh Oah.Odh, "MSC Monitor",0

CSEG at 033H

; any other Aitxlnl handler

LIMP monitor_isr

In addition, since user code is stored in Hash memory, the downloaded code can be used

for the final application. The prototypes for the available embedded subroutine of the

Boot Loader ROM typically must be provided. The MSC Monitor is Hash resident, and the Load command is used to download user code. Since the memory requirement for

the MSC monitor is very low, the user code may be linked with the MSC Monitor. The

MSC Monitor and the general-purpose monitor require a PC terminal emulator such as

Hyper-term, Tera-lerm, Procom. or Telix. These terminal programs have no information

about the source code or monitor operation. However, PC IDE programs have special handshaking with monitor programs for extra source code information that a general- purpose monitor or MSCMon do not have. These sophisticated source-level interfaces, when combined with the debugging commands, provide a user-friendly environment.

5.3.3 IDE-based Monitor: MON51

The MON51 program is a flash memory resident program that communicates

with the IDE to achieve source-level debugging, when it is used for MSC code

54 development. Here is an example to show the usage of the debugger: Program, as shown below, toggles P3.4 after each output message using the built-in ROM routine putstring.

$incltide (reg 1210. hie)

CSEG at 80001{

loop: mov R6, tthigh msg

mov R7, #low mxg

leall put string

epl p3.4

pnp loop

msg: dh "Toggle P3J".Oah,(Mh.O

CSEG A T 0FFD5H

jmi string:; void put_siring(char *string):

END

The IDE GUI greatly enhances the debugging efficiency. At any time, the user can monitor the CPU register and any memory contents. However, this debug strategy requires external memory, putting a great burden on the systems, which do not require external memory.

5.3.4 IDE-based Monitor: ISD51

For small memory configuration devices, with only 4kB of internal flash memory, loading a t5'pical monitor program of around 6kB for debugging purposes is not possible. Some monitors provide a low source-level monitor program, requiring only

500 bytes of code memory. Since it is source-level, debugging quality is much better than assembly-level monitors. It does not need the von Neumann-type external code memory (true In-Systcm-Debugging is possible without extra debugging hardware), which is important for small remote sensor applications. The 1SD51 operation is different from the general-purpose monitor, and MON51. Those monitor programs are preloaded into the target system and wail for user commands lor downloading user code. Due to the small size requirement for the ISD51. it is compiled and downloaded together with user code in the target system. For those monitor programs to implement break• point function (for example, for memory inspection), the CPU has to enter the interrupt service routine for break address check; this is called software break-point. Some chips have a built-in hardware break-point, that delects break addresses with hardware. 1SD51 fully utilizes the hardware break-point function, improving the execution performance over software break-point by a hundredfold.

5.4 Hardware ISD Techniques

5.4.1 In-Circuit Emulator

ICE is hardware interfacing to the MSC device that can perform debugging features such as trace, break-point, and stepping. It docs not use the MSC serial port or occupy any code/data memory space, nor does it require any CPU cycle over for debugging features. ICE can performs the debugging through control of the external memory bus. ICE debugging requires the lowest target system over task and carries the highest debugging capabilities. The ICE is integrated smoothly with the IDE; therefore, the GUI, code profiling, and coverage features are supported. There arc several disadvantages of using ICE:

1. Since ICE is hardware-based, with a deep trace and break point buffer, the development tool cost is much higher than the software-based monitors.

2. External memory ports (PO, P2, PSEN, RD. WR. AIT-, and RST) are needed for ICH connection. These ports cannot be used for target system applications.

3. To perform debugging, the ICE must be running at the same speed as the target system. The max clock rate at 33MHz means optimum requirements for the ICE timing at this speed.

4. When driving the ICE hardware at high speed, the increased loading will compromise analog performance, which is highly undesirable for In-system debugging.

5. ICE is not suitable for low-pin-count devices that typically carry no external memory port for ICE interfaces.

56 5.4.2 Built-in Debug Module (BDM)

The BDM is a hardware logic module that is designed within the device. Typically, the BDM interfaces the target system with the PC via a JTAG port. The BDM has the advantage that debugging is running at the system maximum clock rate with minimum effect on analog performance. The debugging capabilities, however, such as trace buffer size and number of break points are limited. It is because of the feature that hardware occupies the device silicon area.

57 Chapter Six

Software Development

Microcontroller emulation, which is defined as the process of making software and hardware assembly, that works exactly like a specific microcontroller under the control of PC passed through different stages. A significant step was production of Hash microcontroller which allows the microcontroller to emulate itself under the control of some monitoring program controlled by a PC through the serial port. Due to the lack of source information about IDE-based debugger for developing IDE-based monitor, this study dealt with terminal-based monitor program whose source code is given in appendix A. I his chapter will give an overview of the software developed under the monitor program headings and will review the building process carried out to produce it.

6.1 Monitor Program

The program is designed in an interactive way. It displays so many messages

and help information that guide the user during operation. Although it is covering a wide

area of program debugging still more modification is needed to make it efficient

particularly when IDE-based debugger is combined to it and hence breakpoint, single

step and trace can be meaningful. This monitor program is not very optimized for speed

and memory requirement, it is just written in a structured fashion with functions for each

task to make it easy to understand and modify. The simplest representation of this

terminal monitor program is an initialization segment shown in Figure 6.1, a power on

segment shown in Figure 6.2 and a loop that executes menu flowchart shown in Figure

6.3 below:

58 Start

Initialize constant parameters

Figure 6.1 Parameters initialization

Disable Interrupts Reset ports Delay 100.000 cycle Erase flash if enabled Run start up code if any Run autobaud if not defined Display welcome message

Figure 6.2 Power on segment

59 Menu

c ) to UploacT*^

Prompt menu message Input characters

Look for user command in memory

Execute user command

Display nevvline

Figure 6.3 Main menu

It is clear from the flowchart above that the monitor program supports user program downloading, uploading, dumping memory area, jumping to some address location, editing address content, running some program, displaying help messages, displaying directories, erasing external area, displaying internal memory, clearing some memory range and entering new memory location. The flowcharts shown in Figure 6.1, 6,2 and

6.3 above arc simplified. Presenting the whole flow chart requires over 100 pages.

Anyway, the initialization segment flowchart is shown in Figure 6.4 below and some sample flow charts are shown in this chapter later on.

60 location to LIMP iiitanipt v*ctow chutct to = 8OODI1

4*fmlt location for Uqu VKtot, 0x80001 tlteu<«r ptocnm

(•qu p»jn, 0x80001 ttfiiutim of iwrttoiy

•nJ of tl» memory «quW»w,0xl000|

I«t tO >tOn-2»IO VftkM «T> mi»m, OXFTRFL if fU

Iwt imntntv tocitit-m r of Flult ROM |«qaen»h,0«rFTr| *J>I #1 M* j-iit. 0 pi) <-3D »M* *» i«« pin f»At>n* _B5 -3Ppin 15, P3.5(T0 jr D*«» tftVt mini of ehu tittw» to _. _ - pw* Aniitgnplovl* I „I.)it»cloiy [*?i

IJWJJ witJc«y. 'R*| lovl li*x fit*

I *

hmp

«-jn juiup_k«y, 7 [

Figure 6.4a Initialization segment flowchart

61 _ hex dump inemoiy equ dumpjtey, 'H' I hex dump internal memoty equ intm_key, T

_ —edit memoiy equ edit_key, 'E'

clear memory equ clrm_key, 'C

erase flash rem

equerfr_key,'Z'

_.l 1.0592 MHz equ pgmwait, 19 equverwait, 5 twenty delays for 11.0592 MHz

equ eiwait 1,20

^___each delay .5 ms @22.1184MHz equ erwait2,229

value for psw

equ pswjnit, 0

block of 16 bytes for download

equ dnld_parm, 0x10 location of the stack

equ stack, 0x30

save baud for "warm boot, 4 bytes equbaud_save, 0x78 org base

reset vectoi

ijitvp poweiou |.orgbase+3

Ijmp vector+3 tnov dpi, ro" tnov dph, r7

,ret "A

Figure 6.4b initialization segment flowchart

62 The program developed so far, does not have subroutine to allow single stepping and register inspection. But register inspection can be displayed by a print message in the user subroutine. Tor example, if a user wants to examine at a certain step the value of the B register, the following block of code may be placed at the inspection point.

push A

mov A, li

call coul

call new/hie

call cin

pop A

This method of debugging is similar to print/ function using C. The accumulator is stored in the stack. Then register B value is moved to the accumulator. The cout subroutine displays the value of the accumulator, which is the value of B register. The subroutine newline places a new line after the value of the B register. The subroutine cin waits for a character until a key is pressed on the host. Finally the value of the accumulator is restored by poping it of the stack. These steps may be combined in a subroutine as follows:

inspect:

mov A, B

call cout

call newline

call cin

ret

Which is called by the main as follow:

push A

call inspect

pop A

63 Structured programming is adopted, which assigns a different route for each task, to manage a large number of routines. To make the program readable, it's routines are grouped in the source under the following seven headings:

1. Initialization parameters and interrupt vectors

2. Serial I/O subroutines

3. Main menu and monitor user commands

4. Memory, Management Subroutines

5. Power on and initialization

6. Multiplication and division

7. Multi-byte sequence and compressed data processing

The program is written in Assembly language to make it short and fast as required for such objectives. Microvision development tool is used for writing, compiling and debugging which is reviewed in one chapter before.

6.1.1 Initialization parameters and interrupt vectors

This part of the program assigns the constant addresses and values for the following parameters:

1- Monitor base address 2- Interrupt vectors base address 3- User program starting address 4- External memory address range 5- Baud-rate constant value 6- Flash address range 7- Flash enable, erase and write address and data 8- Menu key values (help, directory, run, download, upload, new location, jump, dump, internal memory display, edit, clear memory and erase flash ROM) 9- Power on reset vector

10- External interrupt 1 vector 11- External interrupt2 vector

64 12- Convert registers into pointer subroutine (small one) 13-Convert pointer into registers subroutine (small one) 14-TimerO vector 15- Timer 1 vector 16- Timer2 vector

17-Display dash subroutine (small one)

18- Display space subroutine (small one)

6.1.2 Serial I/O subroutines

cin: receives a character from the serial port.

dspace: sends double spaces to the serial buffer.

newline2: displays two empty lines, by sending CR and I,F to the serial port using cout function.

ghex: gets 2 digit hex number from serial port. C = set if ESC pressed, cleared otherwise. psw.5 = set if return pressed without input, clear otherwise.

2hexl6: gets 4 digit hex number from serial port. C -- set if BSC pressed, cleared

otherwise, psw.5 nT set if return pressed without input, clear otherwise.

fthex!6x: multiplies r3-r2 content by 16 (shift left by 4).

ehex!6y: divides r3-r2 content by 16 (shift right by 4).

asc2hex: converts ASCII character in A to its equivalent HEX. If A content is not a valid hex value (not in the range 0, 1,2 9, A, F) carry is set (C = 1). phex: changes the 8-bits value in A into two nibbles (4-bis). Then changes each nibble to it's ASCII, and sends higher nibble then the lower nibble to the serial port using cout function.

phex!6: changes the 16-bits value in the DFTR into two 8-bits values in DIM! and DIM,. Using phex8 it sends the 4 HEX digit in ASCII form to the serial port.

pstr: prints (sends to the serial port) multiple consecutive strings without needing to

reload DPTR (which takes 3 bytes of code!)... This is useful for inserting numbers or

spaces between strings.

65 upper. Converts the ASCII code in Acc to uppercase, if it is lowercase code.

lemlr. returns the length of the string in rO. The siring mentioned starts at the DPTR content location. The string end is either 0 or bit.7 set.

esc: Checks to see if is waiting on serial port. C=clcar if no . C~set if pressed. Then buffer is Hushed.

6.1.3 Main menu and monitor user commands

menu: first prints out the prompt I, then it prompts another message asking for input and it waits there. When the user enters his response it looks for similar external commands in the external memory. When it is successful it executes corresponding routine. When finished it returns. If it didn't find in the external memory it comes and looks for it in the internal command. If successful it will jump to it and execute it. When not successful it returns back to the beginning of the menu to repeat the process. The details of menu explanation are embedded within the text in appendix.

dnld: routine download hex files from the serial port. 1 lex file is a number of data • records terminated by CR and LF. A data record example is as follows:

:xxyyyy00aabbccddee mmZZ

where : Start of record

xv No. of data byte (two hex digits)

yyyy Starting address of the record (4 hex digits)

00 Record type No. for hex file

aabbccddee....mm Hex data (two hex digit numbers., equal xx)

ZZ Checksum value of all data record digits

. The download function receives from the serial port in this form, interprets it and save it. The procedure explanation is embedded in the text in appendix. Also a number of messages are displayed.

jump: routine asks for the address to which it will jump. If escapc(C=l) was pressed, the program is aborted. If no address was entered (void input, psw.5=l), the program returns

66 to where it was. When an address is entered the program makes a stack of 8 byte length and jump to the specified address. dump: displays 16 lines of 16 address location in hex format, beside it displays the ASCII equivalent of address contents. The starting address is the content of r6-r7. edit: routine edits external ram. It displays a message at the start to let the user enter the address location he wants to edit. Then it displays the address beside it's content and ask the user to enter the new value. When hex characters are entered the routine modifies the specified location and moves to the next address. If non hex characters entered the routine displays a message. dir. routine maps the display formal and send information about the directories in the memory to the display. It starts by displaying some messages and jump searching for headers. It displays the name, value and type of the header it finds. It continues doing this for the whole user memory. run: subroutine searches file headers. When it finds a run-program, it prints its name on the screen in a formatted layout. When il is finished, it asks for the choice to be entered among the list. If ESC is entered the program return control to the menu, otherwise the input is matched within some ranges to check it's compliance with choice list. When it is okay the headers were searched for the run-programs in sequence. When the search is successful the function will pass the address to another subroutine (at the end), which will make a stack of 8 byte length and jump to the specified address. help: routine is invoked from the menu. It displays help text and jump lo help2 to give information about the help. upld: routine uploads hex files to the serial port. I lex file is a number of data records terminated by CR and LF. A data record example is as follows:-

•xxyyyyOOactbbccddee mmZZ where : Start of record

xx No. of data byte (two hex digits)

yyyy Starting address of the record (4 hex digits)

67 00 Record type No. for hex file

aabbccddee....mm Hex data (two hex digit numbers., equal xx)

ZZ Checksum value of all data record digits

Firstly nplil gets the beginning address in r3/r2 (r2=LSB). and the final address in r5/r4 (r4=LSB), and prints them out beside some messages. Then it reads data from the specified address, process it, and sends it to the serial port in the above form. clrm: subroutine clears a memory area. The range is obtained by getjnem subroutine and the clearance is carried by the smart _wr subroutine. The subroutine will scan all the range starting from the lower address and going upward till the end address. nloc: subroutine prompts to the user to enter the new location. If no address was entered or ESC was pressed the subroutine is aborted. erfr. subroutine prompts to the user information about erasing some area. If the user entered 'Y\ erfr erases Hash and ROM. and displays message about erasure or about error. It uses erall for erasure. intm: displays the content of 128 internal address locations. It organizes the display in 8 lines, each one showing 16 location content. It carries out the display in two loops one for lines and the other for frame.

6.1.4 Memory Management Subroutines:- tlash wait: routine polls the flash ROM wait looping until the flash ROM is stable. DPTR must be initialized with the address to read. flash en: routine sends the flash enable codes for writing. prsm: routine writes Acc into flash memory at DPTR. C is set if error occurs, G is clear if it worked. The routine uses flash en routine. It calls also flash wait routine after writing data. The routine then checks the data written to set or reset C flag.

erall: erases all the flash ROM and return C=l if failure, 00 if okay. It calls erhlock for block erasure. Then it scans all the flash area if they are not completely deleted (deletion = FF) to signal error. When deletion is okay 00 otherwise Ol (error).

68 erblock: is an erase command. Il is called by erall. and is intended to be callable for the flash memory so that custom block erase code can be implemented. It uses flash en subroutine find: searches for header in the external memory identified by the sequence A5. R5. P.O and A5. The memory range searched is defined by hinem and emem. The input DPTR pointing to the start of search address (only MSB used). Output is DPTR location of next module. C = set if a header found. C - clear if no more headers smart wr: routine tests the presence of Hash first. If no Hash was found it write to the ordinary RAM. When a flash was found il checks the address to be written tt). is il in the flash range or out. When it is inside, it uses prgm subroutine to write it's contents, otherwise it writes it's content in the normal RAM. Writing to flash ROM or ordinary RAM will be indicated. Carry bit will indicate successfully written (C=0), or not written (C=l).

6.1.5 Power On and Initialization: poweron: makes the hardware to be initialized by the following routine. Description of poweron routine is embedded in the text. stcode: routine is invoked automatically during poweron at the start. This routine will look for startup specifier (249) among file headers. When it is successful, it saves its return location and jump to that startup subroutine. When it returns it continues searching for others and does the same until all startup routines are finished. At this moment the function will return back to poweron routine. aulobaud: routine is invoked automatically during poweron at the start when the following line

equ baud const, 0 ;flag for automatic baud rate detection is selected during initialization. To do automatic baud rate detection, measurement and setting. It is assumed that the user will press the carriage return, which will cause the below bit pattern to appear on port 3 pin 0 (CR = ASCII code of decimal 13 (OBh)),

69 0 10 1 1 0 0 0 0 1 II II

start bit—+ +--lsb msb--+ +—stop bit

To set the baud rate, the following formula is applied in calculation.

baud const =•• 256 - (crystal/(12 * 16 * baud-rate))

Timer HI is started in 16 bit mode at the transition between the start bit and the LSB and is stopped between the MBS and stop bit. That will give approximately the number of CPU cycles for 8 bits. Divide by 8 for one bit and by 16 since the built-in UART takes 16 timer overflows for each bit. After division the result has to be inverted since timer HI counts up. Of course, timer HI gets used in 8-bit auto reload mode for generating the built-in UART's baud rate.

6.1.6 Multiplication and Division: pintSu: prints the unsigned 8 bit value in Ace in base lO.This is carried by dividing the number by 100 and displaying the quotient (hundredth digit), then diving the remainder by 10 and displaying the quotient (tenth digit) and lastly displaying the remainder (units digit). pint!6u: prints 16 bit unsigned integer in DPTR. using base 10. The function use pintxl6 function to divide the number by 10000 to display 10000th digit, and by 1000 to display 1000th digit, and by 100 to display 100th digit. Then it uses div to divide by 10 to display 10th digit. Lastly it displays units digit. pint!6x: divides r2-r3 by r4-r5 and leaves remainder in r2-r3 and returns quotient in Ace. The division is carried by sequential subtraction.

6.1.7 Multi-byte Sequence and Compressed Data Processing: tin filter: looks for multi-byte sequences for up, down, left, right, page-up, and page- down, as well as ordinary escape and ordinary characters. Codes are required to arrive

70 sequentially otherwise the characters are treated as ordinary user keystrokes, cin filler returns a single byte when it sees the multi-byte escape sequence, as shown here.

return value key escape sequence

11 (AK) up 1B5B41

10 (AJ) down 1B5B42

21 (AU) .right 1B5B43

8(AI1) left 1B5B44

25 (AY) page up 1B5B 35 7E

•26(AZ) page down 1B5B36 7E pestr: prints the compressed strings. A dictionary of 128 words is stored in 4 bit packed binary format. When pcslr finds a byte in a string with the high bit (bil.7) set, it prints the word from the dictionary. A few bytes have special functions and everything else prints as if it were an ordinary siring.

Special codes for pcslr:

0 = END OF STRING

13 = CR/FF

14 = CR/LF & END OF STRING

' 31 = NEXT CAPITAL (next word code should be capitalized) dcomp: actually takes care of printing a word from the dictionary at DPTR position in packed words table. This function scans the dictionary sequentially till il reaches the particular word number. Then it reads the nibbles coded in the dictionary location and

translates them using some tables. Then the translated code is printed out. The nibbles

are managed by r4. r4=0 if next nibble is low, 1*4=255 if next nibble is high. It uses getjiextnibble function to read the dictionary.

get next nibble: gets character specifier from table and update DPI"R and switch nibble

specifier r4.

71 6.2 Prc-design Stage (Structuring and [Modularity):

It has to be staled that the hierarchical organization of the software will not be noticed in this chapter but the deep investigation of the source code at the appendix will illustrate that. This will prove the structural and modular nature of the program which is composed of module and subroutines in hierarchy. The lowest subroutines are small and general-purpose used by higher-level subroutines. Bach higher-level routine is more specific to the application. 'litis is due to the considerable efforts devoted to the pre-design stage of the development cycle which is usually overridden. In this stage the problem is partitioned into relatively sub-problems. Such modularization led to reduction in code complexity and better code understandability. Moreover, such modularization raised the necessity of data structures. That is hierarchical charts showing the place of each module in the system, as well as the module-calling convention is used in this stage. Beside that, the interface between the module that communicate together and description of inputs and outputs of each module is developed. That is hierarchical structure was the basis of this modular and structured program.

6.3 Post-design Stage (Maintenance and Modification):

Generally programs do not break-down, all errors were in the program when it is developed. These errors might be due to coding errors, specification errors or incorrect assumptions during parameters passing from one module to the other. Anyway this is minimized by code understandability which is enhanced by clear programming style mentioned above and combined with comment in each line in the source code in appendix. This is regarding maintenance while modification can be carried straight forward by adding the new subroutine and modifying the above flowchart and the jump table in the source code. Drawing flow charts increases code understandability to the optimum, but the problem comes in the huge number of pages needed to make such documentation. However, some samples arc presented here for justification, for example Figure 6.5 shown below describes the asclhex subroutine.

72 asc2hex:ASC2HEX

clrc add a, #208

Figure 6.5 ase2hex subroutine

Another sample describing pstr is shown in Figure 6.6 below

73 pstr; send string to serial port

mov c, acc.7 smla,#)x7F acall cout

" Cany?

Figure 6.6 pstr subroutine

Another sample describing run routine is shown in Figure 6.7 below

74 IUI1 ,RUN

acall newlineIine2 [ (list print the menu, count itrins

nov r2, #255 have we found 'cm all'.'? uov dplr, #binem Jec dph ftgt, 8) Samp, 255. run2b J

-I*, inc dph cjne a. #((«neni+1) Sgt m-<. Catty' mov a, dph sjmp tun 3 I In Kail find

Yes

uov dpi, #1 clra this one doesn't move a. (fftndptr run .. find nest oil a, #0000001 lb .:pla

I icall ilspace inc i2 print the key to press

... inov a. #W »dd a,12 icaQ cout_sp Kcall dash_sp ttov dpi. #32 n.m3 at c Ihet c any to ronW and the command name E ~hcall pssil r / Kcall ncwlinnc e and continue doing this

r cjne r2. #255, rnn-1 nin2|— mov dptr, #prompt5 ajmp pcstrji

<" Late' 1

Figure 6.7 Run routine (continue on next page)

75 T NOV Afttt I¥PI"->MPT3 WALL PC*LR_H MOV A, if A' TT»I4 *

INWA.i'AT

«\-*N TTU VM *JH* CHOW** V*ALL EOUT

TNOV DPTR, #PTOMPT4 WATT PCITT_H CM FILTTT_H

:JWT A, I¥2?, WW4*-I KJMP RMVLUIT TLWY UWY ITIT V$LT .ESdP-gl MOV R3, A NOV a, #31 :LIC ITM» A, I2 «U*»V A, I3

C»NV ? > .1. f%ll.'o.it |^ALL UPP*I I'LT*--L: T*T T#* IF IT** IIIVUT 32, IT"*© EONV*TT LO «IPP*TF*A<» XT. !«OV a. T3

if ttiavtyp*4'! V*J Ih-IN*A*

F3 h*.« tit* »UNB*T TLWY TYP«4 < 'CANY? >

A«3DR2 KU TH* MAXIMUM ITMUF*R Sl3 IF TLWY TYPT'I OR«T TIN MIX TTVN* *, (2 l.C •IT* A. T3

X

Figure 6.7 Run routine (continue on next page)

76 inc i3 movdpU'.flbmem foe dph

Inc dph >, 8j &4INP, mn5b "-•Hnov a. dph _X. sjtnp 11 mS *r-ntt find

mov dpi, UA clr a "H'TNL.IN'T 'VI D« THIS CANY? move a. fc$«+dptr

rpl a

this one doesn't count til we find run... find next the one they want cJjnz t3, nui5 icaflnewline mov dpi, #64

ajtnpjumpvdoit

Figure 6.7 Run routine

6.4 Program development

KEIL uVision is the name of software dedicated to the development and testing of a family of microcontrollers based on 8051 technology, The software can be downloaded and evaluated from the website. Most versions share merely the same interface. KEIL uVision is used for the development and testing of our different subroutine• and the overall program. Here in these paragraphs, the different step undertaken to carry the development process arc reviewed |5|.

6.4.1 Creating the project

To create a project, write and test the previous example source code, open Keil and start a new project follow the following steps:

77 1- To create a project, write and test the previous example source code, the user should follow the following steps in figure 6.8 below |5|.

J^S^i^^&^^BB^^WJ' p*iiPh*"'* I°°'s lyes hiimIOO H«*

import pVislonl Project... £p«n Projoct...

!" ;,3"2^iT»'tV.J. M,- Components, gnvironmont. Books...

Hi •as

1 C!\«l«ctronics\|iioj»cts\Oir."-Oksol»t»V»i>ti t»st\t»roJ««s\DTHERMO\AT8?S52\HO.«imo.Uv2 7 C!\«1««ronics\pioi«cts\ROBOCOtlRl\T.ic'.icii

•I U •» 8-Ci\«l«ctronics\projects\RoboconRl_b«a\AT09S52\slav«.Uv2 2 Cl\*l«ctronlcs\proj«cts\Robocon-Rt_bK»\AT89SS2\M»»Mr_B_2.Uv2 . X° C{\oltctronics\proj«cts\Robocon-Rl_bot»\AT89S32\M»st«r.Uv2 1

ILL

>ste a new project

Fijiure <>.X Clonic new projori

2- The user will be prompted to choose a name for his new project. Create a separate folder where all the files of his project will be stored, choose a name and click save as shown in Figure 6.9 below.

78 Create Mew Project: Egg a d1 ra*

By Recent • Project v;orks PocuT-en:*)

Device

My Documents

% Computer

Place* Seve o t>pe. ^ect *. es:'

II T l\BuiM A Command A fWnFtes /

Figure 6.9 Make new folder

I- The following window in Figure 6.10 will appear. The user will be asked to select levice for target 'Target 1':

$r ,.„..„... ^ „ ...... ffll« i^*;a«.^|^(^'£ftM;,Fli«h. P.tlfktr.li Lol. JVC8 Kind.. B«l|>.

'.; <- -*-iW1 a>.'iimliTai' A A> t«

r U»Ei«^'Ur*er(L>

a AT89LV51 6051 b«i^Fi«i

- ir^^^^^W'^fSr ''''" I •••'OK f - Cancel |" ' •• ' • ' • He*

II'I,,' i I

•'imiie 10 Select

79 4- From (he lisl at the left, select brand name ATMEL. then under ATMUL, select

AT89S52. A brief description of the device appears on the right. Leave the two upper check boxes unchecked and click OK. The AT89S52 will be called your 'Target device', which is the final destination of your source code. The user will be asked whether to

'copy standard 8051 startup code' click No.

5- Then click File. New, the following window in Figure 6.11 should appear. 'I"he box named 'Textl' is where your code should be written later.

^;ii^)^:fj^^^^^^{';p^Mlis .Ioo'ls . $VCS Window M«lp

i' G?B0, i'^.te'i'S'i :W if A % % * %\ "

few---'iJ*#-V"A""

U s'Textl 1

KflllHH

- #1> (Simulation

l-'if.uiv (t. 11 Make new fik

6- Use 'Save as' and choose a file name for your source code ending with the letter

'mm', 'monlest' for example.

80 7- Then add this file to your project work space at the left as shown in Figure 6.12. by pointing the mouse to source group 1 in project work space, and right mouse click.

wtorlsl_l - pVtsfon 3 r iini • i ...... ^n, „, ^^^^^^•>:>^-Y ii"*.

I Target 1 mm 1 ! So'urc« <3>oup nI Options for Group 'Source Croup 1' 1

g*buiW target ;£|y ftuildttrott

Hew Group Add File* to Gioup 'Source Group 1*

' tSl ld*r>a9* Components ; R«mo«« Group 'Some* Group I' »nd its nl«s

ln,c1udt D«p«ndtnci*s 1

mprpnrJT ISmulation

Figure 6.12 Adit life m l.'inid

After right-clicking on 'source group /', click on VlriV//7/t«.y to group...', then you will be prompted to browse the file to add to 'source group 1', choose the file that you just saved, eventually 'montesl.asm' and add it to the source group. You will notice that the file is added to the project tree at the left.

81 8- Make sure that option to generate HEX file is turned ON. This is done by right- clicking on target 1, selecting Options for target 'target 1*, then clicking 'output' tab. Check the box 'generate HEX file' as shown in Figure 6.13. This step is very important as the HEX file is the compiled output of our project that is going to be transferred to the microcontroller |5J.

Options for Target 'Target T m

Device | Target Output J Ustmg j User | C51 | A51 | BL51 Locate j BL51 Msc | Debug | UMet |

Select FoWerforObjects.. Name of Executable: r;'"*"r2

• Create Executable: .vnonitorz

P Debug Information S* Bra-.vse Information

| P Oeate HEX File HEX Format:

<" Create Ubrar/: .'mon

Figure 6.13 Create hex file window

9- Now the user can start to write the source code in the window tilled 'monies!.asm'

Then before testing the source code, the user have to assemble your source code, and correct eventual syntax errors. In KEIL IDE. this step is called 'rebuild all targets' and has this icon: S.

82 6.4.2 Building the project

The user can use the output window to track eventual syntax errors as shown in Figure 6.14 below [5J.

monteit - nVfs!on3 - [C:\Dpcutnerits and totlr>gsVibdulmori^mVD«ktop\coskiiri»moiKHm\8051n)oi).asm) j)Efe Eit &oject BfibuQ Flash Periphwa's Io* S'.'CS 'Mo--' t£%> JaJxll $ Kl 0 Hi : :• i 09 a tMa)

ijectivori-space 0529 0530 3C 0531 0532 xch •>, rl 0533 0531 aoall 0535 0536 n<->\' a, r2 053? 0539 swap a 0539 or! a. r3

El SC51W. [

235Ir.cr..aer.i-H7lt: errcr >.?: syrrrAX S?*CR SvSlrcor..a«r.f : error ^2: ST?~.^ T:F-.*I'.*A7" ;:,s:r.er..asBH«'Hi: warr.ir.e A4i; ::iss:::3 'E::B- 3rATE:-!s::r Targes not creased

<_|} \> f\Build/.Command A F»ri«l?»" /

I ieiiif (>. I) Ituikliiu*. pioccss

If after correcting errors and rebuilding the targets, the 'output window' shows that there is 0 error, then the user is ready to test the performance of his code. In keil, like in most development environment, this step is called Debugging, and has this icon: 'Si.

6.4.3 Debugging the project

After clicking on the debug icon, the user will notice that some part of the user interface will change, some new icons will appear, like the run icon circled in

Figure 6.15 below:

83 jnrwntest -„}iVisfon3 - [C:\Docuinentsand S^ngstatHfulmoneimXDeskb^ f

I'i^iMV 6.15 l)chiii:s.'.in<.". pmci"

The user can click on the 'Run' icon and the execution of the program will start. In this example, the user can see the behavior of the pin 0 or port one as shown in Figure 6.15 above, by clicking on 'peripherals. I/O ports. Port 1'. The user can always stop the execution of the program by clicking on the stop button (O) and he can simulate a reset by clicking on the 'reset' button rJt . He can also control the execution of the program using the following icons: ^ ^ ^ which allows the user to follow the execution step by step. Then, when he is finished with the debugging, he can always return to the programming interface by clicking again on the debug button (@L).

84 Chapter Seven

Results and Discussion

The source program was built using uvision development tool and then tested

(Figure 7.1 and Figure 7.2 below) [7].

QZE9D0SI CI

- S_I T*IM I

"B j tt tU »» ^.

Build t«cget 'Tarftct 1' nssembllug moitl. *>•»... Unking... FtOflCMx 3i*»t dat«-8.0 Kd«t(.-0 cod

Figure 7.1 Building the project

E<# V«W> D«MTT ORTMQ PMR^VALT LOCK SVCS WIDOW TJT»

PrOled, WMfeJfttCW - * J TMMM I

load **C:\\t>oci«nj*nt» *nd 3»*tt.«o*\\c©9kt)n_1j*J

ASM ASSIGN BrRthMonble IttenhRimltle •< I ' I - 1 . K WNM X(

Figure 7.2 Testing the project

85 All features of the program that do not require external RAM were tested using the simulator and found perfect; for example:

Help command of the program when tested showed the result in Figure 7.3.

,= U ART. 01 - 8051 Microprocessor Monitoring Learning » Board

ADDR:8000smon» Help

Standard Commands ?- This help list H- List programs R- Run program L- Download U- Upload N- New location J- Jump to memory location H- Hex dump external memory I- Hex dump internal memory E- Editing external ram C- Clear memory User Installed Commands

ADDR: 8000£mon» ADDR: 8000«roon» V

Figure 7.3 Running of the Help command of the program

Internal memory display in which the program displays the contents of the internal 256

RAM area showed the result in Figure 7.4 [7J.

•• UAUt #1 .. , ADDR:0005£mon» Hex dump internal memory

00: 00 00 01 OB 43 00 05 00 B6 08 00 00 00 00 00 00 10: 00 00 00 00 00 00 00 00 00 00 00 00 no 00 00 no 20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 30: 00 DF 01 82 07 07 84 01 43 BE OE EA OA 00 OA 00 40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 70: 00 00 00 00 00 00 00 00 FA FA AF FA 00 00 00 00 BO: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 90: 00 00 .00 00 00 00 00 00 00 00 00 00 00 00 00 00 AO: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 BO: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 CO: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 DO: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 EO: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ro: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

ADDR:0005«roon>> |

Figure 7.4 Running the displays to see the internal RAM

86 Clear internal memory feature in which the program will clear the internal RAM showed the result in Figure 7.5 [7]

39E1 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 so 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 60 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 70 00 00 00 00 00 00 00 00 FA FA AF FA 00 00 00 00 80 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Of) 90 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 AO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 BO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 CO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ou DO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 EO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FO 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

ADDR:0005smon>> Clear memory

First Location: 0000 Last Location: FOOO Are you sure?

ADDR: 0005 6nron»

Figure 7.5 Display of the clear command running

Download, upload, directory, run, jump, dump, edit and erase commands could not be tested at this stage as they need external memory. In fact some steps were taken in all these features until encountered by the lack of external memory, hence aborted by escape character. This is clear evidence that it is running perfectly.

Using EPROM programmer the HEX file of the source at the appendix was loaded in

8952 microcontroller chip which contains 8Kbyte Hash memory for holding the program. Then the chip is inserted in the circuit described in Chapter 2. Making serial connection between the host PC and the circuit, and then powering up the circuit are the only two steps needed. Using the hyper terminal in (he host PC for communication the test went on as expected as follows when the circuit is powered on the hyper terminal received some characters from the monitor indicating communication and waiting for baud rate measurement. Pressing carriage return makes the monitor enter baud rate measurement and respond by welcome message:

87 Downloading some program using L command resulted in successful download as shown in Figure7.6.

Welcome to MON2

8051 Microprocessor Monitoring Learning « Board

Program Name Location Typo list 1000 E y. I. e r 11 n 1 <: oiniti and Single-Step 1400 External command Memory Editor (VTlOO) 1800 External command

ADDP. Loc:2000 > Download

Begin transfer of Intel ex file, or ESC t.o a)>ort

Download completed

Summary: 114 lines received 1808 bytes received 1808 bytes written No errors detected

J

(C^JnecTed 0:03:23"' JAuto delect"~ |57BW 8-N-i

Figure 7.6 Downloading some program

When the RAM is not working properly, an error like (Unable to write) should appear.

Other errors such as checksums, unexpected hex digits are indicated as download problems.

Running the user program command using R showed what is shown in Fig(7.7) below.

To run the example without a header, use the "Jump" command by pressing "J".

Program will ask you for the address where it will jump to run the program. You can type 2000 or just press enter if the default value is 2000.

88 EJeseiial_poi Edit tVje -w HypeiTetmina £a» Itarofel t Help BIQ0E3 M*wwwJ*lwrtl MwmAiiflrtiJ IWIIWIIMMHIIM *m*mmm " 31

APDR Loc:2000 > Juinp to memory location

Jump to memory location (2000), or ESC to quit: i'000

running program:

Ple««« *"yr« a word ( 4 char max) : TKOT iHtititltlt!! MMUM Mtiltlftt HttittiUM #n#ifit1f1t ####### ####### MfMM ## ## ## ## ## ## ## ## ## ###### ##### ## ## ## ## ## ## ## ## ## ## ####### ####### ## ## ####### ###### ##

Press any key_

C6Wledft11:29 • •: TiAutodeled"' (57600Wfl {lE&OtI."*'|?>JPT'fRFsT*JC*'*|Ff,-«*;i I'igure 7.7 Running some user program

It has to be mentioned that the serial port is used by the monitor program for communication with the host PC; therefore the user should be careful not to change the baud rate and he should be capable of differentiating between communicating with monitor or the user program. Also the hardware can be developed by adding another serial port connector which the user can use freely. Beside this some Programmable Peripheral Interface (PPI) integrated circuits like 8055 can be added to the circuit which allows the user to connect parallel input and output devices like switches and displays. This can be very useful for troubleshooting beside the serial port. This monitor program is designed for using flash memory and static RAM in the external memory. The flash memory (although not present now) is very useful for storing program in the absence of power. In this case all flash parameters have been defined in the source code as required and the (has_flash) parameter should be changed to one. When flash is added also flash erase facility is also imported and should be added using a jumper or push button as in some cases the user need to erase the flash content on reset. To load a program in the flash region it has to be built in the memory range of the flash; therefore the flash range

89 (eflash and bflash) in the source code need to be known by the user and considered in making the hex file.

Single stepping and tracing (the most powerful tools for debugging) could not be executed by this program because they are not included in the program. This is due to the fact that this program is terminal-based monitor, while single stepping and tracing require IDE-based monitor in which the user interface communicates with the monitor by a series of characters rather than single character as in terminal-based monitor.

However this program can be developed to achieve single stepping and tracing if thorough investigation is carried out for IDE based communication protocols.

90 Chapter Eight

Conclusion and Recommendations

Results found in the last chapter indicate that the emulator developed is working properly. Regarding user program downloading, uploading, displaying memory area, jumping to source location, editing, running .displaying directories, erasing, and displaying internal memory showed excellent results.

Although emulation capabilities are limited in the above features only, they are quite enough for debugging significant portion in the emulation process. It worth mentioning that, the work targeted exploration of the emulation process assisting in the development of microcontroller based equipment. It ended up with different strategies for debugging and different approaches, not expected, aiming to incorporate the necessary hardware and software for debugging inside the microcontroller itself. This is why the work concentrated on basic emulation feature and left advanced emulation features like single stepping, tracing and pausing for future work. This could be accomplished if some host PC emulation program is developed or studied thoroughly and this monitor program is modified lo carry out more intelligent communication with the new PC environment.

Furthermore this study could be nucleus for source-level debugging investigation which is optimum debugging when under stood, taking in mind recent trends for debugging and emulation.

It is inevitable to mention here the advantages of such emulator regarding simplicity and low cost while the disadvantages arc the following limitation:

1- Not supporting source-level debugging

2- Hardware restrictions such as external RAM requirement and serial port set up.

2- Commands many need modification.

4- General purpose resources like the serial port is used for debugging so it must not be used in the application.

5- Applications must be coded according to the monitor coding style .

91 As a conclusion this work tried to disclose emulation of 8051 microcontroller so as to facilitate the debugging process and fortunately achieved significant success and hopefully pointed out some point as recommendations for further investigation.

92 REFERENCES

1. 8051 Tutorial, Vault Information Services, 1999.

2. Eight-Bit 80C51 Embedded Processors. AMD Corp.. 1990.

3. 8-Bit Embedded Controllers, Intel Corp., 1990.

4. 8-Bit Embedded Controllers Handbook, Intel Corp., 1998.

5. Getting Started and Creating Applications. Keil I Iser's Guide 2000.

6.1 leffcrnan, D., 8051 Tutorial, 2002.

7. Keil uVision IDE ASM compile tutorial, Hi-Tronic, 2005.

8. Karakehayov, Z., Christensen, K. S., Winthcr, ()., Embedded System Design with

8051 Microcontroller: Hardware and Software, 1999.

9. 80C51 family and hardware architecture. Philips Semiconductors. 1996.

10. 80C51 family programmer's guide and instruction set. Philips Semiconductors.

1995.

11. Microcontroller Users' Guide, Signctics Corp., 1989.

12. Steiner, C, The 8051/8052 Microcontroller: Architecture, Assembly Language, and Hardware Interfacing.

13. Yeralan, S., Ashutosh, A.. Programming and interfacing the 8051

Microcontroller, Addison Wesley Publishing Company, 1995.

14. Douglas V. Hall, Microprocessors and interlacing Programming and hardware,

McGraw- Hill Book company, 1986.

15. URL: http://www.futurlec.com Augst 2008

16. URL:http://www.farnel.com/datashcct June 2008

17. URL:http//wvvvv.NXP.com June 2008

18. URL:http//www.faq.om/microcontrollcr Augst 2008

19. URL:htto//www.spvfu.com Augst 2008

20. URL:http//www.patents.com Atmst 2008

93 Appendix A

Terminal based Monitor program source code

Initialization parameters and .Interrupt Vectors

These two parameters control where MOM2 will be assembled, and where it: will attempt to LJMP at the interrupt vector locations. base equ 0x0000 ;address location for MON2 vector equ 0x2000 /address location to LJt-H' interrupt, vector;:

/These three parameters tell MON2 where the user's memory is installed. 'bmem" and ;"emem" define the space that will be searched foi program benders, user installed ;commands, start-up programs. pgm equ 0x2000 /default: address local ion tor the user pt.oqram bmem equ 0x1000 ;the beginning of external memory • emem equ OxFFFF ;end of external memory

;To set the baud rate, use this formula or set to 0 t.oi aul.o detection baud const ; = 256 - (crystal / (12 * 16 * baud-rate)). ;Most emulation proqrams introduce intentional d<> 1 .!\ wh'Mi S'Midinq nscii. data, ;which you would w.mL to turn oil (<>i downloading lai'.i"» piogiams into RAM. Ko r ;flasli ROM, the maximum speed is set by the time it t,\i:>-:; to program o.-fh .•location.

baud_const equ 0 /flag for automatic baud rate detection (when 0) baud_const equ 255 ; 57600 baud-rate with 11.0502 Mllr. baud_const equ 253 ,19200 baud-rate with 11.0592 MHz baud_const equ 252 ,-19200 baud-rate with 14.7456 MHz baud_const eqn 243 ;480ft baud-rate with 12 MHz line delciy equ 6 ;No. of char times to pause riming uploads

; These are flash ROM parameters. If "has flash' is set to zero, all flash rem ,'features are turned off, otherwise "bflash" anr "of lash" should specify 'be /memory range which is flash ROM. ;"erase_pin" allows you to specify the bit address for a pin which (if h" Id low) .•will tell MON. to erase the flash ROM chip when it starts up. This is useful ii ;you download programs with the "start-up" bonders on t.bem and I he code you've pui ;in the flash ROM crashes.

has_flash oqu 0 /flash installed flag (when not. Z>MO) bflash equ 0x8000 /first, memory location ol Flash ROM eflash equ OxFFFF /last memory location of. Flash R<>K erase_pin equ 0 ;00 - disable erase pin fealui.o erase pin equ 0xB5 ;B5 = pin 15, P3.5 (Tl.) (erase pin address)

/Special flash ROM programming addresses were met. by base address added to flash ;memory register addresses. This is done for flash ROM enabling, writing and /erasing.

flash_base equ bflash /flash start - 0x8000

flash_enl__addr equ 0x5555 + flash base /send data to addr. for flash enable flash_enl addr equ 0x595A + flash base /different, flash version flash_en.l_ data equ OxAA

flash_en2_addr equ 0x2AAA + flash_base /send data to addr. for flash enable flash_en2_addr equ 0x26A5 + flash_base /different flash version

94 /. I ash on2 dai a qu f'.xf.:.

Clash wr addr oqu ()xr>i>5!> ' I l.eish base ;N addr. Cm i ! a:;h wr i t< r l Lash wr addr oqu 0x5<-*5A + flash base /different .lash version flash w> data, OxAO

CJ ash or I addr oqu 0x!°-> i flash base / s«=nd data t.oaddr. for Clash erasure flash erl addr equ Ox.'^'vA » flash base ;di f ferent flash version f lash_erl_data equ 0x80

flash_er2_addr equ 0x555b t flash base ; send dat.a to addr. for Clash erasuc flash_er2 addr equ 0x595A t flash base /different llash version flash er2 data equ 0x10

;Koy do fini. lion:.- foj MOM. i help key oqu /help .••croon • dir key Oqll •M' ; d i I oi -1 nry run key oqu ' R' ;run proqram dntd key equ • IV /download upld key equ •u* ;upload nloc key equ 1M' /new memory loc.it i • >ii jump .key oqu 'J' /jump 1" memory lo

;Tiniing parameters for some flail ROMs. ; pgmwait equ J 0 ;22.1184 MH:-. crystal assumed (delay? M. pgmwait equ 19 ;1.1 .0592 MHz verwait equ 5 ; erwaitl equ '10 ;fourty delay.-- 022.11K4 MH:-. erwaitl equ 20 ; twenty delays for 1. I.0T>"2 MH?. ; erwait2 eqn 22 9 ; oach del ay .' > ms (J22 . 1 11'< 4M11 /.

/These symbols configure MON internal monuuy usage. psw init equ 0 ;value lor psw (which reu bank to use) dnld_parm equ 0x10 ;block of 1 <*> bytes for download stack equ 0x30 /location of the stack baud save equ 0x78 rsave location for baud-'*on.-*t warm boot, (4 bytes)

;The following map some MOM subroutines org base ;start from bane ljmp poweron ;jump to power on reset: vector .**************•***•******** . org base I 3 /start, from base t ' ljmp vect.orH 3 ; jump to e::t into vector .*>*** ****** * * * * * 4 * 4 * 4 1 *• * l . r6r7todptr: ;e<>uvM;t r '"id r 7 into dpt i mov dpi, r6 /move rti to dpi mov dph, r7 /move rG to dph ret /rerurn *******»***. A***********.*. org basei 11 /si.art from ba' II vector-i-l] ; iuinp t o t int'M 0 \-.>clot dptrtdr6r7: /convert dptr .into i:6 and rl mov r6, dpi /move1 dpi to t:C mov r7, dph /move dpli to r7 ret /return

95 org base ^19 /start- t rom base i 1-i ljmp veci '.r:+l /jump to oxt intl vector . 4 *********** * * * * 1 * * •* * * » * * . clash: mov a, » ' - ' ; load (••) i.nl o A ajmp COt.lt /jump to output: ehaiaeter (-) nop /no operation .************* * * * * * •* * * I-*--* .

org baset27 /start I 'ram base i 27 ljmp vector+27 /jump ti> timer! vector .*****•**•** + ****+*••*•*•»< ***** . cout_sp:acall COUt /call con!: to output; eharaeioi ajmp space /jump to display a space nop / no ope t a I i * hi ****** ***** * » * * * *** . ** * *•* . .

org basei35 /start trom base '• 35 ljmp veot.or+35 /jump to uart vector .*************************. dash_sp:acall dash /call to display dash ajmp space /jump to display space nop /no operat i on .************* **********,*. f * org basei43 /start front base i 4 3 r 1 jiiip vector* 43 /jump to timer;*, vect.ru (fco >.>)

.lump Table Lot F't out am'.-. "nbroiit. i ties falls

/Never change this line!! Othet pt.ogt. ims depend on those locations to access mon /functions. org base-i 4 6 ; st art ajmp phox 1 /*-:!•:; (oo t 4< ajmp coul ;30 ajmp c.i.n / 32 ajmp phex /34 ajmp phex16 ;36 ajmp pstr ;3ft ajmp ghox ;3A ajmp ghex16 ; 3C ajmp esc /4F, ajmp upper ;40 ljmp autobaud ;42 pcstr_h: Ijmp pest r ;45 • ajmp newl i.ne /40 ljmp lenst r /4A Ijmp p i n 1811 /4n ljmp pints / 50 Ijmp pint: lt'iu ;53 ljmp cmar 1. wi ;50 ljmp prgm ;59 ljmp erall ;5C ljmp find /5F cin_f ilter_h: ljmp cin_ ft Iter ;62 ajmp asc2hex ;65 ljmp erblock ;67

Serial 1/0 Subroutines ;cin receive- a oha1noter from the serial por< cin: jnb ri, «.:in ; .1 oop il rocttivo interrupt flag not set clr r i ; clear receive interrupt flag mov .a, sbuf ;put serial buffer into A ret ;return

;dspace sends double spaces to the serial buffer dspace: aca.l I. spare ;call. double spare transmit ii.n space: mov a, I! ' ' ;put spare i nt o A cout: _ jnb ti, cout ;d i splay i t clr ti /clear transmit interrupt mov sbuf, a ;put. A into serial butter to send ret ;ret urn

newlineZ displays two empty .linos, by sending <:\K and I.F to the • 1 i A I PER I. us i nq cout function. newline.2: ;print two now lines a call now! i tie ;di splay new li no newline:push acc ;save A (to print one newlitiv) mov a, #13 ;put carriage return into A aca.l 1 cout /display it; mov a, #10 ;puf lino food into A acal 1 cout /display if pop acc ;rest ore A ret ;ret urn

ghex gets 2 digit hex number from serial port. (' - set .if. KSC pressed, cleared otherwise, psw.5 ~ set if return pressed without, input, clear otherwise. ghex: ghex8: clr psw. L> /clear user defined flaq ghex 8 c: acall cin fi iter h /uet f i t st digi• (msb) acall upper / convert. to uppercase cjne a, #27 , ghe.x8f / jump i T. not escape char setb c /clear carLY flaq clr a /clear A ret /RET urn cjne a, #13 , ghexSh /jump i f not a carriage rotnin setb psw. !'i /set THE usot 1 ie 1 i net 1 1 !aq clr c /clear c clr • a /c1ea t A ret / ROT 1.11 11 mov r2, a /move ch. u tmsb) i nt •• 1 2 aca.l I asc2be X ;conver! ascii to hex to check qhexi-'c / j ump i ! net hex xch a, I:2 /EXCHAIKI .i hex char (msb) and char acall cout /display char (msb) ghex8 j: acal! cin_l i 1 tot. h /uer sec •nd dit|i •• (isl-)) a call uppe T: /convert TO uppercase cjne a, #27 , ghexSk /jump i1 NOT escape char sjmp ahexBd / j uinp i f escape cjne a, #13 , ghexiim / j ump i. f not a carriage return mov a, r2 /put HEX (msb) into A clr c /clear c ret / rotu 1 !i

<>7 ghex8iri: cjne a, #8, ghex8p ; jump if not a backspace ghexSn: aca 11 cout /if backspace, display i.t and sjmp ghex8c ;jump back ghex8p: cjne a, 921, ghexBq ;jump if not a negative aeknow 1 edge sjmp ghex8n ;jump if negative acknowledge ghex8q: mov r3, a ;move char (Isb) into r '< acal 1 asc2hex /convert asc.il to h«x to check

jo ghex8j /jump if carry (non hex onar) xcii a, r3 /exchange hex char (Isb) and char (Isbi aca 1 1. cout /display char Msto mov a, r2 /move hex char (msb! into A swap a /swap A (exhango the nibbles) orl a, r 3 /or A vi i V i i hex chart Isb) clr c /clear c ret /return

ghexl6 gets 4 digit, hex number from serial port. (' - set if ESC pressed, cleared otherwise, psw.5 — set if return pressed without input, clear otherwise. ghex16: • mov i-2, #0 /clear rl mov i:3, 110 /clear r? mov r4, #4 /number of digits loft. clr psw. 5 /user defined flag bit ghex16c : acali cin filter h /serial input acal 1 upper /change input char to uppercase cjne a, if27, ghexl6d /jump if input, is not. an escape setb c /handle esc key clr a /clear A mov dph, a /clear dph mov dpi, a /clear dpi • ret /return ghexl6d :cjne • a, If8, ghexlfif /jump if the input not a backspace s jir.p ghex16k /jump down, since backspace ghexl6f :cjne a, #127, gh.ex.16q /jump if it 127 ghexl6k : cjne r4, #4, ghexl6e /jump it some dtqits entered sjmp ghex16c /jump if no digit, entered ghexl6e :acall cout /display input acall ghexl6y /divide by 16 inc r4 /increment r4 sjmp ghexl6c /jump to get. another digit ghexl6g :cjne a, #13, ghexl6i /jump if not carriage return key mov dph, r3 /move r3 to dph mov dpi, r2 /move r2 to dpi cjne r4, »4, ghexlCh /jump if some digits entered clr a / c1eai A raov dph, a /clear dph mov dpi, a /clear dpi setb psw.5 /set general purpose j titerrupt ghexl6h:clr c /clear c ret /return ghe,xl6i :mov r5, a /keep ascii value of the digit aca.11 asc2hex /convert to hex jc ghexl6c /jump if not hex xch a, r 5 /prepare ascii digit: to display lea 11 cout /display digit in r5 mov a, r5 /return hex digit for futther proces push acc /save the digit from destruction acall ghexl6x /multiply by 16 pop acc /restore the digit (1st byte)

98 add a, t;2 ; add d i g it. a !' t ei mu .11 i p! icat ion mov • r2, a ;store new value ju r2 clr a /clear A acldc a, r3 /adjust the (2nd byte) mov r3, a /store r.3 cljnz vl, ghexl6c /jump if r'1 not zet.-., t i bring the next. clr c /clear o mov dpi, r2 /put. r2 in the pointer (1ower byte) mov dph, r3 /put t 3 in 1 he p<> i n! «"r (higher bytet re!:. /1 oi uin

/ghexl6x taul tip lies r3-r2 content by Id (shift left by 4). ghexlfc.x: mov a, r3 /load r3 i nto A swap a /swap A (to process lower nibble) anl , #1111.0000b /mask out (unwanted nibble after swapping) mov v3, •i /put it back info r mov a, r2 /load r2 i nto A for processing swap c! /swap A for further froce^Ping anl a, #00001111b /mask higher nibble orl a, i 3 /anl A with R3 mov ' r3, a /sve result into t3 mov a, r2 /.load A with r2 swap a /swap A for furt hot pioeoss i ng anl a, HI I.110000b /mask out lower nib )} e mov r2, a /save A int o i 2 ret /return

/ghexlCy divides r3-t:2 content by 16 (shift right by 4). ghexl6y: mov a, r2 /load r2 into A swap a /swap A (to process higher nibble) anl a, tfOOOOllllb /mask out. (unwanted nibble after swapping) mov r2, a /put. it. back into r2 mov a, r3 /.load r3 into A for processing swap a /swap A for further processing anl a, #11110000b /mask lower nibble orl a, r2 /and A with R2 mov r2, a /sve result into r2 mov a, r3 /load A with r3 swap • a /swap A for further processing anl a, #00001111b /mask out higher nibble mov r-3, a /save A into r3 ret /return

asc2hex convert ASCII character in A to its equ.iva.lent-. IIKX. If A content is not valid hex value (not in the range 0, 1, 2, 9, A, F) carry is set (C = .1) . asc2hex: add a, #208 /add to execl.udo digits with ascii lower than zero jnc hex_not. /jump if no c.airy, digit lower add a, #246 /add to execlude digits with asei.i higher than nine jc hexjuaybo / jump if eat.ry, digit may bo A, H, 0, I), K or F add a, #10 /add to cancel 246 add.il. ion clr c /clear c ret /totut n hex_ maybe: add a, #249 /add to exeeludo digits with ascii lower than A

99 jnc hex not /jump if no carry, digit lower add a, #250 ;add to execlude digits with as oii higher thar jc hex not ;jump if carry, digit is not A, B, C, D, E nor add a, #16 ; add to cancel last addit ions clr c ; clear c. ret ;return hex_not:setb c ; set c ret ;return

;phex changes the 8-bit s value in A into two nibbles (1 -Ids) . Then cha ;os e.|,:h ;nibble to it's ASCII, and sends higher nibble then the 1 ower nibble t the s(>r ia! ;port using eout function. phex : push •rl CO ;savo A because we handle nibble - (high ! swap a ;swap the nibles anl a, #15 ;mask out lower nibble add a, #24C /add ti. check whet hoi hex h i jnc phex b ; jump to add 58, il ri"l hi iter I li add a, #7 ;if higher therefore did it is A, B, c, b, o r phex b :add a, #58 ;add 58 to adiust it to as oii aca.l 1 ecu t ;output A content pop act: ;iostore A tor 2nd nibble {1ower u i bb1e) phexl: push acc ;save A anl a, #15 ;mask out higher nibble add a, #246 /add lo check whet het h".-: hi ghoi t nan '.' jnc phox c ; jump t (i add '•(!, i f not hi gor t h add a, #7 /if higher therefore digit i s A, B, C, 1), oi K phex_c : add a, #58 ;add 58 to adjust, it to as oi i acal.1 cout ;output A content pop • acc /restore A ret ;return

phexl6 changes the 16-bits value in the dptt into tw>> s<~bits values in dph and dpi. Using phexH it sends t.he 4 HEX digit in Aef'M l"ini to the serial port. phexl6: push acc ;save A mov a, dph ; load higher pointer eontout nil acall phex ;ea.ll 8 bit output function mov a, dp 1 ;load lower pointer content o A acall phex ;call 8 bit output function pop acc /restore A ret ;return

;pstr prints (sends to the serial port) multiple consecutive strings without /needing to reload dptr (which takes 3 bytes of code!)... 'this is useful, for /inserting numbers or spaces between strings. pstr: push acc /save A pstrl: clr a /clear A to use in the pointer move a, @a+dptr /get addr. content inc dptr /point, to next addr. jz pstr2 /jump if it is zero mov c, acc.7 /store bit 7 in carry (end flag) anl a, #0x7F /mask bit: 7 of A content. acall cout /display character jc pstr2 /jump to the end if carry set s jmp pstrl /otherwise, jump to begininq pstr2: pop acc /rest ore A ret / refui ri

100 /upper Converts the ascii code in Acc t <• 'ippetc-is--, if i! js lowereas*. upper: cjne a, #97, upper2 / i ump i f <;har is (a) upper2.: jc upper4 /j ump i f char lower than (a) cjne a, #123, upper3 /j ump i f char is (r.! upper3: jnc upper4 /j ump i f char higher than (z) add a, #224 /convert to uppercase by adding upper4: ret /return

lenstr returns the length of the string in rO. The srinq mentioned si atts at th" dptr content location. The string end is either (.) ot. bit .7 sot. lenstr: mov rO, #0 /returns length of a string 1 n push acc /save A to use the ac.-um lat. >r lenstrl :clr a /clear A move a,0a+dptr /load A with addr. content jz lenstr2 /is it end of string mov c,acc.7 /load carry with acc;. 7 (end f 1 inc rO /increment counter Jc lenstr2 /jump to end if carry SP-' inc dptr ;increment pointer sjmp lenstrl /loop back lenstr2 •pop acc / rest'ore A ret /return

esc Checks to see if is waiting on serial port, '.'-cleat if no '.KSC>, C=s pressed. Then buffer is flushed. esc: push acc /save A to use the aceumlator clr c /clear c jnb ri,esc2 /jump if receive interrupt is not set mov a,sbuf /.load A with serial buffer contents cjne a,#27,escl /jump if serial buffer contents is not an esc setb c /if serial buffer contain esc. Set carry flag clr ri /clear receive interrupt pop acc /restore A ret • /return

The Menu and Monitor User Commands

/menu first prints out. the prompt. 1, then it prompts anol bet message asking for /input and it waits there. When the user enter his response it looks for similar /external commands in the external, memory. When it is successful it executes /corresponding routine. When finished it returns. If it didn't find in the /external memory it comes and looks for it. in the internal command. If successful /it will jump to it and execute it. When not successful it returns back to the /begining of the menu to repeat the process. The del ails oJ menu explanation is /embedded within the text, menu: mov dptr, •promptI /point to prompt 1 message acal 1 pcstr_ h /display message mov a, r7 /move r7 to A for output: acall phex /call phexS to output a byte mov a, r6 /move r6 to A for output acall phex /call phexB to output a byte /mov • dptr, #prompt2 /point to prompt 2 message acall pstr /display message

101 /Now the prompt is past and some: input is expected. aca.l i. cin filter h /get the input character cjne a, #' : ', meuuO /jump to menuO, if not : acall dr\l.d_now ;otherwise down Ioad sjmp menu ;jump to menu meruit): acall upper /•change A content to uppercase ;Push return address onto stack to enable jumping to the program. mov b, #(menu & 255) ;load return address low byte push b ;push the return address mov b, if (menu >> 8) ;J.oad return address high byte push b /push the return address

;look through memory for a program header that, is user installed command, to mate! /with the pressed user command. menux:' mov b, a ;now search f.<.>r extoinal commands.. mov dptr, ft bittern ; load dptr. with bmem menuxl: : acall f ind ;find header of files jnc menuxend ;jump, since all commands searched mov dpi, #4 /point to figure out its type clr a /clear A move a,@a+dptr /.load its type cjne a, #254, menux2 ;jump if not ext command (FK) inc dpi /•increment to find specifier clr a ;clear A move a,da+dptr ;move specifier into A cjne a, to, menux2 ;jump if specifier and B not equal acall space /display space mov ' dpi, #32 ;point to header name acall pstr /display it acall newline /display new line mov dpi, #64 /point to header clr a /clear A jmp @a+dptr /jump to it ! menux2: inc dph / i nc rente nt dph mov a, dph /move dph Co A for eomparision cjne a, # ( (ememU ) >> 8) 1 255, menux] /jump back if not Tid menuxend: mov a, b /move char in B to A ; Since no user installed command was found, use the built.in ones. menula: menulb: cjne a, #help_key, menulc mov dptr, #help cmd2 /point to message aca 1.1 pestr h zdi splay i t a jmp help /jump t.o subroutine menulc: cjne a, #dir_key, menuld mov dptr, #dir_cmd • acall pestr h ajmp dir menuld: cjne a, #run_key, menule mov dp t r, # r un_ cmd /point to message aca .1.1 pestr h /display it ajmp run /jump to subroutine menule: cjne a, #dnld_key, menulf mov dptr, #dnld_ cmd acall pestr h ajmp dnld menuIf: cjne a, #upld_key, menulg mov dptr, #upld cmd acall pestr h ajmp up Id menulg: cjne a, #nloc key, menulh

102 mov dptr, #nloc cmd ;point to message acall pcstr h ;display i t ajmp nloc ;jump to subroutine menulh: cjne a, Hjump key, mennl.i mov dptr, Itjumpcmd acall pcstr h ajmp j unip menul j.: cjne a, tdump key, menuli mov dptr, ttdump emd acall pcstr h ajmp dump menulj: cjne a, HediL_key, menulk mov dptr, #edit cmd ;point to message acall pcstr h ;di splay i * ajmp edit ; j ump I. o subt outine menulk: cjne . a, ifclrinjtey, menul1 mov dptr, #clrm_cmd acall pcstr h ajmp clrm menu11: cjne a, #erfr key, menulm mov a, #has_flash jz menu end mov dptr, #erfr cmd ;point to message acal 1 pcstr_h /display i' ajmp er f r ;jump to subroutine menulm: cjne a, #intm key, menuIn mov dptr, #intm_cmd acall pcstr_h ljmp intm menuIn: /Invalid input, no commands to run...., So newline wi 1.1 just return to menu. menu_end: ajmp newline

dnld routine download hex files from the serial port.. Hex file is a number of data records terminated by CR and hF. A data record example is as follows:- :xxyyyyOOaabbccddee mmZZ where : Start of record xx No. or datci byte (two hex digits) yyyy Starting address of the record (-1 hex digits) 00 Record tyoe No. for hex file aabbccdciee. . . . mm Ilex data (two hex digit, numbers., equal xx) ZE Checksum value of all data record digits The download function receives from the serial pott in this form, interpetts and save it. The procedure explanation is embedded in the text. Also a number messages are explained as follows: dnldsl = "Begin sending Intel HEX format file to abort" dnlds2 = "Download aborted" dnlds3 = "Download completed" 16 byte parameter table: (eight 16 bit values) * 0 = lines received * 1 = bytes received * 2 bytes written * 3 = bytes unable to write ** 4 = incorrect checksums * 5 = unexpected begin of line * 6 unexpected hex digits (while waiting for bo!) * 7 unexpected non-hex digits (in middle of a line) dnld: mov dptr, ttdnldsl /point to message to display

103 acall pestr_h r"begin sending file ESC • to abort' acall dn.ld_in.it call in ifialisat ion >'i low ;Lo.ok for beginlng of line marker i . t

dnldl: acal.I t cin ;get in a character cjne ' a, #27, dnld2 ;jump if not escape sjmp dn.ld_esc /jump since escape dnld2: cjne a, #':', dnld2b ;jump if not : sjmp dnld2d ;jump since (:} to e •nt. inue bel' ;Check to see if it's a hex diqit, error if it is. dnld2b acall asc2hex ;convert ascii to hex jc dnldl ;if carry set (not hex) jump back mov rl, #6 /specify the counter Cor unexpected hex acall dnld_inc /increment counter sjmp dnlcl'l /jump back ;Entry point for main menu detecting " character. dnld now: mov a, #,A' ;move character to A acall cout ;display character acall dnld init ;ca]l initialization below dnld2d : mov rl, #0 /specify counter for Mo. of trials acal 1 dnld inc ; i ncrement. counter taking in the record line of data dnld3: ;mov a, # ' . ' ;move (.) into A ;acall ' cout ;display characfei mov r4, #0 ; i:4 will count up checksum acall dnld ghex /get hex character (No. of data bytes) mov rO, a /move No. <>f data bytes to rQ mov a, V .' ;move (.) into A acal] cou t /display '.' ehuraetot acal] dnld ghex ;qet hex character (starting adck . msb) mov dpit, a /High byte of load address acall dnld ghex ;get hex character (st.artinf addr. ]sb) mov dpi, a ;l.ow byt.e of .load addiess aca.l 1 dnld ghex ;get: hex character (record type..hex etc) cjne a, #1, dnld4 /jump if record type not 1 i.e. (hex type) sjmp dnld end /jump if record type is ] (non hex type) dnld4: jnz dnld unknown ;jump if record type is not zero dnld5: mov a, rO ;mov into No. of data bytes A jz dnld get cksum ;jnmp after last: data was written acal 1 dnld ghex /Get data byte mov r2, a ;move data byte to r:2 mov rl, #1 /specify counter bytes received acall dnld inc ;increment eounter mov , a, r2 ;load A with data byte lcall smart wr ;write byte, c=l if an error writing clr a ;clear A addc a, #2 ,-add 2 to carry (2~ written, 3" not. written ) mov rl, a /specify counter type(writfen or not written) acall dnld inc /increment counter inc dptr /increment dptr (point to the next location) djnz rO, dnldS /jump back to write the rest. t cksnm : acall dnld ghex /get hex and add checksum to i 1 conten I mov a, r4 /move checksum value to A jz dnldl /jump if not zero, to record cheek sum error dnld_sumerr: mov rl, #4 /specify counter type for cksum error: acall dnld_inc /increment counter sjmp dnldl /jump to beciining

104 ;Ilandle unknown .line type. dnld_unknown: mov a, i 0 /move No. of '.lata hyt '•• A jz dri) d getoksum /skip data if size is r:ot*> dnld_ukn2: acal) dnld_ghex /consume all of unknown data djnz rO, dnld_ukn2 ; decrement and jump if data not. finisher sjmp dnld_get_cksum ;jump to get checksum .************************************* ** * * ***** * *. /Handles the proper end-of-download marker. dnld_end: mov a, rO move No. of data bytes to A jz 'dnld end 3 should usually be zero dnld_end_2: acall dnld_ghex rconsume all of useless data djnz rO, dnld ukn2 decrement and jump i f data no T FLLLJ SII'MI dnld_end_3: ;got the last checksum acal 1 dnld_ghex /•move checksum value? to A mov a, r

105 ;Get parameter; and inc to next one (@rl), carry clear iI patamet 1 f, ;bit value returned In dptr. dnld _gp: setb c ; set. carry Cor nun r.er •> parm mov dpi, @rl ;put: what at addr. as dpi inc rl /point to the next mov dpi), t?rl /put what at addr. as Iph • inc rl ;point to the next mov a, dpi /move to check if dp! is zero jnz dnldgp2 / jump if dpi is it"! .:<. t ! • mov a, dph /move to cheek i f dph is z»ro jnz dnldgp2 /jump if dph is not re ro clr c /clear c dnldgp2:ret /ret urn .**< ************** fir*******. /A special version of ghex just lor the download. Does not look for carriage /return or backspace. Handles ESC key by poping the return address and then jumps /to the esc. key handling. This ghex doesn't echo characters, and if it. sees ':', /it pops the return and jumps to an error handler for ':' in the middle of a /line. Non-hex digits also jump to error handlers, depending on which digit. dnld_ghex: dnldghl:acall cm /input 1st digit acall upper /convert char to uppercase cjne a, #27, dnldgh3 /jump if not esc. dnldgh2:pop acc /else pop 2nd pushed pop acc /pop the Ist pushed sjmp dnld_ esc /jump to escape dnldgh3:cjne a, #"':', dnldghS /jump if not (:} boui u i tig > f record 1 i lies dnldgh4:mov rl, #5 /specify counter Cor wi onq i >e.q i ti o f 1 i na acal.1 dnl.d_.inc /increment countet pop ace /pop 2nd pushed POP acc ;pop 1st pus lied ajmp dnld3 /jump to begin!ng (we're on a new 1i no! dnldgh5:acall asc2hex /call asc2hex jnc dnldgh6 /jump if hex mov rl, #7 /specify counter for none hex acall dnld_inc /increment counter sjmp dnldghl /jump back to beg ruing dnldgh6:mov r2, a /keep first digit in r2 dnldgh7:acall cin /input 2nd digit acall upper /convert to uppercase cjne a, #27, dnldgh8 / j ump if not esc. sjmp dnldgh2 / j ump if esc. dnldgh8:cjne a, I":*, dnldgh9 /jump if not : sjmp dnldgh4 / j ump if dnldgh9:acall asc2hex :convert to hex jnc dnldghA. :j ump i f not hex mov rl, #7 /specify counter for none hex ' acall dnld_inc /increment counte L sjmp dnldgh7 /jump back dnldghA:xch a, r2 /exchange 1st and 2nd digits swap a /swap 1st digit orl a, r2 /or 1st and 2nd digits mov r2, a /store result in r2 add a, r4 /add new number to previous checksum •mov r4, a /store result into r4 mov a, r2 /move nev; number to A ret /return .**/****************************************** . /dnlds4 = 'Summary:" /dn'lds5 = ' lines received'

106 /dnidsda - " byte:- received" /dn.lds6b ~ " bytes wr.it-t.en" ; Print, out download summary, dnid sum: mov a, r6 ;move pointer low byte into A push acc ;push it mov ; move a, rl pointer high byte into A push ace ; push i t mov ' dpt r, Kdnldsl ;point 1o message acall pcstr h /display it mov rl, Udnld parm ; move download parameter value in r 1 mov t.6, #dnl.ds5 (, 255 ;move "line ieoeive.1" low byte in ! (> mov r7, fldnldsS » ; move "line received" high byte in 1 acal 1 dnld iO ; ca 1 1 download item display m<>v •:.'> ; tin ivo "byte |eeejve<|" low byl e iii ! 1. it>, lldnl.dsGa h ,'. mo v "byte t e.i vei ; mov" r acal J dnld_i 0 /ea I .1 11.>wn 1 on. 1 i Vein d i sp 1 • iy mov r6, ifdnldsCb S ;;.'.;> /move "byte wt.it ten" low byte in t i. mov r7, #dnlds6b >• o ;move "byte wiilten" high byte in i 7 acall dnld_i() ; call download item display 4***4*1; ****** # * * * 4-+* » * 4 * * 4 * . dnld_err: ;now print out error summary t mov r2, #5 ;make r? as a counter dnlder2:acall dnld_gp ;get parameters jc dnlder3 ;jump if any errors djnz r2, dn.lder2 /decrement and jump t.o see other paiameter /No errors, so we print the nice message mov dptr, #dnldsl3 ;point, t.o message acall , pcstr_h /display it "No errors detected" sjmp dlnd_sum_done /jump to summary done /There were errors, so now we print them. dnlder3: mov dptr, #dnlds7 /point to message acall pcstr_h /display it "Errors :" /But let's not be nasty... only print if necessary mov rl, # (dnld panni 6) mov r6, #dnlds8 & 255 move "bytes unable to write" low byte in r<.> mov r7, ttdnldsS » i! move "bytes unable to write" high byte in r7

acall dnld_item call download item display mov r6, #dnlds9 S 255 move "incorrect, checksums" low byte in r6 mov r7, #dnlds9 » ft move "incorrect checksums" high byte in r7 call download item display acall dnld_item mov r6, #dnldslO & 255 move "unexpected begin of file" low byte in rC mov r7, (fdnldslO » 8 wove "unexpected begin of f.il*»" high byte j n r7 acal .1. dnld_item on 1 I down 1 oa-1 i t em < I i sp 1 ay mov r6, #dnldsll & 255 move "unexpected hex digits" low byte in r6 mov r7, #dnldsll » 8 move "unexpected hex digits" high byte in r7 acall dnld_item call download item display mov r6, #dnldsl2 & 255 move "unexpected iion hex digits" low byte in rt. mov ' r7, #dnldsl2 » 8 move "unexpected non hex digits"high byte in r7 acall dnld_item call download item display ********** 4 * * * * * H * t*» 1****4 •*•*** * *****. dlnd_sum_done: pop acc /pop pushes and put in r7 and r6 mov r7, a /move A to r7 pop ace /pop to A " mov r6, a /move A to r6 ajmp newllne /display newline and return to menu .**********************.**********************•******. dnld_item: acall dnld gp /get parameters (ertot conditions/

107 jnc dnld i:< /jump if errors dnld_i2:acall space /display space lcall pinllGu /print value acall r6r'/todptr /make pointer to the messauo acall pestr h /display the message dnld _i3: ret /return A*****AA**A**A*AA.Ai*Ai**»A»i» . * * fr* • A A- * * . *• * * dnld 10: acall dnld gp /non-error condi f.i.ons sjmp dnld 12 /jump to r2 . * A * A- * * AAA A A- **A /Initialize ail dnld parameters to zero. dnld_init: mov rO, tdnld parm /load r I with oarm base ddt . dnldO: mov PrO, !I0 ; e 1 OH I i i inc rO / go ! ••• the ii">:i cjne 1.0, I)dnld parm I 16, dnldl) ; 1 oop lo cleat ;1 1 I ret /tot iun

/dnlds'7: Ktrors:" /dnldsS: bytes unable lo write" /dnlds9: i ncorrect checksums" /dnldslO: unexpected begin of line" /dnldsll: unexpected hex digits" ,-dnldsl2: unexpected non-hex digits" /dnldsl3: 'No errors detected"

/jump routine asks for I he address to which il will lump. II escape[C~II was /pressed, the program is aborted. Tt NO address was entered (void input, psw.!f>- /the program leturns to where it was. When hii addres is entered the program mak /stack of 6 by!e length and jump to ihe specified address, jump: mov dptr, HP romp T (1 /load pointer with messaae addr. aea .1.1 post r H /display the message aca 11 r6r7 tx» iptr /to prepare data in dpt I FOR next 1 unci ion acall phex1b /display address content mov dptr, #prompt4 /load pointer with message add. acall • pestr_h /display the message acal 1 ghex16 /get hex value (dptr value) jb psw.!», j ump3 /jump if flag sol jnc jump2 /jump if carry not. set. ajmp abort2 /otherwise abort juirtp2: a call DPT I T ..T-l.RV /save dpfi •••line IN Iand I / jump3 :. acal 1 new Li ne / outpu I: a .1 i no mov dpt) , '1 runs 1 /toad point ET with message ictrir . acal I pcsti. II /display THE message aca 1.1 r6r7t odptr /restore pointer /Jump to user code I'dpur: (this used by run command also) jumpdoit: clr a /clear A mov psw, a /move A to psw mov b, a /move A to B mov rO, #7 /move 7 to r 1) (load countoi ) jditclr :mov @r0, a /clear. 7 addresses djnz rO, jditclr /loop to clear mov sp, #8 /start w/ sp**7, like a real reset push acc /unlike a real reset, push 0000 push acc /in case they end with a RF'.T jmp @a+dptr /jump to the address

108 ; clMttij. d isplays K> lines of I (j address 1< i on .in ii'-:-: it anal !•••:.! ide i! disp!.-, /the a soi i. oqn ival.ent of address content T!v-- si nil i n add! ss i:- ! he enlout ;r6-r7 dump : mov ' r2, #16 ; No. of ! i nes i*> • or i ul acaJ 1. nowl ino>' /display new I i tie dumpl aca.I! r(»r7l odpfcr /to prepai" daia in dpi r !•>• nevi !un>:! i"i; acall phexl(> /display addr. location io 'lump in mov a, » ' : ' /move : to A aeal I eout sp /display : tnov r3, #lf> /r3 No. of hyfes to piint acal i. r bi:7l'..ilpl i /to piepaio dpi i I.a u< -xl timet ion dump 2: ol r a /cleat A mo Vi: a, Haldpl.i. /read .ukii i'sr. ••oil oil Inc dpt. r / i noionion! dpi i aca 1.1. phex /display each byte in he:-: acall space /display space •rl jtr.: r3, dump? /.loop I f>t next' byte. acal i dspace /display double space mov r3, #16 zr3 No. of bytes to display hex and non-lies aca! L c 6i:7 todpt. i /make the pointer attain dump 3: clr a /clear A move a, @aiclptr /read again ine dpti /point to next. aril ,a, #0111111 lb /avoid unprintable characters • 127 c jno n, # 127, dtinip31> / check i !.' i s not | 21 clr n / if .127 delete ehatael dump 3 b add a, #224 /add t.o screen control eharaetets jc duiop4 /carry means no eonlio) chat act ••! clr a /avoid control ehnrael"rs dump4 : add a, #32 /addition to compensate for X24 addition a call cout ;di spI ay cha i actot d in:: r.5, dnmp3 /loop again to display next cliaiaclei acall nowline /display a new line acall line dly /delay acall dptrtorf>r7 /save dptr in r6 and i.7 acall esc /call escape jc dump 5 /jump if esc was pressed djnz r2, dunipl /loop back up to print next, line dump5: ajmp nowlino /jump to newliiie to return to menu

/edit routine edits external, rain. It displays a luossaci" at. t lie start to lc-t lire /user enter the address location he wants t.o edit. Then It. displays the address /beside it's content and ask the user to enter the new value. When hex character; /are entered the routine modify the specified location and move to the next /address. If non hex characters entered the routine displays a message. edit: mov dptr, tfodit.sl /load dptr with message addr, acall pcstr _h /display message acal 1 r6r/todptr /to prepare data in dpt.i tor nex t. function editl: acall. phexl6 /display location pointed to by dptr mov a,#' : ' /move : to A acal 1. COIll. Sp /display : mov a, 8 • ( • /move ( to A acall cout /display '(' acall dptr tor<>r7 /save dptt iu r<> • uid 1.7 clr a /clear A move a, @a+dptr / read dpt: i addi . Cent enl. and

109 acal] phex d.i sp ! ,

acall r 6t.'7todpti. 1 ,.r:! . ,, , . ,|p: , ,,,;>. i no dptr point t • •)!•• !!•:•:' aca 1. 1 dpi. r I or in 7 r.a• dpt t is: t '. u>' ajmp edit.1 loop 1 ..•,(•!•. edit2: mov . dpi: r, (fed] 1 s2 load dpi, ' i; a j mp pest i. h d i S| • 1 ay !i"":::' ! !•

;dir routine maps the display !• 1 •-•••'!•! : •:' •!,!•: ;in the memory to the display, it s s by display in /searching for headers . .11 d i sp 1 ays ;finds. It continues doing this for dir: mov dptr, ttprompl '* ;po:„, i r-ss/ acal 1 pes ft h ;di splay :'">ss v

mov t 0, 112 1 ; !•-•') t <• • = • a = dirOa: acal 1 space? /'•lit put 1 Sp V djnz rO, dirOa / Ic.p b:<<-'-. it i ;mov dptr, II prompt 9b ,M"'' i nt • ••• acall pestr h / d.i sp 1 .ay rv •:=." c mov dph, tt(bmem > - 8) /load dph with dirl: acai 1 find / find ho a !-.. j <-• dir 2 / pii'.ip i I ho... |ci dir end : a jmp new]ine dir2: acal I dspaee rdisp' iy ,• mov dpi, in 2 /poj nt ' • • 1 aca] 1 pstr rdisplay it mov dpi, 1(32 /point aca.l 1 1 enstr :! in 1 ! mov a, #33 :b-,l ;, ],- c i. j. a, rO subb tbt mov rC), a I n

mov a, #• ' ;|..=,.| spa-- irp dir3: aca.l 1. cou t /display spa--o djnz rO, dir3 / loop to display mov dpi, #0 /point to headot acall phexl6 /display the h'>.- mov rO, #6 / !ea I count °i mov a, #' • / 1o;vl ' o di spl ,\ dir4: aca] 1 cou I /displ iy spac- djnz rO, dir4 / 1 Oi >p (• t i !!•/'•.•< mov dpi, «4 ; po i n\ '. • • \ i i'.t s • clr a /cJ'vu: A move • a, l?a+dptr /load its t ypo mov L-2, dph /save this, dir5: cjne a, #254, dir.M. / jump it <:••'. !• t mov dptr, #lypel /point ! .. ..;:> ... sjmp dir 7 / inrip to I; . •• p.- dir5b: cjne a, #253, dir'.c / jui-ip i ! ti' ' H t dir5bb: mov dpt. r, Iltype4 / r •' : ;'• '• • • .•• • . i' '

I 10 s jmp di r ? ; jump to i j 7 1 u-! ok air 5c:: cjne ' a, 93:., dirl.d ; jump if not 2 "Mi mov dptr, #t:ypo2 /point to ordinal y pioqinn1 s jmp dir7 ; jump to ,i j t / i..<» 1, ,w Ciir5d: e jne a, Il2i'i, dir.'je ;jump if not sjmp dLr:r>l.i. ; jituip to d i i M>b dirbe: dir6: mov dpt. r, II type 5 /point' to ??? dirV: • aeali pestr li /print, out the type mov dpi), r.2 /(jo bark and find the next one acal! newli i.e /display new lino mov a, #(emem ">> 8) /.load end memory hin.li byt o cjne a, dph, di rH /did we just display the last "M ajmp d i i. end /jump to dir end dir8: inc dph" /Increment, dph mov a, dpi i /move dph 1" A with emem high by! a, !l ( (omomH.) cjne 8) ft 255, cl.irl. /jump it net equal ajmp dir. end / jump to d.i r end

/typel=Ext Command ztype4=Startup ; type2=Program• /type5=???

/run subroutine searches file headers. When it. find a l.'iiri-proqram, it prints its /name on the screen in a formated layout. When it is finished, it. asks for the /choice to be entered among the list. If esc. is entered the program return /control to the menu, otherwise the input is matched within some ranges to check /it's compliance with choice list. When it is okay the headers were searched for /the run-programs in sequence. When the search is successful, the function will /pass the address to another subroutine (at. the end) , which will make a stack of n /byte length and jump to the specified address. run: acal 1 newli no2 /display a .1 ino mov r:2, «2V> /first, pr 1 nl the menu, eounl item:; mov dpt t , IIbmem /load menioi y beqininq dec dph /decrement dph run?.: inc dph /increment dph inov a, dph /move dph to A to compare with emein high byt

s cjne a, # ( (emem-i I) ' > 8) & 25ri, i un2b /did w i each the end sjmp , riin3 /jump if we reached end run2b: acall find /find header jnc run 3 /have we found thorn all? mov dp 1 , If '1 /point to figure out its typo clr a /clear A move a, Oatdptv /load its t ype orl a, HOOOOOOllb /check specifiei |>y orl and epl cpl a /complement A jz run2 /if zero, this one doesn't run... find next. acall dspace /display double space inc r2 /increase Ho. of successful headers mov a, #'A' /.load cliar.act.er to be used as 1 ine-mimboro add a, r2 /change line-charact or s acal. 1 cout. sp /display J ine-eharao! oi and spa':" acall dash sp /display dash and space mov /point to header name acall pstdpir, 1 32 /display it acall newline /display new line ajmp run2 /back to continue find job run3: cjne r2, #255, run4 /are there any more to run? Jump if yes mov dp! t , (pr<•nipt'•> /point In »!•'.-sa-!•' >• i.oOii.i the • a jmp pest 1 It /display il

1 till IV > Ipt i , llpr empt. ', ; ask lie 1 > i q quest i.. n ! aoal 1 pc.-:;tr h /display it mov a, I'A' /load A charade! as (.-.tot .| ta nqe i aca 1J cout /dlap 1 ay i t aca i J dasli /display dash mov a, #'A' ranqo) /load A to add to ,2, as (end of acid /add r2 a, r.'/. acal 1 COIlt. /display addition result mov dptr, If prompt'I /point t.o message r».|adinq the cli Oj CO aeall pestr It /d i sp t ay i 1 acal 1 cin tilt.et h ,-qet input --hat act.ot c i no a, 1127, runlaa / jump i t not • F.:"c • ajmp newli no /when esc jump and ftiini '•• menu run4aa: mov r3, a /save chat aetor in i ' mov a, #31 / load A wit It 3 1 clr c ; o.l.ea i , -at ry lot I esl subb /subttaei Me .-.(' i|.>a..lot r. (s-a oi e 1 <: 11 c.i i t y 1 a, i 2 mov a, r3 /move ehaiactor info A again jc run'I a / jump if headers moie than 3." aca 11 upper /change character to uppoicase rurrla: acal. 1 eout /display ehnraotei mov r 3, a /save in rI aga i n aca.l .1 new!in" /di splay new | i hp ;Check to see i f it's under 32 , if so convert to uppercase. mov a, t-3 /load ehaiaotoi info A add a, !! (2!iCi - ' A' ) /convert chat into a No. slartinq fi'om ".(it•• jnc run4 /jump back, if no carry (typed l.<-•ss than 'A') mov • r3, a /load 1.3 with the No. typed mov a, i;2 /load A with No. of headers clr c /clear carry tor Iesl subb a, r3 /subtract 1 lie No. typed finm No. of header;! jc run 4 /jump 1J catty (Mo.typed more than max tango) inc t.3 /increment- No. typed mov dptr, II b mem /load bmem 1o 1 ind the headei dec dph /decrement (oi adjustment run5: inc dph / j ncremont. dph mov a, dph /move dpli to A to compare it with emem high byte cjne a, # ( (emend 1) >• > 8) & 25)5, ruu5b / jump if not re.ae h the end sjmp run8 /else jump to end runSb: acal 1 find /find header jnc runB /Shouldn't ever do this jump! mov dpi, #4 /point, to f.iqure out its type clr a /clear. A move a, @a-»dptr /load its type orl a, #0000001 lb /check specifier by or 1 and cp.l. cpl a /complement A jz run!i /if zero, thi.s one doesn't" run... find noyt djnz r.3, run.') /count til we find the one they v; •ml ana 11 newline /display new 1ino mov dpi, #64 /point t.o header ajmp jump doi.(• /jump 1" process (in the it imp- f ui > •t ion) run 8: ret /return

/help routine :s envoked from the menu. It displays help text and jump u> lie.lpX to /give'information about the help. help: mov dptr, #lielpitxt. /point to messaqe acall pcstr: h /display it

112 mov r4, llholp key ; 1 o.id • -i w i i ii Hi • • p k-y mov dpt r, Kiielp omd ; pi > • lit 1 o llie;j)j,J..|e acall he 1 p2 ; c. 11 1 lie ] p.; rmiu ui i w mov r4, #di L key /mov dptr, Kd'ir cmd acal 1 help2 mov r4, linn key ;mov dptr, 11 run cmd acal .1 I.e.l.p2 mov r:4, Hdnldkey /load 1.4 with help Ify ; mov dpfr, II do Id cmd ;pei nt t e message aoa 11 lie 1 p2 ; ca 1 1 lie] p/ subt mil i»»* • inov r-1, II up Id key ; mov dptr, Hupl

aca.l 1 helP2 IIIOV a, Alias Hash jz help skerim mov r4, llei.fr key /load r4 v/i t h help lie-. ;mov dptr, llerfr cmd /point to message acal 1 iie.l.p2 /call liel.p2 sul.rout, i !)• help. erfm: mov dptr, llhelp2t.xt. /point to help2txt acal l pestr h ,'tl i splay message

mov dptr, llbroem jnuivo tmietn 1 o dpi t ! •. se„,,:h help3: acal 1 find / fi rut headei jnc help4 / j iimp i ! ne hea' !• •! I ••un d niov dpi, #4 / poi nt' t <> 1 i guro out its t ype clr a ;c1oa t A move a,@a+dptr /load its type cjne a, II2•SI, help3a /jump if liel KK (ext command i acall dspaee /display double space inc dp] /increment', dpi clr a /clear A move a, @a t-dpt.r /move specifier into A acall cout. / d i sp.l a y S) >ee i tier acali dash sp /display dash and space mov dpi, #32 /point to header name aca 11 pstr /display it acall newline /display a new lino help3a: inc dph /increment dph raov • a, dph /move dph to A to ceinpa.t e it. wi fh eraem high cjne a, # ( (emend-1) » 8) « 25'j, heJp3 / jump If not reach the end help4:

113 ; he.! p2 print ••••• i j st an. la id I i nos of !K 'P. ;1 n dpti) in . •potato command above. help?: acal 1 dspaoo ; d i spl ay d< 'ul • I e space mov a, r4 /load A with help key acal 1 cout /display help key acall dash sp /display dash and space aca 1.1 pcstr h /display message point'-" i n dp • r ajmp newline /display new line and r»turn to ak I ep

upld-routine uploads hex files to the serial port. Hoy. file is a number •< •t data records terminated by CR and I..F. A data record example is as toliows:- : xxyyyyOOanbbcc.ddee liimZ!'. where : Start of record xx No. of data byte (two hex digits) yyyy Starting address of the lec'U'l (4 hex digits) 00 Record t yoe [jo. for hex file anbbceddoe....mm [lex data (two hex diq.il numbers., equal xx) 7,'L Checksum value of all data record digits Firstly upld gets the beginning address in r3/r2 (r2"lsb), mid the final :ldr ess in r5/r4 (r4-lsb), and prints them out. beside some messages. Then it reads data from the speed Tied address, process it and sends i I r. t he • •rial pott in th* above form.

aca 11 get mem /get command local i oiir; mov dptr, Huplds /point to message (.'darting adi acall pcstr h /display i t mov a, r:3~' /move high starling addr.. byte aca 11 phex /di splay l: mov a, r2 /move low starting addi. byl • I e a aca 11 phox /di spI ay i t /mov dpt.r, Sup Ids-! /point to message !in I i mi a. Idi . ) aeai 1 pes I. r /•lisp I ay il mov /move high ending ad-ii . byl e to t acal 1. pin / d i sp.l ay i t mov a, r'l /move low '-nding ,iddi . byt r- to A a call phex / d i.sp I ay i ! acal 1 newli no /display new line .-Need to adju:: end location by I... mov dph, t-5 /make dpi.r . Move rS to dpi-, mov dpi, r-1 /move r'l to dpi inc dptr /increment dpti mov r4, dpi /save dptr.., move dpi to r-'l mov t.S, dph /move dph to r5 mov dpt.r, IIprompt7 /point to message acall pcstr h /display it. acall e i n /input any response cjne •i, 1127, upld.V /jump il 11-'l escape ajmp abort i t /jump to al'oi t and uMurn t /output new Iine upld2e: aca.l.l new 11ne /make dpt.i., move i A t.o mov dpi, i2 dpi /move r< to dph mov dph, i3 /clear c upld.3: clr mov a, rA /move to A "ending addr. low by! . subb a, dpi /subtract, "starting addi . lower hyt' from A mov r?., a /move rest to r2 mov a, r5 /move to A "endinn addr. li i.Q'i by to. subb a, dph /subtract, "ending addr. lower byte" from A

114 jr.". Upi.Pl ; i:itn}• i ! •..".<. 1 • • i i , ' in -n i. • i,•••::' i 1. mov a, t. / ; move i ewei 1 >y i . oi1l | . . .-. A i "• lipid'/ ; jump i ' ill • l<>iie a til tiled in 11> I >yt.e packatf. jnz up.id 4 ; i 1 >.. 16 left, then do next 16 i, fill 1001)01. ; becaiisi. • da! .i man i pu sjmp lipid*. /otherwise just jini upld'l: /load r2 with the No. .sl i of it datoffa 1 •• upload upId5: IIIOV ar.z,, #m< • >: ' lUOacaV I : /displa/ bou in y t h(:e ) I i tie inov a, >>r Z11 /load A with No. oi data to uploa •leal 1 Phex ! .yl.es f • > up iloa«i d acall phex 1 f. /displa/d i sp1 a yy memoiNo. ofy d1-it oc a mov a, dph /make ehoekssum, inov. t ion add a, dpi /add lower adfii. byl • - • hi'ihei i«ld> . byl '• t •• -\ add a, i 2 lplo.,.1 > /add No. ..! dil a 1 e . clr a /clear A 111' VI 1 i, .1 /slur e . .||< •. -(:•-! mi in 1 acal 1 1 >: /display 0(1 (.-...).• I',. e.l r a /clear A i ic.i I yp. : upld6: move a , Wa • • Ipl i a call phex /display each byte / pul ad Ii ess 1 • i. m i i. o oi. ,.., • j |,! acid a, r 3 /update checsum /save checksum in r3 111in'c VI dptri.3, : a /point" to next: addr. d jnz r2, upldO /dec; emeul. and jump :s i.nce inoi •.• ;., •I.es need in mov a, r 3 /prepare checksum I'm out put op] a ; compi emenl' checks'iin Inc. a / ineremenl complement {olio' s • • mil •' 1 enieni ) acall phex /dispLay checksum acall tiewlirio /display new lino acall line dly acall esc /delay some t ime ipe is pen.fin 1 1 i lie jnc upld3 /chec/.if nko esc sepressee if d d. to e:.;c. sjmp abox 1 ii • i;e>:t roi'oi'i upld7: mov a, /move (: ) to A (i.eeoi d 1 i.ne star'. i / jump lr. db.it i i I )i< a e is escape aeal .1 cent: /display ( : 1 clr a /clear A acall phex /display zeros acall phex * it it a call phex i it ii inc. o ; i ncreinenl A acal 1. phex /display .1 mov a, »2W.> aca 1 1 phex /displa/.load Ay wKPi t"h IT upldR: a imp new 1 i ii"Z laoi: lop /display new i i ne .md return to s . * * * * * •» * * * * * * * * ***************•>•*.*. ly delay s bet ween 1 i ne while up 1 o.i'i i ii.j, so ! ho.sl c,n b< /(i.e. most windows sol'twaro) . Id tic delay value is determinehe !0.-ejy.d!Hc bf y oqu duritm ; ini t iali zat.i en. line dly: mov a, ril /move r fi emiton! -I'-'iii'i aec ; save i i) e.>nl . 'iii push ! o A f ei : inov i 0, 1! 1 mo del ay' 2 /.load rO with del ay 1 act oi i. i :•'! d2 : iiiov a, UiO /get baud rate ci •list d3 : inc • a /increment thO nop /no operation

nop * / . ii jnz line d' /jump back i| A n< • .-.oio djnz rO, Tine &,: /..leci einenf and jump back if del ay not zeti pop acc /pop A to restore rO

115 ;get mem sulicontiiie g«l.s I ho begin and end ioco ions lot .: ) <-v; commands. |t ;ESC or iin input 'nil "i'>(i, i.l peps it 's »wn lotm i» and '•• ' lie M"ii';.

.•routine is called by e.i rm routine and i: oil; :!,-vi ii i un ••! ions ' till u/ • Ipi.r, Sbeg sti ;poin;d i spl 1 .ityo I"askin wo 1 gi ip>slats ! j nq ad.lt. message" a .-a 1 i pcstr ii ;d isplay message aoaJ .1. gtiex 11. /enter the slaii ing addi jc pop i l ; •jtmip il carry sol (K.';.'.'. is p. esse.!) psw. '>, oop i I ; jump it 11 ag set (i -R. w push ,ipl, i 1 h hi 1 ! i gu I e • -n t e i. e-1', pusli dpi ;sav; save ,ipst a| i 1. i 1add i . aca 11. new.l irio ;d i sp1 ay now 1i no mov ciptr, Dot id st r ;point to "asking ending addi. . message" aca 1.1 pcstr h ; d i sp 1. a y mo s s a g e acal. 1 qhexl 6 /enter the ending addi . r!>, dph /transfer ending addr. t • rS and i 'i 111. mo IvV rl, dpi /1 ranst or dpi t '> vl pop acc /pop to i esl •>i o s 1.art i net addi . ( low byt e) i n !•'•' mov 12, a /move. ! o r>' POP ace /pop. to rosloio si irr ing addt . (high byt e)i u i mov r.<, a /move |. o i l jc pop i t. /jump i •' car i y set (h'.:~-C is p|.-SSe..i) jb psw.5, pop i t /jump if flag set (CR wi .•hour figure entered) ajmp new .11 ne /displ.y new lino and ret irn to stack pointer pop acc /pops to cancel pit.'-lis pop acc. t: aea.l 1 new 1 it to /dis|i 1 ay new I i n.> mov dptr, ilaboi t /point to abort, message ajmp pcst.r It /display it-

clrm subrouti; ie. clears a memory area. The range is obtained by get iu-mi; subr oil, i no and the clear, nice is carried by the smail: wr subroutine. The subroutine will scan all the range starting from the iowot address ami going upward I iII the end address. clrm: acal 1 get mem /get start: and end addresses mov • dpt.r, Inure /point to message asking delete ..Y or else acali pcstr h /display it acall cin_filter_h /enter Y or else acall upper /change character i.o uppercase cjne a, ft'Y', abort it /jump il not Y to abort acall newline?. /.if Y display new line clrm2: mov dph, r3 /point to addr., move starting addr. high to dpii mov dp 1, r 2 /move st.arting addi . low byte to dpi clrm3: clr a /clear A lcall smart wr /actual clearing mov a, r5 /move ending addr. high byte t.o A cjne a, dph, clrml /jump back if dph not: equal to ending high byte mov a, r4 /move ending addr. low byte to A cjne a, dp), clrm'l /jump hack if: not. egti.il lo ending low by!" ret ;return inc dptr /increment dpii clrm

116 ; nioe subi.oi.it i no pi • >ni|'i to the user lo ei,t<;i i |,,. new 1 • •<• i Li. ai. 1! n • .1' !' i I ' • s a vi • /enter od or F.P c was pie sscd ill e subroutine is aborted. nloc: mov dptr, 11 r tempi 6 /point to display mossa-v aoai I pesti. Ii /display it. a on 11 ghexl '"• /enter hex a I'll . jc abort..:.; /jump to abort if <:''•. pi.-ssod with'. lit 1! jb psw. 5, abort;' /jump to abort if KSC is pressed

acall dptrt oi(-.r7 /change dpi r returned by ghex If. t< r t.. H1..I t / ajmp riewli no/ /display new line and return l... menu

- /erf r subroutine prompt s to the user information about erasing some I t ea If the /user entered >Y' ,oi. 1 i •lase.s 1 lash and ioia, and -lipiays lues.-'ag.- alio il •• usure • ;abou r error. 1 t. uses e rn 1 1 for erasure. erf r: aoai .1 now! i ne>' /di sp.l ay t wo 1 i nes in.'V dpt) , if e i J: r cind /point to display in.-ss.ge aca 1.1 pestr Ii ;d i sp.l ay 1 f mov a, #\' /prepare to display ',' acal 1 cout sp /display and space mov dptr,' ilr u re /point I., display message acal i /display it pestt h acal 1 c in fill er!. /gel. input V oj "is.-- aeal 1 upper /convert to uppercase O j no • i, «'Y\ ,ibci l. i I / jump i t not Y to abor < aeail ni'-wl j ne>' /display donbl<> nev.' lines 1 oa 1 1 era 1 1 /erase .ill (flash and I>

; i n t in displays t he cent .111 o| I 'tt internal uddte-:s 1 • "-.it ions.. '! oiu• r, i •••• it-..- ! lues, ea :h one showing 1 i> local ion c.nleni . |l cni. io • -.:il I in• /display in V /display in tw .. loops o ie lei. I i lies. an. 1 ' h- • •. •! IH-U 1 "i I i am' •.

in tin: anal 1 new Ii ne /d.i sp 1 ay new 1 i no mov it), 110 /load r.ero in ill (1 n i t i a 1. ire count "i-l intm?: acal 1 newline / display now 1 i lie cjne i:0, #0xft t't, in I'nit /jump if counter oouteui is not. 12 a imp new!i ne /otherwise display new line and returH n to menu intm'i: mov a, ri) /move counter cent cut to A aca.l I phex /display eount.e: content (once ea--h H-. t iiii.--) mov a, #':• /move ':' to A lo display acnll cout /display 1:' in tan4 : aca.l 1. space /display space mov a, (•!) ti /move conl out of ad-lr. in '-ouuier t i • A aca 11 phex /display addr. . content i ne rO / iiicreinent count or mov a, rO /move count or ami nil to A an.l • a, 80000.1 1.111. /mask A with IS (organize every 1<. i n • • no 1 ine jnz /jump if: line not finished in tin A sjmp i utm? / jump for a new 1 i no

Memory Managmenl Subroutines

/flash wait routine polls the flash com wait looping until the I lash rum-is /Stable. DPTK must be initialized with I h'- address t" read.

117 flash wait

push h ;savo B loqistor 11< toqistoi is used'.

c i t: .-i ;eleai A m. -v i, /move what it dp' : t- • A fiwi: mov b, ;iimvf> A <-"nt or.l !.<> l< (or '•!i'""!;i,Uii i no r '• ; inci omen I ! el r a /cleat A ll|. IVC a, ;movo wlirtl- al. dpt t i-> A WAII! cine a, ;cciii[Mir- pimp Pari: i! A 'Hid )• n.J oqn. pop I, ;whon si able pop whit is pushed ret ; to I. u 111

; flash en roiUino sonds the flash enable codes for wi i I i ii'i. flash en: mov dot r, 8 flash on 1 addr /load dptr wi I h flash on' addi mov a, II flash, onl data /.load A with flash onl data movx fctdptr, a /move onl data to o;t i addi mov dpfr, II flash en? addr /lead dpt.r with flash on.- addi mov a, #flash ..en?, data /load A wiih Mash <<\\/ data movx ' fldpt l., a /novo on? da'a to on? addi ret / i et urn

/prgm routine • /rites Arc .into flash memoi y at. !>!TR. '' 'S sol I: oiio; oconis. /clear if .it worked. The routine uses flash en rout in", it calls also flash wai /routine after writing data. The routine then chock.-: 1 ho data written le set. .a /reset C flag.

prqm: xch a, lO / exchanqe dat i t.o wi tie with r (I push ;i<-< • /save A push dpi /save dpi push dph /save dph aca 1 1 flash en /do first step, enable wiifinq mov dptr, il flash wr addr /load dpt.t with flash wi addr mov a, II! lash wr data / load A flash wr da I a movx Pdptr, a /.send 1 lash wi il" eommand pop dph /iest ore dph pop dpi / 1 est et •• dpi mov a, rU /move data to wtite in'o a movx (•'opta , a /write 1 ho • la I a acal 1 ffash w .!! ; w.i i t mil. i i it's d< 'tie clr a /eieat A fa lost move a, fardptr /iead i 1 back elr <•: /clear C (as tlaql xt 1 a, ill ;>:•'! A and ri) )~ prgmotii 1 /'•limp i! data is wt il ten i .:• -1 ••>) setb c ;w!f n it- •! set o ::>•; '' (is II iq) prqmend:pop ace ; les to..-. A xch a, 1U / • -xchanqe data !•> write <••• i t h r'.; t.et /ietnrn

/erall erases all the flash rom and return '.:-] it t at lure, On il ol.. it ca! ! <. /erblock for Idock erasure. Then if scans all I he flash area if they are not /completely deleted (deletion ••• F'FI to signal eiior. When deletion is okay c---u /otherwise c=-.l (error) . eral1: mov dpi r , III i ash or? a. Idi / po i nl t. • I 1 isIk-i ac Mi . mov a, ft! lash or? data ; read addr . content a call orhlock /use orb.loek t.o send erase all. mov dptr', dbflash /point to back flash -vllr. erall?: clr a /el eat A

118 move i, i't.i t'lpta- ;r<-.id l.-i'-t: I lash I:K mory

•-'!51 i ; o- -inj •! .-•I:I<-.|. i i . |,| JNV. oral.I --11 ; check i I • i ' y. :. -i j I y e i aso.;i IN. •lot. I ; i ii'-i ,|pt ; IW'V l, I! i (oi.laslli I ) >. .15b) ;iiiu7i- Id k I--woi .-,ddi . |-,. A c j no dpi, ei.a.ll,' /lump l-ioi: |- bit M-.I !. i fi i ::l i. •• i mov a, S ( ( (of i-isht t 1 ••'- ti} ''•'S; /ni've id k l.i'iii.o .iddt . 'i o A c j no . i, • lp! i, e r..i 1.1..: /jump oack il ill not finish'-.i c i r. ;i-Jivii <•'., (1 i no » ot urn; ret ;rot nt n ual J nri: : pot b ; .•••>• t >', ( fa I so r "tut n j cot ; i e i 1111!

erblock is ia.se c-.-mmaii!.!. 1! is culled by oiuli, and is inl'-nd'-d t. callable Cfro m the Plash memory <:o that custom block ni,,<••<. co.|r. can ),,-. implemented. uses flash on subronl inc. erbiock: push •'iCC ;save Acc push dp] /save dpi push dpi) ;save dph aeal 1 flash on /send (lash '-tialdo .-Out! mov dptr, II f I ash ••u.l addr ;point: to flash blk mov a, ft !.I.1.-I1 '.,. ; data ;II1OVH flash erase dita movx 9dpt r, a /send "i:;i;«! enable aea 1 ! t lash on ;s<--nd 1 lash enable skull

pop dph ,-|e:;(o|e dph, dpi and Aoo pop ' dp] ; rest.01 0 dpi pop ace ; t>.--.-il;i>i e A movx Gdpt.r, a ;send erase command ajmp f iaslp w.-i i 1 ; jump to wait and loiui.n 1

/find searches for header in the external memory identified by the sequence /A5,E5,EO,A5. The memory range searched is defined by bmem and emem. The input /DPTR' pointing to the start, of search address, (on! y Mob used). Output: is DPTK

/location of next module, c - t;»| j « header found, >' - cle.o if RI-< more headers

find: mov dpi, fid /point, to headei clr a /cleat A move a, Pa-tdptr /point, to 1st specifier cjne a, #0xA5, fjnd3 /jump if Ist specifier not egu.-I i A'; inc dptt: /increment dptr clr a /clear A move a, Oa-tdptr /point, to 2nd specifier. cjne a, #0xliV->, Jind< /jump if 2nd spec.i 1 i.oi not equa ! Kl- inc dptr /increment dptr clr • a /clear A move a, Wa+dptr /point to 3rd specifier cjne a, OOxKO, Cind3 /jump if 'rd spec.ilr.ee nor equa 1 Kti inc dpt r /increment dptr clr a /cleat: A move a, l-laldpfi. /point to 4th specifier c j ne a, IIOxAS, fin.;13 /jump if 4 tii spooi fie-, no! oqua; A'. mov dpi, *(> / found one horn I setb ,~ /set (' (found f big status} ret. / ret 11 • 11 find3: m- IV a, li (emem :•'- 01 /load A with win hi (ill addi . byl •> (foi end check) c jne a, dph, find'! /compare and jump, il not. c. gual (n- .1 t lie end; clr c /clear C (the end flag status)

1l<> ret ;return f irid4: inc •iph ;keep on searching sjmp find ;jump h»i'-k to continue soarchinq

; smart wr routine tests the pi esenco nf flash I irst . II. in I lash was found i' wi i!< ; to i he ordinary PAM. When a I lash was found it checks the address to bo written ;to, is it in the flash ranqo or out. When it. is inside it uses prqm subjoin in • - f /write it's contents, otherwise it writes it's content in the notrtrtl 1'AM /Writing to l-'iash ROM or ordinary PAM will be indicated. Cny bit will indicate /successfully written (<.'-()), 01 nor wiiflen ((' I).

smat t wr: push ac< ; st oio A push b ;sl oi e l< mov i>, a ; in- ivo dal a to wr i I e i nl.• H ; Do we have a t lash |.«; mov a, Uh.-is flash /l.l'.ye 1 . • cliocl;, i s •lnqe flash:' j'' wr t am ; i i.im) • i ! tie || ,,s.li (has f bach • ,-otoi ;There is a ish rom, but is I hi; 0'ldt.ess in it : mov dph ;move dph In A to • .la 1 a 1 o writ o i ii I-. back ! o A lUOVX fldpf.r, a ; writ '.- the va J no t o memory cir a ;c1ea r A move a, '. idpfr ; 1 e.-,. 1 i t 1 ,.•)(-1 | i . ,ni e.'-do memory clr c /clear <\ subb 1/ h ;subl tad i.o chock i s i. i wr i ft '.'ii jn :>i:it, tro!: movx (•'dptr ; read i t back fromi dala memory a t clr e ; cleat <: sub)' a, b ; sul.M ract to chock 1s iI wri t ten aqa i n J* smwrok ; lump if successful smwrbad : setb c /set. (.', no! sue.cos sfu 1 sjmp smwrxiI ; inmp to 1 est ol e ;> lid 1 e 1 11 til smwrok: cl r e /•dear C, successfully written smwrxit. : pop b /tester" !< pop ••to ; resl oi e A ret / I ol. in 1, wr flash: mov a, b /move data 1 o wi i f e i ;i H back 1 o A lea 11 prqm /wri fes A i tit o f 1 as h iiioiii"iy at dpt.i pop b ; 1 esl oi e I' pop aec ;res tor" A ret ; ret ui tt

Power-On Initialization cod"-

/poweron make the hardware to bo initialized by I lie following routine. Description /of poweron routine is embedded in the text. intr_return: reti /return from inter!upt poweron: clr a /clear A mov re, a /reset inter nipt enable tog.istei

120 ir.ov ip, a ; i es»l. in'oirnpt priority leqisioi moy psw, lipsw ini.l ; i n.i I i a I. i y.e pi og: im stif.us wui d /Clear any interrupt status, just .in case the iirpi put "Pimp 0" ins vie theii ;interrupt service code. aca 1.1 inft rotm n ;clear ptnbabl e iril eiri.pl (call aca.l. 1. int'.r teturn ;clear again ( ea 1 1 vdd sub rout ill"] cp.l i /complement A to re set a 1 i. p. .rt s. inov pf>, a ;i"set port 0 (all poi l s b bin 1 mov P i . a ;reset poit 1 mov p2, a ; I esei. noi I / lllOV Pb a ;Ieset port < • niov sp, iistaek ; ! oad si act. p,,i n i. • • i with si a. •!: if-11

Betore vie st a i 1 do i iki any 1 /' ,> a she: i. .|el ,i y i:: rogu i imj so l hat V est na I /hardware which may be in "reset mode" can initialize. Th.is is I yp •. -a I I y -i f •• ol /when a P2C.r>!> .-hip is use,) and its i esel line is driven I r.-in t ho K-i' i..;-..| cii<

/used for the snvi. Because the 02'.:',!.. reset pin switches t i .,m .-er.. i, • ,

r /higher voltage than the >.<.').> i., any H2C'.1. chips would si i.! i be in tes.->t mo.jo > j. /now... rst_dly: mov rl, #200 /appro:: lOOOOn cycle- rdly2: mov r2, #249 / bOO cycles djnz r2, rdly2 /decrement and jump back if" t.2 is not zero djnz rl, l.d.lyi! /decrement, and jump b-vk it rl is not. zeio /Check for the•Erase-on-st.artup signal and erase flash KOM if it's there. mov a, Dlias flash /Load Mast, installation flag int. A jz skip erase lump if has flash is zero (flash not installed) mov a, Heraso_pin /otherwise move oiease pin st.slus into A jz skip erase /jump if eiase pin is zero (eras" pin no' enable' mov rO, #250 /load 2"SO Into rO, to check 250 times, to be sur chkerase: . mov c, etaso pin /move riw pin status int.. A mov rl, 11200" /load rl wilii 200 (delay time) chk erasl: d jnz rl, chk erasl /doeremetil r I , loop in same I in", it it s not ze jc skip erase jump to skip erase if eiasc- pin is high djnz 0, .-hi-, oiase /decrement r'l and jump lac); ;f uoi ::•- >. leal 1 •!i a.I 1 • le.l et e all flash /Run any user i ui t ia 1. i za t i on programs in external memory. skip_erase: tnov b, H2-19 /load P with 24'> (si art up code) aca.ll st.code /do start up code /Initialize the serial port, auto ban I det.ee» il nece^p.-n y. acall autobaud /set up the sot in I pott /mov a, t.hl /load I im<• • i high byte int.- A /lcall phex /display limerl tiigli byte /Run the start.--up piogiams In external memory. mov b, !!2V /load A with 2r>''. (si a r ! up or- | . II. p 1 : • • I J. .-I!'l aca] i steode /call star I up code /Now print out. wo.le.eme messacio sve 1 come: mov ru, #24 /load in with X4 (l-|... oi. lines to displayed) welcm?!: leal new.I. i ne /display new line d-jn:: i 0, we 1. cm2 /decrement rO and jump back to d.i splay next lint mov r-0, #la /load 10 with I r> (Do. of: spaces to be displayed) mov a, ;!• ' /move space I o be displyed welcm4: lcall cout /display space djnz rO, weLoro4 /decrement. rO and lump back to display n<\--;. spa*, mov dptr, 1' Logon) /point to logon! message lea .11 post r /display it mov dptr, S logoti2 / poi.nl to Iogou2 message

121 leal 1. pesfcr /display ii leal 1 dir. /..-.all di:oot,,iy idisidys Iff files and ••.:<••.•• mov rO, 8 (pgm *. 2'..a) / load i. << with pgm I • >w byte mov rl, 8 (pgm >> H) /load r7 with pgm high byte ljmp menu /return Io menu

/steode rout.in.- is invoked automatically during pow"!'..n at t h" star! . '."his r .ui : : /will. Look f'oi sl.ail.up specifier (241) .,m<is. When ii is success': i , i /save i1:s return location arid 'pimp l:r.> that star! up sub,outino. When il nonius i! /continues so.nchi.iig tor others and rloes 'he same unt'il all startup routines a?e /finished. At. tliis moment the f.uof.ion will ifhui; hack "o pow-aon routine.

stcode: mov dpi t , !ll'.iiiem /Joarl hmeiii lu ;••-a i ••!•. i nq st.ii'up toitrin"s stci'drv': J ca i. 1 l in.I / I i nd h'-adot ••! Mies

jnc slcdo'.'. /jump, sine a.l i o. .:,,m.i!i. is so.-, i hod and no lr-on- mov dpi, l!'l /point to (brute onl its type cl.r a /cleat A move a, Haldptr /load its typo Cjll" i, p, SI cod""' /j l.llll| '. '• I V| •'• II"1 l: -It. 'h'.S .••tarlllj !' '.'I •-• push b /stoio the I yp>- push dph /si.'i.. ttigh hyt •> ,q : ype addi. mov a, II (strode.-! 4 /:5!>) /move stood" •! add! . low byte f.o A push acc /st:"io stood".* addr . low byte mov a, II (stoodeS •• 8) /mo»o st..co.lo.< addr. high byte to A push aoo /sto:e .strode* ad.'h. high byte, mov dpi, I11>1 /p.iii! to stat tup headoi clr a /cl«.'ii A imp tlaldpti. /jump to the slat tup code stcodea:pop dph /hopefully it'll retui n to here, restore dph pop b /restore b stcode4:inc dph /increment dph tot another sear..:h mov ,i, dph /iiii-'Ve dph to be compared cjno a, Il ( (oiiiem I I ) •• K) *, steed".: / iiimp back, i! "ml not i "ached stcode5:ret /now u" "xcciil 'al all

autobaud routine is invoked automatically dining poweien o the si art vii",- > !.• following .iino is •:•••>i octod . egi.i baud const, 0 /flag for automatic baud iate detection

To do automatic baud rate defection, measurement, and sotting. It. is assumed thai the user will press the cari'i.iae return, which will cause th" below bit IMI nun to appear on port H pin 0 ("K ~ ascii code of decimal I"'. (OlMi),

0 1 ii I 1 0 0 0 0 1 1 I II / start bit i- ^—Isb msb—i i stop bit /To set the baud i.ate, the following toimuli is applied in "a ten la I. i on. / baud__const - 2S6 - (crystal / (l:- *• 1 i> ' band-rale)).

/Timer 81 is started in 16 bit mode at the transition between the start bit. and /the LSB and stop it between the MBS and stop bit. Thit will give approx the /number of cpu cycles for 8 bits. Divide by 8 for one bit and by 16 since the /built-in UART takes 16 timer overflows for each bit. After division the tesuil /has to be inverted since timer 81 counts up. Of course, timer III gets used in 8- ;bit auto reload mode for generating the built-in tlART's baud rate. autobaud: • mov a, Hbaiid_const /load supplied baud ran constant jit 7. .nit oeud jmp ; i iintf • TO an t . .en-! imp mov a, ban.'! S.ivf'I ; I oad baud "n.l n- I't n b i I •••it -b.ii... I,

mov tmo.i, II 0x1 1 /configure I inters V I ai aof b>li '.i BIT clr /clear A mov toon, / i eset I* iMOT*0 and I imeil •:••»»! i • mov ! 10, /clear timet 0 lew byte mov t.hO, /clear timerO high byte mov til, /clear IinuIL1 low hyi_'- mov till, /clear t liner 1 high byte

;Make sure there is no act is ity on the line hefoie we actually f .eg i n 'o,-.l: ing ;the carriage return. mov ITT, II .'00 /load HI with ,00 lor delay fact-ui autoblbtmov r.l, NO /load r I with '.fi In delay I act m ^ autoble:jnb p 1. (l, an toll! / jump i I pin p <. 0 is • • n-i djiiK rl, antobfo /decrement delay laoto.,: and i,., ,p i! net :•••. re • dj nr. ri), ant obib /decrement delay laid a 1 ami I OOI • it net :-.ero

/Look for the bits oj t bo can bine relntn. Wait f.a slait lot- in I HE I j I s! | /until! it is lew ,.ga i n . Then .heck il a LEV; n-..:- t im-.s, in o'LI'-I lines, t ••> v.i /SUIE WE DELL'! I: bc|. ' '•(, some lioi.SE. a ut ob;': jb p.i.ti, aui ob /.LOOP I ! PIN PT. ILGH jb pf.!>, an fob/ jb P-'.O, nut ob: jb pM.0, anl ol>2 jb p.<.0, a lit obi: autob2b:jnb p.?-.0, autob/b /wait fi.i bit 110 /Here counter L will start I Lmlng the UK dura' ion dm ing its FT bits shown abo /After bit fimerO is skarl -od t.oo. When t he stop bit c-mes (after bil '/) th /timers are stopped. setb trl / now we' re t i m i n't i t. autob2c : jb t fl, autobl. / check 1 or t inieoiii wh i 1 o wa.i.t i ng

jb r.2..O, aul.ob2e /wait for bi!.. * 1 t o begin autob2d : jb t N, aui obi /chock lor riiii'-ont whi1e wa iI i ng jnb p-<.n. aui olvd /wait for bit !I2 1 O begin autob2e :jb t; i, an 1ob1 /check loi 1 iiiieout wh i 1 e v.'.i i i i ng

) 1 ' pt.O, ante)-:.'.. /wail lor bi l II-1 l • • begin ?e t:.b i I ('1 / si art 1 i II; i ng I ast '1 bil s autob21 :jf. IN, nil OBI / '-heck lot 1 i me. >u! whi 1e wa ii i ng jnb P bit, aui olv'f / wa.i t f • -r s top b i 1 to begin clr tr I / stop 1. i mei 1. clr trO /stop timet 0 jb ff 1, anlobi /check foi I' iin..out olio ):n.r,< i lino /Compute the baud rate based on timer!. This is .lone by dividing the i imnr v: /by by 16 and then by H because timet is in fast baui (doubled; mode.'''he liv /is done by canoe.! 1. i rig timer! low byte except the most si gn i f.i ••anl bit which /shifted to fin.oil high byte as least significant byte. i:,oV '., t '• [ /move I ill'" l ! b >w !<••/><• i •> A Mt: i /rotate A bo'I wild cart-, mov 1», a r-in'JVfi A , onl out i.- i

n.ov a, I.hi /move I- i i I di'ld I •• V' • - ' A. rle a /rotate A I "II wil'n ea t i y "jo autoh! /oiror if timet ! • o'V.Y:' /After division by 1 (> and by l<, wo hav i« ili«i-lc by i.S. 'I'd i :• a) a o:: i ma I "O i /adding bit."' wnioh is equivalent to bit .

c:pl. i /complement A I" in 1 !•.•'• ;i ii"oa I. i v'• >.i snbt i a..:! i >-i ino .. ;add I !•< m.iko i' ••qaii. |.. ( ..'SO A) jz aul.obl /jump il baud rate !.>•••• fast

/AL'l.oi we qel I do rin • ago retail., k" n""d i'•• rr.a 1: • • sure I h'o " i on' t any "crap" ;l;)lO serial Mil", as ! here is in the oa.se wet" we qel lh" ini !•'>: K (and oonol'l' ; the wrung baud rat"), ltntorli.mate.ly 1 ho simple appioaeh o! iusi looking al I IK ; Line dor. silence doesn't woik, because wo hav I-, ..•-••ep' I |t< • ease whet > • ' Id-• /user's tormina I emuiai ion is eoniigmod !•• send . lino to,...] .nio, i oairbvi< /return. The b"-st thinq so do is lis.; Hi" nail and .b-.,k so-- il it i o.-o i ves /anything. If. nothing received, there is an eitor. antob!): mov thi, a /move auto to timer I h i.qh byte ('•• 11i I q : i :r."i i ; mov til, «2V. /move IK to timet I low byte (i,.g • i.|ii i ! i c in | i mov finod, ,10:: 2'! /antorel oad mode of ' i.m"r I setb ton /set reroivo enable of serial p,,i i son! ro i setb 1 ri ;se.f time) | oonlioi bit Is. si air inov a, tli'i /move t.imori hiqh byi.- i.. A epl •-, / oompioiiiet A and ine 3 /increment I o mat." it- pos.itv mov • rl, a /P.IOV l imoi\1 high byre t.o j | -is go j I A- •; I -R autob3b :mov rO, it 2 •".!., /move f'F to rO as delay fa.-.i. •: / autob3c : djnz rO, aiitol> U. /docrement fat" m, I and jump il not 1 djnz ri, am ob.il /decrement faciei/! and jump if u j rib I i, an! o!.,4 /jump il. r oc".i >.'" jiil .a i ntii is not /If we got hero, there was sent" stuff /if let the caiiiag" rot urn, I /and see if it was I lie lino feed. clr r.i /clear recei.v iittoitnp! i<> t ec-; ve more mov a, sbui. /.load reci.pl cliai.acl.ot into A anl a, 11011 I. id lib /mask the higher id I add a, !!.?4("> /add 24.'-. I.o chock is i! a line Joed (1.0 • OA!!) jz aut.ob4 /jump if zero (ok, lino food character) add a, #5 /add 5 (0101B) iz autob'1 /jump it zero, perhaps we missed start bit autobl_jmp: ljmp outobi /otherwise jump and return t.o stack fop /Compute the baud rate based on timerO. This is don" by dividing the t imor!) ,;;i.l /by by 16 and then by 8 a: •ihown in tiraerl above. autob4: mov a, flu /move I. iinorO low byte ! <.• A rlc . a /rotate A lol.t with cany mov rh, a /move A content to i 0 mov i, !hi i /move I. i me rO high byte In A r 1 e /relate A loll with on!iy mov r 1 , a /move A conleni to i0 jc aut.ob! jnip .•••o. ror i I" I imot 0 A rle a /lol.ate A loft with cany

124 1HOV 1., .i /move A ooni em t,, !•. mov • i, ri /move rl to A rlo • i /rota!e A i ••• tt with -i t y /After li vi .ii on I >y i i. y / v.-. ~ na to i i V i fie 1 and by i*, and mult iplie.it b>n i /This i .<> apr. :'. imai '••..) •y add. r.'i bit. .7 wl-.io II > S e<|,i j ! en! o i 1 i.e. f ' .'I I ••• /rotnti >n. mov .:, )... / /put I.; i I . 7 in

addr -1, HO /add /..-it o v i t h >• 11 r y •j 7. llll i li' i imp / jump i 1 -.-.<• •ro, ei i >>r i f bat! -i : •- e l.-l.-M 1 opl i /oomp1emel A to make • lieq it i •• < lot sub' ! ... • i.no .1 /add 1 1 <•• make i | e.|ii.I 1 1 o t t- - A) /Cheek •iga i a: 1 t i t:ier 1 v.-i I'.le.

; O'jlie .1, Oil , .ml,.! d imp iutitp t ' w. *• I i in'. i I'• .dings •-! 1 " 11" /Ac: li.-i tlil ••• i i in • . 11 :hi.- | ..in! . •llltootld mov band .'• a Vet '•, • i Jit OI e I j,e | M'1.1 1 ll.- ( . , j • ,<•X I W.I 1 III mov baud .• a ve I , a , / t mov hand r ave i- 1 , a / 1 I * t • ' 1 mov baud s ave10, a / I 1 t 1 t / 1 t xrl • baud s avei2, #0J.0l0l01b / xor band <. i-ive i •;. and '.Ml xrl baud r ave i-J., #11001100b / xoi baud : ta ve I 1 and < :ai xrl baud save+0, #00011101b / s"t band : VIVO 1 0 an. 1 .1 IjII mov t hi , ' •- /move 1 he i "lii.nl hi- • ! o ! ,1 mov t :i i, /move the reload va I :i>> !.o I i "1 mov tmod, ilOx.H /net I imet ill tor « b it lilt 1 oad mov peon. 9 0x80 /confi qu re double ban 1 rate bill it — i n ua i 1 mov soon, (fOxfi/ / i:onf i qui e .tor i a 1 poi 1 • :• >r. t ol setb t rl /start the baud rate . i me r rot /t etuin

Pat.- Mi 11 f i p 1 i. -a I i hi ant 1 11 i '.' i a i.oti

/ pinttlti prim s I he uns i qnod !i bil va 1 lie i I A-:.- in ba no in 'I'll i .-: is '• 111 i I -1 I / di.vi di ng t ln> nuiubo' >y 1 OO and d i :ipl ay i n | the quele nl (In ll-ll. •dl 1. d i q i ! ! , ! /diving the r ein.i i nder by it) and displaying the quel e 111 .'!< •Ill II • i i q i 1 , and 1- displaying the remainder (units digit), pi attiu: push push •T'.i* ,- -.1 o| .

s imp pin! tlb / 11imp

/Print-.s the .« -. iqned H Id | v-l ! lie in A'-f in l-l.-f in. T|,;: •I-! /minus sign. II the ntimbnt is- neq.itive, : ho mi tins sign i •: iispi.iy.-id .no t he /.is complemented and incremented (two's o .nip I emonl ! . In Hi" i"sl pa t t I h<- f. /is similar to pi.iitDu. pi nl: H: push i. /Stolo it push aee /store A jnb aeo. .', Dim (tb / j 11111)1 il the siqu bit. is not set mov a, I!'-'' /otherwise move (-) to A lea 1.1 < :ou 1 /display (-) sign pop aoc / ret r i eve A push aer /store A cp 1 a /complement A add a, 1! 1 /add I to make the I rue value mov b, HI 00 .-move 100 to B div ab /divide A by 100 (J ind 100th liqi setb ' to

125 pint He ; jump, i f A gin >i en i is -lie oir ft) add a, 1ft" ;add Ml' ! e A (moke as, ' i i ,"|'l I "a 1 on; ; 1 ea 1.1 con! /display A pint.bi.:: muv a, b ;mov" i ema i in!" i in I*, i , A ItlOV b, HI (i ;ill'>ve 1 ,1 to \\ d i. v ab ;di vide )\ | ,y I (i j i i t:d I'll"- 1 (H ii d i a it ;• j rib til, pintHd ; j >"• . pint «p ; i pinfHd: add a, I'd' ;add \'i' ! o A (make a.s,i d i e.-p.i i v;i 1 enl j 1 oa 1 J • :..HI 1 /display A pint, tie: mov •i, b ; Hi' a'" 1' I •> A

add a, »"!• ; a. id 'n' ... i\ (ma ,:s, : i i "oil i '•' l 1 ,'T,I ' ::i •. | i i, i , •• • '•• 11 1 ! ' ' ! | O • ' , pop ; 1 .'Si o| '• .-'. ; i >•s! o: o i; . pop 1. ; I .' • 1 n i 11

/pint. l( i in l.it'l'K, using base In. I'll" 1 unci ion use /pint xl C> tune linn to divide til" nuiubet by IllOUll to di.g.iay Mill'!'. il h diu.i 1 , and by ; 1.000 to disp Say lOflflth digit , and by 10(1 I .. display Itltll h di'li : . Then i 1 uses d ; to d i v i.do by 1 !> to d i splay 1 01 1/ di<| i 1 i isi g i. f . . List 1 y i I displays onei 1

pintl6u: pin.li a co ;sioi e A r.iov a, ,.0 /move i 0 to A push ace /store A clr psw. S /clear psw.'i inov r2, dpd /move |ow«->r by!" to 1 •<• pi i nted !•<• v','. mov 1.3, dpi. /move li i gher byl •"• to : o printed to )•/ pint 1.6a :mov r.4, #l

mov r'.>, i)" >it ii it aoa i I pi id .1 (•:; /divide by HlMi'i! 1 •• I 1 !:• ! i '.).).".'l!.|; .) i g j • jz pi nt. 1 t;b ; jump i 1 i "sn 1 1 is ,.ei o add a, l!'u' /••|. Id MO i o A (m.!'.-•• .. •••i i eguiValenl 1 1 oa 1 i .:..ul /display A

• sot.b psw..'. ; sot 1 I ac s i nee I i i .-1 d i g i I : s ' • i i sp 1 ay. pint 1 6b:mov 1-1, i;'t /move 1 1100 oqit i "a Ion! 1 o i 4 and i '•

mov i-'., If 3 ill il it aoa 1.1 pi nl: l(e: /.li v ide by i 0(111 ! o Mi id KHHH h digi '

pint 1.6o ! r n jnz / jump ' 1 '* •! i;: j nb esw.;.', ;•:::•>•••! ; '• •;;:•[ • .1 '. :•.-.}•• i '. • • •••,:> •• • ••••'• !-e- pi ntl6o:add a, S'0' /add Mi' : o A (make a: tc i i egg i va lent ! ica 1! coat: /display setb psw. 5 /set flag since there is display pintl6d:mov r4, 8100 /move 100 equivalent t '•> r'l ind r'j

mov i:5, 8 0 lit it ii acall p intlfix /divide by 100 to find1 1 001 1: digi 1 jnz pint. I do / jump if : osn!. j is no:. jnb • psw. 5, pin1.1.61" / j 1111111 if zero is Ist digit to display pint16e:add a, 8'0' /add M" to A (make as c Li. egu i va lent) lca.1.1 C Hit /display A

r setb psw. > / 1 1 ;ig s i nee | here is d isp1 ay pintlGf:mov a, t /move lowei byl " to A mov i-3, b /sav H in t'l mov b, 810 /load H with 10 . div ab /divide A by P to i ind t ho 10th d i.g i.!. jnz pi.nt.16g /jump .1 f resit 1 ! is not 7 or o jnb psw.5, pinti&h /otherwise, jump it no previous display pintl6g:add a, #'0' /add M.)' to A (make as c.i.i equivalent) leal! cout /display A

126 pint i < E •-. 1 I -m • ••V id i, if ' f ' /add '1!' ' • • N IFL.• !:• • as- • I ; R • in I v. >:.>!. I P-.i) ; • •out /display -\ • . . . | • .-. J •./, .

IIIOV T:I, .-i /rest..)., i (; pop •i"C ret / r e t urn , —• - r / p.i ritif.x di.vb ics ix-i i by i •!- i '. iiid leaves roma i ndei in r .'• T A and ;*.*•.! • i: I I.: qu. -I S • ;.in ace. The •. livisi'IU I r: oar: b • i a 1 sal it i i • -n . pint 1 fix :mov r(!, «0 ; clear rU pint J tiy: ino I c ; i nc.i'-I'ient : LI at 1 OI o-i.-l, il i .i--i INN { JII. •: '• • -n < i Cli ;.: 1eaI •: < • I! subl 1 • ICL i lie I.'...ot r 1 i-/i . • IUO'/ •, T 2 ;movo sub! ract hcnd 1. »>i !>yiII • to A subb a, ! •! ; suit! ract. S'LL.L 1 a.'t e. | ,,«'.) I : T >TII A raov rX, a /move rcan;T . i LIT lo i IN >.;• mov a, r3 /move sub! racrhend higher i-..; ! o I .. A subb a, I/ suht riot. .subl i act EI HI OHO; ! I • :m A mov i 3, a /move ietna i IKI'S TO rt jnc pi nf 1 Cy / jump back i I ... • • a • : Y dec ILL /decrement T ('• ( CI HTPJIISS ' ion LOT- EYN| subt. r act i' mov a, rX /move rema i itdet o.we: i.• y 1 e I• o A add a, r'l /add subt.i ado r .I.I me i by t • • .• o A to unpens.it I..inJ • mov 1 2, a /move lesnlt to r-' '! inal r< •ma i ink- r) mov a, 1.3 /move i ema indei liiglier byt< t .-. A add< •. a , rf> / add sul •! I act er higher byl e t o A !' ojt:pensa f I on1 mov r3, a /move result tor! (I i.na i I' •TILL i ;I> It- ! > inov a, rO /put quo!! ent I lit) A ret / ret urn

Hult.I-I.iyle frequence and ComoI OSSO.J btf.a ft ,•<•< •seise

; o i n f i 1 for 1I <.il:• n lot inn 1 t i-by> E soqu.'iie.os tor up, d>>wn, IO•it , I iql.I , paq.-UP, /pagodown, as >..-o! i as ordinary escape and •II d ' na ry •'Irn ac.L a s . '.'. >wn li"i". ; i el. ui n va 1 lit key escape SEQIH-L • ••••• II C-K) up 1 n '•!< 1 i H> (MS down ii' ''I'- -I." Xi ('II) i iqhl i ft !;P .) ! 8 CH) lei t. if '-.B

page ,loW|: IB Ml Ut .'K . equ esc c'n i, , 27 cin filter: jnb : i , tint ! / jiinij • i 1 | .-<••> i VE in' • • I i apt. i s no' so! leaf 1 • • i n / i npui ! 11mi set i - if port • VILLI' a, lies-.• char, cinf end ; jump it. i I. is nc • t IBii charactor. ;If esc was al if.vly in sbuf, ins.! if)iiote IT, lo avoid peudititi escape. cinf 1 : icai! c i n / i npnl f t ..MTI nor i

127 .1 call ; input i i "id SOT i a! pot I cj ne• • t, H. ' I. ', oi n ! ••• itisi.iiii, /jump if A ••• li'.-iii !s no; ar, a 1 ! olnf wail /wait lei "i «'. i i t iirl.'M, l i ansmi ' I : im • jnb ri , din lilt .•>• /jump if iocoi'->> interrpl n-.t s-'O Ion 1.1 •iii' / i npul ' i on, •:<•> • i a i p. • r I cinfba: eju<- a, N ' A ' , ciut:.!. /choc! if not bp key m- •'/ / i 1 A, b.ad ! i ird< A". rot. / i ••' n' n o in!fib: i- jne i, ii'i / • -lie. •!: '• I in., i iv.-ii is Km >V i, !ilo ; i I A, ! • ..id ! '' into ret / I "lllll;

: ci n t'5e: 0 jn< •i nl !..! /1 'ho.:!. i I not i i. |h I Key

iu< <« i, !l ? ! / i I A, I • -id • ! i III o 'Ve rot ; I "I in ii oin !">.!: in.- -1, » ' I: /olioel: il no! )••!: h-y m< >v / i ! A, lead H inl " A.-.- 1 oi. / I o I I; | 11 einf5e: ojno a, "•!•, <•! n t'. I /••I.e. k i ! not •• -|Mp toy bo disc .VI o sjmp einffi / iili»| • cinf:it: o jne .1, IK'x'H,, dill!"'...! ; elioe.K ;! not l.'qbp key Jrd eiiarael. sjmp o.i.n!.!.' / i'liup cinf5g: sjmp dini eonsumo /unknown K:t''ape sequence ;Whon we get. bore, we've qm i h- /more ine.om.iini byte i.. chock... lot p.-i.|onp/p-i!;.'".i..)WN, but (hero's. • •!!••• einf«:

ptisn fio: /sioio A content (.t'-'h or '}i'-h) I't • t urn aeal i. oiiif wai f /wail f"i some niomeni jnb r.i , e i nf I est a 1.1 /ehodi'. 'I'll ' il.l I •!< ! e |. presence tea If o in / i itpul i i < .in • •• i n ! p. ii i c jne a, i!0::7P;, •inf ii'.-tp / i •);.! i n •! ers II-! I'.ilij- (>| |"|ptl pop ace / 1 est oi o A add / .!• id { t'.h • • I '•'•!!! I • • .,' I i'I.-1 i > •! ; cinl end: t oi ; : e l i, i 11 cin' rest art : pop /lCSFore A s jir.p I ! o / jlllllj • lo i .eg ! |i i 11'.! einl__notp<): P'--P / I "Si el'- A /Unrecognized escape?... oat. up everything that's loll, coming in quickly, ! hen /begin look i no •igai n . cinf consume: aca! 1 etui wait. /wait tor some iiv..motn

jnb ri, e.i u_fi.l for /jump to begini no ii i i no; ; el lcall cin /input from serial port, cjne a, Heso char, cinf_consuiiie / loot., liere i! not l!ib iliarac'ei sjmp cinf?. /if. it is lump ba.-k /This thing waits for a character to bo received for apptox A character transmit /time periods, it returns immedately or aft.ei (he >~nf. iie wait time. It does not /remove the character from the buffer, so ri should be cheeked to see if somel.h i no /actually did show up while it was waiting. .equ ohat:_de)ay, •! /Ilo. s-l eh.t; rmi t I lilies w.-i i ! ing cinf_wait: mov a, r2 move r2 to A to sav" if push ace save i? vaI no mov 1.-2, llchar d'-lay' load 12 will. !i times ehoi delay- cinfw2: inov a, this load A with time i (l hiqh byte cinfw3: jb ri, cinfwl jump if i "C" i V" inl or t tip! is so! inc a i ticromen I A

jnz • :IN f H,' j uinp i '•' A is not ::• -r. • djnz r?, cinfw? dec! omen! I? jump if it is ik-1 prints i. a. • e'.mpi esse, i si I i li'IS . A did ionaiy o| \ v;o:ds is ;pest :t ; pa c k »<1 bin ii y i oi n.a: . Wlisn posl i lino, s a hyf" i Ii . 1 i no w i '• >.: 1 ii' • ; i. V. p r i nts i he vi. l.i ! i .Mil 1 he 1 i ei- : "ii'i r y . A 1 (••! byl os iiav spec i a I I . ;every! iiing els;•• > pr i nl s .is i ! i 1 WPI o an o r. 1 i n.ii y I i i.. i' i. ; Speeia .1. . .Kies 0 •••• EtJI. i)i .•J'i'iUNo 1 .< --' e-R/f..!'' 14 = (JR/I.K >, Kill' oi- STi-.III.: 31 NEXT ; :Ai'ITAI, (next word code siioiil i Ih < cap i 1 a I i :•'.• " ••} pcs'tr: push nee ;save i. e 1 i s I. o 1 niov a, rO ;move iu 1 . , l,o • • , a .••• i push a oo ;s.foi" .a inov a, i. !. ; in. 'Vo • 1 to be tl o.e-1 push ace /.'.-tore 1 mov a, i:4 ;::iove i 4 1, o be s! orod

push a eo ;s|oj.o r •i setb psw. i ;sol us" i def itj-'d : l.vi ; !• a-.b sel h psw.!. use i d"l ined t l.iu • ,p: i pcstrl: el r a ;• i.oa.l A loi Iu-xi i lis! ••!:.: 1 ion 1,1. 'V( • a. Paldpt( ; I o.i' 1 wli. il a! ad. it . i in: dptt ;i ncrement )y- pOS 1 !."/ ; •'lump i !: .-ei o (KMP i .f !•: i ;:<•,) hi 1 .' se| lb acc. 7, deer-nip ; iump i1 an 1 a, IfOx.'P /mask hi !• •' pesIrsi :ojn- a, !!1 •, p.-SfJ ; j urn; • i 1 i ea 1,! :i'--w i ino /display l.o'.'' '• • !.e sol b psw. i ;s.'' i'M' i i no . 1. i, !• -1 -a ' ! a.| sjmp pes!i1 ; ;, u:np ha- • i. po.strs? : e;in.- a. Ml, post 1 s < ; jump i1 t:ol anil .•:• •(>•. a e , a ;| • i,l t psw..'. Ji'l'VII c. ip i 1 i o!i;i I .'.el e • I :.. | simp pest 1 1 ; > inn!- ! >a:!- : :e jno 1, 1) 1 4, (.CSt I S'l ; jump i I !.•.' ei: i ! ! -••it o-|.. ••!,;.• pest >:•• i b-.i 1 1 now lit:" /lisp! ,y nr-\ ! i•v -ha i .!• •! . I s imp posl, i ; iump •• o ! on i n ' ii'! pest../I: pe-b ; i ol I i"V •• A mnv r -1, ,-i ;.e«lore J •'! pop • >::• • ;rotri"ve A mov • if ; rest «'l e I ! P'P •MS- ; • .-f r i !•••.> A mov i. 0, a ;res!ore 1 >! pop- acc ; !.'•• t J. iev---. A ret ; i otui.li

;dcomp actually takes care oi printing a word lion, she dictionary at dpi,) posit /.in packed words table. This function scans the dictionary sequentially til! it /reaches the particular word number. Then it reads the nibbles coded in the /dictionary location and translate." them using some l ab! es. Then liie translated ;code is printed out . The nibbles are managed by i4. i. 4 e i( no.-d nibble is •...... ;r 4=255 if next nibble is high. It use; <|el no;-:l nibble I unci ion t o id >i-..-. /dictionary.

129 dee.'mp: an ! :, S'i-.7K

inov .-(), •• psw. i , • lo. :• .iu[ ..I J!' ; pimi • i i o t i ;.. ,.; J i, t si . • •• IF Mis! d leal I sp,...:.- /dispb.,y spec p.-:;/. 1. decbmpl:cir /ciei! ll-.-.i !>..! ioa.iiti-; • -ha r ATS o. push • dpi /st ore dpd PUSH dpli /ST"!e dph MOV dpci, llwo.ds /load dpt t with wolds -idol . mov 1 vA, !!<• / ini ialize nibble spec i I i.er wit.h an mov T:> a, / bod wot • i fl->. into A l r. doomr? / 11nut • i I W' ud Mo . i s ::o ,. /Hero w>. mu.'.:!. seek pas 1 oil ! . '. i-Is. it. the ;.tl.|.. that •.••i|i. • iel.i. ; h" • ir- ;supposed io f i in!..

mo>' I ! , o / I O.|. i . I w ill! w- ! • I '/' . dcomp2: act i f •!•>•: MeXt tiibbi ; juiiij • • i. • :• • I [•-.•::i n I i>i i •. .in 7 • (<-. (ii.i •', / I. >. .p i ! i • lei. t !!!"l IS t|- a -a i i'i' W a •! . n.

/When we gel: H eto, a wov.t ha- ; to I;he oor.re.- t one.

din? il, .-tcon-ix: •i B. O( ;;(,! I ! W M I Mo. IS

/Mow WO' CO po i ] no to • !,.:• .:•• * t- • Il I Ve • • I" * • . • p I I I] 1 IT OIL I dcomp3: aca 1 1 . .;oi ,,cx! u.i bid jz d<-omp ond / i umi • if i d.-n I i I i •• i i: cjne a, !!!'•, dco.up.i

/The citara.;l i s KITE o!.: • i.o •.•• is I • • .I;L'.-IO:I I \ • ei ! •• I s .

: • n:.i i : / iciap i •:> -let. t,.nibble l I as r specifier; / i iso oitiont the id.-ni if jot point to slwoi.-l ..i J m: move a, a.'.'pc ; i ivi.l . :ha i act ... i f i . >m I lit: •!•-.•'.!. table r S j RIP dcomp. . / 'pimp . db "h rw-.iyb/:v!;g i z"

/The charact <• i i s one o 1. i HE dcomp i: i nc .; :ii,-|'(1!l"li! I ho biet! I. i i i • a it. p.-.. ii:' •:a: act • move a, s , Ipe road oha l act or fi..m fh" ir-vi tai.b s jmp deomp.'-. iimio . d!. "e! .i i. tt i so 1 uiitp. 1

/Decide .if .id should he tippet t dcompS: mov c P.-W. r Hi. ive • '.ij.. i I ,11 !"l l(.| I bio !.<. '' mov ac.-.b, c move .-apial flag t •.. Acc.. 5 (make small oi. oapr.a i ! set b psw..'. sol. eip.ila.l flag t small I e f i e >. s fo> next.; cjne tO, #20, ..Icomp jump if woi d No. is not: 20 (20 is special, word! clr ace.!. cleai Ace.!, (make let-1 or capital) dcompS: cjne rO, 1112, doomp' jump i.i word No. is no!. 12(12. is special wosd)

clr ace.. 5 c lea r A. -c.. S (in:i ke I et-1 <\r tv.p i t a I.) dcomp7: lealI co-.\t ci t sp i iy i •)>• i r :Ct. • •! sjmp dcoinp3 / jump back dcomp end:

POP dph /restore dpi-, pop dpi /restoio dp! ajmp pcst.r 1 /jump lack to calling (miction

130 ;.|r.i n j b! . i ' •liurnol spo.-i I i. • i ui> l-i t e dpi i -ih.i sw i re ; nibble spe.-; I ••.

ae!. next uibi '•<• elr ;c!e,c A raovc •:•, H-l i dpi ! ; ,-ni-isk ..in iii.ili uibbb- rel. ; to! in n A as i > i.•••i! : i i •1 • gmi2: inov r-'i, Ip.i ;swi.l-c!i nil.l.le !,. po .i n c dpi i ; i iieronioii! dpi i I .. i" • ••-.! I • - swap . l ; ...::c!i iih|O 1; it;t• .Mid : •-w i. • i -i - an! a, ii 0000 1 mi, /mask out hiijli nibble ret. ; ; el il; li as i d< i:' i ! i o i

; Hot • I -.11." I • I da! ! sbl. in. I :C I : n !: ; ;Th.is is t:he I.i or i (inniof 128 w..nl:i used by p'-sl words: OxH.2, Ox 00, OxSH, 0x2 0>:h6, '••;-s:r;, -'rsio, db Ox-M , OxP.i, OxBO, OxBI , II.V.1H, Ox'.i- , n.xr'i!, Ox 1 : dr. 0x7F, OxAO, Ox 1 ;">, 0x7 F, OX I'.', o;-; ''••-.! d , li;.; ;-s db Ox-'-A, 0x50, Oxfoi , 0x0 i, Ox!'-!- , O.xBA, OxOC, Ox F 1 •• • >•;•;, .lb Ox'36, 0x01 , i'.xiib, (»x '.F, Or." '., 0x01 •, o:-;. •-•

db 0x5F, Oxl 2, 0x07, 0x7 1 , Os/'K, ox'.n, •x,' ••!:•:•!' db 0x31?, 0x62, 0x!.8, 0x2 0, Ox 1 I- , Ox Ox Ox t:

db 0x24, 0x40, i!xB!l, 0x4 o, OxFi , ex'. 1 , , •':;-:•.; ' db 0x34, OxOB, OxCA, 0x«9, 0x03, f :•.'.•>!, 0;., OxFO, -'X-l /, axis' db 0x20, Ox.l F, 0x2 \, Ox , ey.BO, OxF '•, Oxi •• db 0x60, 0x25, 0x4 ! , o.-.r., 'ISl''l, •2---.sK, OX'Xb, Ox I •> db Sv i 2, ;>x.u;, OxO: , Ox 1 F. -is - i , exlb, iixO l, 0;: i .1 db Ox-lb , 0x7 6, 0x12, Ox 0-1, OxAU, 0:<27, Ov'H), Ox'-.. db Oxl.i 1 , 0x2 if, 0xA8, Oxt'1-, OxFO, OxAA, 0x26, 0x20 db Ox :")!•', Oxl 0, OxFO, 0xF3, 0x61 , Oxi- F., Oxo i , 0x4 1 db 0x7 3, 0x0 I, 0x27, OxCi, 0x00, 0x84, Ox'U: , Ox.is.

db Oxo 1 , U>;07, 0x70, o.".!.'., o.x-; !!••;! '1 ( ux7 0. ox ! I' db 0xA8, 0x09, OxOO, ox/.;, Oxo,!, 0X1 7, ox 4 ,-t, Oxi- K db 0x01 , OxCl, 0x84, oxor-, 0x15, 0>;7 F, 0x02, 0X.8B. db . Ox ! 4, 0x30, 0x8 F, 0x6 !, Ox VI, OXi.fc , Ox pi, OxF.' db Oxl 1 , 0x09, Oy.1 0, 0x60, 0x02, 0x3F, Or.o 1 , 0x0'. db Ox 7A, ox4 J , Ox DO, Ox OA, OxOC, Ox ib. i i •.; 2. •':•, ox'-.- db 0x07, 0xF2, Oxl 1 , Oxi 7, 0X2 0, 0x4 I , OxbB, Ox '•'• db 0x09, 0xF7, 0x75, 0x1 3, OxOB, O.xA.', 0xl'<2, 0x4 u db 0x02, ox.'.F, 0x64, 0x12, ilxAO, OxOO, ox;: •>, •i.xF. : db 0x9F, OxCO, 0x14, 0x77, Ox/0, Oxl i , 0x4 0, 0x7' I

131 db 0x2 1, OxC-.u, 0x68, 0x25, 0x4 | , OxKO , 0x6?, db oxb'. Oxno, 0x21, Oxb1, 0x6.!, OX.'H; , 0:;!, OxISA, db 0x75, 0x42, OxEA, 0x62, 0x5!5, Ox AO , OxK5, db 0x5.3, Ox-11:', OxHI, OxCO, 0xA3, OxO'l . u.-'4 2. db OxI-'V, 0x12, iixt)4, Oxt-2, fx! H, ox. 30 , ox K'',, db 0x1.7, 0x65, (5:00, Ox!'., Ox 1 5, Ox -0 , Oy/H?, Ox.?!.' db Ox?,, 0x14, Ox4K, Ox1! , ex' •(!, Ox (el , l exOO ; S'F'R logon 1: db "Wo loom.;-" , 1 ?>!, l 4«, ".! v? • ! , by' , < ! , logon2: db 5 1 t • 'OO , 1 4>t, "2 . IH.c, ", M»,' ? . K'.i ••" , 1 '••! db I 4y,"? .tin!?" , ! MI), ? 1 3, ! 1 l,".", ! abort : db •' ",'1,1 '"•«, ii , 1 CO, " ! ", 1 prompt I : db 14H,"2 I,--.:: ", o prompt 2 : db " •", ICO ;mns! !• ! b-: a to. oiompl: prompts : db 1 34, 2 02, ! <( prompt4 : db "),",! 4<3, ! 40, l?H,?00, " , ii ti it prompt 5 : db . 31 , ! 5 i, .130, .1 05, 1 ">., i 60, 1 > i i i ..... , db iid,," JUMP" ,12«,134,1 id 0, 13 , ! 1 prompt 6 : db 13, i3,31,13 5,131, 12'b"; , ",' 0 ft. prompt"/ : db 31 ,???!, ?f, 1, " hey: ",() prompt!' : db .1 3, 13,31, 1 36, ! 2», 1. 11 , i ? i i prompts : db 1 '•,!.<, 3 i , M (!, -:i,:"" '., e pron.pt."-lb: db ii , 12.,52, 5:, -i,,ei, 1 I ; inn prompt10: db ") ",.U,13C- , » , >7-', ": " beg str : db "First",3!, i2'b": ",0 end str : db "Last. ", 31, 120, ": ", 32 / tl sure: db 31 , 1P5, If.!, " sure ?",("• edi tsl : db 13, 13, H , 15'-, 154, bin, ", ", !40, 1 20,.'no, li edits?: db " ••,3 3,136 , l.'3 b ", ", ! 4? , !?',,:••! /, 1 ! 1 dnldsi: db 13, 13,31, 15 '"«, " as.-i i !«, ! 5<, 1 60, "ed", ! ;:, I 4 dnlds3: db 13,3 ! , 1 38,153,"d", 13, 14 dnlds4: db "Summery:", 1.4 dnlds5: db " ",108,"s" ,145,"d",14 dnlds6a : db " ",!39,14 5 ,"d",14 dnldsCb : db " ", I3<>, " written", 14 dnlds'7: db ' 31,1!.!-,":", 14 dnlds8: db " ",139," enable",.!.?-!," in i t •>" dnlds9: db 32,32,"bad" ,245,"s", )4 dnlds10 : db " ", 1 13,150 , 150, 150, 14 dnldsll : db " ",i33,132 , 1 57, 14 dnlds12 : db " ", I 33, " non", I 32, 15/, i •! dnlds13 : db 3.1, 1:> 1,155, " defected", 13, 14 runslr db .13,1 34, "ning", 1.30, " : ", 1 1 4 tiplds 3: db 13, ! 3, ".'-ending", 31 , 1.5/, !3?,!37 , 172, 32,32,i lipids 4: db " ",12ft,32, 32,0 IIIUS! i -1. lei- up bis help! t.xt: db .13,13, "Stan •lard", .31, 1 50 " s " , i1 t< i help2txt: db 31,21.3,31,2 4 4 , "eci",.*•! , 1 .• O • , •" S. " , 1 4 typel: db 31,154,1.53, 0 type2: db 31,130,0 type4: db 3.1, 143,31,2 26,31,17 0,0 type5: db "???",0 help__cmd2: db 31,215,0 help_cmd: db 31, 1.42,21.5,209,0 1 hose 11 <. ii'd st.i.

132 dn.ld Up Id siloe jump cmd: . db *'! 136, 128, 1 JI, 1 2", 0 dump cmd : .db 3 1 ! 32, 219,154, 131 ,o intir. cmd : .db 31 132, 219,192, 131,0 edit cmd: . db u i ;•>(>, 154,14 6, 0 clrra_ cir.d: .db .'•] :.',3'/, .131,0 erf r_ cmd: .do .>•} 20 5, 153,144, 0 erf r_ "ok: . db 3.1 i 53, 144,203, '•!•, 13, erf r e r r: .db u 1 33, 155, 13,1 4