Page 1
8-BIT MCU FAMILY USER GUIDE JANUARY 1999...
Page 2
USE IN LIFE SUPPORT DEVICES OR SYSTEMS MUST BE EXPRESSLY AUTHORIZED. STMicroelectronics PRODUCTS ARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN LIFE SUPPORT DEVICES OR SYSTEMS WITHOUT THE EXPRESS WRITTEN APPROVAL OF STMicroelectronics. As used herein: 1. Life support devices or systems are those 2.
1 INTRODUCTION 1.1 WHO IS THIS BOOK WRITTEN FOR? This book is a technical guide for ST7 users and may be approached in different ways: For students and anyone unfamiliar with microprocessors, but with some experience of logic circuits; they should start by reading Chapters 1 through 3.
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.
Page 14
1 - Introduction The following table shows a comparison of these solutions. Each one is discussed below. Solution type Advantages Drawbacks Very high speed Wired logic Only for simple circuits Cheap Limited number processing High speed Programming languages are specific Programmable logic and non-portable Able to handle complex digital signals...
1 - Introduction achieve the required computational power. These external chips may simply be interface com- ponents, to adapt the electric signals to the input-output pins of the microcontroller, or addi- tional memory or peripheral components if the buses are available externally on the pins of the microcontroller.
Page 16
1 - Introduction Array of Current resistors generator Analog input Micro controller Push pull Analog display output with PWM signal Analog keyboard Example of simplified circuitry thanks to a microcontroller 01-anal Such peripherals are typically available in many families. This example shows how two periph- erals properly selected can drastically reduce the component count and thus the printed circuit area.
1 - Introduction 1.4.2 Choice of microcontroller model The selected model of microcontroller must meet the requirements in terms of computational power. It must be able to handle the input-outputs, process the data in the required amount of time, and have enough memory to store both the program and the data. An application is made of both hardware and software.
Page 18
1 - Introduction memory of the application. The tools are able to test both the hardware and the software, and analyze any malfunctioning in order to allow corrections to be made. This can be done using only a Personal Computer, or external instruments connected to the computer, such as an emulator, analyzer, PROM programmer, etc.
2 - How does a typical microcontroller work? 2 HOW DOES A TYPICAL MICROCONTROLLER WORK? There is a wide range of microcontrollers available on the market. They differ in their compu- tational power, their internal organization, the number of their inputs and outputs, the type of peripherals they provide.
2 - How does a typical microcontroller work? 2.1 THE CENTRAL PROCESSING UNIT What is the Central Processing Unit (CPU)? It is made up of the core, and auxiliary blocks like the clock generator, the reset circuitry, etc. The CPU of a microcontroller is the actual programmed logic circuitry that is the heart of the application based around the microcontroller.
2 - How does a typical microcontroller work? Table 1. Table of the main processor sizes Relative Data size Common applications power 4 bits Lowest Watches, calculators, TV remote control, washing machines. 8 bits Industrial products and home computers in the '80s; most microcontrollers today where little numeric computation is required.
Page 22
The first one, named «Von Neumann» after the name of its inventor, provides only one ad- dressable space. The program and the data are only distinguished by the address they oc- cupy in this space. The ST7 belongs to this category: 0000h...
2 - How does a typical microcontroller work? The second one, named «Harvard», provides separate addressing spaces for the program and data. No instruction can thus write anything into the program space, protecting the pro- gram from accidental changes and doubling the total addressing range. Examples of this ar- chitecture are the ST6, the ST9, and the 8051: 000h Data...
2 - How does a typical microcontroller work? 2.2.4 Interrupt Controller This is a piece of logic circuitry that manages the implementation of the interrupt concept de- scribed later in this chapter. Interrupts are the most common means of altering the normal course of the program, when an unexpected event (or an expected one but occurring at an un- expected time) occurs.
2 - How does a typical microcontroller work? Features provided may include queueing of interrupt requests, handling requests according to their priorities, or even modification of priorities to increase the chance that low-priority re- quests will be eventually processed in a context where there are numerous requests. 2.2.5 Bus The bus is the set of connections that links all the components of the system and allows all the data moves, and the distribution of the address and control signals.
2 - How does a typical microcontroller work? The ALU is connected to a register that holds the state of the last calculation done, with bits in- dicating (among other things) whether the result was zero, negative, or overflowed the ca- pacity of the ALU.
(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 of the ST7, starting with the simplest. 2.4.1 Parallel Input-Outputs...
2 - How does a typical microcontroller work? push-pull or open drain. Some outputs also allow for a higher current to directly drive relays, LEDs or opto-isolators. In addition, these pins can also be used at the same time as the input-output pins of other pe- ripherals like Timers, Serial to Parallel Interfaces, or as inputs to the interrupt circuitry or an Analog to Digital Converter.
2 - How does a typical microcontroller work? quences in applications where the microcontroller must keep in control, like in automotive ap- plications or in security systems. Various solutions have been imagined to prevent such situations. The most popular is the watchdog timer.
Page 30
2 - How does a typical microcontroller work? The effect of the interrupt is shown in the following diagram: An interrupt is requested and authorized The current instruction is executed, the PC is incremented The PC and a small number of registers are saved, they are automatically pushed onto the stack.
ST7. An interrupt request is a binary signal (a flag) generated by several external sources. Most pe- ripherals of the ST7 can produce interrupt requests, for example the I/O ports, the timers, the SPI, the I C interface, and so on.
ST7, the Program Counter, the X-register, the Accumulator and the Condition Code Register. It should be noted that the Y register is not saved, (this is because the ST7 has evolved from an architecture that did not have a Y register). If needed, the Y register should be pushed explicitly on the stack at the beginning of the interrupt service routine.
Page 33
2 - How does a typical microcontroller work? Depending on the source of the interrupt (I/O, timer, etc.), the core fetches, from a predefined location in memory, the address of the interrupt service routine especially written to process that event. The vectors are always located at the end of the addressing space. 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.
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 pushed, namely the Condition Code register (at this point the I bit is also restored), the Accu- mulator, the X register and the Program Counter.
2 - How does a typical microcontroller work? Thus it is up to the programmer to save it, by pushing it to the stack at the beginning of the service routine, and popping it before executing the IRET statement. 2.5.2.2 Managing the stack This is just a reminder, since it applies anywhere in the program.
2 - How does a typical microcontroller work? 2.5.2.5 Data desynchronization and atomicity This paragraph addresses the precautions that must be taken, in the main program or any service routine that may be interrupted. In many cases, data is organized in blocks in memory, that is, several bytes, successive or not, make up a piece of data.
Page 37
2 - How does a typical microcontroller work? The following example shows: What happens when the data are desynchronized. Let us assume the main program wants to increment the word variable (16-bit register in page zero), that currently contains hex. The following code will be used: 42FF ;...
2 - How does a typical microcontroller work? reading the first bytes of the data, then the interrupt occurs; on return, the remainder of the data are read, but unfortunately there may not be coherence between the first byte that was read before the interrupt and those read after it.
2 - How does a typical microcontroller work? 2.6 AN APPLICATION USING INTERRUPTS: A MULTITASKING KERNEL The conclusion in the previous paragraph states that interrupts are well-suited for a certain class of events to be processed. However, there are other cases outside this category. Some of them are better addressed by the concept of multitasking.
Page 40
2 - How does a typical microcontroller work? process of updating the data, and another task uses that data, there is a risk of desynchroni- zation. The same type of precautions must be taken to ensure atomicity of data updates. The same problem may also occur if more than one task handles control sequences for an external device.
2 - How does a typical microcontroller work? 2.6.2 Cooperative multitasking Cooperative multitasking draws its name from the fact that task switching is not spontaneous. It only occurs when the task-switching function is called by the currently active task. This im- plies two facts: Task switching occurs only when the code decides it.
2 - How does a typical microcontroller work? 2.6.3 Multitasking kernels 2.6.3.1 Advantages of programming with a multitasking kernel The multitasking kernel is the piece of code that controls the multitasking. The way it does it, and the flexibility it offers may vary greatly from one kernel to the other. It is generally supplied ready made, and the programmer has to give his program the appropriate architecture to get the benefits of it.
The ST7, being a small 8-bit core, provides for at most 256 bytes of stack. This allows for a multitasking kernel with a limited number of tasks and services.
Page 44
2 - How does a typical microcontroller work? Common parts of the program Stack pointer Code of the first task Stack area for task #1 Stack area Code of the for task #2 second task Stack area for the last task Code of the last task Stack RAM...
3 - Programming a microcontroller 3 PROGRAMMING A MICROCONTROLLER A microcontroller is basically a programmable component. This means that it can do almost anything, when properly programmed. In fact, the design of the electrical schematic of a microcontroller-based application raises few questions;...
When the program is fully functional, it is often stored in an EPROM that is either external, or as in the ST7, internal to the microcontroller. This produces a prototype of the microcontroller that must be extensively tested before being launched to production, especially if, for large...
3 - Programming a microcontroller quantity production, the microcontroller includes a masked ROM programmed by the device manufacturer and that cannot be altered afterwards. 3.1.2.1 Assembly language Assembly language is merely a set of mnemonics that duplicates each instruction in a more legible way, to help writing the programs.
The error messages tell where the error is located, and, as much as possible, the cause of the error, as in the following example: TRIAL.ASM(6): ERROR: not a ST7 instruction or directive 48/317...
3 - Programming a microcontroller Here again, the format of all the above mentioned files is chosen by the assembler's manufac- turer, and differs from one to another. File.obj Relocatable object file Assembler File.asm File.lst Source file Listing file Assembler invocation 03-asm 3.1.2.3 Linker If the whole application program is small, it is easy to put the source text into a single file.
Page 50
3 - Programming a microcontroller The tool that glues together all the object files, each the result of assembling the source files, is called the Linker. The linker performs the following tasks: It takes all the object files, and merges them into a single object file by concatenating them one after the other.
3 - Programming a microcontroller File.cod File1.obj File.abs Absolute object file Linker File2.obj File.sym Symbol table File3.obj File.map Relocatable object files Map file Linker invocation 03-link 3.1.2.4 The project builder/make utility In the process introduced above, that relies on splitting-up the processing to save time, it is im- portant to keep track of which sources have been altered, only re-assemble these and not the others and then link all the object files.
3 - Programming a microcontroller Each time a file has a successor with a date older than its predecessor, the corresponding tool is run to update the successor. This is done in an orderly fashion, from the top of the hierarchy (the source files) to the bottom (the absolute object file).
3 - Programming a microcontroller Eprom Executable file File.cod File.s19 programmer formatter File.abs Absolute object file Memory content image file microcontroller with built-in EPROM Programming a microcontroller 03-prom 3.1.2.6 Simulators A simulator is a tool that pretends to run an absolute executable program. Like the other tools, it runs on the programmer's own PC.
3 - Programming a microcontroller the correct values, so as to avoid having to edit and make the program each time an error is found. In fact, simulation is limited to pieces of code that do not access the input-outputs, since this would require a complex program at simulator level to also simulate the behaviour of the ex- ternal world that the application is supposed to interact with.
3 - Programming a microcontroller this type of situation, its a difficult task for the programmer to complete the debugging of the application so that it can be validated. 3.2 C LANGUAGE 3.2.1 Why use C? Many high-level language exist; some have been written specifically for a family of microcon- trollers, while others are widely-used languages from the computer world that have been adapted to suit the needs of microcontrollers.
Page 56
The first drawback is that C was originally designed for mainframe computers. In these ma- chines, there is only one memory space, that contains both code and data. In the ST7, there is also a single memory space that contains code, data and input-outputs, but the code re- sides in ROM and data in RAM.
3 - Programming a microcontroller ability of programs to another machine. You will have to take account of this, especially when testing the code on your PC first as suggested above. This can in most cases solved by a dec- laration file that is included in the project and that exists in two versions, or uses conditional compilation, to fill the gap between two different dialects of C.
3 - Programming a microcontroller File.obj File.c compiler C source file Relocatable object file (on some File.asm compilers) Assembler source file C compiler invocation 03-comp 3.2.3 Debugging in C Debugging in C is done the same way as explained for assembly language. However, the sim- ulator and debugger screens designed for high-level languages can also show the progress of the execution directly in the C-language source text, while another window shows the corre- sponding assembly language statements.
Page 59
3 - Programming a microcontroller easy interrupt declaration and servicing in both assember and C language; efficient optimization that may be switched off at 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.
3 - Programming a microcontroller 3.3 DEVELOPMENT CHAIN SUMMARY The development chain discussed above can be understood more clearly using a diagram. The diagram below shows the various files involved in the development process as cylinders; the translators used to change one file type into another are shown as rectangles. Relocatable C source files object files...
An application builder for the ST6 and the ST7, the STRealizer, 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.
KB Flash EPROM, 10+ KB RAM, ADC, 16-bit timer, USART, and more. As the table shows, the ST7 is positioned towards the low-end. It provides an economical trade-off between speed and price and is suitable where moderate computational power is needed together with a low-consumption device, like in TV remote control transmitters.
4 - Architecture of the ST7 core 4.2 ST7 CORE The ST7 core uses an extended version of an industry-standard instruction set. This set is both exhaustive (almost all instructions are available, with the exception of division) and fairly orthogonal (the instructions allow for most addressing modes). This makes the instruction set of the ST7 both clear and easy to use when programming in assembler.
Page 64
4 - Architecture of the ST7 core CPU Control Core Accumulator Arithmetic Reset and logic Y index register unit CPU Clock X index register Stack pointer Interrupt requests from Program counter peripherals Condition code register Page 0 ( 8 lines wide)
Ease of programming, due to simplification resulting from the first two advantages As a typical 8-bit processor, the address bus of the ST7 is 16 bits wide, and thus able to ad- dress 65,536 bytes. This is enough for most applications within the range of the ST7.
Page 66
4 - Architecture of the ST7 core Condition code register 04-ccreg The leftmost three bits, indicated as ones, are not used. When read, they yield ones. C bit bit is the carry that is generated by an addition or subtraction. When adding 16-bit num- bers, for example, we first add the two least-significant bytes together, then the most signifi- cant ones.
4 - Architecture of the ST7 core H bit This bit is a similar to the bit, since it is set when a carry occurs. This time, it is the carry be- tween the two nibbles of a byte. A byte is composed of two four-bit groups called nibbles. The bit is set whenever an arithmetic instruction produces a carry between bit 3 and bit 4 of the accumulator.
4 - Architecture of the ST7 core two addresses as is needed in a memory-to-memory data move, with or without alteration in between. However, these registers may also be used to store temporary data. 4.2.2.4 Program Counter (PC) The program counter is the register that controls the sequencing of the instructions. The pro- gram is written as a series of instructions, and these instructions are stored in consecutive cells of the program memory.
Page 69
4 - Architecture of the ST7 core 0140h Top of the stack 64 bytes of RAM (Reset value) 017Fh Bottom of the stack Stack organization of the ST72251 04-stack When a value is stored using the stack pointer, the stack is decremented, so that the next value stored will be placed at the address just below the previous one.
The stack pointer must be initialized at the start of the execution. The instruction resets it to its bottom value, that differs from one variant of the ST7 to another depending on the number of registers provided at the beginning of page zero.
Page 71
0FAh In the Motorola and and few other conventions, any hexadecimal number must start with a special character, like $ for Motorola; no ambiguity is possible then. The ST7 tools use this convention by default. All other categories except comments are made of single words that begin with a letter. For example, is a legal name for a label.
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 computed when the program executes, and it is this address that indicates which byte must be read.
C language, since these programs frequently use complex data structures. 4.3.3 Instruction set The instruction set of the ST7 includes many instructions. They can be sorted in different ways. Here is a grouping by number of addressing modes 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.
256 combinations of an operation 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.
4 - Architecture of the ST7 core 4.3.4.2 Opcode byte The opcode uses a bit-level coding to specify the type of operation to perform (add, subtract, jump, etc.) and the addressing mode used (direct, indexed, indirect, etc.) in a single byte.
Page 76
4 - Architecture of the ST7 core Low digit High digit BTJT BTJF BTJT BTJF BTJT BTJF BTJT BTJF BSET BRES BSET BRES BSET BRES BSET BRES JRNH JRPL JRMI JRNM JRIL JRIH short SWAP SWAP SWAP short, X SWAP...
4 - Architecture of the ST7 core 4.3.4.3 The addressing modes in detail Immediate mode When a register has to be loaded with a constant value that has been fixed in the program source, that value is determined in the program source text and must be stored in the program memory to make it fixed and permanent.
Page 78
4 - Architecture of the ST7 core in memory below address . The assembler automatically takes care of this, by selecting 100h the appropriate addressing mode when possible. Example: the instruction LD A, 1234h A is loaded with the value stored in an absolute extended memory address.
Page 79
These short-range jumps are usually called branches to contrast with the jump instruction that uses long addressing mode and that can jump anywhere in the addressing space. In the ST7, they are called relative jumps.
Page 80
4 - Architecture of the ST7 core Example: At address 1200h, the following instruction: JRA 11F1h The absolute address supplied in the source code will be translated into a relative displacement by the assembler. is coded as: 20 EF The two bytes of the instruction occupy addresses .
Page 81
4 - Architecture of the ST7 core where are labels respectively designating the destination of the jump, and the THERE HERE address of the instruction that follows the jump instruction. Here again, if the difference yields a number that exceeds the range of a one-byte value, the assembler generates an error mes- sage.
This instruction takes three bytes of memory. 4.4 ADVANTAGES OF THE ST7 INSTRUCTION SET AND ADDRESSING MODES In many programming applications, data may have complex forms. To ease data handling, high-level languages have been created that simplify coding by allowing expressions like:...
Page 83
4 - Architecture of the ST7 core A[I] = B[J] + C[K] Where are arrays of numbers, and the indexes to these arrays. The high- level language compiler translates this so as to read the element of array using the avail- able machine-language instruction.
5 PERIPHERALS 5.1 CLOCK GENERATOR The core of the ST7 is supplied with an internal clock that comes from the division of the os- cillator frequency. This division rate is programmable, allowing you to select the best compro- mise between speed and power consumption.
5 - Peripherals 5.1.2 ST72311 Miscellaneous Register The SMS bit works the same way as in the ST72251 (see previous paragraph), but in addition, the two bits PSM1 and PSM0 (prescaler for slow mode) select the supplementary division 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).
Interrupt requests may be generated by several external or internal sources. Most peripherals of the ST7 can produce interrupt requests, such as the I/O ports, the timers or the SPI. The In- terrupt request depends on the type of the peripheral: the I/O ports may have some bits con- figured to generate an interrupt, either on low-level, falling edge, rising edge, or both.
5 - Peripherals 5.2.1.2 Interrupt sources for the ST72311 Source Block Description Register Vector address Priority order Reset Reset FFFEh-FFFFh Highest Trap Software FFFCh-FFFDh Not used FFFAh-FFFBh Not used FFF8h-FFF9h PA0-PA3 FFF6h-FFF7h PF0-PF2 FFF4h-FFF5h PB0-PB3 FFF2h-FFF3h PB4-PB7 FFF0h-FFF1h Not used FFEEh-FFEFh Transfer complete SPISR...
5 - Peripherals As shown in the rightmost column of these tables, these sources are prioritized. This means that if several interrupt requests are active at the same time, the interrupt controller will choose to service the highest priority request. When this interrupt is fully serviced, the next highest pri- ority request will be serviced.
- CC, A, X, PC to be popped from stack. - The interrupted program to resume or another interrupt program to start. The interrupt mechanism of the ST7 family 05-int 5.2.3 Global interrupt enable bit RESET and TRAP (explained in the next paragraph) are non-miscible interrupt; the other...
Accumulator and the Condition Code Register. It should be noted that the Y register is not saved, for compatibility with the standard instruction set which the ST7 adheres to. If needed, the Y register may be pushed explicitly to the stack at the beginning of the interrupt service routine.
5 - Peripherals The interrupt service routine is supposed to take the appropriate actions that will vary ac- cording to the interrupt source. For example, if an Input bit has changed its state, the service routine may change the state of an output bit; if the interrupt was generated by the timer, this may produce the transmission of a byte by the SPI, etc.
Page 93
5 - Peripherals bled during the service of an interrupt. In this case, all interrupts are validated and the service routine may be itself interrupted by a request having a lower priority than its own. If the service routine must be interruptible only by certain requests and not others, the routine must first clear the interrupt enable flags of all peripherals that are not allowed at that time, then clear the global interrupt mask.
I/O ports (alternate function). The ST7 offers a very flexible feature on its parallel I/O that it shares with many other STMi- croelectronics families: each bit can be independently configured as either an input with two options (with or without pull-up resistor), or an output with also two options (open-drain or push-pull).
Page 95
5 - Peripherals Table 3. ST72251 I/O configuration Input configuration Output configuration ( DDR = 0) ( DDR = 1) External interrupt source, OR = 0 OR = 1 OR = 0 OR = 1 Polarity option bits Port Port A: Floating with True open Floating...
5 - Peripherals EI1: Ports B & C EI0: Port A vector address: vector address: FFF8-FFF 9 FFFA-FFFB PEI3 PEI2 PEI1 PEI0 ST72251 Falling edge and low level (reset state) Falling edge only Rising edge only Rising and falling edge External interrupt polarity Options EI0 and EI1 of the Miscellaneous register 05-EI251...
Page 97
5 - Peripherals Table 5. ST72311N I/O configuration Input configuration Output configuration ( DDR = 0) ( DDR = 1) Port External interrupt OR = 0 OR = 1 source, OR = 0 OR = 1 Polarity option bits Floating Pull-up with Open drain Push-pull...
Page 98
5 - Peripherals Table 6. ST72311N I/O alternate functions I/O pin Alternate function 1 OCMP2_B (Timer B) OCMP1_B (Timer B) ICAP2_B (Timer B) ICAP1_B (Timer B) MISO (SPI) MOSI (SPI) (SPI) (SPI) Ain0 (ADC) Ain1 (ADC) Ain2 (ADC) Ain3 (ADC) Ain4 (ADC) Ain5...
5.4.2 Watchdog Description The ST7 watchdog timer is controlled by a register that includes two control bits (bits 7 and 6) and six time-setting bits. The general control bit, bit 7, starts the watchdog activity if it is set to one. From that time on, it continues to work, even if one tries to reset it to zero.
Page 101
ST72251 Watchdog timer operating description 05-wdg1 In some ST7 family products, for example the ST72311, two options are available for the Watchdog: software-activated, as above, and hardware-activated, where the Watchdog is al- ways active, regardless of the state of the MSB of the WDGCR register. This option is selected differently in the ROM version and the EPROM version.
Page 102
5 - Peripherals Software-activated: Activation bit is Reset Watchdog status register cleared by hardware WDOGF after a reset, can be set once Flag bit set by a watchdog reset by software. Can only be cleared cleared by software or power-on reset by another reset Hardware-activated: Watchdog control register...
5 - Peripherals This bit is set whenever the last reset was triggered by the Watchdog. This allows the program to check whether the current start is a fresh one, or results from the recovering from an error condition. 5.4.3 Using the Watchdog to protect an application The right value for the watchdog time-out is always difficult to find, except when the rewinding is performed in the service routine of a timer interrupt, that occurs at a fixed frequency.
2 (normal mode) or a higher value that depends on the variant of ST7 considered (slow mode), as selected in the miscel- laneous register (see the beginning of this chapter).
5 - Peripherals 5.5.2 Free running counter The main component of the 16-bit timer is the Free-Running counter, called the CHR (Most Significant Byte) and CLR (Least Significant Byte) register. This is a binary counter that incre- ments by one at each clock cycle, hence its name. It is possible to read the value of this timer, but it is only possible to reset it to its start value that is FFFCh, either under program control or automatically depending on the working mode selected.
5 - Peripherals If the low byte is read again, the actual value of the low byte of the counter can be read. To benefit from the latching feature, it is necessary to read the high byte first. Conversely, reading the high byte one more time will always yield the same value as before: a read of the high byte must be followed by a read or the low byte.
5 - Peripherals 5.5.2.3 The TOF flag The Timer OverFlow flag is a bit in the Timer Status Register. It is set each time the free-run- ning counter overflows from FFFF to 0000. It can be cleared under program control by the following sequence: A read to the TSR register, followed by A read or write to the CLR register.
5 - Peripherals TOIE : Timer overflow enable bit (bit 7 of TCR1) TOF : Timer overflow bit (bit 5 of TSR) : Global interrupt enable bit (bit 3 of CCR) FFFFh - 0000h (counter) TOIE Timer control register 1 (TCR1) Timer overflow Timer status register (TSR) interrupt to the core...
Page 109
5 - Peripherals The clearing of ICFi is done by a sequence similar to that described for the TOF bit: Read the TSR register, and Either read or write the ICiLR register. Only the ICIE flag is common to both channels. Thus, if both channels are used simultane- ously, on interrupt, the TSR register must be read to determine whether the ICF1 or the ICF2 bit is set (or both).
5 - Peripherals ICF1 : Input capture flag 1 bit (bit 7 of TASR) ICIE : Input capture interrupt enable bit (bit 7 of TACR1) (common bit to both channels of the timer) IEDG1 : Input edge 1 bit (bit 1 of TACR1) I : Global interrupt enable bit (bit 3 of CCR) 16 bit input capture register...
Page 111
5 - Peripherals The change of the state of an output pin; The reset of the free-running counter (only in PWM mode). The PWM mode will be studied later. The block diagram of one of the compare circuits is the following: OCF1 : Output compare flag 1 bit (bit 6 of TAS R) OCIE : Output compare interrupt enable bit...
Page 112
5 - Peripherals There are two such compare circuits for each free-running timer; the table below summarizes the register, bit, and pin names for both timers A and B and for compare 1 and compare 2 cir- cuits of each. Timer A: Channel 1 Channel 2...
5 - Peripherals The TAOC1HR-TAOC1LR pair is a 16 bit register whose value is continuously compared to the free-running counter. If the compare function is not used, it can be used for general purpose storage. When the match occurs, the OCF1 flag is set in the TASR register. This bit can only be reset by the following sequence: a read of TASR, then an access (read or write) to TAOC1LR.
Page 114
5 - Peripherals loaded with the duration Input of the pulse capture 1 16 bit output compare register Free running counter TAOC1HR, TAOC1LR Configuration of the Compare input capture pin FFFCh (see the input capture mode diagram) Timer A control register 1 (TACR1) ICIE OCIE...
5 - Peripherals The input capture event, corresponding to the leading edge, sets the ICF1 bit of TASR. This can trigger an interrupt if the ICIE mask bit is set. It must then be reset by software as explained above. The output compare 2 event, corresponding to the trailing edge, sets the OCF2 bit of TASR.
Page 116
5 - Peripherals loaded with the duration loaded with the duration of the pulse of the period 16 bit output compare register 16 bit output compare register Free running counter TAOC2HR, TAOC2LR TAOC1HR, TAOC1LR FFFCh Compare Compare Timer A control register 2 (TACR2) Timer A control...
5 - Peripherals Set the TAOC2HR-TAOC2LR register pair to the number of ticks corresponding to the duration of the whole cycle (this number depends on the clock frequency), minus 4. Set the OLVL2 bit in the TACR1 register to the state required for the output pin for the duration of the pulse, and OLVL1 in TACR1 to the complement of this state to terminate the pulse.
The ADC of the ST7 is a ratiometric converter, that is, it returns a binary number that ex- presses the ratio between the input voltage and the supply voltage. A input of zero volt (or lower) provides a binary result of zero;...
5 - Peripherals The COCO bit is reset when the ADCCSR register is written. ADON COCO ADC Control / Status register (ADCCSR) COCO : Conversion Complete ADON: A/D converter On CH2-CH0: Channel selection AIN0 Analog Sample hold ADC Data register (ADCDR) AINn AD6 AD5 AD4 AD3 AD2 AD1 ADC block diagram...
Generally speaking, implementing a numeric servo loop requires very high resolution and lin- earity, combined with a short conversion time. This means an expensive converter, 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 - Peripherals The second method uses an absolute rectifier circuit that produces a voltage that is the abso- lute value of the input voltage. This circuit also provides a bit that indicates the sign of the input voltage. Thus the conversion of the whole range is increased by one extra bit that doubles the resolution.
Page 122
5 - Peripherals Let us now add to that voltage V0, a small voltage, that is equal to half the smallest step, that Vdda ----------------- - × If the voltage V0 is included within × Vdda Adc0 -- - ...
Page 123
5 - Peripherals Vdda ----------------- - × This will yield two results, Adc0 and Adc1. If we take the sum of these values, whatever the value of V, it will range from 0 + 0 = 0 to 255 + 255 = 510. This new result now has a resolution of 511 points, which is almost double the original resolution.
5 - Peripherals Actually, this method is not very convenient, because the typical error of the converter is 0.3 LSB which is too high compared to the small voltage that we intend to use as an extra step. Also, the noise would make this increased resolution meaningless. A practical way of increasing the converter resolution is to use the method of low-pass filtering of noisy signals.
5 - Peripherals 5.7 SERIAL PERIPHERAL INTERFACE The Serial Peripheral Interface is a device that allows synchronous, bit serial communication between a microcontroller and a peripheral such as a serial-access memory, a Liquid Crystal Display module, etc.; or between two or more microcontrollers. This interface only requires three lines, thus saving pins for other purposes.
Page 126
5 - Peripherals When one master controls two or more slaves, a method must be used to distinguish between the two slaves. Several methods are available. The one shown below uses the SS pin of each slave to control which slave is active at any given time. These pins are each driven by a sep- arate output pin of the master controller: MSTR=0 MSTR=1...
Page 127
5 - Peripherals An example of the use of the SPI to send data to a LCD display module is given in the second application, Chapter 10. The configuration used is shown in the figure below with the appro- priate values in the registers. Parallel data out Serial Serial...
5 - Peripherals The CPOL and CPHA bits in the control register allow you to select which clock edge is used externally as the active one (leading or trailing) and its polarity (low or high level after trans- mission). 5.8 SERIAL COMMUNICATION INTERFACE The Serial Communication Interface is perhaps the most classical interface used when two systems are connected together.
5 - Peripherals With another core clock, we would get different values. The values in bold are the most com- monly used. Please note that they are not exact; however, asynchronous serial transmission is by nature tolerant of bit rate errors of up to 4%. The error here is only 0.16%. The division ratio is selected by bits in the Baud Rate Register, with two bits for the prescaler value, then three bits for the receive divisor, and three more bits for the transmit divisor.
Page 130
5 - Peripherals TCIE: Transmission complete interrupt enable assign TDO pin to alternate function TDRE: Transmit data register empty Transmission complete 1=9 bits to store the 9th bit when M=1 0=8 bits Word length SCICR1 Internal data bus Internal write command Data register Baud rate transmit...
Page 131
5 - Peripherals The resynchronization is the most difficult thing. It uses a clock a 16 times the bit rate, and the state of the receive data pin is checked at each period of that clock. When a falling edge is de- tected, a mechanism takes that time plus half a bit period as the reference time for the sam- pling of all subsequent bits.
5 - Peripherals 5.8.3 Status register The Status Register includes the following bits that show the current status of the SCI: The TDRE and TC bits, if set, indicate that a new character may be supplied to continue the transmission. The difference between these bits comes from the fact the SCI has a buffer before the transmit shift register.
Status Register bits to know which event caused the interrupt. For this reason, and as ususal for most of the ST7 peripherals, once an interrupt has been ac- cepted and the interrupt service routine is started, the interrupt request must be cleared by program.
Page 134
5 - Peripherals been received by a flag set by the interrupt service routine. Conversely, if the main program wants to send data, it prepares the character or string to send into a buffer in memory, then 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.
6 STMICROELECTRONICS PROGRAMMING TOOLS This chapter describes the STMicroelectronics programming tools, their installation and their use, based on a simple example program. The standard ST Microelectronics ST7 programming tools package includes the following items: Assembler ASM.EXE V1.9 Linker LYN.EXE V1.7 Librarian LIB.EXE V1.2...
Page 136
30 characters are meaningful, that is, if two names have the same first 30 characters, they will be considered the same and 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.
6 - STMicroelectronics Programming Tools The assembler automatically recognizes the addressing mode after the syntax of the operand, as in the following examples: LD A,#2; immediate LD A,VALUE; direct short LD A,VALUE2; direct long LD A,VALUE,(X); indexed with short displacement LD A,VALUE2,(X);...
Page 139
On the other hand, the absolute position of a variable in memory is virtually irrelevant, pro- vided it is positioned within the addressable space. For the ST7, there is a little subtlety with this point. There are addressing modes called Short, or variants thereof, as explained in the chapter about the instruction set.
The Motorola style is to put the most significant byte first, that is 34h , 12h . The Intel style is the opposite, i.e. 12h , 34h . The ST7 fol- lows the Motorola style in its instruction syntax: when extended addressing mode is used, the first byte of the address is the most significant one.
6 - STMicroelectronics Programming Tools wish to build a table of jump addresses, you must use this order to make the jumps occur as expected. On the other hand, a CALL instruction pushes the return address Most Significant Byte first, which means that in memory the Most Significant Byte is stored at a higher address than the Least Significant Byte that is stored next.
6 - STMicroelectronics Programming Tools If you use the symbol DISPLAY_WIDTH several times in your program, and you place the above declaration at a convenient place in the source text (in general at the beginning), when the dis- play is later enlarged to 24 characters, this line is the only one you have to change: DISPLAY_WIDTH EQU 24 for the program to be able to handle the new display size and without risking discrepancies re- sulting from failing to change all occurances of 16 to 24.
6 - STMicroelectronics Programming Tools the way that these functions communicate with each other has been defined, and that some common writing rules have been set out. Since the program is divided into several files, a problem arises because each programmer does not know at which address his program should start.
Page 144
6 - STMicroelectronics Programming Tools The read-write memory is divided into two areas: a short-addressable area and the remainder, which is accessible using extended addressing. The input-output area is organized as a collection of individual registers that each have their own function, and that are not interchangeable with other registers.
6 - STMicroelectronics Programming Tools Combine option This option has the following effects: 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.
6 - STMicroelectronics Programming Tools ld a, #cpudiv2 ld miscr, a ; fq 8MHz /2 = CPU clock = 4MHz etc. For a block of code, the SEGMENT directive may only occur after either an unconditional jump or a return instruction. This is because two segments are independent objects, that can be put in different places in memory.
Page 147
6 - STMicroelectronics Programming Tools All segments found later in the program with the same class name will be allocated after this one. To make this work, the module that defines the classes has to be first in the object file list when you invoke the linker.
6 - STMicroelectronics Programming Tools .LongValue DS.L 1 ; a long number data1 SEGMENT byte common 'DATA' .Byte1 DS.B 1 ; first byte of the long value .Byte2 DS.B 1 ; second one .Byte3 DS.B 1 ; third one .Byte4 DS.B 1 ;...
Page 149
6 - STMicroelectronics Programming Tools rectly during debugging; but when the product is put into production or, even worse, later at the customer, the byte could then have a value that makes the program behave wrongly. The consequences would then be very serious. To provide a more convenient way of initializing all the variables that need to be, and to guar- antee that they are all initialized without exception, the assembler has a feature that we shall describe here.
Page 150
6 - STMicroelectronics Programming Tools ld ({VARIABLES-1},X), A dec X; Next byte jrne InitVar1 This routine uses the addresses of both segments, and the length of one of the segments, as calculated by the expression SIZE_RAM: EQU {* - VARIABLES} where the * character means “the current address in memory”.
6 - STMicroelectronics Programming Tools drive the data copy loop in the piece of code above, you get your variables initialized in a con- venient and error-free way. 6.1.5.6 Referencing symbols and labels between modules Declaring external symbols If a program is split into several modules, you have to use special declarations in the modules to tell the assembler that some symbols are not defined in the current module, but in another one, and that this is not a mistake;...
Page 152
6 - STMicroelectronics Programming Tools output. Besides this, he is free to organize his work as he likes – though some writing style rules might have been given to the team for sake of homogeneity of style and ease of mainte- nance afterwards.
Page 153
6 - STMicroelectronics Programming Tools dressing at all. Thus, the you are advised to pay special attention to these questions if you want to optimize the execution time of your program by using the data in page zero. Another way of declaring an identifier as public is to insert a dot before its name in the line where it is defined.
6 - STMicroelectronics Programming Tools SEGMENT 'DATA_Page0' BYTES Value1 DS.W 1 ; a word data in page zero SEGMENT 'DATA_Extended' WORDS Value2 DS.B 1 ; a byte data in extended memory The lines containing the SEGMENT pseudo-op may appear either before or after the line with the , WORDS or LONGS pseudo-op.
Page 155
6 - STMicroelectronics Programming Tools As an example, let us consider a product for which two different suppliers of displays are con- sidered. These two displays are almost the same, except for a few differences. The product is produced for some time with one type of display, then a better price has been negotiated with the second supplier, so the production switches to the second type of display.
6 - STMicroelectronics Programming Tools #DEFINE FIRST_TYPE must be removed, or changed, like this: #DEFINE SECOND_TYPE Then, the identifier FIRST_TYPE is no longer defined; that the identifier SECOND_TYPE is defined instead does not prevent the FIRST_TYPE throughout the program being false, and thus ena- bles the assembly of the ELSE part of the source.
6 - STMicroelectronics Programming Tools The following code, in the same module, invokes the macro by inserting its name in the oper- ation field. ld A, d1 ld d2, A MyCode ld A, d3 The result is, when assembled: 0000 R C60000 A, d1 0003 R C70000 d2, A...
6 - STMicroelectronics Programming Tools nition of the macro is: IncByTwo MACRO TheByte inc TheByte inc TheByte MEND The macro is used by adding the symbol of the byte to be incremented: IncByTwo CounterLo The macro is expanded by the assembler to the following code: IncByTwo CounterLo 000F 3C00...
Page 159
6 - STMicroelectronics Programming Tools ments a word variable. Unlike the example above, the low byte is incremented, then we test if it is zero. If yes, we increment the high byte: IncWord MACRO LowByte, HiByte inc LowByte jrne NoIncHigh inc HiByte NoIncHigh: MEND...
6 - STMicroelectronics Programming Tools 0019 3C00 CounterLo 001B R 2602 jrne LOC1 001D 3C01 CounterHi LOC1: We can see that the label NoIncHigh has been replaced in the first expansion by LOC0 and in the second by LOC1 . The multiple definition problem is now avoided. 6.1.7.3 Conditional statements in macros You can have the macro expand a different way according to the value of the arguments.
Page 161
6 - STMicroelectronics Programming Tools 001F B602 A, NbOfApples 0021 BB03 A, NbOfPears 0023 #IFB NbOfFruit 0023 B704 NbOfFruit, A ; result in third argument 0025 #ENDIF 0025 Addition NbOfApples, NbOfFruit, 0025 B602 A, NbOfApples 0027 BB04 A, NbOfFruit 0029 #IFB 0029 B704...
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 statement, being a label, must start on the first character of the line. As a label, it has a...
By default, the MOTOROLA style is used. 6.1.9 Object and listing files Note: For the invocation of the assembler and the command-line options, refer to the ST7 Software Tools User Manual, paragraph 4.6. 163/317...
6 - STMicroelectronics Programming Tools 6.1.9.1 Object files The result of the assembly of the source text is its translation into machine language. This is a binary file that contains the binary values of the instructions, addresses and constant data. This file is called the object file, and is named by default with the same name as the source text, but with the extension .OBJ .
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...
Page 166
6 - STMicroelectronics Programming Tools File.cod Absolute object file File2.obj File.grp Memory usage map File1.obj lyn.exe File.map File3.obj Segment map data base Relocatable object files File.sym Linker invocation : Symbol table "lyn file1+file2+file3, file" 06-lyn Caution: The linker is invoked with the list of object files ( ) to be linked, and if you wish, .OBJ with the name of the resulting file ( .COD ).
The ST7 programming tools include a librarian that can be used to build library files. If you are inte rested in using lib raries, we sug gest yo u re fer to the ST7 Programm ing T ools User Manual, Chapter 7.
6 - STMicroelectronics Programming Tools This choice allows you to download the executable progra m to virtually an y commercial EPROM programmer. When using the WGDB7 debugger, the program is loaded into the de- bugger using either the Intel or Motorola format. 6.2.3 The back-annotation pass of the assembler When the WGDB7 debugger is used, to work properly, it expects the listing files to be fully documented with the actual absolute addresses.
(for example if these tools must be installed in a different hard disk). Then the installation proceeds. At the end, the ST7 Tools group is added to the Run menu (or a group under Win- dows 3), and a box requests whether you want to read the Readme file that gives some ver- sion information.
This directory and its contents should be copied to the hard disk of your work station. We assume that it will be copied to directory C:\ST7\WORK\CATERPIL . This directory is men- tioned in the configuration file. If you want to use another directory, you m ust modify the file accordingly.
The two files REG72251.ASM and MAP72251.ASM define the microcontroller that is used for the project. If the project has to be changed to use another member of the ST7 family, it is only necessary to change these two files for those of another microcontroller of the ST7 family and the project will work the same way—provided the new microcontroller contains all...
Page 172
6 - STMicroelectronics Programming Tools 06-proj.bmp The Project Name is just free text. It is not the name of the project file that can be saved by pressing the Save... button. The Working Directory is that of the project. It is advisable to have one separate directory for each project.
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 in the directory C:\ST7\WGDB7 . The two files mentioned here are present in the companion software, so the settings above need not be made by hand.
Page 174
6 - STMicroelectronics Programming Tools The main program is the following: ST7/ ;============================================================= Main (caterpillar) ;============================================================= #include "Register.inc" EXTERN Delay500 ; By default, external label defined as a word ; definition of the constants ; ========================= BYTES ; The following constants defined as bytes...
Page 175
; reset vector ($FFFE) The main program calls the following subroutine that has been written in a separate file on pur- pose, though it would be easier to write it in the main source file: ST7/ ;============================================================= timer 0.5 second ;=============================================================...
EXTERN statem ents are a dded to tha t source file. Here is an excerpt from the REG72251.ASM file: ST7/ ;************************************************************* ST72251 registers : This file declares the labels of all the registers of the Input/Output peripherals.
Page 177
6 - STMicroelectronics Programming Tools declarations are in the include file REG72251.INC that must be included in the source files that use them. ;************************************************************* BYTES ; the following addresses are 8-bit long ;************************************************************* segment byte at 0-71 'periph' ;************************************************************* ;************************************************************* I/O Ports registers ;************************************************************* .pcdr...
6.4.3.4 The MAP72251.ASM file This file contains only absolute segment declarations. These declarations tell the linker where the ROM, the RAM and the stack are. Here is the text of the file: ST7/ ;************************************************************* ST72251 memory mapping 178/317...
6 - STMicroelectronics Programming Tools ;************************************************************* BYTES ; following addresses are 8 bit long ;************************************************************* segment byte at 80-FF 'ram0' ; user ram in zero page ;************************************************************* WORDS ; following addresses are 16 bit long ;************************************************************* segment byte at 100-13F 'ram1' ;...
6 - STMicroelectronics Programming Tools The first four lines make the assembler translate the four source files of the project. The fifth line gives the object files to link, then the name of the result file, and the name of the libraries that may be needed.
Page 181
Pressing the space bar, or the enter key, or clicking on Analyze Results, makes the sentence “No errors on assembly of 'C:\ST7\WORK\CATERPIL\MAIN.ASM'” be displayed in the status bar at the bottom of the screen. This is the message from the assembler.
Page 182
6 - STMicroelectronics Programming Tools To assemble all the source files, open all of them, and on each, perform the assembly in turn. When all the source files are assembled, it is time to build the result files. To do this, press the hammer button. This starts the batch file described above. A DOS box then opens, and the linker is started.
They include the STMicroelectronics Software Tools, so that the board can be driven using the EPROMER software. They do not provide any emulating capability but the De- bugger can run in simulation mode. They also include a selection of ST7 chips depending on the flavor selected.
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 EPROMER. The following window opens: 07-prog1.bmp...
Page 186
7 - Debugger and PROM Programmer Tutorial for ST72251 Select the option Configure/Configure 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;...
Page 187
7 - Debugger and PROM Programmer Tutorial for ST72251 In this window, select the device that will be used. Then press OK. The EPROMER is now configured. Typically, to program an EEPROM, we need to load the hexadecimal file into the programmer, then to program the device.
Page 188
7 - Debugger and PROM Programmer Tutorial for ST72251 This window is an edit window, that allows you to alter the values to be programmed directly by putting the cursor on one byte and typing in the new value. The tabs at the bottom allow you to select between the program memory (EPROM) and the non-volatile memory that is reprogrammable by the application program (EEPROM).
7 - Debugger and PROM Programmer Tutorial for ST72251 tents of the window. However, this test is automatically performed prior to programming, and thus, is optional. 7.3 EMULATOR AND DEBUGGER 7.3.1 Introducing the emulator and the debugger The emulator and the debugger constitute together the essential tool for testing and debug- ging a program.
Page 190
The first question asked is the directory into which the debugger is to be installed. We have chosen to put it in the directory C:\ST7\WGDB7 . W hen the choice has been validated, the file copy process starts. Since the 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.
Page 191
7 - Debugger and PROM Programmer Tutorial for ST72251 07-emu1.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: 191/317...
Page 192
7 - Debugger 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 192/317...
7 - Debugger and PROM Programmer Tutorial for ST72251 The installation process finishes a short time later. Once it is installed, we can start using it at once. If either of the settings in the boxes above has to be changed,you do not need to repeat the whole installation procedure.
Page 194
7 - Debugger and PROM Programmer Tutorial for ST72251 Press OK. The hexadecimal file, containing the machine-language program, is loaded. The debugger expects that the map file of the project also resides in the same directory and has the same name, but with the extension .MAP. For this to happen, the batch file that builds the program must produce a .S19 file with the same name as the output file of the linker: lyn REG72251+MAP72251+TIMER500+MAIN,CATERPIL, obsend CATERPIL,f,CATERPIL.s19,s...
7 - Debugger and PROM Programmer Tutorial for ST72251 Since the processor has been automatically reset after the object file was opened, the first line of the program is underlined, showing where the execution will start from. Opening the Sources pull-down menu, we get the list of the modules of the project. As many other source files as you wish may be opened at the same time.
Page 196
7 - Debugger and PROM Programmer Tutorial for ST72251 07-emu8.bmp Now, we want to see how the timer routine affects the variables in memory. Let us select the toolbox Windows/Dump option. A window opens, showing the contents of the whole memory. Using the scroll bar, let us watch the value of the memory bytes near the address of the timer variables, situated at 80h : 07-emu9.bmp...
7 - Debugger and PROM Programmer Tutorial for ST72251 07-emu10.bmp Now, if we step through the timing loops, we can see the values changing. 7.3.3.4 Using Inspect and Watch The mem ory inspection as shown above gives access to the whole data and program in memory;...
Page 198
7 - Debugger and PROM Programmer Tutorial for ST72251 The address and the type of the variable, shown here, are only displayed if the Misc/Info op- tion of the box is selected. The Misc/Hot option also allows this window to be refreshed each time the execution of the program is suspended.
7 - Debugger and PROM Programmer Tutorial for ST72251 7.3.3.5 Using breakpoints Our timing loop is very long. It is impractical to step through it. There is an easier way to do it: put a breakpoint. For example, we want to watch what happens to the outer loop. Put the cursor on line 57, where the conditional jump that closes the outer loop stands.
7 - Debugger and PROM Programmer Tutorial for ST72251 07-emu12.bmp When we press Continue, the program runs at full speed until the next breakpoint, if any. During this time, we are blind to what happens in memory. To compensate for this, we have a tool called the trace recorder.
7 - Debugger and PROM Programmer Tutorial for ST72251 The top line is where we are now. The next line is where we came from. If we click on this second line, and select the View/Source option, the window showing the Main.asm source- pops up and line 45 is highlighted in blue.
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.
Page 203
7 - Debugger and PROM Programmer Tutorial for ST72251 verter. When at the highest position, it provides the full V voltage that is converted to a value of 255. The relationship provides for a frequency that changes from about 0.5 Hz to 10 Hz. Frequency (f) f = (9.5/255) ADC +0.5 Analog to digital...
7 - Debugger and PROM Programmer Tutorial for ST72251 The 16-bit Timer runs continuously and g enerates an in terrupt every 10 m s. A software counter is used to count the half-period time of the blinking. The parallel input-output ports are used both to input the four voltages to the ADC and to switch the four LEDs.
As mentioned in a previous chapter, to implement a multitasking kernel on the ST7, you must sacrifice a lot of features. On the other hand, the ST7 is not expected to handle programs re- quiring extensive computing power, and so the reduction in performance can be outweighed by the advantages of simpler programming, and better coordination between tasks that a mul- titasking approach brings to the programmer.
Page 207
7 - Debugger and PROM Programmer Tutorial for ST72251 Now, at the top of each of the stacks, the routine writes the address of the beginning of each task, and initializes the variable Permut to zero. This variable keeps track of the number of the current task.
7 - Debugger and PROM Programmer Tutorial for ST72251 7.6.3.2 The Yield routine A call to this routine must be inserted in the code of each task, at least once within the main loop. As many calls to Yield as you wish may be inserted in each task. W hen this function is executed, the current task is suspended and control is passed to the next task in the order they have been declared.
Page 209
7 - Debugger and PROM Programmer Tutorial for ST72251 This mechanism is illustrated in the diagram below: Task1 is awaken Yield Task2 is woken up The active area Permut = 1 Permut = 0 of the stack is used in each task of this program, to PCH Task4...
Page 210
7 - Debugger and PROM Programmer Tutorial for ST72251 The next figure shows, in detail, the modifications to the stack when moving from task one to task two. Task1 is running ; Permut = 0 Active area of the stack 17F (sp) "Call Yield"...
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.
7 - Debugger and PROM Programmer Tutorial for ST72251 , that is the batch file that does the linking and the back-annotation. Multitsk.bat Here are details on each of these. 7.6.4.1 Main file (Multitsk.asm) The main file contains the code for the initialization of the system, that is terminated by a call to StartTasks .
Page 213
7 - Debugger and PROM Programmer Tutorial for ST72251 The source code for the main program and for the multitasking kernel follow. First, the main program: ST7/ ;================================================================== Demonstration of a simplified real-time cooperative kernel ;================================================================== ; This program performs a voltage to frequency conversion on four ;...
Page 214
7 - Debugger and PROM Programmer Tutorial for ST72251 AddrTasks: DC.W Task1, Task2, Task3, Task4 ; Table of pulse duration. Returns the result of the voltage to period function. TimingTable: DC.B 100, 93, 87, 82, 77, 73, 69, 66 DC.B 63, 60, 57, 55, 53, 51, 49, 47 DC.B 46, 44, 43, 41, 40, 39, 38, 37...
Page 215
7 - Debugger and PROM Programmer Tutorial for ST72251 ld A, #t_timer ; Initialize TAOCR1 register ld taoc1hr, A ; (comparison register) clr taoc1lr inc A ; A counter reset will happen ld taoc2hr, A ; before it reaches the value ;...
; vecteur de reset ($FFFE) 7.6.4.2 ADC source file(Acana.asm) The analog to digital conversion handling is done in this short file: ST7/ ;============================================================= Analog to digital conversion ;============================================================= ; relocatable sub-routine to initialise the ADC and to run a ;...
7 - Debugger and PROM Programmer Tutorial for ST72251 7.6.4.3 Kernel source file (Littlk.asm) The multitasking kernel is contained in the following file: ST7/ ;============================================================== Simple real time kernel ;============================================================== PUBLIC StartTasks, Yield EXTERN wdgr.b, AddrTasks ; Constants ; ========== org1.b...
Page 218
7 - Debugger and PROM Programmer Tutorial for ST72251 ld X, {AddrTasks+4} ; MSB address Task push X ; Written at top of stack ld A, S ld ImStack3, A ; Remember position of stack pointer ld A, #org2 ; Top of stack for task 2 ld S, A ld X, {AddrTasks+3} ;...
Select File/Configure (if no previous configuration is loaded) or Project/Configure (if there is a current configuration), click on Open, then find the file Project.wpj in the directory \ST7\Work\Multitsk Here, it is possible to assemble one or several sources files one at a time, as follows: Open all the required source files ( .ASM )
Page 220
7 - Debugger and PROM Programmer Tutorial for ST72251 lator. When you have played with it for a while, you will be ready to consider designing your own application. The following chapter will first introduce the C language and related software tools and dis- cuss its advantages.
The HICROSS development chain is compatible with the STMicroelectronics emulator for the ST7, but the file formats between the C Compiler, the Assembler, the Linker and the software accessories (librarian, decoder, simulator, EPROM burner) are not compatible with those of the STMicroelectronics Software Tools.
8 - C Language and the C Compiler compilers to see which one matches your needs, and carefully read the user manual of that compiler. The details given below apply only to the HICROSS development chain. 8.2 DESCRIPTION AND INSTALLATION OF THE HICROSS TOOL CHAIN The HICROSS development tool chain contains: The Hiware Tools, that is actually a control panel that allows you to make settings and launch the following items...
Page 223
8 - C Language and the C Compiler To do this, press 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.
Page 224
8 - C Language and the C Compiler Click on 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 224/317...
Page 225
8 - C Language and the C Compiler Now click on the Additional tab, and complete the line with ERRORFILE so that it reads: ERRORFILE=\edout 08-HWTO5.BMP Press OK twice. W e are done with the Hiware Tools. The second button of the tool bar now shows the Winedit icon.
C language, even if he is not an expert; but some experi- ence is required to appreciate the specific features of C programming for the ST7. When programming in C for a microcontroller, the following points must be taken into account:...
8 - C Language and the C Compiler The availa ble m emory varies with the mode l of ST7 chose n. T o o ptim ize the access to memory, the compiler offers four memory models that set the rules for data allocation. These...
RAM. 8.3.1.2 EEPROM non-volatile storage Some members of the ST7 family have, in addition to RAM and ROM, some EEPROM that constitutes some non-volatile storage to store data and configuration parameters over power- off periods.
8 - C Language and the C Compiler float Coefficient ;{ two non-volatile parameters } #pragma DATA_SEG DEFAULT int Value[10] ;{ an array of ten integers, volatile } 8.3.1.3 Page Zero variables Direct addressing, as mentioned in the chapter that discusses addressing modes, is much more efficient than extended addressing, both in terms of code size and speed.
8 - C Language and the C Compiler 8.3.2 Initialization of variables and constant variables On starting, a C program initializes all variables to zero, except those that are defined with an initial value. Example: int i ; int j = 3 ; Here i is initialized to zero, and j is initialized to 3.
8 - C Language and the C Compiler 8.3.3.1 First method: using macros The method that the documentation of the compiler suggests relies on the definition of a macro that produces a pointer definition, as in the following example that defines PADR that is located at address 8: #define PADR * ((unsigned char *)(8)) This notation is almost equivalent to a variable definition;...
The ST7 family provides a limited RAM size, of which the stack takes only a part, that can be as small as 64 bytes. This does not allow the use of the stack for parameter passing. Thus, the...
8 - C Language and the C Compiler rameters, and allocates local variables to RAM just like global variables. This works the same way as in a typical implementation, but with the following restrictions: Functions are neither reentrant nor can they be used recursively. The compiler uses temporary variables in memory at fixed addresses and thus are not reentrant.
8 - C Language and the C Compiler #define EnableInterrupts {asm RIM;} #define DisableInterrupts {asm SIM;} 8.4.1.2 Multiple-statement assembler block When a block of several lines must be included, the lines must be enclosed in an asm block, as follows: <statement>...
8 - C Language and the C Compiler 8.4.2 Using the Hiware assembler The Hiware assembler is comparable to the assembler described in Chapter 6. The same principles apply, so they will not be repeated here. However, the syntax that Hiware uses is specific and different from that of the STMicroelec- tronics assembler.
Page 236
8 - C Language and the C Compiler Here is an example of a link parameter file taken from the X10XM IT project described in Chapter 9: LINK X10XMIT.abs NAMES main.o interrup.o map72251.o+ start07.o ansi.lib SECTIONS APORTC = READ_WRITE 0x00 TO 0x02;...
File destination, and type the file name in the next box. The format is Motorola S, the data bus width is 1 byte (the ST7 is an 8-bit core). To start the con- version, press the button 1st Byte.
Page 238
8 - C Language and the C Compiler 08-Burn.bmp Then use the EPROMer programmer software as described in Chapter 7. 238/317...
8 - C Language and the C Compiler 8.7 PROJECT DIRECTORY STRUCTURE Needless to say, a well organized set of files on the computer's hard disk helps in designing and in maintaining a software project. Using the following recommended directory structure will make your project easier to support, since STmicroelectronics engineers, if solicited for assistance, will quickly be able figure out where the files are, a very important thing when de- fining the environment file, link parameter files, and more.
Page 240
The path tab contains lists of paths grouped in classes. In 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...
To allow the compiler, linker, etc. to find their way in this structure, the DEFAULT.ENV file placed in the main directory of the project, specifies the various paths. In the example below, the path of the project is c:\st7\work\x10xmit . You will of course replace it with your own path. Paths 241/317...
The MAP_72251.C and MAP_72251.H files provide the declarations of the registers of the 72251; a set of thse files also exists for each variant of the ST7. The C source file must be compiled, and the object linked with the other files of the project.
Page 243
8 - C Language and the C Compiler The effect of this + sign is to remove the optimization for this file, that would normally remove all the unused variable declarations, which would interfere with the allocation of the registers to the proper addresses.
Page 244
(e.g. OC1E ) with its position within the register (here, 7). Since the ST7 does not provide 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.
8 - C Language and the C Compiler The register is and ed with the one's complement of 1 shifted by the appropriate number of places, which preserves all bits except the one that we want to reset; and the result is written back into the register.
8 - C Language and the C Compiler For example, in the project given in Chapter 9, three push-buttons are called CLOSE, OPEN and TIME. These push-buttons are wired so that pressing one grounds the corresponding pin, that is otherwise kept high by a pull-up resistor. The following macro yields a zero when no button is pressed: #define PUSH_BUTTONS ( ( ~PBDR ) &...
8 - C Language and the C Compiler However, this does not mean that you should adopt a loose programming style, as it is often the case when programming for computers. There, a clear style, using techniques that can be quickly written, is recommended, but this may be at the expense of memory and/or the proc- essor resource.
In addition, floating arithmetic does not guarantee proper results for equality tests. Sine the ST7 is a 8-bit machine, try to use as char variables as often as possible. Another point about long and floating arithmetic was described earlier, some precautions are needed when interrupts are used.
9 - A Carrier-current System for domestIc Remote Control We shall first explain what carrier-current control is, taking the X-10 standard as a reference; then, we shall describe the transmitter. The second part of this chapter will describe the re- ceiver.
Page 251
9 - A Carrier-current System for domestIc Remote Control tion. They are synchronized to the zero crossing point of the AC power line. They must be transmitted as close to the zero crossing point as possible, but certainly within 200 microsec- onds of the zero crossing point.
Page 252
9 - A Carrier-current System for domestIc Remote Control The next four cycles represent the House Code and the last five cycles represent either the Number Code (1 thru 16) or a Function Code (On, Off, etc.). This complete block, (Start Code, House Code, Key Code) should always be transmitted in groups of 2 with 3 power line cycles between each group of 2 codes.
Page 253
9 - A Carrier-current System for domestIc Remote Control Within each block of data, each four or five bit code should be transmitted in true complement form on alternate half cycles of the power line. So, if a 1 millisecond burst of signal is trans- mitted on one half cycle (binary 1) then no signal should be transmitted on the next cycle, (bi- nary 0).
Page 254
9 - A Carrier-current System for domestIc Remote Control The tables in the next figure show the binary codes to be transmitted for each House Code and Key Code. The Start Code is always 1110 which is a unique code and is the only code which does not follow the true complementary relationship on alternate half cycles.
9 - A Carrier-current System for domestIc Remote Control Note 1: Hail Request is transmitted to see if there are any X-10 transmitters within listening range. This allows the user to assign a different House Code if a “Hail Acknowledge” is re- ceived.
Page 256
9 - A Carrier-current System for domestIc Remote Control The PB1 pin is connected to the gate of a transistor that switches the 120 kHz oscillator on or off. The output of this oscillator is amplified, and injected to the second pole of the line through a capacitor.
Page 257
9 - A Carrier-current System for domestIc Remote Control 220 V ac N Ph Pb0 Pb3 Pb4 Pc4 Pc5 Test (11) (8) (7) (13) (12) (26) BS250 BS250 Pc0 (17) Pc1 (16) Pc2 (15) HDSP HDSP Pc3 (14) 3900 3900 ST72E251 Pb5 (6) Pb6 (5)
Page 258
9 - A Carrier-current System for domestIc Remote Control The features of the 72251 are used as follows: The first timer is set to PWM mode. It is configured to generate a pulse on the OCMP1_A output, that is the alternate function of the PB1 pin. The repetition period is set to exactly 1/6 of a power line cycle, and the duration of the pulse is set to 1 ms.
9 - A Carrier-current System for domestIc Remote Control So the repetition period will remain within the correct value. The variation of the timer period is constrained within narrow bounds, so that large frequency deviations are not possible. This prevents surges or stray pulses on the line from erroneously changing the position of the 120 kHz pulses relative to the actual zero crossing of the power line.
Page 260
9 - A Carrier-current System for domestIc Remote Control /* This function triggers the sending of one command */ void SendCommand ( Byte Command ) KeyCode = Codes[Command] ; /* prepare the two variables that */ HouseCode = Codes[HOUSE_CODE] ; /* contain the data to send.
Page 261
9 - A Carrier-current System for domestIc Remote Control return 0 ; /* No button pressed or more than one button pressed. */ Please note the use of the macro PUSH_BUTTONS in the text. This macro is defined as follows: #define PUSH_BUTTONS ( ( ~PBDR ) &...
9 - A Carrier-current System for domestIc Remote Control while ( CycleNumber != 0 ) ; /* wait for end of transmission */ while ( Debounce () != 0 ) ; /* wait for all buttons released */ Only those lines that are not self-explanatory have been commented. 9.2.3.2 Timer A Capture interrupt service routine There are two different capture events that can occur for each timer.
Page 263
9 - A Carrier-current System for domestIc Remote Control The ICF1 flag is first tested to know whether the interrupt was caused by a Capture 1 event. If yes, the first block is executed; if not, the second block is executed. In the first case, the two bytes of Compare register 2 are set to the value held in the global var- iable TimerPeriod .
Page 264
9 - A Carrier-current System for domestIc Remote Control The next five pairs of bits carry the Key Code, and work exactly the same way as for the House Code. Since the whole process above must be repeated, all the case tags are duplicated with an offset of 22.
Page 265
9 - A Carrier-current System for domestIc Remote Control case 29 : case 31 : case 33 : if ( ( TempHouseCode & 1 ) != 0 ) TACR1 |= ( 1 << OLVL1 ) ; /* Validate pulse for next interrupt */ else TACR1 &= ~( 1 <<...
Page 266
9 - A Carrier-current System for domestIc Remote Control case 36 : case 38 : case 40 : case 42 : case 44 : if ( ( TempKeyCode & 1 ) == 0 ) TACR1 |= ( 1 << OLVL1 ) ; /* Validate pulse for next interrupt */ else...
Page 267
9 - A Carrier-current System for domestIc Remote Control if ( ( KeyCode & 1 ) == 0 ) TACR1 |= ( 1 << OLVL1 ) ; /* Validate pulse for next interrupt */ else TACR1 &= ~( 1 << OLVL1 ) ; /* Invalidate pulse for next interrupt */ KeyCode >>= 1 ;...
Page 268
9 - A Carrier-current System for domestIc Remote Control As described in the ST72251 data sheet, a mechanism to avoid data desynchronization pre- vents any captures occuring once the high register has been read, until the low register has been also read. This implies that we must ensure that the high byte is read first, then the low byte.
9 - A Carrier-current System for domestIc Remote Control The operation of the PLL is illustrated by the diagram below: T : 20ms (50Hz) Transmission windows Depending on the difference The value of Compare1 registers found between the Capture 2 timer is always equal to the contents of value and the Compare 1 registers, Compare2 registers - 2000...
Page 270
9 - A Carrier-current System for domestIc Remote Control The interrupts are triggered by an overflow of the free-running counter. At each interrupt, the PA7 bit is toggled, so that each digit is lit every other interrupt, that is, there are 32 refresh cy- cles per second.
Page 271
9 - A Carrier-current System for domestIc Remote Control if ( Second > 50 ) /* The display blinks at 1 Hz with a short duty cycle. */ PADR = DISPLAY_OFF ; /* Switch LED off. */ else PADR = SevenSegment[Delay][Second & 1] ; /* Light one of both digits at a time.
9 - A Carrier-current System for domestIc Remote Control 9.3 RECEIVER 9.3.1 Instructions for use Whereas there is only one transmitter in a house, there are several receivers, each located near the blind to be controlled. All receivers are identical, and, provided they are set to the same house code as the transmitter, they receive the same commands at the same time.
Page 273
The ST7 will also be used 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.
Page 274
9 - A Carrier-current System for domestIc Remote Control The following figures show the schematics of the receiver: 220µF 100nF 100K 400V 6.2V 100K 47pF 100K 100K Power supply 47pF (18) (19) (20) (21) Vdd (28) 47pF 47pF Vss (27) 10nF Reset (1) 1µF...
Page 275
9 - A Carrier-current System for domestIc Remote Control The four switches at the top select the House Code of the receiver. The receiver only obeys the commands that are sent to its own House Code. The power supply circuit looks like a classical Scheinkel voltage doubler. Actually, the input capacitor (0.1 µF) presents a reactance that limits the current to about 7 mA RMS.
The pull-down resistors guar- antee that at power on, no coil is powered, allowing the ST7 to start with enough power and preventing undue activation of the motor.
Page 277
9 - A Carrier-current System for domestIc Remote Control case 24 : case 25 : /* First 3 half cycles must have a pulse (start condition) */ if ( ! CarrierDetected ) CycleNumber = 1 ; Reset the whole process if incorrect header.
Page 278
9 - A Carrier-current System for domestIc Remote Control case 43 : TempKeyCode >>= 1 ; /* Shift right by one bit */ if ( CarrierDetected ) TempKeyCode |= 0x10 ; /* Set least-significant bit to one */ break ; /* Key code has five bits */ case 14 : case 16 :...
9 - A Carrier-current System for domestIc Remote Control TempKeyCode |= 0x10 ; /* Set least-significant bit to one */ At the end of the reception, these codes can be checked to determine if the receiver has any- thing to do with them. In the checking phases, if the bit is found to be incorrect, the receive process is aborted by setting CycleNumber back to 1: if ( ( ( TempKeyCode &...
Page 280
9 - A Carrier-current System for domestIc Remote Control the interrupts, for whatever the initial value of TBOC2R, there will necessarily be a Compare 2 event before the free-running counter overflows. This would trigger an interrupt request as soon as the interrupt mask bit is set. To avoid this, the Compare 2 event flag is also cleared though it is not actually used.
Page 281
9 - A Carrier-current System for domestIc Remote Control switches. To allow this, the voltage at both phases of the motor is reduced, then rectified and the resulting voltage is the higher of the two. When the motor is steady, the voltage at its ter- minals is the line voltage (e.g.
Page 282
9 - A Carrier-current System for domestIc Remote Control The control of the relay coils The relays are arranged so that one relay switches the motor on or off, while the other relay selects the open or close direction. As said above, the relays are of the locking- or bistable-type. This means that only a short pulse of current in the coil is needed to trip the relay from one state to the other, thus con- serving energy.
Page 283
Main function. Now we can lo ok at th e ma in pro gra m. It is ma de of a f ew lin es, be cau se mo st 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.
Page 284
9 - A Carrier-current System for domestIc Remote Control InitPorts () ; InitTimerA() ; InitTimerB() ; MISCR = 0x0 ; /* Normal mode (clock/2). */ EnableInterrupts ; LastDirection = STOP_OPEN ; /* to properly start manual cycle */ StopMotor () ; /* To guarantee motor off at power on */ while (1) if ( HOUSE_CODE == Codes[HouseCode] )
The power drainage of the ST7, already low, could be further reduced by slowing the clock down as much as possible taking into account the required computing power needed. W ith the...
In addition, the absolute speed and direction of the wind are displayed, as it is useful in all cases. This is also relevant when sailing before the wind. In this application, the ST7 peripherals are used as follows: A timer is used for measuring the period of the digital signal supplied by the speedometer.
Page 287
10 - Second Application: a Sailing Computer Weather vane / anemometer Visible wind Printed board Real wind circuit with Visible angle Real angle ST72311 Boat speed Loch-Speedometer Sailing computer 10-vmg 287/317...
10 - Second Application: 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. AlphaR AlphaV Against the wind 10-again 288/317...
Page 289
10 - Second Application: a Sailing Computer AlphaV AlphaR Before the wind 10-befor 289/317...
Page 290
10 - Second Application: a Sailing Computer The meaning of the symbols used in these diagrams is the following: Symbol Meaning Visible wind angle (weather vane) AlphaV Visible wind speed (anemometer) Boat speed (speedometer) Real wind angle AlphaR Real wind speed Real boat speed against the wind, or in before the wind The mathematical relationships involved in the calculation of , α...
10 - Second Application: a Sailing Computer They apply for Alpha ranging from zero included to 360° excluded. The angles are counted clockwise, according to nautical usage. 10.2 INTERFACING THE MEASUREMENT DEVICES There are three measurement devices to interface: the speedometer, the wind gauge and the weather vane.
10 - Second Application: a Sailing Computer To achieve the required accuracy, a clocking frequency of at least 2.048 kHz is required, so as to produce a count of 20 points or more at the highest speed, meeting the required resolution of 5%.
10 - Second Application: a Sailing Computer unchanged when the trimmer is at the center; the values are decreased or increased by 20% when the trimmer is at one end or the other, respectively. The trimmers are only read once at power on. 10.2.2 Interfacing the weather vane The weather vane can occupy any angular position in a full circle.
10 - Second Application: a Sailing Computer 10.3 INTERFACING THE DISPLAY The display used is made of three, three-digits-and-a-half, liquid-crystal display. option option Visible wind Real wind display display Visible angle Real angle Boat Speed V.M.G. 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.
10 - Second Application: a Sailing Computer 10.3.1 Display circuit First display MOSI (Pc5) 4094 4094 4094 4094 (Pc6) 3 LCD Modules, each driven by 4 shift registers -1st display: Visible / Real Wind speed Push -2nd display: Visible / Real Wind angle buttons: -3rd display: Boat Speed / VMG (ain)
Page 296
Sending this data would consume a lot of core time, if it were to be performed entirely by soft- ware. Luckily, the ST7 has a very useful peripheral, the Serial Peripheral Interface. The SPI is able to send each of the eight bits of one byte serially, producing a clock pulse for each bit sent.
10 - Second Application: a Sailing Computer Thus, displaying a number, say -1.234, consists of finding the corresponding pattern in the table above and sending all four patterns in a row, starting with the right-most digit. In this ex- ample, we would send the bytes (in hexadecimal): Digit or symbol to show Value sent The Liquid Crystal Display component used here is said to be static, meaning that there is a...
10 - Second Application: a Sailing Computer able pins is not sufficient. This is not the case here, as far as parallel ports are concerned, however a restriction lies in the fact that the display board is connected to the main board using a 9-pin connector.
10 - Second Application: a Sailing Computer 10.5 PROGRAM ARCHITECTURE The program performs the following tasks: Read the values of wind speed and direction and boat speed Compute the absolute values and the VMG Display these values On request from the PC, send the appropriate data The values based on frequency are read from the timer and converted in an interrupt service routine each time a capture is performed.
Page 301
10 - Second Application: a Sailing Computer ld a, TBIC1HR /* Get new time */ ld Capture1.W.Low, a ld a, TBIC1LR ld Capture1.W.Low:1, a BoatPeriod = Capture1.Long - LastCapture1 ; /* calculate time difference */ LastCapture1 = Capture1.Long ; /* Remember this time for next capture */ if ( TBSR &...
10 - Second Application: a Sailing Computer high-order word of both capture variables. To do so, the capture variable is declared as fol- lows: typedef union uCapture LWord Long ; struct sCapture Word High ; Word Low ; } W ; } tCapture ;...
Page 303
10 - Second Application: a Sailing Computer The contents of this array are copied to the SPI, one byte at a time, by the following function. The last three bytes of the array contain the values to be displayed. The function uses the lookup table to find the pattern to be sent to the display shift registers.
10 - Second Application: a Sailing Computer variable is also toggled here, so that the drive voltage will have a frequency of Polarity 50 Hz since the function is called 100 times per second. 10.5.3 Polling the push-buttons The push-buttons are wired to a resistor arrangement that produces different voltages at one of the inputs of the Analog to Digital Converter.
10 - Second Application: a Sailing Computer OldState = NewState ; /* Remember for next time */ The button number is determined by checking that the voltage is within a certain range. The debouncing consists of checking that the voltage remains in the same range for a certain number (here 3) of consecutive conversions.
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 number of element that is an exact power of two (32), and we divide by shifting the sum right by 5 bits.
10 - Second Application: a Sailing Computer if ( Turn ) GetPushButtons() ; ReadDirection () ; Turn = ! Turn ; RefreshAllDisplays () ; 10.5.6 Computation of the results The main program takes the raw values and applies to them the formulae given at the begin- ning of this chapter.
Page 308
10 - Second Application: a Sailing Computer The results of the computation are word values that must be converted into a string of charac- ters. This is done by the following function which is a very classical number-to-string conver- sion. The leftmost digit is processed separately: if the result is between 1000 and 1999, the 1 is displayed;...
10 - Second Application: a Sailing Computer 10.5.7 Handling of the serial interface The serial interface is configured to both transmit and receive under interrupt control. The con- figuration function is the following: void InitSCI ( void ) SCICR1 = 0 ; /* 8 bits, one stop */ SCIBRR= ( 3 <<...
10 - Second Application: a Sailing Computer If the interrupt cause is the reception of a character, the interrupt request is cleared by reading the Status Register (which is done when it is tested), then reading the Data Register. The character received is copied to the global variable that is used by the main RemoteCommand...
Page 311
10 - Second Application: a Sailing Computer The three calibration parameters are read from the position of the three trimmers. The three voltages are read and converted into the proper numeric values to work appropriately when used in the calculations. These parameters are produced by the following function: void InitCalibration ( void ) ADCSR = ( 1 <<...
Here, a size of 16 Kbytes is necessary. The RAM allocation is a little bit trickier. The ST7 has two direct addressing modes: short and extended. The mode must be chosen at compile time, while the actual memory allocation is done at link time.
Page 313
10 - Second Application: a Sailing Computer ARAM2 = READ_WRITE 0x200 TO 0x27F; AROM = READ_ONLY 0xC000 TO 0xFFE0; PLACEMENT DEFAULT_ROM, ROM_VAR, STRINGS INTO AROM; DEFAULT_RAM INTO ARAM; _ZEROPAGE INTO AZRAM; _OVERLAP INTO ARAM2; SSTACK INTO ASTACK; PORTS INTO APORTS; MISC INTO AMISC;...
(for data transfer from the sensors to the calcu- lation block). Although the ST7 is a medium-range 8-bit product, it benefits from the full use of the C lan- guage, that allowed us to write both the byte-level actions and the floating-point calculations with the same ease.
The Analog to Digital converter expands the ST7 by putting it in touch with the analog world, without using external circuitry. This can also be used to perform digital expansion, like in the application described in the introduction where a keypad is connected to the microcontroller using only two wires.
Page 316
In addition to being powerful for its size, the ST7 is also easy to use, using the available pro- gramming tools. In particular, C language has been shown to be the language of choice, that stands up well even when compared to C language running on much bigger machines.
Page 317
11 - Some Last Remarks In short, the range of tools offered for the ST7 spans all different needs from those of a small lab to a large Engineering Department. The mid-range solution is also particularly valuable for education purposes.
Need help?
Do you have a question about the ST7 and is the answer not in the manual?
Questions and answers