Файл: Beginers introduction to the Assebly Language of ATMEL-AVR Microprocessors (Gerhard Schmidt,2003, англ).pdf
ВУЗ: Не указан
Категория: Не указан
Дисциплина: Не указана
Добавлен: 13.06.2025
Просмотров: 643
Скачиваний: 1
Avr-Asm-Tutorial |
17 |
http://www.avr-asm-tutorial.net |
The value RAMEND is, of course, specific for the processor type. It is defined in the INCLUDE file for the processor type. The file 8515def.inc has the line:
.equ RAMEND =$25F ; Last On-Chip SRAM Location
The file 8515def.inc is included with the assembler directive
.INCLUDE "C:\somewhere\8515def.inc"
at the beginning of our assembler source code.
So we defined the stack now, and we don't have to care about the stack pointer any more, because manipulations of that pointer are automatic.
Use of the stack
Using the stack is easy. The content of registers are pushed onto the stack like this:
PUSH MyPreferredRegister ; Throw that value
Where that value goes to is totally uninteresting. That the stack pointer was decremented after that push, we don't have to care. If we need the content again, we just add the following instruction:
POP MyPreferredRegister ; Read back the value
With POP we just get the value that was last pushed on top of the stack. Pushing and popping registers makes sense, if
•the content is again needed some lines of code later,
•all registers are in use, and if
•no other opportunity exists to store that value somewhere else.
If these conditions are not given, the use of the stack for saving registers is useless and just wastes processor time.
More sense makes the use of the stack in subroutines, where you have to return to the program location that called the routine. In that case the calling program code pushes the return address (the current program counter value) onto the stack and jumps to the subroutine. After its execution the subroutine pops the return address from the stack and loads it back into the program counter. Program execution is continued exactly one instruction behind the call instruction:
RCALL Somewhat ; Jump to the label somewhat [...] here we continue with the program.
Here the jump to the label somewhat somewhere in the program code, Somewhat: ; this is the jump address
[...] Here we do something
[...] and we are finished and want to jump back to the calling location: RET
During execution of the RCALL instruction the already incremented program counter, a 16-bit-address, is pushed onto the stack, using two pushes. By reaching the RET instruction the content of the previous program counter is reloaded with two pops and execution continues there.
You don't need to care about the address of the stack, where the counter is loaded to. This address is automatically generated. Even if you call a subroutine within that subroutine the stack function is fine. This just packs two return addresses on top of the stack, the nested subroutine removes the first one, the calling subroutine the remaining one. As long as there is enough SRAM, everything is fine.
Servicing hardware interrupts isn't possible without the stack. Interrupts stop the normal exection of the program, wherever the program currently is. After execution of a specific service routine as a reaction to that interrupt program execution must return to the previous location, before the interrupt occurred. This would not be possible if the stack is not able to store the return address.
The enormous advances of having a stack for interrupts are the reason, why even the smallest AVRs without having SRAM have at least a very small hardware stack.
Bugs with the stack operation
For the beginner there are a lot of possible bugs, if you first learn to use stack.
Very clever is the use of the stack without first setting the stack pointer. Because this pointer is set to zero at program start, the pointer points to register R0. Pushing a byte results in a write to that register, overwriting its previous content. An additional push to the stack writes to 0xFFFF, an undefined position (if you don't have external SRAM there). A RCALL and RET will return to a strange address in program memory. Be sure: there is no warning, like a window popping up saying something like „Illegal Access to Mem location xxxx“.
Avr-Asm-Tutorial |
18 |
http://www.avr-asm-tutorial.net |
Another opportunity to construct bugs is to forget to pop a previously pushed value, or popping a value without pushing one first.
In a very few cases the stack overflows to below the first SRAM location. This happens in case of a neverending recursive call. After reaching the lowest SRAM location the next pushes write to the ports (0x005F down to 0x0020), then to the registers (0x001F to 0x0000). Funny and unpredictable things happen with the chip hardware, if this goes on. Avoid this bug, it can even destroy your hardware!
Avr-Asm-Tutorial |
19 |
http://www.avr-asm-tutorial.net |
Jumping and Branching
Here we discuss all commands that control the sequential execution of a program. It starts with the starting sequence on power-up of the processor, jumps, interrupts, etc.
Controlling sequential execution of the program
What happens during a reset?
When the power supply of an AVR rises and the processor starts its work, the hardware triggers a reset sequence. The counter for the program steps will be set to zero. At this address the execution always starts. Here we have to have our first word of code. But not only during power-up this address is activated:
•During an external reset on the reset pin a restart is executed.
•If the Watchdog counter reaches its maximum count, a reset is initiated. A watchdog timer is an internal clock that must be resetted from time to time by the program, otherwise it restarts the processor.
•You can call reset by a direct jump to that address (see the jump section below).
The third case is not a real reset, because the automatic resetting of registerand port-values to a welldefined default value is not executed. So, forget that for now.
The second option, the watchdog reset, must first be enabled by the program. It is disabled by default. Enabling requires write commands to the watchdog's port. Setting the watchdog counter back to zero requires the execution of the command
WDR
to avoid a reset.
After execution of a reset, with setting registers and ports to default values, the code at address 0000 is wordwise read to the execution part of the processor and is executed. During that execution the program counter is already incremented by one and the next word of code is already read to the code fetch buffer (Fetch during Execution). If the executed command does not require a jump to another location in the program the next command is executed immediately. That is why the AVRs execute extremely fast, each clock cycle executes one command (if no jumps occur).
The first command of an executable is always located at address 0000. To tell the compiler (assembler program) that our source code starts now and here, a special directive can be placed at the beginning, before the first code in the source is written:
.CSEG
.ORG 0000
The first directive lets the compiler switch to the code section. All following is translated as code and is written to the program memory section of the processor. Another target segment would be the EEPROM section of the chip, where you also can write bytes or words to.
.ESEG
The third segment is the SRAM section of the chip.
.DSEG
Other than with EEPROM content, that really goes to the EEPROM during programming of the chip, the DSEG segment content is not programmed to the chip. It is only used for correct label calculation during the assembly process.
The ORG directive above stands for origin and manipulates the address within the code segment, where assembled words go to. As our program always starts at 0x0000 the CSEG/ORG directives are trivial, you can skip these without getting into an error. We could start at 0x0100, but that makes no real sense as the processor starts execution at 0000. If you want to place a table exactly to a certain location of the code segment, you can use ORG. If you want to set a clear sign within your code, after first defining a lot of other things with .DEF- and .EQU-directives, use the CSEG/ORG sequence, even though it might not be necessary to do that.
As the first code word is always at address zero, this location is also called the reset vector. Following the reset vector the next positions in the program space, addresses 0x0001, 0x0002 etc., are interrupt vectors. These are the positions where the execution jumps to if an external or internal interrupt has been enabled and occurs. These positions called vectors are specific for each processor type and depend on the internal hardware available (see below). The commands to react to such an interrupt have to be placed to the proper vector location. If you use interrupts, the first code, at the reset vector, must be a jump command, to jump over the other vectors. Each interrupt vector must hold a jump command to the respective interrupt service routine. The typical program sequence at the beginning is like follows:
Avr-Asm-Tutorial |
20 |
http://www.avr-asm-tutorial.net |
.CSEG
.ORG 0000
RJMP Start
RJMP IntServRout1
[...] here we place the other interrupt vector commands
[...] and here is a good place for the interrupt service routines themselves
Start: ; This here is the program start [...] Here we place our main program
The command RJMP results in a jump to the label Start:, located some lines below. Remeber, labels always start in column 1 of the source code and end with a :. Labels, that don't fulfil these conditions are not taken for serious by many compiler. Missing labels result in an error message ("Undefined label"), and compilation is interrupted.
Linear program execution and branches
Program execution is always linear, if nothing changes the sequential execution. These changes are the execution of an interrupt or of branching instructions.
Branching is very often depending on some condition, conditioned branching. As an example we assume we want to construct a 32-bit-counter using registers R1 to R4. The least significant byte in R1 is incremented by one. If the register overflows during that operation (255 + 1 = 0), we have to increment R2 similiarly. If R2 overflows, we have to increment R3, and so on.
Incrementation by one is done with the instruction INC. If an overflow occurs during that execution of INC R1 the zero bit in the status register is set to one (the result of the operation is zero). The carry bit in the status register, usually set by overflows, is not changed during an INC. This is not to confuse the beginner, but carry is used for other purposes instead. The Zero-Bit or Zero-flag in this case is enough to detect an overflow. If no overflow occurs we can just leave the counting sequence.
If the Zero-bit is set, we must execute additional incrementation of the other registers.To confuse the beginner the branching command, that we have to use, is not named BRNZ but BRNE (BRanch if Not Equal). A matter of taste ...
The whole count sequence of the 32-bit-counter should then look like this:
INC R1
BRNE GoOn32 INC R2
BRNE GoOn32 INC R3
BRNE GoOn32 INC R4
GoOn32:
So that's about it. An easy thing. The opposite condition to BRNE is BREQ or BRanch EQual.
Which of the status bits, also called processor flags, are changed during execution of a command is listed in instruction code tables, see the List of Instructions. Similiarly to the Zero-bit you can use the other status bits like that:
BRCC label/BRCS label; Carry-flag 0 oder 1 BRSH label; Equal or greater
BRLO label; Smaller BRMI label; Minus BRPL label; Plus
BRGE label; Greater or equal (with sign bit) BRLT label; Smaller (with sign bit)
BRHC label/BRHS label; Half overflow flag 0 or 1 BRTC label/BRTS label; T-Bit 0 or 1
BRVC label/BRVS label; Two's complement flag 0 or 1 BRIE label/BRID label; Interrupt enabled or disabled
to react to the different conditions. Branching always occurs if the condition is met. Don't be afraid, most of these commands are rarely used. For the beginner only Zero and Carry are relevant.
Timing during program execution
Like mentioned above the required time to execute one instruction is equal to the processor's clock cycle. If the processor runs on a 4 MHz clock frequency then one instruction requires 1/4 µs or 250 ns, at 10 MHz clock only 100 ns. The required time is as exact as the xtal clock. If you need exact timing an AVR is the optimal solution for your problem. Note that there are a few commands that require two or more cycles, e.g. the branching instructions (if branching occurs) or the SRAM read/write sequence. See the instruction table for details.
To define exact timing there must be an opportunity that does nothing else than delay program execution.
Avr-Asm-Tutorial |
21 |
http://www.avr-asm-tutorial.net |
You might use other instructions that do nothing, but more clever is the use of the NO Operation command NOP. This is the most useless instruction:
NOP
This instruction does nothing but wasting processor time. At 4 MHz clock we need just four of these instructions to waste 1 µs. No other hidden meanings here on the NOP instruction. For a signal generator with 1 kHz we don't need to add 4000 such instructions to our source code, but we use a software counter and some branching instructions. With these we construct a loop that executes for a certain number of times and are exactly delayed. A counter could be a 8-bit-register that is decremented with the DEC instruction, e.g. like this:
CLR R1
Count:
DEC R1 BRNE Count
16-bit counting can also be used to delay exactly, like this
LDI ZH,HIGH(65535)
LDI ZL,LOW(65535)
Count:
SBIW ZL,1
BRNE Count
If you use more registers to construct nested counters you can reach any delay. And the delay is absolutely exact, even without a hardware timer.
Macros and program execution
Very often you have to write identical or similiar code sequences on different occasions in your source code. If you don't want to write it once and jump to it via a subroutine call you can use a macro to avoid getting tired writing the same sequence several times. Macros are code sequences, designed and tested once, and inserted into the code by its macro name. As an example we assume we need to delay program execution several times by 1 µs at 4 MHz clock. Then we define a macro somewhere in the source:
.MACRO Delay1 NOP NOP NOP NOP
.ENDMACRO
This definition of the macro does not yet produce any code, it is silent. Code is produced if you call that macro by its name:
[...] somewhere in the source code Delay1
[...] code goes on here
This results in four NOP incstructions inserted to the code at that location. An additional Delay1 inserts additional four NOP instructions.
By calling a macro by its name you can add some parameters to manipulate the produced code. But this is more than a beginner has to know about macros.
If your macro has longer code sequences, or if you are short in code storage space, you should avoid the use of macros and use subroutines instead.
Subroutines
In contrary to macros a subroutine does save program storage space. The respective sequence is only once stored in the code and is called from whatever part of the code. To ensure continued execution of the sequence following the subroutine call you need to return to the caller. For a delay of 10 cycles you need to write this subroutine:
Delay10: NOP NOP NOP RET
Subroutines always start with a label, otherwise you would not be able to jump to it, here Delay10:. Three NOPs follow and a RET instruction. If you count the necessary cycles you just find 7 cycles (3 for the NOPs, 4 for the RET). The missing 3 are for calling that routine:
[...] somewhere in the source code: RCALL Delay10
[...] further on with the source code
Avr-Asm-Tutorial |
22 |
http://www.avr-asm-tutorial.net |
RCALL is a relative call. The call is coded as relative jump, the relative distance from the calling routine to the subroutine is calculated by the compiler. The RET instruction jumps back to the calling routine. Note that before you use subroutine calls you must set the stackpointer (see Stack), because the return address must be packed on the stack by the RCALL instruction.
If you want to jump directly to somewhere else in the code you have to use the jump instruction:
[...] somewhere in the source code RJMP Delay10
Return:
[...] further on with source code
The routine that you jumped to can not use the RET command in that case. To return back to the calling location in the source requires to add another label and the called routine to jump back to this label. Jumping like this is not like calling a subroutine because you can't call this routine from different locations in the code.
RCALL and RJMP are unconditioned branches. To jump to another location, depending on some condition, you have to combine these with branching instructions. Conditioned calling of a subroutine can best be done with the following commands. If you want to call a subroutine depending on a certain bit in a register use the following sequence:
SBRC R1,7 ; Skip the next instruction if bit 7 is 0 RCALL UpLabel ; Call that subroutine
SBRC reads „Skip next instruction if Bit 7 in Register R1 is Clear(Zero)“. The RCALL instruction to UpLabel: is only executed if bit 7 in register R1 is 1, because the next instruction is skipped if it would be 0. If you like to call the subroutine in case this bit is 0 then you use the corresponding instruction SBRS. The instruction following SBRS/SBRC can be a single word or double word instruction, the processor knows how far he has to jump over it. Note that execution times are different then. To jump over more than one following instruction these commands cannot be used.
If you have to skip an instruction if two registers have the same value you can use the following exotic instruction
CPSE R1,R2 ; Compare R1 and R2, skip if equal RCALL SomeSubroutine ; Call SomeSubroutine
A rarely used command, forget it for the beginning. If you like to skip the following instruction depending on a certain bit in a port use the following instructions SBIC und SBIS. That reads Skip if the Bit in I/o space is Clear (or Set), like this:
SBIC PINB,0 ; Skip if Bit 0 on port B is 0 RJMP ATarget ; Jump to the label ATarget
The RJMP-instruction is only executed if bit 0 in port B is high. This is something confusing for the beginner. The access to the port bits is limited to the lower half of ports, the upper 32 ports are not usable here.
Now, another exotic application for the expert. Skip this if you are a beginner. Assume we have a bit switch with 4 switches connected to port B. Depending on the state of these 4 bits we would like to jump to 16 different locations in the code. Now we can read the port and use several branching instructions to find out, where we have to jump to today. As alternative you can write a table holding the 16 addresses, like this:
MyTab:
RJMP Routine1
RJMP Routine2 [...]
RJMP Routine16
In our code we copy that adress of the table to the Z pointer register:
LDI ZH,HIGH(MyTab)
LDI ZL,LOW(MyTab)
and add the current state of the port B (in R16) to this address.
ADD ZL,R16 BRCC NoOverflow INC ZH
NoOverflow:
Now we can jump to this location in the table, either for calling a subroutine:
ICALL
or as a jump with no way back:
IJMP
The processor loads the content of the Z register pair into its program counter and continues operation there. More clever than branching over and over?