background image

119/317

5 - Peripherals

The COCO bit is reset when the ADCCSR register is written.

05-adc0

5.6.3 The problem of the converter's accuracy

Linearity and accuracy are different ways of expressing the same reality: the successive

voltage steps that correspond to each of the binary values are not absolutely equally spaced

(otherwise the converter would be perfect), leading to a conversion error. Depending on the

type of work the converter is employed for, one way or the other is better for expressing the

suitability of the converter.

If the converter is to be used as a measuring input, like measuring a temperature, a voltage,

the level in a tank, to send it for information purposes, accuracy is the best expression. It indi-

cates how much confidence one can have in the data.

If the converter is to be used as the feedback input for a servo loop of the second order, for ex-

ample a positioning device using a DC motor and a feedback potentiometer, then linearity is

the key factor. Not only must a servo loop be accurate (since this accuracy translates into an

error expressed in mm in the positioning system) but also it must be stable. So, the parame-

ters of the whole system must meet certain conditions summarized in the so-called Nyquist

AIN0

AINn

Analog

mux

Sample

and

hold

ADC

COCO

-

ADON

0

-

CH2

CH1

CH0

f

CPU

AD0

AD7

ADC Data register (ADCDR)

ADC Control / Status register (ADCCSR)

COCO : Conversion Complete

ADON: A/D converter On

CH2-CH0: Channel selection

ADC block diagram

AD6

AD5 AD4

AD3

AD2

AD1

Содержание ST7 Series

Страница 1: ...ST7 8 BIT MCU FAMILY USER GUIDE JANUARY 1999 1 ...

Страница 2: ...e which a are intended for surgical implant into the body or b support or sustain life and whose failure to perform when properly used in accordance with instructions for use provided with the product can be reasonably expected to result in significant injury to the user 2 A critical component is any component of a life support device or system whose failure to perform can reasonably be expected t...

Страница 3: ...2 2 2 Memory 21 2 2 3 Input Outputs 23 2 2 4 Interrupt Controller 24 2 2 5 Bus 25 2 2 6 Clock Generator 25 2 2 7 Reset Generator 25 2 3 CORE 25 2 3 1 Arithmetic and Logic Unit ALU 25 2 3 2 Program Counter 26 2 3 3 Instruction Decoder 26 2 3 4 Stack Pointer 26 2 4 PERIPHERALS 27 2 4 1 Parallel Input Outputs 27 2 4 2 Analog to Digital Converter 28 2 4 3 Programmable Timer 28 2 4 4 Serial Peripheral ...

Страница 4: ...ING KERNEL 39 2 6 1 Pre emptive multitasking 39 2 6 2 Cooperative multitasking 41 2 6 3 Multitasking kernels 42 2 6 3 1 Advantages of programming with a multitasking kernel 42 2 6 3 2 The task declaration and allocation 42 2 6 3 3 Task sleeping and waking up 42 2 6 3 4 Multitasking kernel overhead 43 3 PROGRAMMING A MICROCONTROLLER 45 3 1 ASSEMBLY LANGUAGE 45 3 1 1 When to use assembly language 45...

Страница 5: ...byte 75 4 3 4 3 The addressing modes in detail 77 4 4 ADVANTAGES OF THE ST7 INSTRUCTION SET AND ADDRESSING MODES 82 5 PERIPHERALS 84 5 1 CLOCK GENERATOR 84 5 1 1 ST72251 Miscellaneous Register 84 5 1 2 ST72311 Miscellaneous Register 85 5 2 INTERRUPT PROCESSING 86 5 2 1 Interrupt sources and interrupt vectors 86 5 2 1 1 Interrupts sources for the ST72251 87 5 2 1 2 Interrupt sources for the ST72311...

Страница 6: ...R 117 5 6 1 Description 117 5 6 2 Using the Analog to Digital Converter 118 5 6 3 The problem of the converter s accuracy 119 5 6 4 Using the ADC to convert positive and negative voltages increasing its resolution 120 5 6 4 1 Measuring negative and positive voltages 120 5 6 4 2 Increasing the resolution 121 5 6 4 3 Application Examples 124 5 7 SERIAL PERIPHERAL INTERFACE 125 5 8 SERIAL COMMUNICATI...

Страница 7: ...E pseudo op 162 6 1 8 3 Numbering syntax directives 163 6 1 9 Object and listing files 163 6 1 9 1 Object files 164 6 1 9 2 Listing files 164 6 2 LINKER AND ASCII HEX CONVERTER 165 6 2 1 The linking process 165 6 2 2 Hex file translator 167 6 2 3 The back annotation pass of the assembler 168 6 3 INSTALLING WINEDIT AND THE SOFTWARE TOOLS 168 6 3 1 WinEdit text editor 168 6 3 1 1 Installing WinEdit ...

Страница 8: ...he application 193 7 3 3 2 Running the application 195 7 3 3 3 Watching the registers and variables 195 7 3 3 4 Using Inspect and Watch 197 7 3 3 5 Using breakpoints 199 7 3 3 6 Watching the contents of the stack 200 7 3 3 7 Watching the execution trace 201 7 3 3 8 More features to come later 202 7 4 PURPOSE OF THE TUTORIAL 202 7 5 SCHEMATIC DRAWING OF THE PRINTED CIRCUIT BOARD 204 7 6 DEVELOPING ...

Страница 9: ... of C language 232 8 4 USING THE ASSEMBLER 233 8 4 1 Using In line assembler statements within a C source text 233 8 4 1 1 Single statement assembler block 233 8 4 1 2 Multiple statement assembler block 234 8 4 2 Using the Hiware assembler 235 8 5 USING THE LINKER 235 8 6 USING THE EPROM BURNER 237 8 7 PROJECT DIRECTORY STRUCTURE 239 8 7 1 Config directory 239 8 7 2 Object directory 241 8 7 3 Sour...

Страница 10: ...276 9 3 3 1 Interrupt functions 276 9 3 3 2 Main program 279 9 4 CONCLUSION 285 10 SECOND APPLICATION A SAILING COMPUTER 286 10 1 THEORY OF THE COMPUTATION 288 10 2 INTERFACING THE MEASUREMENT DEVICES 291 10 2 1 Frequency type devices speedometer and wind gauge 291 10 2 1 1 Interfacing the speedometer 291 10 2 1 2 Interfacing the wind gauge 291 10 2 1 3 Using a common timer for both speed measurem...

Страница 11: ...tion 305 10 5 5 The periodic interrupt service routine 306 10 5 6 Computation of the results 307 10 5 7 Handling of the serial interface 309 10 5 8 Initialization of the peripherals and the parameters 310 10 6 MEMORY ALLOCATION AND COMPILE AND LINK OPTIONS 312 10 7 CONCLUSION 314 11 SOME LAST REMARKS 315 ...

Страница 12: ...stems and industrial computer science at the Electrical Engineering department of the University of Cergy Pontoise France Jean Marc Delaplace is an electronics and software engineer at Gilson S A a laboratory au tomation instrument maker As a team they have already written books on the ST6 published at Dunod Editions and the ST9 published by STMicroelectronics 1 3 HOW IS THIS BOOK ORGANIZED This b...

Страница 13: ...imitations Chapters 9 and 10 describe application projects using the ST72251 and the ST72311 mem bers of the ST7 family They tell the story of the design of devices that though they do work were not intended to be commercial products 1 4 WHY A MICROCONTROLLER The microcontroller is just another choice when one has to design an application and it com petes with other technologies like wired logic a...

Страница 14: ...like the clock generator the interrupt controller etc Many more chips must be added to it in order to make a functional application memory chips in particular Ac tually this solution is only used in computers either general purpose computers like PCs or built in to complex applications like industrial robots It allows the designer to tailor his circuit exactly to his needs The microcontroller is d...

Страница 15: ...educe the external component count and to carefully se lect each one to get the best value In order to satisfy this requirement the various chip man ufacturers offer for each family a choice of variants to allow the designer to select the one that best fits his needs in terms of input outputs and auxiliary circuitry Roughly speaking a microcontroller variant that is loaded with features will allow...

Страница 16: ...educe the component count and thus the printed circuit area The solution shown may or may not fit the needs but it is difficult to imagine a simpler design 5v Analog input GND Micro controller R R R R R R Array of resistors Current generator Analog keyboard Analog display Push pull output with PWM signal Example of simplified circuitry thanks to a microcontroller ...

Страница 17: ...on not to mention the delay in the product availa bility with its commercial consequences Also even if a microcontroller is suited to the product as it is first commercialized this product may undergo changes during its commercial life As a general rule changes are always addi tions never removals If the chosen microcontroller matches current needs too closely in terms of capability there is a ris...

Страница 18: ...grammer etc depending on the development phase The dia gram below shows where each phase takes place 01 proc The microcontroller itself and the related development tools are described in Chapters 2 and 3 Source text editor Compiler Assembly software tool Linkage software tool Simulation or emulation software tool These software tools are specific to a microcontroller family Typing of the program s...

Страница 19: ...e can find in a microcontroller Other peripherals designed for special tasks or communication protocols may be found as well Let us mention just a few I2 C serial interface Radio Data System decoder Liquid Crystal Display interface etc We shall gain an overview of the main blocks in the remainder of this chapter general purpose and dedicated registers accumulators instructions decoder program coun...

Страница 20: ...lled by a common control panel with a large display that shows the FM frequency or the CD track number and elapsed time etc Here a single microcontroller performs the overall control displays the data re sponds to the keys that are pressed by the user to select the required radio channel CD track etc The word data that is so commonly used must be understood here in the widest sense Though we may f...

Страница 21: ...er than that of the hard disk the capacity of the memory is usually much lower than that of the disk Only a fraction of the disk contents resides in memory at any time In microprocessor based systems the memory is the only storage and various types of memory are used according to its use read only memory for the program read write memory for the data and or non volatile solid state memory for thos...

Страница 22: ... the product the data continuously change This calls for a non volatile read only memory in the first case and a read write memory that may or may not be volatile in the second case The difference in roles of these two memories has led to two different approaches in the memory architecture The first one named Von Neumann after the name of its inventor provides only one ad dressable space The progr...

Страница 23: ... the outside world are often of the analog type and must be translated back and forth so that the system that is fully numeric can process them The peripherals can be just input output gates for some data that are of the numeric type in the external world or they can be somewhat complicated if the data is either analog or numeric but conforming to some strin gent timing pattern All the translation...

Страница 24: ...rogram when an unexpected event or an expected one but occurring at an un expected time occurs It may be more or less complicated according to the features it pro vides 02 inter Interrupt 2 enabled Interrupt 2 Interrupt 2 requested but masked Non maskable or authorized interrupt 1 requested Interrupt 1 Main Flowchart of a program with interrupt sub routines The main program is interrupted Return t...

Страница 25: ...is circuit detects when the system has just been powered up and resets it in a known state from which the program execution will start The reset ensures that each time the system starts everything occurs exactly the same way This is a major condition for the reproducibility of the behaviour of the system 2 3 CORE The main components of the core are 2 3 1 Arithmetic and Logic Unit ALU This is where...

Страница 26: ... are called jump and call instructions In particular some of these instructions perform their action only if one or more bits of the status register have certain values so as to jump only if for example the last calculation produced a zero value or continue in sequence otherwise These instructions provide the means of translating the branching boxes in an algorithm 2 3 4 Stack Pointer The stack is...

Страница 27: ...he required circuitry for processing the data convert it etc so that it is easier to handle for the core The less work the core has to do the more it is available for other tasks According to the proper ties of the signal the peripheral designed to process it we say interface it may be anything from very simple to very sophisticated We shall give here an idea of some of the most common peripherals...

Страница 28: ...o use it intensively since it is the peripheral that provides the highest accuracy when taken as a measuring device Thus when the measurement of a physical parameter like a temperature a level a pressure etc is needed instead of designing a sensor that outputs an analog voltage it is easier and more accurate to design it to produce a square signal with a frequency that reflects the parameter Such ...

Страница 29: ...tring of statements known as the program Therefore it apparently cannot perform more than one task at a time However most if not all applications require a single microcontroller to handle many things at once Usually for cost effectiveness and simplicity the designer of a microcontroller based system tries to pack as many functions as possible in a single chip The answers to this problem are based...

Страница 30: ...ator code condition register etc Depending on the type of microcontroller the lower priority or all the maskable interrupt sources are masked The PC is loaded with the interrupt vector address which is a pointer to the address of the interrupt sub routine The sub routine is executed and ends with the return from interrupt instruction The masked interrupt sources are authorized The PC and predefine...

Страница 31: ...ts configured to generate an interrupt either on low level falling edge rising edge or both The timer may request an interrupt on timer overflow external capture or output comparison The SPI may request an interrupt on end of transmission etc 2 5 1 2 Hardware sources of interrupt The hardware interrupt sources are summarized in the diagram below 02 mec Input pin edge detect circuit External source...

Страница 32: ...hat precise time However this in struction may be used in other ways as well 2 5 1 5 Saving the state of the interrupted program When an interrupt request triggers an interrupt the first task of the core after completing the current instruction is to save its current state so it will be able to restore it after the interrupt processing is finished This is done by pushing all the core registers on ...

Страница 33: ...e When the mi crocontroller is reset these interrupt vectors are fetched together with the reset vector for get ting the start address of the main program The following table shows the interrupt vectors 02 tabv I C Bus Interface Timer B Interrupt vector table of the ST72251 Timer A Serial Peripheral Interface Ports B and C TRAP Software Interrupt Reset vector Higher priority Lower priority Memory ...

Страница 34: ...ng to the interrupted program All the core registers were pushed on the stack when the the interrupt request was granted ex cept the Y register They must now be restored so that the execution of the service routine will not leave any trace in the core This is the role of the IRET instruction in the ST7 The IRET instruction proceeds by popping all the data off the stack that had previously been pus...

Страница 35: ...rvice routine would be called again immediately after executing the IRET instruction and the core would loop indefinitely through this interrupt service routine thus blocking the main program How to reset the interrupt request flag is described as part of the description of each periph eral 2 5 2 4 Making an interrupt service routine interruptible On interrupt granting the I bit of the Condition C...

Страница 36: ...rst writes some bytes then more bytes until it is finished with a new data in memory If an interrupt occurs in the middle of the process of altering the data the following risk may appear If the interrupt service routine uses the data that the main program is writing the service routine may get data that fail to follow the coherence rules since not all bytes have been updated yet The service routi...

Страница 37: ...w to make the handling atomic To avoid this situation it is sufficient to mask out all the interrupts by changing the code as fol lows increment word variable X by 1 sim prevent interrupts from occurring inc reg 1 add 1 to the low byte jrne endinc increment high byte if carry endinc rim allow interrupts to occur here the program continues both bytes are incremented reg 4300 hex now the interrupt c...

Страница 38: ...te pins of the microcontroller or they are the result of the working of internal peripherals that reach a certain condition for example the internal timer has overflowed Though the timer is built in the same chip as the core it is functionally considered external to the core They occur at their own time and thus unexpectedly for the main program They require a quick reaction from the core either b...

Страница 39: ...they are switched too often the proportion of the time taken to switch tasks becomes too large and the corresponding part of the microcontroller computing power is lost The designer must check whether the power remaining for each task is sufficient or not if not the type of microcontroller is probably unsuitable for the project There are two kinds of multitasking namely pre emptive multitasking an...

Страница 40: ...erfere with the unfinished sequence of the previous task Here again a protection mechanism is required In summary the advantage of pre emptive multitasking is that task switching is done automat ically and independently from the code of each task the relative power attributed to each task may be adjusted to fit the requirements of each task The drawback is the opposite of the advantage since the t...

Страница 41: ...cannot be set at will since it is not possible either to insert into the code as many calls to the switching function as necessary or to put them at the right places to control the time intervals allocated to that task The reader can easily see that the strong and the weak points of one type of multitasking are the opposite to those of the other system This explains why both are used the type bein...

Страница 42: ... existence of the tasks their number and their start ad dresses Some kernels expect this to be stated at compile time in this case the number of tasks is known from the beginning of program execution and cannot change afterwards Some others allow tasks to be added or created while the program is running This allows tasks to be created when the need shows up for example to process an incoming event...

Страница 43: ...s equally obvious that the kernel is a piece of code that occupies a certain amount of program memory as well as data memory But overall the main concern with memory require ments relates to the stack The stack is the place where the state of a program is continuously stored This amount of data is often referred to as the context Each task has its own context which consists of all the return addre...

Страница 44: ...3 4 Selection of the task The stack pointer points to the last data of the task to activate that is stored in the stack Activation of the task The popping of the data off the stack restores the tasks as it was before being unselected Deselection of the current task The state of the pro gram is saved in the stack before it is deselected Selection of the following task The stack pointer points to th...

Страница 45: ... reason the use of the right tool to program the application is critical since program design and testing time can vary greatly according to the tools and the language chosen This chapter addresses the two main issues the programmer faces selecting the appropriate language for the best productivity then selecting the appropriate software tools that will allow not only to program in that language b...

Страница 46: ... described as follows The first phase is when the programmer defines what the program should do This is only paperwork even if it is done using a computer and a word processor or a spreadsheet This phase defines the main program blocks the data inputs and outputs the storage and some of the algorithms The second phase is the translation of the first one into the chosen computer language The result...

Страница 47: ...ine Comment 000000 A6FF ld A FF load accumulator with immediate data FF hex 000002 AE64 ld X 100 load X register with value 100 000004 F7 loop ld X A load location pointed to by X with contents of A 000005 5A dec X decrement X register 000006 26FC jrne loop jump to label loop if X not equal to zero This short program is a loop that fills memory addresses 100 to 1 decimal inclusive with the value F...

Страница 48: ...he source file as explained above as an input then after translation it outputs depending on the user specifed options any of the following files The object file containing binary data intended for further processing It can not be read by man The listing file is a report containing both the original source code and its numeric translation presented in a tabulated manner It can be read by man and u...

Страница 49: ...iles and to assemble them separately This way a change would affect only one of the files which can be quickly re assembled Working this way requires additional features A means of telling that a particular source file references a data variable or a label that is defined in another source file in order to prevent the assembler from merely stopping and issuing an error message saying that somethin...

Страница 50: ...e re assembled which saves time then all the object files must be linked again The linking process is fast compared to assembly since the files contain binary data and their format is optimized to make the linker s job easier If a hardware change is made to the board that changes the address of some memory or a pe ripheral it may be only necessary to alter the linker control file and link the prog...

Страница 51: ...nd linked Thus a tool that can guarantee that the programmer will never forget to reprocess his files is an invaluable help This tool is called Maker or Make utility The maker is a tool that works under the control of a file that gives the names of the source files the name of the output object file the names of the tools needed to process a file to an other file assembler linker and the dependenc...

Страница 52: ...r a microcon troller you can still keep the maker you are accustomed to 3 1 2 5 EPROM burners EPROM burners or programmers are tools that have a hardware interface with a zero inser tion force socket that matches the characteristics of the specific EPROM chip or microcon troller with built in EPROM They transfer the contents of an absolute object file into the phys ical programmable memory Burner ...

Страница 53: ...eaches the address of the instruction where the breakpoint was put This can be used to run some parts at full speed and then stop on reaching parts that are not yet fully functional to avoid walking step by step through a lot of in structions that have already proven to be correct The progress of the execution can be followed on the screen in a special window that shows the source file and a curso...

Страница 54: ... application hardware at the same time informs an external intelligence the programmer of everything that happens in that world An emulator offers exactly the same features as a simulator does in terms of running an ap plication either at full speed or step by step setting breakpoints examining registers memory and input outputs The major difference is that while running the program the microcontr...

Страница 55: ... language statement like int UnitPrice Quantity Cost float Discount void main Cost float UnitPrice Quantity 1 Discount is easy to read and translates into about eighty instructions without taking into account the subroutines that perform multiplication and subtraction We can see at a glance the produc tivity gain we can expect from a high level language C language was initially designed as the pro...

Страница 56: ...hardware the quicker the development takes The portability of C is also a guarantee for the future The microcomputer world evolves so fast that it is not unusal to have to redesign an existing application for another microcontroller or to reuse parts of the code of a previous application for a future one In such an event the C language allows you to reuse code with virtually no change from project...

Страница 57: ...ore and more products through ISO9000 standards or the constraints of product liability must be ready for quality assurance certification Software quality assurance is a very difficult subject it is not the purpose of this book to enter this field But one thing is sure only properly docu mented and structured software is likely to meet these quality assurance requirements 3 2 2 Tools used with C l...

Страница 58: ...rtion as choosing a high level language does in terms of shrinking the source code Thus the advantage of high level languages is twofold it reduces both the programming time and the debugging time This is an invaluable benefit as the resource that is probably the scarcest nowadays is time even more than money However you are advised to check whether of the programming tools you selected fully supp...

Страница 59: ...critical places A simulator and a debugger that properly display the C source text allowing you to easily change the values of variables or even code in memory to make patches and that correctly synchronizes the timers during step by step execution These are just a few of the features that may make the difference between apparently equiv alent competing products ...

Страница 60: ...program include files Assembler source files include files C module 1 Relocatable object files C compiler Assembler Linker Absolute object file To the EPROM programmer or the debugger for simulation or in circuit emulation Compiling assembling and linking instructions can be written in a make utility file 1 Linker parameter file 1 Depending on the development tools chain this file which contains t...

Страница 61: ...Realizer allows you to use graphical input techniques and build programs based on functional block diagrams Version 2 2 of the STRealizer is available on the ST7 CD ROM 3 5 FUZZY LOGIC COMPILERS Fuzzy logic is a mathematical theory that has been applied to cope with problems that are at the border between logical and analog computation It has lead to many articles and books to explain both its bas...

Страница 62: ...rkably versatile for a microcontroller of its class It has a wide choice of versions in order to minimize the component count of each specific application Type Word size Main features Typical applications ST6 8 bits Very low power consumption 1 2 to 8 KB ROM timer ADC watchdog timer and more depending on the subtype Appliances home automation suitable for direct power line supply ST7 8 bits Indust...

Страница 63: ...er For those of you already familiar with the standard instruction set the extension resides mainly in the following two points A second index register Y that can be used anywhere the X register is used like indexed addressing or like X moved to any other register The indirect addressing modes that come in addition to the direct long and indexed modes The core as described here is limited to the p...

Страница 64: ...c and logic unit CPU Control Core Reset CPU Clock Interrupt requests from peripherals Data Memory from 0000h to 017Fh Peripheral registers User RAM Stack RAM Program Memory from E000h to FFFFh user ROM Interrupt reset vectors Address bus Data bus 16 lines wide 8 lines wide 16 lines wide Page 0 8 lines wide The core and the addressing space of the ST72251 ...

Страница 65: ...a are located in page zero Also in the ST7 all input outputs are always located in page zero 4 2 2 Internal registers The core uses only six registers A X Y PC SP and CC 4 2 2 1 Accumulator A The accumulator is the register where the arithmetic and logic operations are performed To perform a two operand operation between two values stored in memory one of the values must first be moved to the accu...

Страница 66: ...it are mainly addition and subtraction the shift and ro tate instructions and of course instructions that directly affect the CC register The instructions that use the C bit are ADC and SBC subtract with carry the rotate instructions and some conditional jump instructions Z bit This bit is set to one to reflect the fact that a value is zero whenever the accumulator is loaded or after any arithmeti...

Страница 67: ...orm the ADD instructions on these numbers we find 7Ch as the rules for adding two binary numbers imply This is because 3 9 C in hexadecimal C is not an acceptable digit in BCD However it is easy to see that if we add 6 to the total the difference between 15 and 9 we get 82h which is also the right answer in packed BCD No half carry has occurred Third case adding 28 and 59 We expect to get 87 Once ...

Страница 68: ...ing the course of the program is called jumping or branching Jump and Branch are the names of instructions that actually change the contents of the PC by setting it to a value specified with the instruction Jumps may also be conditional that is the jump instruction effectively alters the contents of the PC if certain conditions are met These conditions can be the values of one or more bits of the ...

Страница 69: ...ted succes sively the first RET instruction will pop the last address pushed the second RET will pop the one but last address and so on This feature provides for the nesting of subroutines where the last called is the first exited Interrupts being a kind of subroutine call also use the stack to store the context of the inter rupted process Since interrupts occur at unexpected times all the core re...

Страница 70: ...e core has not many in ternal registers 4 3 INSTRUCTION SET AND ADDRESSING MODES 4 3 1 A word about mnemonic language In the text above we have given examples that use the mnemonic language For those of you that are not familiar with the mnemonic language of the ST7 here is a refresher More details will be given in the paragraph that discusses addressing modes and in the chapter about the assemble...

Страница 71: ...oller commonly called opcodes There are also other words that are not opcodes but that have a similar function in the language For that reason they are named pseudo ops Opcodes are named after the abbreviation of the function of the instruction Some are ob vious like ADD some abbreviated like SUB subtract others are acronyms like TNZ Test for Negative or Zero The pseudo ops include commands to the...

Страница 72: ... direct mode addresses page zero long direct mode addresses the whole range If the address of the byte is not known when the program is written this means that the data has the form of a record a string an array or any other structure that holds complex data Since the ST7 only processes bytes it is necessary to process this kind of data byte by byte Then the address of the byte to be read is compu...

Страница 73: ...s available This kind of sorting may seem arbitrary but there are actually groups of instructions that have a common function and also the same set of addressing modes Table 2 Table of the number of addressing modes versus the instruction types Type of instruction No operand system Multipli cation and branch relative Push and pop Load memory with index Load and compare index Single operand arithme...

Страница 74: ...ration and an addressing mode may be coded The original industry standard instruction set only uses one byte for the opcode The ST7 in creased the choice of addressing modes so that it was no longer possible to code them all using a single byte A prefix byte has been created When this prefix is put before an opcode it changes the addressing mode of the opcode There are three prefixes PDY 90h means...

Страница 75: ...m 0 BTJF m 0 BTJT m 1 BTJF m 1 BTJT m 2 BTJF m 2 BTJT m 3 BTJF m 3 1 BSET m 0 BRES m 0 BSET m 1 BRES m 1 BSET m 2 BRES m 2 BSET m 3 BRES m 3 2 JRA JRF JRUGT JRULE JRUGE JRULT JRNE JREQ short 3 NEG CPL SRL SRA RRC SLL A 4 NEG MUL CPL SRL SRA RRC SLL X 5 NEG CPL SRL SRA RRC SLL short X 6 NEG CPL SRL SRA RRC SLL X 7 NEG CPL SRL SRA RRC SLL 8 IRET RET TRAP POP A POP X POP CC 9 LD X Y LD S X LD S A LD ...

Страница 76: ...ES m 6 BSET m 7 BRES m 7 2 JRNH JRH JRPL JRMI JRNM JRM JRIL JRIH short 3 SLA RLC DEC INC TNZ SWAP CLR A 4 SLA RLC DEC INC TNZ SWAP CLR X 5 SLA RLC DEC INC TNZ SWAP CLR short X 6 SLA RLC DEC INC TNZ SWAP CLR X 7 SLA RLC DEC INC TNZ SWAP CLR 8 PUSH A PUSH X PUSH CC RSP HALT WFI 9 RCF SCF RIM SIM NOP LD A S LD A X immedi ate A XOR ADC OR ADD CALLR LD X LD m X short B XOR ADC OR ADD JP CALL LD X LD m ...

Страница 77: ... bytes of memory Direct short mode There are two direct addressing modes short and long They are identical except for the number of bytes of the address of the operand Direct addressing means that the opcode is followed by the address of the data in memory to be read or written In the short version the address is situated between the addresses 0 and 255 and only one byte is used for it Example the...

Страница 78: ...the value stored in a memory address in page zero pointed to by the chosen index register loads the accumulator with the value stored in memory at address 26h The coding of the in struction is in hexadecimal F6 This instruction takes only one byte of memory This mode is used if the address of the op erand is not known at assembly time and must be calculated according to some rule Indexed with shor...

Страница 79: ...of X and the offset exceeds 0FFFFh the effective address rolls over zero For example if X contains 83h and the offset is FFC2h the effective address will be 45h Caution there must be no space on either side of the comma within the parenthesis Example 4523h X is incorrect Relative direct mode This addressing mode is only used in jump instructions The opcode is followed by a byte that represents the...

Страница 80: ... error message Relative indirect mode This mode is also only used for Jump Relative instructions The opcode is followed by a byte that is the address in memory that contains the displacement Example if the displacement EEh is stored in the memory byte at address 58h the following in struction is stored at address 1200h JRA 58h The value of the relative displacement is stored at the specified memor...

Страница 81: ...struction is in hexadecimal 92 B6 10 where the first byte is the PIX prefix This instruction takes three bytes of memory Indirect long mode This mode is similar to the indirect short mode but the effective address contained in memory is a 16 bit word This allows the whole address range to be accessed The pointer must still be placed at an address below 100h For example if the pointer at addresses ...

Страница 82: ...exadecimal 92 E6 23 where the first byte is the PIX prefix This instruction takes three bytes of memory Indexed with indirect long offset mode This mode takes a 16 bit index in memory and adds its contents with the 8 bit contents of the index register yielding the effective 16 bit address of the operand For example if the 16 bit pointer at address 23h contains 7945h the index register X contains 5...

Страница 83: ...in page zero the following instruction sequence can be used LD X I Set Index register to value of index I of array A LD A A X Get value A I LD X J Set Index register to value of index J of array B ADD A B X Add value of B J LD X K Set Index register to value of index K of array C LD C X A Put result into C K This is only one of the many examples where powerful addressing modes help translate high ...

Страница 84: ...laneous Register is laid out differently from one ST7 device type to another We will describe only two variants here 5 1 1 ST72251 Miscellaneous Register The SMS slow mode select bit when set places the core and the peripherals in slow mode This speed is 1 16 the normal speed which is the oscillator frequency divided by 2 The bit MCO main clock out when set enables a clock signal with this frequen...

Страница 85: ...ision rate between 2 and 16 The bit MCO main clock out when set enables a clock signal with this frequency to be output on bit 0 of port F PF0 05 misc2 PEI3 PEI2 PEI1 PEI0 MC0 PSM1 SMS Main Clock Out Slow Mode Select and Prescaler bits of the ST72311 Miscellaneous Register 2 Oscillator PF0 normal I O port fCPU to the core and peripherals 0 normal mode 1 slow mode 0 normal I O 1 Pf0 fCPU ST72311 PS...

Страница 86: ... output comparison The SPI may request an interrupt on end of transmission etc 05 sourc 5 2 1 Interrupt sources and interrupt vectors The interrupt sources are summarised in the tables of the following paragraphs There are compared the interrupt related information for the ST72251 and the ST72311 It is interesting to see the differences Interrupt request sent to the core Hardware external sources ...

Страница 87: ...FF7h SPI Transfer complete SPISR FFF4h FFF5h Mode fault TIMER A Input capture 1 TASR FFF2h FFF3h Output compare 1 Input capture 2 Output compare 2 Timer overflow Not used FFF0h FFF1h TIMER B Input capture 1 TBSR FFEEh FFEFh Output compare 1 Input capture 2 Output compare 2 Timer overflow Not used FFECh FFEDh Not used FFEAh FFEBh Not used FFE8h FFE9h Not used FFE6h FFE7h I2C I2C Peripheral interrup...

Страница 88: ...B0 PB3 N A FFF2h FFF3h EI3 PB4 PB7 N A FFF0h FFF1h Not used FFEEh FFEFh SPI Transfer complete SPISR FFECh FFEDh TIMER A Mode fault Input capture 1 TASR FFEAh FFEBh Output compare 1 Input capture 2 Output compare 2 Timer overflow TIMER B Input capture 1 TBSR FFE8h FFE9h Output compare 1 Input capture 2 Output compare 2 Timer overflow SCI Transmit buffer empty SCISR FFE6h FFE7h Transmit complete Rec...

Страница 89: ... inputs are further discussed in the paragraph about the parallel input out puts 5 2 2 Interrupt vectorization When the core decides to grant an interrupt it must know the address of the code to be exe cuted when this event occurs This is the purpose of the interrupt vectors The interrupt vectors are a table of 16 bit words in program memory that contain the address of the beginning of the various...

Страница 90: ...d when the I bit is reset The core finishes its current instruction PC X A CC are pushed onto the stack The I bit is set The PC is loaded with the address of the interrupt vector The interrupt program starts At the beginning of this program you can temporarily save data if needed such as the Y register You must restore them at the end Before returning the pending bit must be cleared The iret instr...

Страница 91: ...upt mechanism 5 2 5 1 Saving the interrupted program state When the interrupt request triggers an interrupt the first task of the core is to save its current state so as it will be able to restore it after the interrupt processing is finished This is done by pushing all the core registers to the stack namely the Program Counter the X register the Accumulator and the Condition Code Register It shou...

Страница 92: ...reg isters have been pushed on granting the interrupt request except the Y register They must now be restored so that the execution of the service routine will not leave any trace in the core This is the role of the IRET instruction The IRET instruction proceeds with popping off the stack all the data that had been pushed previously namely the Condition Code then the I bit is also restored the Acc...

Страница 93: ...ack plus the interrupt service routine may push some bytes to protect any data in memory that may be used globally The problem of atomicity as explained in Chapter 2 If an interruptible service routine handles multi byte data it must take into account the possibility of being interrupted in the middle of a data read or write with the risk of data incoherence The applications described in Chapters ...

Страница 94: ...en drain Selecting these options is done through registers that are associated with each port They are memory mapped and are named Option Register OR and Data Direction Registers DDR Some pins configured as input may also be connected to the external interrupt circuitry when the corresponding bit of the Option Register is set This allows an interrupt request to be trig gered when the state of the ...

Страница 95: ... 4 ST72251 I O alternate functions Note All pins of port C have two alternate functions Input configuration DDR 0 Output configuration DDR 1 Port OR 0 OR 1 External interrupt source Polarity option bits OR 0 OR 1 Port A PA0 PA7 Floating Floating with interrupt EI0 PEI0 PEI1 True open drain Reserved Port B PB0 PB7 Floating Pull up with interrupt EI1 PEI2 PEI3 Open drain Push pull Port C PC0 PC5 Flo...

Страница 96: ...its of Port B are configured by the PEI2 and PEI3 bits in the same register However bits 0 to 3 are assigned to the vector at FFF2 FFF3 while bits 4 to 7 are assigned to the vector at FFF0 FFF1 Note PB5 to PB7 are not available on the smaller packages J series PEI3 PEI2 PEI1 PEI0 MC0 SMS ST72251 0 0 1 0 0 1 1 1 Falling edge and low level reset state Falling edge only Rising edge only Rising and fa...

Страница 97: ... precautions are discussed when needed in the paragraph related to the corresponding peripheral Input configuration DDR 0 Output configuration DDR 1 Port OR 0 OR 1 External interrupt source Polarity option bits OR 0 OR 1 PA0 PA3 Floating Pull up with interrupt EI0 PEI0 PEI1 Open drain Push pull PA4 PA7 Floating n a True open drain high sink capability PB0 PB3 Floating Pull up with interrupt EI2 PE...

Страница 98: ...nsition map in the datasheet All the applications described in this book Chapters 6 7 9 and 10 give examples of using the parallel ports in various combinations I O pin Alternate function 1 PC0 OCMP2_B Timer B PC1 OCMP1_B Timer B PC2 ICAP2_B Timer B PC3 ICAP1_B Timer B PC4 MISO SPI PC5 MOSI SPI PC6 SCK SPI PC7 SS SPI PD0 Ain0 ADC PD1 Ain1 ADC PD2 Ain2 ADC PD3 Ain3 ADC PD4 Ain4 ADC PD5 Ain5 ADC PD6...

Страница 99: ...pherals A microcontroller or any programmed machine is not an electronic brain in spite of how it was first introduced Rather it is an automaton that has a precise job to perform taking into account events and conditions that are considered when the program is written However not all events can be taken into account some occurrences are even neglected since they are supposed to never happen Rightl...

Страница 100: ... to the microcontroller It is up to the program to periodically rewind the clock the watchdog timer to indicate that it is still alive Actually it is not a full protection since some parts of the program may crash while the part that has been elected to rewind the timer still functions It is up to the wise pro grammer to find the program segment that is very unlikely to still work while some other...

Страница 101: ...re activation This register does not belong to the addressable space of the ST7 and is only accessible by the EPROM programmer In the ROM version the customer has the option to select software or hardware activation by specifying it on the order form WGDA T6 T4 T5 T3 T2 T1 T0 Activation bit cleared by hardware after a reset can be set once by software can only be cleared by another reset Reset 1 0...

Страница 102: ... watchdog it is sufficient to write a new value to it keeping the two high order bits high It is possible to rewind the watchdog to different value depending on the circum stances to allow a shorter or longer time out In the 72311 the watchdog has an extra register the Watchdog Status Register WDGSR that only has one meaningful bit WDOGF WGDA T6 T4 T5 T3 T2 T1 T0 Reset 1 0 0 0 0 0 0 0 1 1 1 1 1 1 ...

Страница 103: ...uble this value and try again If no reset occurs take the value at midway and try again Reduce the value this way as much as possible each time using the program with all its features if possible When you think you have found the smallest value that never produces a reset multiply this value by a safety factor and keep it The safety factor depends on how much opportunity you had to actually test t...

Страница 104: ... one parallel input output pin into a clock input The frequency applied to the pin is directly fed to the timer with no predivision The external clock is only available on Timer A on the ST72251 and ST72311 05 timck To give an idea of the time resolution of the timer the following table give the resolutions avail able with a 16 MHz crystal for all divider selections Timer clock predivisor Core pre...

Страница 105: ...R where reading does not alter the TOF bit 5 5 2 1 Reading the free running counter The free running counter can be read at any time However since this is a 16 bit register and the core is an 8 bit one it is not possible to take a snapshot of the counter value at once This can lead to data desynchronization problems as mentioned earlier in this book To avoid this problem the timer has a buffering ...

Страница 106: ...o reset it by writing any value to the low byte of either CLR or ACLR the value written is irrelevant It is im portant to note that when reset the counter is not set to zero but FFFCh or 4 This must be taken into account in the timing calculations The hardware reset also resets the timer to this value 05 timrs To make a software reset of the free running counter Any writting access to the low byte...

Страница 107: ...r enabled or disabled by the TOIE bit of Timer Control Register 1 For this interrupt to be serviced interrupt requests must be globally enabled by the I bit of the Condition Code Register TOF bit 5 of TSR Timer overflow flag TOF is set by the transition FFFFh 0000h of the 16 bit free running counter TOF bit to be cleared First step reading access to TSR Second step a read or a write access to the ...

Страница 108: ...lways enabled the ICAPipin is shared with a parallel input output port pin and that port must be configured with the corresponding pin as an input to be able to use the capture input The IEDGi bit in the Timer Control Register 1 selects either the rising or the falling edge of the ICAPi pin as the active transition When the transition occurs the ICiHR ICiLR pair contains the value of the counter a...

Страница 109: ...annel 1 the reader can transpose it for the other channel or the other timer by substituting the register bit and pin names as in the table above Channel 1 Channel 2 Function TAIC1HR TAIC1LR TAIC2HR TAIC2LR Input capture registers 16 bit read only access ICAP1_A PB0 on ST72251 PF6 on ST72311 ICAP2_A PB2 on ST72251 doesn t exist on ST72311 Input capture pin ICF1 ICF2 Capture event flag in TASR IEDG...

Страница 110: ...ng interrupt mechanism diagram for channel 1 timer A ICF1 Timer A status register TASR I Condition code register CCR ICIE Timer A control register 1 TACR1 Input capture interrupt to the core 1 0 Input capture 1 pin IEDG1 Free running counter 16 bit input capture register TAIC1HR TAIC1LR Read only registers load ICF1 Input capture flag 1 bit bit 7 of TASR ICIE Input capture interrupt enable bit bit...

Страница 111: ...VL1 Free running counter 16 bit output compare register TAOC1HR TAOC1LR Read write registers OCF1 Output compare flag 1 bit bit 6 of TASR OCIE Output compare interrupt enable bit bit 6 of TACR1 OLVL1 Output level 1 bit bit 0 of TACR1 OC1E Output compare 1 enable bit bit 7 of TACR2 reset general purpose I O pin set timer A output compare 1 pin OCMP1 I Global interrupt enable bit bit 3 of CCR 16 16 ...

Страница 112: ...72251 PF4 on ST72311 OCMP2_A PB3 on ST72251 doesn t exist on ST72311 Output compare pins 1 and 2 OCF1 OCF2 Output compare event flag bit in TASR OC1E OC2E Output pin enable bit in TACR2 OLVL1 OLVL2 Level to be output on compare bit in TACR1 FOLV1 FOLV2 Force compare bit in TACR1 OCIE Common Interrupt Mask Flag in TACR1 Channel 1 Channel 2 Function TBOC1HR TBOC1LR TBOC2HR TBOC2LR Output compare reg...

Страница 113: ...it can only be set by software to reset it it is necessary to perform a hardware reset 5 5 5 One pulse mode The input capture and output compare features are intermingled in One Pulse Mode This mode is selected by setting the OPM bit in the TACR2 register or TBCR2 for Timer B In this mode an active edge on the ICAP1_A pin toggles the OCMP1_A output pin then after a predefined delay this pin is tog...

Страница 114: ...de and corresponding interrupt mechanism diagram for timer A Interrupt to the core Input capture 1 pin Free running counter 16 bit output compare register TAOC1HR TAOC1LR 16 16 Compare loaded with the duration of the pulse OCIE Timer A control register 1 TACR1 OLVL1 OLVL2 Configuration of the input capture pin see the input capture mode diagram Clk latch Clk latch Configuration of the output compa...

Страница 115: ...ts of the same timer are involved simultaneously in Pulse Width Modulation mode This mode is selected by setting the PWM bit of the TACR2 register or TBCR2 for Timer B The PWM mode and the OPM mode are exclusive if both selection bits are set at the same time OPM mode is overridden by PWM mode In this mode no external event resets the free running timer instead the second compare cir cuit is used ...

Страница 116: ...upt to the core Free running counter 16 bit output compare register TAOC1HR TAOC1LR 16 16 Compare loaded with the duration of the pulse Timer A control register 1 TACR1 OLVL1 OLVL2 Clk latch Clk latch Configuration of the output compare pin see the output compare mode diagram ICIE ICF1 I Condition code register CCR Timer A status register TASR Output compare 1 pin FFFCh PWM Timer A control registe...

Страница 117: ...t application in Chapter 9 In this application the timer generates periodic pulses while its frequency is controlled using a Phase Locked Loop scheme to synchronize it with an external reference frequency The application described in Chapter 9 uses the timer in PWM mode with interrupt generation The capture feature is also used at the same time to synchronize pulse generation with an ex ternal sig...

Страница 118: ...lso slowed down 5 6 2 Using the Analog to Digital Converter Controlling the ADC is fairly simple since it is controlled by a single register ADCCSR Bit 5 of the CSR ADON is the on off switch of the ADC When off it does not consume power reducing the dissipation of the ST7 When switched on again for the first 30 µsecs conver sions may be inaccurate Bits 2 to 0 select the input pin whose value is to...

Страница 119: ...to send it for information purposes accuracy is the best expression It indi cates how much confidence one can have in the data If the converter is to be used as the feedback input for a servo loop of the second order for ex ample a positioning device using a DC motor and a feedback potentiometer then linearity is the key factor Not only must a servo loop be accurate since this accuracy translates ...

Страница 120: ...erter and will be outside the range of the ST7 ADC unless the application just needs a servo loop but does not need high performance 5 6 4 Using the ADC to convert positive and negative voltages increasing its resolution 5 6 4 1 Measuring negative and positive voltages There are two ways of handling both positive and negative voltages with a converter that can only handle positive voltages The fir...

Страница 121: ...voltages that the converter can internally produce and compare to the input voltage It would appear that it is not possible to change it since it is built into the silicon chip Luckily there are ways of doing it from the outside Let us examine the principle first then a real application Let us assume that we feed the converter with a voltage V0 This voltage will lead to the con version result Adc0...

Страница 122: ...the voltage V0 is included within the converter will convert it as Adc0 1 We can now distinguish more finely between two values of the input voltage as soon as they differ by more than Let us exploit this by doing two successive conversions of the voltage V the first time with V0 alone the next time with Vdda 255 2 Vdda Adc0 255 V0 Vdda Adc0 1 2 255 Vdda Adc0 1 2 255 V0 Vdda Adc0 1 255 Vdda 255 2 ...

Страница 123: ...alog input Vana Extra step analog voltage equivalent to 1 2 lsb VDDA 510 1 2 adc0 adc0 1 V0 V1 Vana min V1 V0 V with V VDDA 255 and extra step V 2 V0 Vana V0 V 2 adc0 adc0 1 V0 V1 Vana min V0 V 2 Vana V1 Vin acquisition without extra step Vin Vana adc0 adc0 Vin acquisition with extra step Vin Vana V 2 adc0 adc0 1 9 bits accuracy Result 2adc0 2adc0 1 Vin Vin Conversion Conversion Example of a simpl...

Страница 124: ...an of these values we just add them we get a number that ranges from 0 to n 255 where n is the number of readings added together Since the succes sive conversion results are not identical all the values in the range are possible For example if we sum four readings the result ranges to 4 255 1020 We can now distinguish 1021 dif ferent values of the input voltage This explanation is a bit too simple...

Страница 125: ...el transmission since the instruc tions needed to put or get a byte through the channel take longer than the transmission Actually transfer is bi directional at the same time that data is sent on one line it is received from the other line this allows full duplex transmission at the rate mentioned above when two microcontrollers are connected together A supplementary pin SS allows the SPI to be en...

Страница 126: ...rol which slave is active at any given time These pins are each driven by a sep arate output pin of the master controller 05 spi2 MOSI MISO MOSI MISO SCK SCK SS SS VDD permanent MASTER 8 bit shift register SPI Clock generator 8 bit shift register SLAVE 1 Single master system for a dialogue with SPIs between three microcontrollers MSTR 1 MSTR 0 MOSI MISO SCK SS 8 bit shift register SLAVE 2 MSTR 0 O...

Страница 127: ... 1 CPOL 0 CPHA 0 SPR1 0 SPR0 0 Max speed fcpu 4 Permanent master mode SPI alternate functions connected to pins No interrupt in this application SS Vdd SPI State Control 3 Serial data out Serial data in External shift registers Clock 8 Parallel data out 4094 4094 Expanding the parallel outputs using the SPI and external shift registers 8 8 SPICR ST72311 I O or alternate function circuitry SPE mast...

Страница 128: ... low order bit The last data bit is followed by a Stop bit 5 8 1 Bit rate generator The bit clock is derived from the CPU clock divided by a user selectable value There are two ways of doing this For the most popular bit rates the Baud Rate Register offers a choice of four prescaler values and the output of the prescaler is further divided by two separate divisors that provide the re ceive bit rat...

Страница 129: ...t is cleared the word length is 8 bits otherwise it is 9 bits The ninth bit when received is copied to the R8 bit of that same register To transmit a 9 bit word the first 8 bits are taken from the Data Register least significant bit first and the value of the T8 bit of the CR1 register is used as the ninth bit No automatic parity generation or checking is provided If needed parity may be calculate...

Страница 130: ...e transmission that is 11 bits This gives a tolerance of about 5 which is not a problem to achieve Baud rate generator fcpu 1 stop 0 start transmit shift register 8 or 9 bits long Internal data bus Data register T8 M 1 9 bits 0 8 bits SCICR1 TDO TDR Transmit control TDRE TC SCISR I CCR TCIE SCICR2 SCI simplified transmit bock diagram TCIE Transmission complete interrupt enable TE assign TDO pin to...

Страница 131: ... it is a zero the FE bit is set in the SCISR The RDRF bit is set when the reception is complete It can generate an interrupt so that the re ceived character may be picked up 05 sci2 Receiver baud rate generator fcpu Bit rate 16xBit rate Start bit detection Good start bit ON Stop 8 7 6 5 4 3 2 1 0 OFF Receive counter 1 9 if M 0 1 10 if M 1 R8 M SCICR1 only if M 1 1 9 bits 0 8 bits Bad start bit Int...

Страница 132: ...me the NF bit Noise Flag is set and the bit value is determined according to the 2 to 1 majority rule The FE bit Framing Error indicates that a proper stop bit was not present at the end of the character The interpretation of these error conditions is not necessarily pertinent however the occurrence of any of these errors tends to mean there is a transmission problem and that the data transfer is ...

Страница 133: ...eived and if that address is not its own the microcontroller just sets its RWU bit and from that time on it is not disturbed by the traffic on the line 5 8 6 Handling the interrupts All the interrupt causes of the SCI share the same interrupt vector Thus the same interrupt service routine is used for all causes and the interrupt service routine must start by testing the Status Register bits to kno...

Страница 134: ...en starts the transmission by enabling the transmit interrupt This will make the interrupt mecha nism send the characters one at a time an interrupt occurring each time the SCI has sent a character The sending is terminated either by exhausting a character counter or encountering a terminator at the end of the buffer An example of this type of handling is described in the second application Chapte...

Страница 135: ... WinEdit and the STMicroelectronics programming tools expect to find WinEdit already installed on the computer before they can be installed So the installation of WinEdit is also described and all subsequent references to text editing in volve WinEdit This chapter concludes with the demonstration of a very simple program that shows how to write source code assemble it and link it A more complete p...

Страница 136: ... an error will occur The ST7 assembler is case sensitive that is upper case and lower case characters are considered different Ex ample ThisLabel and Thislabel are different The source text is made up of lines that are terminated by a carriage return character Each of the lines of the source text represents one complete command and is called a Statement A statement itself is divided in fields numb...

Страница 137: ...r tabulation character The comment field must be preceded by at least one space or tabulation character then a semicolon The remainder of the line is ignored by the assembler This allows to add com ments in the source code to help to maintain the program by explaining the working of the in structions used The various services that the ST7 assembler provides are detailed below 6 1 2 Instruction cod...

Страница 138: ...type a variable is given a symbolic name to be used in a program Another feature of a variable is that it may be changed during the execution of the program in which case it must reside in read write memory or RAM We have already introduced the notion of symbolic data The term VALUE given in the exam ples above is the symbolic name that the programmer may assign to a data object somewhere in the a...

Страница 139: ... the assembler performs this task provided that the programmer specifies the length of each variable and the address of the first one of the list This is done using pseudo ops that are not machine instructions but commands that the assembler interprets for specific results Syntax the data storage for variables is specified with the pseudo ops DS B DS W and DS L that reserve a byte a word or a doub...

Страница 140: ...y set the memory to the value of the operand field Example PowerOf2 DC B 1 2 4 8 16 32 64 128 powers of 2 The following instruction reads one byte from the table according to the value of the index X The input value being loaded first into X the value in A after the execution is 2 raised to the power X 1 for X 0 2 for X 1 4 for X 2 etc LD A PowerOf2 X The pseudo ops BYTE WORD and LONG are similar ...

Страница 141: ...seudo op is primarily used to define character strings but actually any sequence of bytes can be defined with it Message STRING Hello this message is the same as the following Message2 STRING 48h 45h 4Ch 4Ch 4Fh 6 1 4 2 Symbol definition Symbols are like constant data in that they are defined in the source text and they cannot be changed by program execution The difference is that constant data us...

Страница 142: ...an occur later 6 1 5 Relocation commands 6 1 5 1 What is relocation According to the description of the assembler so far writing a program besides the logical analysis it involves looks pretty straightforward The program is made of a sequence of in structions starting from a specified address and extending towards upper memory Similarly the variables in memory are mapped by increasing addresses fr...

Страница 143: ...alled a Linker This program puts all the pieces together placing the pieces of code one after the other in memory and does the same for the variables defined throughout the files Then all external references made in each piece are adjusted to match the true addresses of the referenced objects The object files fed to the linker having no absolute memory addresses are called relocatable objects whic...

Страница 144: ...longing to a certain segment Any number of segments may be defined but in practice it is not necessary to define more segments than the number of areas in memory where the objects can be placed To be used in the program a segment must first be defined The definition can involve the fol lowing items Name This is necessary if the same segment is used in more than one place it is optional otherwise A...

Страница 145: ...e file or until the next SEGMENT pseudo op whichever comes first the block is considered to be long to that segment Example segment rom reset Key word Properties none If none of the options below is chosen the list of defined segments defined is appended to the list of segments of the same class that class must have been already defined by using the AT keyword below AT start address end address Th...

Страница 146: ...ero except the segments with the combine option AT see above that start at the specified address Such segments are called absolute segments They apply a constraint to the linker since the linker is not free to place them anywhere there is room but at a precise address This can lead to conflicts if two absolute segments overlap by mistake This is why absolute segments must only be used where necess...

Страница 147: ...til all the segments have been allocated The result is that objects that are in sequence in a source text may be dispersed in the memory and on the other hand objects that are scattered thoughout the various modules may be contiguous in memory if they belong to segments defined in this way This mechanism is slightly altered when a segment is specified with the common combine op tion As said above ...

Страница 148: ... empty state of all variables is zero This means you initialize the RAM using a loop that sets all bytes in the RAM area to zero This is very easy to do and for security you should do it in all your programs There are variables however that must have an initial value other than zero You must supply values for them and ensure that all the variables are initialized each with its own value be fore th...

Страница 149: ...me module provided they use the same segment name Then data constants are defined in another segment in ROM in the same order and with the same size as those in RAM This looks like the following The segment in RAM is declared as a series of DS statements since these are storage for var iables data segment INITDATA VARIABLES EQU d1 w DS L d2 DS L d3 DS L d4 DS W d5 DS B SIZE_RAM EQU VARIABLES The s...

Страница 150: ...xactly the same structure otherwise the wrong values would go to the wrong variables To avoid this problem the assembler provides a syntax that allows to you create two seg ments at once for these data using this sequence of declarations data segment byte at 80 INITDATA VARIABLES EQU data segment byte at E100 ROM INITIAL_VALUES EQU data segment byte INITDATA ROM d1 w DC L 1234 d2 DC L 12 d3 DC L 1...

Страница 151: ...dress of the identifier that is either contained in a byte when the identifier is located in page zero or in a word when the identifier must be accessed using extended addressing mode Caution These suffixes do not mean that these data are of the byte or word type i e that they store bytes or words it is their address that is either a byte or a word Byte or word identifiers are symbols or labels lo...

Страница 152: ...blic Unlike in the EXTERN directive each identifier already has a type that is either byte word or long and that has been defined with the identifier itself The following example will show the difference between the type of the identifier and the type of the object it represents PUBLIC Value1 Value2 Constant1 Constant1 l EQU 1350000 a large value that does not fit a word SEGMENT DATA_Page0 Value1 ...

Страница 153: ...e suffixes b w or l as above the labels may be declared using their plain name and the current default type applies You may select the appropriate default type using one of the pseudo ops BYTES WORDS or LONGS In the example above this could give LONGS Constant1 EQU 1350000 a large value that does not fit a word SEGMENT DATA_Page0 BYTES Value1 DS W 1 a word data in page zero SEGMENT DATA_Extended W...

Страница 154: ...riants For these types of situations conditional assembly provide an efficient way of mastering the updates of all versions simultaneously Conditional assembly uses structures IF ENDIF or IF ELSE ENDIF like in high level lan guages The general syntax is There are several types of conditions Most use expressions evaluated from symbols that may or may not be defined in the current module Thus changi...

Страница 155: ...FIRST_TYPE some program source lines IFDEF FIRST_TYPE first conditional block source text for the first type of display ELSE source text for the second type of display ENDIF continuation of the program IFDEF FIRST_TYPE second conditional block source text for the first type of display ELSE source text for the second type of display ENDIF continuation of the program IFDEF FIRST_TYPE third condition...

Страница 156: ... invocation line of the assemble must have the argument D FIRST_TYPE This de fines the identifier FIRST_TYPE before the program is assembled Then the program is assem bled for the first type of display If this argument is omitted or changed the program is assem bled for the second type of display There are other types of IF pseudo ops although they can be used for the same function they are usuall...

Страница 157: ...can save lots of lines of text and provide error free text generation since the expansions always conform to the definition of the macro This means that once a macro is fine tuned it can be used in sev eral places in the source text with a guarantee of success We shall study the various features that macros allow and illustrate why macros can be so helpful 6 1 7 1 Replaceable parameters Macros may...

Страница 158: ...n a third variable The definition of the macro is Addition MACRO VarA VarB Result ld A VarA add A VarB ld Result A MEND The macro is used by typing the names of the symbols to be added and that of the result Addition NbOfApples NbOfPears NbOfFruit The macro is expanded by the assembler into the following code 57 Addition NbOfApples NbOfPears NbOfFruit 57 0013 B602 ld A NbOfApples 57 0015 BB03 add ...

Страница 159: ...label NoIncHigh is also defined in the second expansion which makes a duplicated identifier Obviously a macro that can be expanded only once is not very useful To get rid of this difficulty the macro language allows you to define local symbols When a symbol is defined as local to the macro it will be automatically replaced by a special symbol that is unique for each expansion So the following slig...

Страница 160: ...oduce dif ferent code depending on their argument values We have already seen the IFDEF condition Here are some other conditions that can be tested IFB Conditional This conditional tests whether an argument is blank This may be used to mean something special For example let us look again at the Addition macro This macro requires three argu ments two values to add and a variable to receive the resu...

Страница 161: ...ddition macro but changed so that the first two arguments may be at will either labels or constants The third ar gument must be a label The macro is AddFlex MACRO argA argB Result IFLAB argA ld A argA ELSE ld A argA 1st arg is constant ENDIF IFLAB argB add A argB ELSE add A argB 2nd arg is constant ENDIF ld Result A MEND We see that according to whether the argument is a label or not a different a...

Страница 162: ...as a label and can be used anywhere a label is used Example d2A EQU d2 100 Be careful with the syntax of expressions They always must be enclosed in curly braces Please refer to the ST7 Software Tools Manual for more details The identifier on the left of the EQU statement being a label must start on the first character of the line As a label it has a size that is derived from the current default B...

Страница 163: ...8 3 Numbering syntax directives The most popular chip makers have defined for their products a numbering syntax for non decimal numbers Unfortunately these are not all the same The ST7 assembler offers the choice of four different notations so that the programmer may keep his habits or just choose the syntax he prefers These syntaxes are summarized in the following table Table 8 Table of the numbe...

Страница 164: ...eferences for the objects that are declared EXTERNAL in the source text Instead the object file contains tables that give the names of the unresolved references and the locations in the file where these references are used This information will be used by the linker to merge the object file together and correct the references using the values supplied by those object files where the corresponding ...

Страница 165: ...a letter R is added in the third column to indicate that this address is relocatable The fifth column contains the exact reproduction of the corresponding source text 6 2 LINKER AND ASCII HEX CONVERTER Note For the invocation of the linker and the command line options refer to the ST7 Software Tools User Manual paragraph 5 2 6 2 1 The linking process Once all source files have been assembled we ha...

Страница 166: ...age and the linking process will fail The same would occur if an object is defined twice across two different relocatable object files Another kind of error that is only detected at link time is when an external object is defined in one source file as a one byte address a label with a b suffix and the symbol happens to be defined as global in another source file as a two byte address the label has...

Страница 167: ... of the program or the engineer who will debug the program The files with GRP and SYM extensions are used by the debugger They contain the same in formation as the map file but their internal format is especially defined to be read by a pro gram instead of a human being 6 2 2 Hex file translator The COD file generated by the linker is not suitable for either debugging or PROM program ming It must ...

Страница 168: ... absolute ad dresses The result is a listing file where all the addresses are absolute The debugger can then display the source text and the corresponding code with the actual addresses in a window This extra assembler pass is not required when using another debugger for the other debug gers perform the external resolution themselves using the relocatable listing files and the map file generated b...

Страница 169: ...e tool bar of WinEdit starts the assembly process and if an error is detected by the assembler the mes sage describing the cause of the error is displayed at the bottom of the screen while the cursor is automatically put at the line where the error has occurred and this line is highlighted You have to figure out what is wrong in this line correct it and press the assembly button again until the so...

Страница 170: ...he LED con nected to bit 7of port A is off the next LED off will be that connected to bit 0 of port A and the cycle resumes The 500 ms delay is done using a loop of instructions that is tuned to last for exactly 500 ms taking into account the cycle time of each instruction with an 8 MHz crystal 6 4 2 Inventory of the program files The program includes the following input files The PROJECT WPJ proj...

Страница 171: ...mes of these bits can be used in instructions like BSET or BRES that expect a bit number The MAP72251 ASM file is a bit similar to REG72251 ASM It defines the location and size of the memory available in the ST72251 CATERPIL BAT is the file that defines the assembly link hex file generation and the back annotation process The two files REG72251 ASM and MAP72251 ASM define the microcontroller that ...

Страница 172: ...ine argument is li to say that a listing is required The name of the file to as semble is produced by the expansion of the macro n as explained above in the box The name of the file whose edit window is active at the time the compile command is given is passed to the command For example if the currently active edit window is that of the source file MAIN ASM the command that will be generated will ...

Страница 173: ...ng the build com mand the hammer button To launch the debugger from WinEdit it is not sufficient to write its path in the Debug com mand field you must also add a few parameters so that the command to be placed in the Debug Command box of the configuration parameters looks like the following text C ST7 WGDB7 WGDB7 EXE target emust7 lpt1 dll st7hds2 dll This supposes that the debugger is installed ...

Страница 174: ...d a cpudiv2 ld miscr a fq 8MHz 2 CPU clock 4MHz ld a watch ld wdgr a Start watchdog ld paddr a port A as output clr paor open drain no pull up ld padr a leds off rsp initialize stack Main program Start ld x 00 Next ld a table x ld padr a Switch one LED on pa0 OFF others ON call Delay500 according to table contents inc x cp x 08 If at end of table go back to the beginning jreq Start jra Next table ...

Страница 175: ...easier to write it in the main source file ST7 timer 0 5 second This subroutine generates a 500ms timing by looping PUBLIC Delay500 include Register inc definition of the constants BYTES The following constants are defined as 1 byte values watch EQU FF DELAY1 EQU 10 DELAY2 EQU 100 DELAY3 EQU 140 definition of the variables in page 0 segment ram0 Time ds b 3 reserve memory space in RAM for a page z...

Страница 176: ... file provides one public label and that the corresponding external declaration stands in the main program 6 4 3 3 The REG72251 ASM file and the REGISTER INC file The REG72251 ASM file contains the declaration of all the registers of the ST72251 in an abso lute segment because their addresses are fixed by hardware Each declaration is made public by adding a dot before each label so that any other ...

Страница 177: ...S B 1 empty byte to be continued When you get to the point of inserting EXTERN declarations in the source files you have two choices You may add only the external declarations you need You may include the REGISTER INC file and get the whole set of external declarations at once since adding useless externals does no harm This method is obviously quicker and easier Here is an excerpt from the REGIST...

Страница 178: ...SPE equ 6 serial peripheral output enable MSTR equ 4 master CPOL equ 3 clock polarity CPHA equ 2 clock phase SPR1 equ 1 serial peripheral rate bit1 SPR0 equ 0 serial peripheral rate bit0 bit names of spisr SPIF equ 7 serial peripheral data transfert flag WCOL equ 6 write collision status bit MODF equ 4 mode fault flag to be continued In addition to the external declarations this file provides the ...

Страница 179: ...ecial reasons relating to the memory map of the component that is fixed by hardware When changing the type of microcontroller you have to change this file and replace it with a file spe cially written for the other model of microcontroller 6 4 3 5 The CATERPIL BAT file This file drives the assembly link hex file generation and back annotation of the listing files The contents of the file are asm l...

Страница 180: ...e the two source files to be re assembled but with the option FI CATERPIL MAP that tells the assembler to produce an absolute listing taking the informa tion from the CATERPIL MAP file to evaluate the effective addresses of the relocatable ob jects The sym option also used causes the table of symbols to be built This table is used by the emulator to identify and locate the various program objects ...

Страница 181: ...ontains the include statement so that it reads include register inc and let us press the funnel button A box appears then requesting whether we want to save the source file before assembling We must answer yes because the assembler uses the files on the disk and not the contents of the editor buffer Then after assembly and analysis of the results the status bar at the bottom of the screen shows Er...

Страница 182: ...link time are one of the following An external label is used in a source file that is not defined anywhere or is not public An external label is used with short addressing mode and it happens not to be defined in page zero It is sometimes not easy to see that a label is defined somewhere as a word and used some where else as a byte When talking about labels do not confuse a byte label with the lab...

Страница 183: ...uipment from lightweight PROM programmers to full real time emulators 7 1 STMICROELECTRONICS HARDWARE TOOLS The STMicroelectronics tools range has three levels EPROM Programming Boards Develop ment Kits and Emulators For each level several models are available depending on the type of microcontroller involved However only two software packages are required to drive them all the EPROMER to program ...

Страница 184: ...all that emulators do except real time tracing They constitute a very convenient and cost ef fective development tool They also include a selection of ST7 chips plus the software tools and documentation They exist in the following models ST7MDT1 DVP for the ST72101 ST72212 ST72213 and ST72251 except R and N variants ST7MDT2 DVP for the ST72121 ST72311 and ST72331 except N6 variants 7 1 4 Emulators...

Страница 185: ...rammer using the supplied cable then apply power to the board using the power supply provided The software has already been installed with the STMicroelectronics Software Tools as de scribed in the previous chapter 7 2 2 Using the EPROMER software The EPROMER is accessible from the ST7 Tools program group that the installation has put on the hard disk of your computer Using the shortcut launch the...

Страница 186: ...nfigure EPROMER then the following window pops up It is made of two tabs Select hardware and port and Select Chip Let us start with the first one 07 prog2 bmp In the left hand box select the type of board in the right hand one select the port number Next switch to the second tab 07 prog3 bmp ...

Страница 187: ...in the previous chapter It has a S19 exten sion So let us select File Open and in the file type combobox select S19 files the default is HEX files Once the file is read its content is displayed in the window 07 prog4 bmp Please note that the range of the addresses in the hexadecimal file must fit the actual memory size of the selected device The display above allows you to scroll throughout the en...

Страница 188: ... the interrupt vectors This is one of the ways of protecting the program against software or hardware mal functioning If we are done with loading and altering the program we can program the chip Using the Pro gram menu you can select either the current memory space or part of it or all of them when a device includes EEPROM 07 prog5 bmp It is also possible to read back an already programmed chip us...

Страница 189: ...drive program execution and monitor what is going on as well as reading and writing any memory byte or register except that it is not possible to write into read only peripheral registers The debugger is the software part of the system that drives the emulator by presenting the data in a legible way on the screen and providing controls for startins stopping stepping through the execution or settin...

Страница 190: ...e software is delivered on two disks at some place during the in stallation you will be requested to insert the second disk in the reader Then a box appears to inform you that some VBX files will be copied to the Windows System directory Press OK Then if needed the ST7 Tools group is created and icons are created Then a box request you to insert the configuration disk be inserted Proceed and press...

Страница 191: ...u1 bmp If you have selected the HDS1 emulator you are requested to give the serial port number to which the emulator is connected 07 emu2 bmp If you have selected the HDS2 emulator you are requested to give the parallel port number to which the emulator is connected ...

Страница 192: ... and PROM Programmer Tutorial for ST72251 07 emu3 bmp Then in both cases you are requested the type of probe that is connected to the emulator this is also the type of chip you want to use in your application 07 emu4 bmp ...

Страница 193: ... change the type of emulator the port to which it is con nected and the type of probe chip used 7 3 3 Using the debugger 7 3 3 1 Loading the application Start WGDB7 After a delay the debugger is started and the following box shows up 07 emu5 bmp This is the main window of the debugger that is called the Toolbox The first thing to do now is to load the map file of the project This file provides all...

Страница 194: ... same name as the output file of the linker lyn REG72251 MAP72251 TIMER500 MAIN CATERPIL obsend CATERPIL f CATERPIL s19 s This is common practice and should be adhered to When you open this file for the first time you have to specify which microcontroller type you are using with the Command Micro name option Then you can select the appropriate type from the list supplied 07 emu6b bmp All other tim...

Страница 195: ... start of the program When a section of program is known to be working like the first lines of the program up to line 44 it is more convenient to execute it at full speed and stop where it is worthwhile stepping again To do this let us click on line 44 This line is then highlighted in blue Press the Goto button of the source window or press F4 Line 44 is now underlined meaning that the pro gram ha...

Страница 196: ...ress of the timer variables situated at 80h 07 emu9 bmp Now we know the value of the three bytes of the timer at 80 81 and 82 This window shows the memory contents at the time it was opened If we step through the program the window will not reflect the changes We have two solutions for this Press the Refresh button when we want to see the latest values Check the Hot box From that time on the windo...

Страница 197: ...uried among a lot of irrelevant information When your attention is focused on a particular variable it is much more convenient to use the Inspect function as follows First place the cursor anywhere on the name of a variable in the source window Then press the button Inspect at the top of the window Let us assume that we have selected the variable Time in the Timer500 source window The following bo...

Страница 198: ...a separate window This can lead to a large number of windows it may then be more efficient to group them all in a single window called the Watch window To do this just select the Add Watch option in the Inspect window A new window will open and display the data in a slightly dif ferent format For each variable a different format may be selected using the various Display menu options 07 emu10c bmp ...

Страница 199: ...nter decreasing from 9 down to 0 Each time we pressed Continue we went through one round of the outer loop Since the initial value was 10 after ten presses on Continue we reach zero The inner loops themselves have done many more rounds Now we can for example press Step repeatedly and watch the program exiting from the subroutine to the main program Several breakpoints may be set at various places ...

Страница 200: ...ints and press Run The program now runs continuously and if eight LEDs are connected to port A we see the unlit LED moving from one position to the next one each half second To return control to the debugger press the Stop button on the toolbox The application must be stopped to close the debugger 7 3 3 6 Watching the contents of the stack Another piece of information we can get from the debugger ...

Страница 201: ...roduces The stepping method described above seems okay but actu ally it might not always be usable The main two reasons for this are The piece of program to run is too long to be traced in a reasonable amount of time This particular piece of program deals with real events that cannot be slowed down and the program must run at full speed to correctly handle them The answer to this problem is the re...

Страница 202: ...ll discuss them when we have introduced C language programming in the next chapter 7 4 PURPOSE OF THE TUTORIAL This chapter has as its sole purpose to help you build an application using the ST7 from scratch This includes designing the test board writing the program and debugging it The subject of this application is the demonstration of a simple multitasking kernel This will show that multitaskin...

Страница 203: ... Hz to 10 Hz 07 func Since we use a timer to produce a frequency this formula must be inverted to give something like This formula requires performing 16 bit division at least Since this would take too long a time we shall use a look up table to convert the converted voltage into a number that can be written to the timer reload register 10 0 255 Hz Analog to digital conversion ADC Frequency f f 9 ...

Страница 204: ... Digital Converter is used to convert the input voltage produced by the potenti ometer Since it only converts one channel at a time the proper channel must be selected prior to reading the potentiometer position Pa4 21 Pa5 20 Pa6 19 Pa7 18 Pc0 17 Pc1 16 Pc2 15 Pc3 14 Vss Vdd 33pF 10M 8MHz Oscin Oscout ST72E251 10nF 28 27 2 3 5V 33pF P2 P3 P4 P1 L2 L1 L3 L4 330 330 330 330 5V Pa0 25 Pa1 24 Pa2 23 P...

Страница 205: ...rithm of each task Since the functionality for each channel is identical we shall describe only one of them The algorithm is the following 07 task Four such algorithms will run simultaneously each belonging to one task The initialization part of the program will thus initialize the core and the peripherals then start all four tasks They will run forever since they are made of a loop with no exit c...

Страница 206: ...we shall describe a more advanced one that is more complicated and specially written to be used in a C language program This kernel is of the cooperative type It provides only two routines StartTasks and Yield described below 7 6 3 1 StartTasks routine The main program defines the table AddrTasks that contains four constant words that are the start addresses of the four tasks Each task must be wri...

Страница 207: ... instruction that expects a return address to be present on the stack even be fore the task has been ever started hence the minus two Everything is ready to start multitasking Now the stack pointer is set to the contents of ImStack1 and the ret instruction that terminates StartTasks is executed But since the stack has been reorganized the execution will not return to the instruction that follows t...

Страница 208: ...lement of the ImStack table that corresponds to the current task whose number is kept in Permut Now all the information on the state of the task we leave is saved Permut is incremented or if at the number of the last task it is cleared The contents of the element of the ImStack table that corresponds to the new value of Permut are then copied to the stack pointer The stack pointer now points to th...

Страница 209: ...s awaken Active area of the stack PCL Task1 PCH Task1 17F 16F 15F 14F The active area of the stack is used in each task of this program to call and return from acana and timerA interrupt routines PCL Task3 PCH Task3 PCL Task4 PCH Task4 16F sp 17D 15D 14D Task2 is woken up Active area of the stack 17F 16F 15F 14F Yield Permut 0 Permut 1 Little kernel the Yield routine effects switching from task1 t...

Страница 210: ... 17F Call Yield instruction is executed SP 17F PCL Task1 PCH Task1 PC is pushed onto the Task1 stack Yield routine is executed Little kernel Breaking up the Yield routine PCL Task2 PCH Task2 16F 1 SP is saved into ImStack1 2 SP is loaded with ImStack2 3 Permut is incremented modulo 4 SP Ret instruction of Yield routine is executed 16F sp Active araa of the stack 16F Task2 is running Permut 1 PC is...

Страница 211: ...re only 16 bytes available for each stack for the 72251 other members of the ST7 family have bigger stacks 5 bytes for ainterrupt is not a lot However the advantage of this kernel is its speed since the code of Yield is very short and does not take many machine cycles To finish this discussion about the mechanism of the stack we should bear in mind that the role of the stack is to store whatever i...

Страница 212: ...on is retrieved then con verted using the lookup table defined in this file The number found in the table is written to the timing register Regn where n is the task number Then there is a loop that decrements Regn and calls Yield This loop is only exited when the count has reached zero then the corre sponding bit of port A is toggled and the endless loop resumes This algorithm is a very typical al...

Страница 213: ...Convert voltage ld X adcdr ld A TimingTable X Get result of timing function from table ld reg Channel A InnerLoop ld A reg Channel tnz A jreq TaskCont Yield until timing register 0 call Yield jra InnerLoop TaskCont ld A 1 SHL Channel 1 When register is zero toggle output xor A padr ld padr A jra TaskLoop Continue looping for this task MEND include Register inc EXTERN StartTasks Yield acana PUBLIC ...

Страница 214: ... 11 11 11 DC B 11 11 11 10 10 10 10 10 DC B 10 10 10 10 10 10 10 10 DC B 09 09 09 09 09 09 09 09 DC B 09 09 09 09 09 09 09 09 DC B 09 08 08 08 08 08 08 08 DC B 08 08 08 08 08 08 08 08 DC B 08 08 08 08 08 08 08 07 DC B 07 07 07 07 07 07 07 07 DC B 07 07 07 07 07 07 07 07 DC B 07 07 07 07 07 07 07 07 DC B 07 07 07 06 06 06 06 06 DC B 06 06 06 06 06 06 06 06 DC B 06 06 06 06 06 06 06 06 DC B 06 06 06...

Страница 215: ...artTasks Start kernel Though it is a call it will never return Timer A interrupt every 10ms intTim_A dec reg1 Update timing registers dec reg2 dec reg3 dec reg4 clr taclr Reset free running counter tnz tasr clr taoc1lr Clear OCF1 iret Code of task 1 Task1 TASK 1 Code of task 2 Task2 TASK 2 Code of task 3 Task3 TASK 3 Code of task 4 Task4 TASK 4 Vecteurs d interruption segment vectit FFE0 DC W 0 sk...

Страница 216: ... ADC and to run a conversion The program which calls this routine selects the channel to be converted by loading the accumulator with the channel number include REGISTER INC PUBLIC acana EXTERN watch b SEGMENT rom WORDS ADC initialization acana On entry A contains the channel selector bit add A 20 Make up the ADC control word set ADON A D converter on ld adccsr a Start the conversion Analog to dig...

Страница 217: ... for task 1 ImStack2 b DS B Position of the stack pointer for task 2 ImStack3 b DS B Position of the stack pointer for task 3 ImStack4 b DS B Position of the stack pointer for task 4 Permut b DS B Number of the current task 0 to 3 Segment rom Words StartTask This routine creates and initializes the stack for all four tasks StartTasks This macro initializes the stack for one task which numer is pas...

Страница 218: ...ack pointer ld A org1 Top of stack for task 1 ld S A ld X AddrTasks 1 LSB address Task push X ld X AddrTasks MSB address Task push X Written at top of stack ld A S ld ImStack1 A Remember position of stack pointer clr Permut Set task counter to first ret Jump to first task Yield Yield ld A watch Loading the watchdog ld wdgr A ld X Permut To select the element where to save ld A S The stack pointer ...

Страница 219: ...d the file Multitsk s19 and press Run Each potentiometer sets the blinking frequency of the corresponding LED and it is easy to see that varying the frequency of one channel does not affect the others If you want to execute the program step by step there is a point to pay attention to Each of the tasks is contained in a single line of the source file since it is written as one ex pansion of a macr...

Страница 220: ...roduce the C language and related software tools and dis cuss its advantages It will also introduce the debugger functions that are specifically meant for C language programming Once you are familiar with the the tools and languages you will be able to analyze the two ap plications that make up the following two chapters that fully use the capabilities of the micro controller and the power of C la...

Страница 221: ...t are written in assembler must be written in the HICROSS dialect and assembled using the HICROSS assembler It is not possible to reuse source files or object files from the STMicro electronics Software Tools in a project using the HICROSS development chain 8 1 C LANGUAGE EXTENSIONS FOR MICROCONTROLLERS The C language formerly designed for mainframes has been extended for the use in the mi crocont...

Страница 222: ... following items The HICROSS ANSI C Compiler The HICROSS Assembler The HICROSS EPROM Burner And more accessories that are described in the HIWARE manual The installation itself calls for no special comment After all files have been copied it asks whether Winedit s configuration file should be updated Answer yes Then you are told that Notepad is the default editor and you are asked whether Winedit ...

Страница 223: ...the left hand button which is the configuration button The following window opens 08 HWTO2 BMP This box allows you to create a project configuration open an existing one or change the cur rently open configuration For the time being press Change 08 HWTO3 BMP ...

Страница 224: ... the Editor Tab and select the Winedit option in the combobox In the Executable box write the path for Winedit You may use the Browse button next to it In our case Winedit is installed in the directory C Program Files WinEdit Winedit exe 08 HWTO4 BMP ...

Страница 225: ...d other tools to the EDOUT file in the root directory This works in conjunction with a setting in the win edit ini file in the windows directory To make the setting use Explorer to locate win edit ini in the windows directory Double click on it to open it in Notepad Do not use Winedit for this purpose Look for the lines OUTPUT EDOUT There are three of them At each occurrence alter it so that it re...

Страница 226: ...tion In a microcontroller the program is stored in ROM and variables are stored in RAM as every body knows This means that you must take care to specify for the development tools the ad dresses in memory of ROM and RAM so that the linker puts the right things in the right place This is not required when programming in C for example for a PC the development chain de cides by itself where to allocat...

Страница 227: ... In many cases some variables are only read by the program but never written to they are ac tually constants In C unlike Pascal or other languages constants do not exist Instead the modifier const may be applied to a regular variable declaration for the same purpose It is used as follows const int SIZE 100 Model name Local data Global data Effect Small direct direct Data are referenced using direc...

Страница 228: ...rameters over power off periods The data that must be saved are read write variables declared like any other variable How ever to ensure that these variables are allocated to EEPROM a special segment must be de fined that will be later linked and located at the start address of the EEPROM By default variables are allocated to the predefined segment DEFAULT_RAM To direct that a variable is to be al...

Страница 229: ...y data generated by the compiler and may be enlarged with the user s variables pragma DATA_SEG _ZEROPAGE int FastVariable Of course the effect of these pragmas must be reversed as appropriate using pragma DATA_SEG DEFAULT 8 3 1 4 Far and near pointers Two kinds of addressing mode short and extended are to be found in direct addressing as well as in indexed and indirect addressing This leads to two...

Страница 230: ...ong with the other files As explained above all variables are allocated by default to the DEFAULT_RAM and they are initialized before the user program starts by copying their values stored by the compiler in ROM into the appropriate RAM locations If initialized variables are actually constants and especially if they are bulky do not forget to move them into the ROM_VAR segment using the const attr...

Страница 231: ...e available in the example files that come with this book It consists of defining a segment for each peripheral and within this segment the list of the registers as a series of variables of the unsigned character type Serial Peripheral Interface pragma DATA_SEG SHORT SPI volatile unsigned char SPIDR SPI Data Register volatile unsigned char SPICR SPI Control Register volatile unsigned char SPISR SP...

Страница 232: ...ed by the statement pragma TRAP_PROC that says that the routine must end with a IRET instruction Since the ST7 does not have a large stack the standard interrupt call only saves the registers necessary for character and integer arithmetic However it is possible to use long and float arithmetic in interrupt subroutines provided that the work area used for this arithmetic is ex plicitly saved using ...

Страница 233: ...st be called at the beginning of the interrupt service function the second at the end Either or both of these pairs must be used depending on the need However there is no stack to save the variables It is not possible to nest two levels of interrupt that use long or floating arithmetic Other less important restrictions also apply that are detailed in the compiler manual 8 4 USING THE ASSEMBLER The...

Страница 234: ...the proper operation of the timer Since the C compiler optimizes the code size some assignments might not be performed in the order they are written In this case it is safer to use in line assembly language as in this example asm ld a TAIC2HR ld Position a ld a TAIC2LR ld Position 1 a This assembly code is logically equivalent to the following expression that reads a word value at the address star...

Страница 235: ...heir arguments in a certain way and return the result in a prede fined manner For more details on this refer to the Hiware manual paragraph III 3 8 5 USING THE LINKER The Hiware linker offers a powerful tool that allows you to finely control the memory allocation module and section placement and more Its operation is guided by a parameter file called link prm in the examples used in this chapter T...

Страница 236: ...0 TO 0x71 AZRAM READ_WRITE 0x80 TO 0xFF ARAM READ_WRITE 0x100 TO 0x13F ASTACK READ_WRITE 0x140 TO 0x17F AROM READ_ONLY 0xE000 TO 0xFFDF PLACEMENT DEFAULT_ROM ROM_VAR STRINGS INTO AROM DEFAULT_RAM INTO ARAM _ZEROPAGE _OVERLAP INTO AZRAM SSTACK INTO ASTACK PORTA INTO APORTA PORTB INTO APORTB PORTC INTO APORTC MISC INTO AMISC WDG INTO AWDG I2C INTO AI2C SPI INTO ASPI TIMERA INTO ATIMERA TIMERB INTO A...

Страница 237: ...nabled must be vectored to the corresponding service rou tine Unused vectors are connected here to a special function for safety The linker in addition to the absolute object file produces a map file that gives the addresses of all the segments variables and other information useful for debugging 8 6 USING THE EPROM BURNER The output of the linker is a abs file This format is not suitable for prog...

Страница 238: ...238 317 8 C Language and the C Compiler 08 Burn bmp Then use the EPROMer programmer software as described in Chapter 7 ...

Страница 239: ...rst application as described in Chapter 9 The top di rectory is the main directory of the project It contains the default env file that contains all the settings that may be defined in the Paths and Additional tabs in the configuration box that is displayed when you press the left hand button of the Hiware Tools bar It is also divided into three subdirectories 8 7 1 Config directory Config holds t...

Страница 240: ...n the current example the appro priate settings for each group are Absolute this is where the absolute file created by the linker is put C ST7 WORK X10xmit object General path C hicross LIB ST7C C hicross LIB ST7C INCLUDE C hicross LIB ST7C SRC C hicross LIB ST7C LIB C ST7 WORK X10xmit C ST7 WORK X10xmit config Library ...

Страница 241: ...tory C ST7 WORK X10XMIT SOURCES MAIN directory C ST7 WORK X10XMIT SOURCES INTSUB directory C ST7 WORK X10XMIT SOURCES MAP directory C ST7 WORK X10XMIT CONFIG 8 7 3 Sources directory This directory contains the user written source files and the header files either user written or supplied in the package or by STMicroelectronics It is divided into four subdirectories each containing source files C a...

Страница 242: ...UT 8 8 HINTS ON C WRITING STYLE FOR THE ST7 STMicroelectronics supplies a set of files that define the registers and the memory map of the ST7 Also to make support easier a particular directory tree arrangement is recommended This paragraph gives advice and rules that will provide you with pre written definitions and a working frame that will help you start and organize your work 8 8 1 Accessing i...

Страница 243: ...h register extern volatile unsigned char TACHR timer A counter low register extern volatile unsigned char TACLR timer A alternate counter high register extern volatile unsigned char TAACHR timer A alternate counter low register extern volatile unsigned char TAACLR timer A input capture 2 high register extern volatile unsigned char TAIC2HR timer A input capture 2 low register extern volatile unsign...

Страница 244: ...ovide for individual bit addresses to reach a single bit it is necessary to give the name of the register that holds that bit and the number of the bit in the register To test the state of a single bit the following syntax is suggested if TASR 1 ICF1 Determine which interrupt cause where the expression 1 ICF1 yields the value 0x80 1 shifted left seven times anding the whole register with this valu...

Страница 245: ...o these devices In many cases when devices need less than eight bits like switches decoders etc the circuit designer connects several of them to the same eight bit port to fully use the capabilities of the device This will require the programmer to use binary expressions to extract those bits he needs at a certain time without taking into account the other bits that are only relevant at other time...

Страница 246: ... to write simple expressions that are easy to read like if PUSH_BUTTONS code to be executed if any button is pressed More complex expressions may be written like if PUSH_BUTTONS CLOSE_BUTTON code to be executed if the CLOSE button is pressed if PUSH_BUTTONS CLOSE_BUTTON OPEN_BUTTON code to be executed if CLOSE button or OPEN button is pressed Such expressions both make the code easier to read and ...

Страница 247: ...ral times The C language is powerful and may generate a lot of code for a single line For example the following statement for p1 string1 p2 string2 p2 p1 p1 p2 copies one string to another by copying each byte from the first location in memory to the second one incrementing both pointers looping back and stopping when the zero character is encountered The code generated occupies 95 bytes of memory...

Страница 248: ...les as often as possible Another point about long and floating arithmetic was described earlier some precautions are needed when interrupts are used 8 9 CONCLUSION This chapter has demonstrated that C language is well suited to microcontrollers like the ST7 when care is taken as specified throughout this chapter the performance of the program written in C is adequate and the ease you will gain wri...

Страница 249: ...of the house from a single point the blinds are supposed to be already actuated by motors with a switch near each one to have them close or open or stop in any intermediary position The objectives of the project illustrate the implementation of various functionalities of the ST7 such as Pushbutton interface Zero crossing detection Motor current detection Transformerless power supply etc The archit...

Страница 250: ...ole wiring of a house involves tens or hundreds of meters of wire that constitute a antenna with a large extent This translates into The best value for the carrier frequency lies in the 100 150 kHz range The voltage of the R F signal must be barely more than one volt The consequences are the following The frequency chosen is almost completely blocked by the electric meter thus limiting the extent ...

Страница 251: ...the zero crossing point and a Binary 0 by the absence of 120 kHz These 1 millisecond bursts should equally be trans mitted three times to coincide with the zero crossing point of all three phases in a three phase distribution system The figure below shows the timing relationship of these bursts relative to zero crossing 09 timing A complete code transmission encompasses eleven cycles of the power ...

Страница 252: ... should be transmitted continuously at least twice with no gaps between codes See figure below 09 xcode Example the next figure shows the transmission of Key 2 to House Code A 09 xex Start code House code Key code 2 cycles 4 cycles 5 cycles A complete transmission code is composed of 2 identical blocks with no gap between them Start code House code Key code X 10 Technology code transmission princi...

Страница 253: ...t of signal is trans mitted on one half cycle binary 1 then no signal should be transmitted on the next cycle bi nary 0 See the following figure 09 xbit A burst on the zero crossing point followed by no burst on the next zero crossing point Logical 1 Logical 0 X 10 Technology bit transmission principle House Key codes except Start code No burst on the zero crossing point followed by a burst on the...

Страница 254: ... 1 0 4 1 0 1 0 0 E 0 0 0 1 5 0 0 0 1 0 F 1 0 0 1 6 1 0 0 1 0 G 0 1 0 1 7 0 1 0 1 0 H 1 1 0 1 8 1 1 0 1 0 I 0 1 1 1 9 0 1 1 1 0 J 1 1 1 1 10 1 1 1 1 0 K 0 0 1 1 11 0 0 1 1 0 L 1 0 1 1 12 1 0 1 1 0 M 0 0 0 0 13 0 0 0 0 0 N 1 0 0 0 14 1 0 0 0 0 O 0 1 0 0 15 0 1 0 0 0 P 1 1 0 0 16 1 1 0 0 0 Function codes All Units Off 0 0 0 0 1 All Light On 0 0 0 1 1 On 0 0 1 0 1 Off 0 0 1 1 1 Dim 0 1 0 0 1 Bright 0 ...

Страница 255: ...ransmissions no gaps between each pair The one exception to this rule is bright and dim codes These are transmitted continuously with no gaps between each 11 bit dim code or 11 bit bright code A 3 cycle gap is necessary between different codes i e between bright and dim or 1 and dim or on and bright etc 9 2 TRANSMITTER 9 2 1 Instructions for use The transmitter has a control panel with the followi...

Страница 256: ...or is loaded by a 100 kOhm resistor and this signal is fed to the PB2 pin The three pushbuttons are connected to PB5 thru PB7 with a pull up resistor so that the pin is pulled to the ground when the button is pressed The display is made of two one digit seven segment LED devices Each of the segments of both devices are connected in parallel and to one pin of port A and the common electrode of each...

Страница 257: ... 6V 470µF 16V 220nF 100K 100nF 400V 10 BDX 33 BDX 34 100 NE 555 10K 3 2 6 8 1 4 1nF BS170 Pb1 10 Vss Pb2 9 ICAP2_A OCMP1_A N Ph HDSP 3900 HDSP 3900 d c g e b f a 10K 10K 10K 5V 10K 5V 330 330 330 330 330 330 Vdd 78ls05 1µF 16V 33pF 33pF 10M 8MHz Oscin Oscout 5V ST72E251 Carrier current system diagram of the transmitter circuit 10nF 220 V ac Reset 1 1µF 28 27 2 3 Pb0 Pb3 Pb4 Pc4 Pc5 Test 11 8 7 13 ...

Страница 258: ...ies the RF energy to the power line is gated to control the times the carrier is present This is done using the PB1 pin that is used as the Output Compare of Timer A OCMP1_A This is configured by the Output Compare Enable bit of Timer Control Register 2 OC1E of register TACR2 that is set to 1 Thus configured the timer would produce a continuous burst of 1 ms pulses To modulate these pulses accordi...

Страница 259: ...at each line zero crossing It synchronizes the timer The third interrupt service routine is run each time Timer B overflows This occurs 64 times per second The service routine does two things It refreshes the display that is multiplexed and that must be switched fast enough to appear as steady It counts down the time providing the necessary time base for the delay displayed The software has been e...

Страница 260: ... state of the three inputs con nected to the buttons and checks whether the current reading is equal to the previous one If this holds true for a certain number of readings the set of buttons is regarded as stable Then the value of these three bits is tested If only one button is pressed the value of that button is returned If no buttons or more than one button are pressed the value zero is return...

Страница 261: ...inition at the beginning of the source text allows you to easily rewire the electronic circuit so that the buttons can be connected to another input in a different order or set the level to high when active only these four lines have to be changed which is easier than having to scan the source text to find where and how the push buttons are read The main program is the following void main void Ini...

Страница 262: ...he common Timer A interrupt service routine Here is the code of the interrupt service routine pragma TRAP_PROC SAVE_REGS void TimerAInterrupt void WDGR 0xFF reload watchdog if TASR 1 ICF1 Determine which interrupt cause This is a pseudo capture 1 interrupt TAOC2HR TimerAPeriod 8 Set new period as calculated in the capture TAOC2LR TimerAPeriod 0xff interrupt service function High MUST be written fi...

Страница 263: ... process but the read from TAIC1LR is ensured Then a counter is incremented so as to count three interrupt services the SendOneFrameEle ment function is called every third interrupt This is because the X 10 standard requires that each pulse be sent three times for each half period so that receivers connected to other phases of the power line and thus synchronized 120 or 240 degrees away from the t...

Страница 264: ...e is in progress Please note that the low order bit is sent first The source code is the following This function is the frame transmission procedure It is called when a time element of a frame is to be sent that is 2 times per line cycle void SendOneFrameElement void static Byte TempKeyCode TempHouseCode switch CycleNumber Increment counter just after test case 1 First 3 half cycles must have a pu...

Страница 265: ...34 if TempHouseCode 1 0 TACR1 1 OLVL1 Validate pulse for next interrupt else TACR1 1 OLVL1 Invalidate pulse for next interrupt TempHouseCode 1 Finished with this bit Ready for next bit break case 13 case 15 case 17 Transmit one of the five bits of Key code case 19 case 21 case 35 case 37 case 39 case 41 case 43 if TempKeyCode 1 0 TACR1 1 OLVL1 Validate pulse for next interrupt else TACR1 1 OLVL1 I...

Страница 266: ...n The basic structure is a switch statement that jumps to the piece of code related to the current bit number This number is incremented just after it is tested so that it travels from 1 to 23 Then it is set to zero When it is zero the common interrupt service routine does not call Sen dOneFrameElement any more until CycleNumber is set to 1 again by the SendCommand func tion switch CycleNumber Inc...

Страница 267: ...oid PhaseLockedLoop void int Position Deviation asm ld a TAIC2HR ld Position a ld a TAIC2LR ld Position 1 a This assembler code is logically equivalent to Position int TAIC2HR get signed value of counter but the order of reading of the two bytes is important and C does not give any guarantee regarding the order Thus assembler is used Deviation Position TIMER_A_PERIOD PULSE_LENGTH Deviation 4 Divid...

Страница 268: ...ue to the nominal period value This value is stored in the global variable TimerAPeriod that is used at the beginning of the inter rupt service routine to update the compare register This ensures that the compare register is updated separately from the comparison avoiding the problem that would occur if the compar ison occured between the writes of the two bytes of the register as the value of the...

Страница 269: ...FCh 1ms Compare 2 interrupt stops the burst and restarts the counter Compare 1 launches the burst if need be Sine wave Zero crossing point Capture 2 interrupt desynchronisation measurement Carrier current system phase locked loop of the transmitter Depending on the difference found between the Capture 2 timer value and the Compare 1 registers the TimerAPeriod variable loaded in the Compare 2 regis...

Страница 270: ... display The constant array is defined as follows const Byte SevenSegment 16 2 0xff 0x84 0xff 0xed 0xff 0xa2 0xff 0xa8 0 3 0xff 0xc9 0xff 0x98 0xff 0x90 0xff 0xad 4 7 0xff 0x80 0xff 0x88 0x6d 0x84 0x6d 0xed 8 11 0x6d 0xa2 0x6d 0xa8 0x6d 0xc9 0x6d 0x98 12 15 This constant table is located in ROM or program segment by means of the const modifier and the Cc compiler option added in the Compoptions it...

Страница 271: ...e delay has elapsed the CLOSE command is sent and the display is switched off The code is the following pragma TRAP_PROC SAVE_REGS void DelayCounter void WDGR 0xFF reload watchdog asm ld a TBSR ld a TBCLR Dummy read to clear interrupt request if Delay 0 PADR DISPLAY_OFF Switch LED off else if Second 50 The display blinks at 1 Hz with a short duty cycle PADR DISPLAY_OFF Switch LED off else PADR Sev...

Страница 272: ...ers that switch the blind motors on and off and select the direction of the motion open or close The receiver must be designed to take the following constraints into account It must be small to be easily installed where needed with an acceptable appearance and size It must be cheap These constraints preclude the use of a transformer for the power supply because it is both bulky and expensive For t...

Страница 273: ...d in an economical manner For this reason it is clocked by a 1 MHz crystal that provides an internal clock of 500 kHz Being a CMOS device the ST7 has a con sumption roughly proportional to its main clock frequency Reducing the frequency will there fore reduce the current drawn In addition the Analog to Digital converter is only powered when needed and the core is set to wait state whenever it has ...

Страница 274: ... 180 Pb2 9 1M 22pF 47pF 47pF 22K 22K 20K 47pF 47pF Pc1 16 100nF 400V 6 2V Power supply 100K 100K 100K 100K Va 220µF Pa7 18 Pa6 19 Pa5 20 Pa4 21 ST72E25 Carrier current system diagram of the receiver circuit part 1 the input signals 33pF 33pF 10M 1MHz Oscin 2 Oscout 3 Reset 1 1µF Vss 27 Vdd 28 10nF Va 100pF 2N 2222 4 7K 150 10K 100K 1M 2N2222 Va ...

Страница 275: ...or 220 µF The first diode both rectifies the current and limits the voltage when blocked to 6 2 V However two diode drops should be subtracted from that voltage which produces a net voltage of about 5 V The filter has an adjustable resistor to tune its center frequency to that of the transmitter 09 xr 2 1M 100nF 10K 10K 1M 1M Va Mot 1 All diodes 1N4148 Ph N Pc0 17 ana ST72E25 Carrier current syste...

Страница 276: ...ing an appro priate threshold the microcontroller can detect when the motor is running and when it has been stopped by one of its integral end of travel switches 9 3 3 Software 9 3 3 1 Interrupt functions The receiver works basically like the transmitter Timer A is used to produce an interrupt every half cycle of the power line 10 ms at 50 Hz and it is synchronized with the line voltage using a ph...

Страница 277: ...mpHouseCode 0 First initialize house code value case 7 case 9 case 11 case 29 case 31 case 33 TempHouseCode 1 Shift right by one bit if CarrierDetected TempHouseCode 8 Set most significant bit to one break House code has four bits case 6 case 8 case 10 case 12 Check that the next even bit sent is the complement of the odd one case 28 case 30 case 32 case 34 if TempHouseCode 8 0 CarrierDetected Cyc...

Страница 278: ...eck that the command is received twice identically if TempHouseCode2 TempHouseCode TempKeyCode2 TempKeyCode HouseCode TempHouseCode Make data received accessible to main program KeyCode TempKeyCode break default CycleNumber 1 Reset the whole process if incorrect bit number break The first thing this function does is to read the analog voltage at the output of the detector Then for each bit positio...

Страница 279: ...l Timer B is used to generate an interrupt after a predefined delay using the Compare 1 reg ister When a delay is required the WaitDelay function is called This function sets up Timer B by first setting the free running counter to FFFC then setting the Compare 1 register to the required time delay 5 to compensate from the resetting to FFFC Then all interrupt requests are cleared and the interrupt ...

Страница 280: ...sed WaitForInterrupt Keep asleep until time elapsed When the comparison occurs it triggers an interrupt that is served by the following code void CoilEndOfPulse void COILS DE_ENERGIZE TBCR1 1 OCIE Inhibit further interrupts This function masks out the interrupt requests generated by Timer B and also switches off all the relay coils Since these two functions are mainly used to produce current pulse...

Страница 281: ...e entrancy ADCCSR Channel 1 ADON while ADCCSR 1 COCO Perform one reading to stabilize ADCCSR Channel 1 ADON while ADCCSR 1 COCO Perform good reading ADCCSR 0 Turn off ADC TACR1 1 ICIE Re enable timer A interrupts return ADCDR Here is a special remark about this function It is called both from the main program and the Timer A interrupt service routine through the ReceiveOneFrameElement function Sin...

Страница 282: ...n Pulse the on off relay to the on position To stop the motor we must do the following Pulse the on off relay to the off position The function for stopping the motor is very simple void StopMotor void COILS STOP WaitDelay COIL_PULSE It energizes the appropriate coil and starts the timer as described above When the time has elapsed the current in the coil is switched off To start the motor in one d...

Страница 283: ...unction Now we can look at the main program It is made of a few lines because most of the processing is done in functions called from it This both saves the code size and improves the clarity of the code for later modification After initializing the program enters an endless loop Each time a remote command is re ceived that requests either to open or close the blind the motor is started in the app...

Страница 284: ...interrupt case CLOSE_COMMAND SwitchMotor START_CLOSE break case OPEN_COMMAND SwitchMotor START_OPEN break KeyCode NO_COMMAND Erase order HouseCode NO_COMMAND Erase order if ButtonPressed Take into account the push button It overrides the remote control switch LastDirection case START_OPEN SwitchMotor STOP_OPEN break case STOP_OPEN SwitchMotor START_CLOSE break case START_CLOSE SwitchMotor STOP_CLO...

Страница 285: ...file for assembler language The timers have been used in PWM mode with capturing and in free running mode with com parison These are only some of the ways of using the timers but these are worth knowing Actually the application could have been done in a less sophisticated way especially relating to the phase lock loop scheme but this application gives a good example of the possibilities available ...

Страница 286: ...7 peripherals are used as follows A timer is used for measuring the period of the digital signal supplied by the speedometer This a square signal with a frequency proportional to the speed The edges of the signal trigger the timer capture function The same timer is used for the wind gauge that supplies the same kind of signal as the speedometer the other capture input is used the same way as above...

Страница 287: ... 10 Second Application a Sailing Computer 10 vmg Loch Speedometer Weather vane anemometer Visible wind Real wind Visible angle Real angle VMG Boat speed Printed board circuit with ST72311 MCU Sailing computer ...

Страница 288: ...lication a Sailing Computer 10 1 THEORY OF THE COMPUTATION The following diagrams apply against the wind starboard side and before the wind port side respectively 10 again Against the wind AlphaV AlphaR Bs VMG Bs VMG Rw Vw ...

Страница 289: ...289 317 10 Second Application a Sailing Computer 10 befor Bs Rw Vw VMG AlphaR AlphaV Before the wind ...

Страница 290: ...tionships are rewritten under the following shape and Which give Symbol Meaning AlphaV Visible wind angle weather vane Vw Visible wind speed anemometer Bs Boat speed speedometer AlphaR Real wind angle Rw Real wind speed VMG Real boat speed against the wind or in before the wind MG R V Rw α 2 1 sin cos V V Vw Vw Bs Rw α α V R V Bs Rw α α α sin sin 2 1 cos 2 V Bs Vw Vw Bs Rw α V V R Rw Bs α α α sin ...

Страница 291: ...i cient accuracy would mean taking one measurement every three seconds or more This is much too slow for practical use Thus instead of measuring the frequency directly we shall measure the period of the signal This will allow us to perform at least one measurement every 1 0 75 1 33 s for the lowest speed this pace may increase at higher speeds The easiest way to perform this measurement is by usin...

Страница 292: ...Unfortunately the lowest clock frequency that can be applied to the input of the timer is the CPU clock divided by 8 that is 500 kHz using a 8 MHz crystal The solution consists in expanding the range of the timer to more bits by software using the interrupt on overflow At that frequency the timer would overflow less than eight times per second so the interrupt service routine would not overload th...

Страница 293: ...ctronic means when tuning the system The first problem can be solved by providing a numeric type low pass filtering of the voltage read In any case the various movements of the boat will add a rather high amount of noise to the reading that must be filtered out This filtering involves computing the mean of a certain number of readings The effect of doing so is twofold it reduces the variation spee...

Страница 294: ...a half liquid crystal display A pair of LEDs indicates the value currently being displayed in each LCD display Toggling be tween the values is done by pressing a push button next to the corresponding display 1st option 2nd option 1st display Visible wind Real wind 2nd display Visible angle Real angle 3rd display Boat Speed V M G ...

Страница 295: ... 99v 0x65 1 24v 0x3f 5v 390 5v 390 5v 390 Pa4 Pa5 Pa6 drain Sailing computer principle of the digital display board Wind speed Wind angle Boat speed Visible green Real red Visible green Real red VMG red Boat speed green 1st display Visible Real Wind speed 2nd display Visible Real Wind angle 3rd display Boat Speed VMG First display Pd2 Pd3 Pd4 5v 3x10K Wind speed calibration Boat speed calibration ...

Страница 296: ...ritten to and the data is output at the MOSI pin if the SPI is set to Master mode This way the whole display is re freshed by sending only one byte for each digit of the display that is twelve bytes altogether The clock frequency may be chosen from 1 2 to 1 64 of the core clock Here we shall use the fastest clock that means that sending eight bits will take 16 core cycles Each of the right hand th...

Страница 297: ...of the first shift register 0 0xF6 0 0xFE 1 0x90 1 0x98 2 0x75 2 0x7D 3 0xF1 3 0xF9 4 0x93 4 0x9B 5 0xE3 5 0xEB 6 0xE7 6 0xEF 7 0xB0 7 0xB8 8 0xF7 8 0xFF 9 0xF3 9 0xFB 7 segment codes for all digits Bp X Z Y K L Bp Bp g3 f3 e3 dp3 b3 a3 d3 c3 g2 f2 e2 dp2 b2 a2 d2 c2 g1 f1 e1 dp1 b1 a1 d1 c1 X Z Y K 1 L d0 d7 ...

Страница 298: ...r and severely degrade the component To avoid this the voltage polarity must be reversed periodically This does not alter the clarity of the display provided the frequency of the reversing is high enough In practice a frequency of 50 Hz is sufficient that is 100 reversals per second Since the backplane is connected to one output of the shift register reversing the polarity merely involves the one ...

Страница 299: ...dication of whether the reading is absolute or relative The red LED of the pair is lit when the open drain output that drives it is on When off the green LED is lit as it is in parallel with the red one but with a diode in series that provides an additional threshold voltage To provide enough current the high current open drain outputs PA4 to PA6 are used 10 4 INTERFACING THE OPTIONAL PERSONAL COM...

Страница 300: ...ind and boat speeds are both input as a square wave with a variable frequency that is proportional to the speed The frequencies are too low to be able to measure them by counting the periods in a sufficiently short time This is why in this application the speeds will be calculated from the inverse of the period duration Actually this conversion will be done in the calculation block for an interrup...

Страница 301: ...flow interrupt yes asm ld a TBCLR clear interrupt request Capture1 W High Increment high order word Capture2 W High on both channels All timer events trigger the same interrupt request At the beginning of the function the TBSR status register is tested for one of the following three events Capture 1 event Capture 2 event Timer overflow event Once the origin of the interrupt has been determined the...

Страница 302: ...has a spe cial mechanism that locks off the capture mechanism when the high order byte has been read until the low order byte is read Since the compiler does not guarantee the order of handling of the two bytes of a word it is necessary to do it in assembler 10 5 2 Refreshing of the display The display must be refreshed periodically with a bit pattern that changes from true to comple ment and back...

Страница 303: ...eDisplay char s signed char i for i 3 i 0 i Right 3 digits while SPISR 1 SPIF 0 Wait for end of transmission SPIDR SevenSegmentCode s i Polarity Send current byte with proper polarity while SPISR 1 SPIF 0 Wait for end of transmission SPIDR s 0 Polarity Send leftmost digit with proper polarity The pattern is sent to the display device after performing an exclusive or with the variable Polarity that...

Страница 304: ...bal variable ButtonState that is zero when no button is pressed otherwise 1 2 or 3 depending on the button pressed This variable is used by the main pro gram which puts it back to zero The debouncing mechanism is such that to produce the same value again or another value the user must first release the button then press it again or press another There is no auto repeat function unlike on a compute...

Страница 305: ...ulo 256 is needed To increase the resolution it is necessary to take the mean of a certain number of successive readings This also has the advantage of filtering the signal thus damping the oscillations that the weather vane undergoes because of the pitch and roll This is performed by building an array of the successive values of the direction and shifting these values each time a new value is rea...

Страница 306: ...it has reached the last element A new average is computed each time by summing the values of all elements and dividing the sum by the number of el ements Actually since we need to increase the resolution from eight to nine bits we divide the sum by only half the number of elements Since the ST7 has no division instruction and the division takes a long time the solution used here is to have a numbe...

Страница 307: ...lue is converted to a string and sent to the display Since the raw values are produced by an interrupt service routine it is important to read them atomically A function provides for this by disabling the interrupts for the time the value is read Word Atomic Word p Word Result DisableInterrupts Result p EnableInterrupts return Result A similar function is also available for long values Since they ...

Страница 308: ...icient way to do it One might question why the standard C function sprintf is not used here There are two rea sons the first one is that this function requires a large amount of code that would not fit the available ROM The other reason is that this function yields an ASCII string which is not what our display needs anyway void NumberToString int Value char S Byte i div_t Step Step quot abs Value ...

Страница 309: ...ys the case when nothing is being sent Thus the transmit interrupt is always masked out except when there is something to send The bit rate is supplied by the normal rate generator applying only a division by 13 which after the wired divider by 32 gives a bit rate of 9600 from a 4 MHz internal clock The pins corre sponding to the input and output of the SCI are configured as floating inputs The in...

Страница 310: ... This triggers interrupt servicing immediately since the request is already pending and the first character is sent immediately This way of handling the SCI is both fast and memory efficient the interrupt service routine just copies a character from one address to another It is the main program that calculates the string to be sent as the response to the request received and this can be done when ...

Страница 311: ...LIB_CHANNEL while ADCSR 1 COCO 0 Wait for end of conversion WindFactor float ADCDR 128 0 640 0 1 NOMINAL_WIND_FACTOR ADCSR 1 ADON BOAT_CALIB_CHANNEL while ADCSR 1 COCO 0 Wait for end of conversion BoatFactor float ADCDR 128 0 640 0 1 NOMINAL_BOAT_FACTOR ADCSR 1 ADON VANE_CALIB_CHANNEL while ADCSR 1 COCO 0 Wait for end of conversion VaneAdjust signed char ADCDR 128 0 4 The first two parameters vary...

Страница 312: ...56 byte area some of it may be allocated for variables The arrangement used here is to put the DEFAULT_RAM section from 0x100 to 0x18F overstepping the stack area a little bit The _OVERLAP section is set at 0x200 The _ZEROPAGE section can only be set below 0x100 This is fully detailed in the link parameter file below SECTIONS APORTS READ_WRITE 0x00 TO 0x17 AMISC READ_WRITE 0x20 TO 0x20 ASPI READ_W...

Страница 313: ...are as follows COMPOPTIONS Or Cni Cc Mlx The Cc option indicates that the constant data the table of 7 segment patterns is to be placed only in ROM The linker must also be aware of these choices by specifying the linking of the ANSIX LIB li brary and the START07X O startup file along with the project files instead of ANSI LIB and START07 O Note The README TXT file in the main HICROSS directory sum...

Страница 314: ...ed by means of a proper balance between the in terrupts and the main program The interrupt service functions have been designed so that they had as little computation as possible to perform just moving data between memory and peripherals The main program then retrieves the data from memory processes it and puts the results in yet another memory storage so that it can be displayed or sent through t...

Страница 315: ...may not be us able where the controller must be woken up quickly Also the only way of waking it is through a reset which is not ideal when the context must be kept from one run to the next However this mode is the most efficient since it divides the power consumption by about 1000 Wait mode only puts the core to sleep The peripherals are still alive and can still handle timing tasks receive charac...

Страница 316: ...uage and an EPROM programmer It allows to you familiarize yourself with the component for ex ample to check whether it is suitable for the application you have in mind The Development Kit is a good value package that also provides assembly language tools and a cheap but powerful emulating board The only missing feature is real time tracing but it is sufficient for simple applications This tool rea...

Страница 317: ...ut notice This publication supersedes and replaces all information previously supplied STMicroelectronics products are not authorized for use as critical components in life support devices or systems without the express written approval of STMicroelectronics The ST logo is a registered trademark of STMicroelectronics 1999 STMicroelectronics All Rights Reserved Printed in France by Imprimerie AGL P...

Отзывы: