TKT-3500 Microcontroller systems Lec 6 – Reset, From C to assembly Ville Kaseva Department of Computer Systems Tampere University of Technology Fall 2010 Copyright Tampere University of Technology Department of Computer Systems
TKT-3500
Microcontroller
systems
Lec 6 – Reset, From C to assembly
Ville Kaseva
Department of Computer Systems
Tampere University of Technology
Fall 2010
Copyright Tampere University of Technology Department of Computer Systems
#2/60
Sources
Original slides by Erno Salminen
Robert Reese, Microprocessors: From Assembly
to C with the PIC18Fxx2, Charles River Media,
2005
Thanks also to Heikki Orsila, Mauri Kuorilehto,
Teemu Laukkarinen
Copyright Tampere University of Technology Department of Computer Systems
#3/60
Contents
Compilation, linking
Data endianness in memory
Reset and program bootup
Purpose
Sources, power-on reset circuits
Timing
C and corresponding assembly
Conditions
Looping
Copyright Tampere University of Technology Department of Computer Systems
#4/60
C in embedded systems
Copyright Tampere University of Technology Department of Computer Systems
#5/60
”Kääntäjät voipi olla kohtuullista kuraa, mutta silti ei kannata hirveemmin lähteä "optimoimaan" käsin ellei oo
pakko” – wisdom from industry
Copyright Tampere University of Technology Department of Computer Systems
#6/60 Copyright Tampere University of Technology Department of Computer Systems
#7/60
A simple C program
#define avalue 100
unsigned char i,j,k;
main(void) {
i = avalue; /* avalue = 100 */
i = i + 1; /* i++, i = 101 */
j = i; /* j is also 101 */
j = j - 1; /* j--, j is 100 */
k = j + i; /* k = 201 */
}
Copyright Tampere University of Technology Department of Computer Systems
#8/60
A simple C program (2)
Variables can be in any
general-purpose RAM location:
Selected here:
Copyright Tampere University of Technology Department of Computer Systems
#9/60
Simple C program in assembly
INCLUDE "p18f242.inc"
; C Program equivalent
; #define avalue 100
; unsigned char i,j,k;
;
; i = avalue; /* avalue = 100 */
; i = i + 1; /* i++, i = 101 */
; j = i; /* j is 101 */
; j = j - 1; /* j--, j is 100 */
; k = j + i; /* k = 201 */
; Register Usage
; start at location 0 in data memory
; reserve space for 3 byte variables
CBLOCK 0x000
i, j,k
ENDC
avalue equ D'100'
ORG 0
goto main
;; reserved space between 0x0-0x1FF
;; for interrupt use
org 0x0200
main
; i = avalue;
movlw avalue ; w <- 100
movwf i ; i <- w;
; i = i + 1;
incf i,f ; i <- i + 1
; j = i
movf i,w ; w <- i
movwf j ; j <- w
; j = j - 1;
decf j,f ; j <- j - 1
; k = j + i
movf i,w ; w <- i
addwf j,w ; w <- w + j
movwf k ; k <- w
here
goto here ; loop forever
end
Copyright Tampere University of Technology Department of Computer Systems
#10/60
Simple C program in machine code
address machine code mnemonic
0000 EF00 GOTO 0x200
0002 F001 NOP
...
0200 0E64 MOVLW 0x64
0202 6E00 MOVWF 0, ACCESS
0204 2A00 INCF 0, F, ACCESS
0206 5000 MOVF 0, W, ACCESS
0208 6E01 MOVWF 0x1, ACCESS
020A 0601 DECF 0x1, F, ACCESS
020C 5000 MOVF 0, W, ACCESS
020E 2401 ADDWF 0x1, W, ACCESS
0210 6E02 MOVWF 0x2, ACCESS
0212 EF09 GOTO 0x212
0214 F001 NOP
0216 FFFF NOP
Copyright Tampere University of Technology Department of Computer Systems
#11/60
Compilation of a program
Compilation is straightforward when only one input line is considered at a time These examples make assume such simple transformation
Expert assembly hackers and optimizing compilers may consider multiple lines (statements)
Each C line may take several lines in assembly
Assembly can be inlined into C Place asm code between _asm + _endasm
Optimization may be performed also on the produced assembly object file
Debug information may be part of object file For example, source code appears as comments
Some object files use absolute addressing reset and interrupt vectors are common examples
designer must take care to avoid overlap
Copyright Tampere University of Technology Department of Computer Systems
#12/60
Compilation of a program (2)
Object files can also be relocatable They can be stored in any memory address
Compiler does not decide in which addressvariables or functions are stored -> Symbols areused instead
Exact locations will be defined by the linker whichchanges the symbols to absolute memoryaddresses
Assembler produces machine code from asm
Linker combines compiled code modulestogether User tells where to store code and variables
Some modules are built-in libraries (stdio.h) and some user-defined code (radio.h etc.)
Copyright Tampere University of Technology Department of Computer Systems
#13/60
Object code sections
1. code (aka text) segment - read-only (rodata) machine instructions and constants (incl. strings)
2. data - read/write (rwdata) global variables initialized by programmer
3. bss (block started by symbol) - read/write (rwdata) Uninitialized global variables (can be initialized to zero by
compiler)
Compiler-generated initilization function setsdata and bss
Remember that memory for local variables is reservedruntime from the stack
Sometimes data, BSS, and heap areas are collectively referred to as the "data segment“
Try gcc –Wall -O2 –S foo.c (-S -> Compile only do notassemble or link)
Copyright Tampere University of Technology Department of Computer Systems
#14/60
Program relocation phases during linking
1. Merge all sections of similar type into a single
section of that type
2. Linker then assigns runtime addresses to each
section and each symbol
At this point, the code (functions) and data (global
variables) will have unique runtime addresses
3. References to symbols are modified so that they
point to the correct runtime addresses
Replace logical symbol name with its real address
4. Linker produces symbol table that shows where the
symbols were located
Copyright Tampere University of Technology Department of Computer Systems
#15/60
Data endianness in memory
Copyright Tampere University of Technology Department of Computer Systems
#16/60
Data location with PIC
Arrays larger than 256 bytes need special attention dueto banked memory Linker script must reserve space for the array
array is defined like this (where buffer_scn is reserved in the linker script)
#pragma udata buffer_scn
static char large_buffer[0x180];
#pragma udata
Accesses to the object must be done via a pointer:char * buf_ptr = &large_buffer[0];
if (large_buffer [3] > 0)... // illegal!
// examples of legal use
buf_ptr[5] = 10;
if (buf_ptr[275] > 127)...
Detailed instrcutions at FAQ-10 http://ww1.microchip.com/downloads/en/DeviceDoc/MPLAB_C18_Getting_Started_51295f.pdf
Copyright Tampere University of Technology Department of Computer Systems
#17/60
Data location with PIC (2)
Constants are placed into data memory by default
Limited amount of data mem available
Contents are lost in power-down
Data can be placed into code memory using specifierrom far
e.g. uint8_t rom far data_array[128];
pointer to that data must defined also with specifier rom
Code memory contents cannot be directly updated
1. copy to data memory
2. modify data
3. copy back to code memory
Copyright Tampere University of Technology Department of Computer Systems
#18/60
Endianness – Byte ordering
Some architectures store integers in big endianorder (also called network byte order), others have little endian order
Differ in what is stored into the smallest byte address (word address + 0) big = most significant byte
little = least significant byte
This makes no difference when addressed via int or int* variables Using char* may cause problems
Endiannes can also mean bit ordering (dependson context) – Examples concetrate on byteordering but the same rules apply to bit orderingalso
Copyright Tampere University of Technology Department of Computer Systems
#19/60
Endianness – Byte ordering(2)
Pay attention when copying data bytewise/bitwise
To/from peripheral
To/from I/O bus
They have ”equally good” performance in practice
MSB B2 B1 LSB
LSB B1 B2 MSB
little-endian mem location
big-endian memory location
byte index
0123
Copyright Tampere University of Technology Department of Computer Systems
little-endian vs. big-endian
byte ordering
#20/60
Endianness – Byte ordering (3)
int huippu = 0xacdc;
int nojoo =0xabba;
char ankarin[] =”Slayer”;
char *cptr = (char*) &huippu; //now things get interesting...
Little endian Big endian
Left-to-right
Right-to-left
ac dc
1 0
0x2000 ab ba
3 2
0x2004 reya
0x2008 lS??
dc ac
1 0
0x2000 ba ab
3 2
0x2004 Slay
0x2008 er??
ba ab
2 3
0x2000 dc ac
0 1
0x2004 ayer
0x2008 ??Sl
ab ba
2 3
0x2000 ac dc
0 1
0x2004 yalS
0x2008 ??re
Byte offsetByte offset
Word
addressWord
address
Byte offset
numbering
order in
figure:
EndiannessCopyright Tampere University of Technology Department of Computer Systems
#21/60
System reset and program bootup
Copyright Tampere University of Technology Department of Computer Systems
#22/60
Reset
Reset forces the CPU into known statea) When the system is powered up
b) When things have gone horribly wrong
Program counter gets certain value, e.g. 0x0, and program execution restarts
Many possible sources, e.g. external: reset pin connected to button
internal: brown-out detection or watchdog
internal: stack overflow or underflow
Reset behavior can be vectorized Vector tells what to do next (where to jump)
Copyright Tampere University of Technology Department of Computer Systems
#23/60
Reset vector
Located in default memory location (address)
where the CPU starts execution after reset
That address contains a pointer (address) of
where to continue
e.g. it points to the first instruction of main(argc, argv) or compiler generated init
function
main: mov r1,0
program
counter
(PC)
2. 0x0
0x70
GOTO 0x70
0x72 mov r2,5
...
3.
4.
(program) memory
1. External reset pin driven low
2. After reset, PC ← 0x000
3. PC ← mem[0x000]
1. i.e. PC ← 0x70
4. PC ← mem0x72
XMCLR#
1.
Copyright Tampere University of Technology Department of Computer Systems
#24/60
Brown-out and watchdog as reset sources
Brown-out detection (BOD)
Detects partial loss of electricity, Vdd drops below certain
threshold
compare to black-out = total loss of electricity
Resets the CPU to avoid corrupting the memory contents
Watchdog
HW timer that triggers a system reset if the main program,
due to some fault condition neglects to regularly service the
watchdog
Writing a service pulse to it, aka “petting the dog” or “kicking
the dog"
E.g. when main is stuck into infinite loop, communication
caused deadlock (circular wait condition)
Can wakeup the CPU from low-power sleep mode
Copyright Tampere University of Technology Department of Computer Systems
#25/60
Reset sources in PIC18
Oscillator start-up timer
delays the release of reset
so that oscillator stabilizes
Schmitt trigger-
hysteresis provides
noise immunity
Watchdog timer – the dog
must be kept happy regularly
Power-up timer waits that
power source is stabilized
master clear – ext.
reset pin
Supply voltage is
also monitored
Copyright Tampere University of Technology Department of Computer Systems
Reset is high when S = 0
and R = 1
#26/60
Reset circuitry – 3 basic choices
i. External Power-on Reset (POR) rises accroding to RC constant of the circuit -> Needed if Vdd rises slow
(else Internal POR can be used)
ensure that device operating conditions are met (e.g. stable voltage) beforereset released
ii. External POR+ discharge diode fast switching of Vdd could leave capacitor charged and PIC would not be
reset -> diode helps discharge the capacitor quickly in power down
Rs protects CPU by limiting current into pin MCLR
iii. User reset button mandatory in prototypes
R limits short-circuit current, R [10, 100k] Ω
PIC
MCLR
PIC
MCLR
PIC
MCLR
Vdd
GND
R
C
R
C
Rs
i) power-on reset ii) power-on reset +
discharge diode
iii) user reset button
R
Copyright Tampere University of Technology Department of Computer Systems
#27/60
Schmitt trigger at reset input
Special buffer for inputs
Does not change state when input changes only a little Phenomenon is called hysteresis
Also transforms slowly changing signals into sharp ones (fast rise/fall times)
input output
Vin
Vout
Vin
Vin
Vout
Vout
TTL input
Schmitt
trigger
1.0 V 4.0 V
Vdd=5 V
0.8 V 2.0 V
thresholdLH
t
t
thresholdHL
1. Schematic symbol 2. Vout output changes only
when Vin goes beyond
threshold voltage
3. Voltage transfer curves for basic
TTL and Scmitt
Vdd=5 V
Copyright Tampere University of Technology Department of Computer Systems
#28/60
Internal Power-on-reset (POR) timing
Power-up timer has own clock – time-out
TPWRT occurs usually after 72 ms
Oscillator timer’s time-out TOST occurs after
1024 (master) clk cycles
Vdd
MCLR
internal POR
PWRT time-out
OST time-out
internal reset
TPWRT
TOST
Copyright Tampere University of Technology Department of Computer Systems
MCLR tied to Vdd
Power-up timer waits that
power source is stabilized
Oscillator timer waits that
oscillator is stabilized
#29/60
Finding out the reset source from SW
RCON register contains status bits that
indicate the reset type
Next actions can be selected accordingly
C language has special type qualifierpersistent
prevents variable from being initialized by start-up
code prior to main()
can be used for logging reset sources and to
count them (if reset occurs due to power down
persistent does not work -> EEPROM needed)persistent char reset_cnt; /* global variable*/
void main () {...
Copyright Tampere University of Technology Department of Computer Systems
#30/60
Program bootup
Linked executable image is copied into non-
volatile memory (Flash)
Contains .code and .data sections
Initialization function prepares the
microcontroller
aka. boot(strap) loader
Knows the size and location of .bss
Sets initial values for global variables:
1. copies user-defined initial values from Flash
2. writes zeros to .bss
After that execution jumps to main()
Copyright Tampere University of Technology Department of Computer Systems
#31/60
Program bootup (2)
1. Set the CPU mode (buses, interrupts, stack...)
2. Set stack pointers
3. Copy contents .data to to work memory
4. Write zeros to .bss section
5. Optionally, also the .code can be copied to different
memory for faster execution
Especially interrupt vector if not all
Flash SRAM SDRAM
CPU (+ cache)
image .data .bss code
Example boot:
stack
3.
4.
1. config reg
2. 5.0.
Copyright Tampere University of Technology Department of Computer Systems
#32/60
From C to assembly
Copyright Tampere University of Technology Department of Computer Systems
#33/60
About following examples
These examples highlight the relation between C
statements and PIC assembly
Examples from R. Reeses slides
http://www.ece.msstate.edu/courses/ece3724/
Actually they use PIC24 assembly
Nevertheless, principles apply to PIC18 as well (or any
CPU)
1. Conditions
if-else: non-zero, equality, larger than
switch-case, if-else with two or more conditions
2. Loops
while, for
loop unrolling, HW-support for loops
Copyright Tampere University of Technology Department of Computer Systems
#34/60
Conditions in C and assembly
Copyright Tampere University of Technology Department of Computer Systems
#35/60 Copyright Tampere University of Technology Department of Computer Systems
#36/60
Processor status flags
Copyright Tampere University of Technology Department of Computer Systems
Negative (N) flag tells if the
result was negative
#37/60 Copyright Tampere University of Technology Department of Computer Systems
#38/60
SR = status register
Z= zero flag
btsc =Bit Test – Skip if Clear
Copyright Tampere University of Technology Department of Computer Systems
#39/60 Copyright Tampere University of Technology Department of Computer Systems
#40/60 Copyright Tampere University of Technology Department of Computer Systems
In PIC24 W0 and WREG
mean the same register
#41/60
#42/60
C= carry flag
Copyright Tampere University of Technology Department of Computer Systems
#43/60 Copyright Tampere University of Technology Department of Computer Systems
#44/60
#45/60 Copyright Tampere University of Technology Department of Computer Systems
#46/60 Copyright Tampere University of Technology Department of Computer Systems
#47/60 Copyright Tampere University of Technology Department of Computer Systems
#48/60 Copyright Tampere University of Technology Department of Computer Systems
#49/60 Copyright Tampere University of Technology Department of Computer Systems
#50/60 Copyright Tampere University of Technology Department of Computer Systems
#51/60 Copyright Tampere University of Technology Department of Computer Systems
#52/60 Copyright Tampere University of Technology Department of Computer Systems
#53/60
Reminder
Copyright Tampere University of Technology Department of Computer Systems
#54/60
Loop structures in C and assembly
Copyright Tampere University of Technology Department of Computer Systems
#55/60 Copyright Tampere University of Technology Department of Computer Systems
#56/60 Copyright Tampere University of Technology Department of Computer Systems
#57/60 Copyright Tampere University of Technology Department of Computer Systems
#58/60
Loop Unrolling
With small loop body, control instructions cause
notable overhead
index increment/decrement, comparison, branch
Loops can be unrolled when bounds are known
aka. loop unwinding
Execute loop body 2/3/4... times per iteration
Many data-flow applications, such as filtering,
execute always the same number of iterations
for (i=0; i < 99; i++){
sum += a[i];
}
for (i=0; i < 99; i+=2){
sum += a[i];
sum += a[i+1];
sum += a[i++]; //aargh
}
for (i=0; i < 49; i++){
sum += a[i];
sum += a[i+50];
}
Original loop Loop unrolled twice Another way to unroll twice
Copyright Tampere University of Technology Department of Computer Systems
#59/60
Loop Unrolling (2)
Trade-off between contradicting
consequences because unrolling
1. Increases performance
Less overhead from branching
2. Increases code size and makes
maintenance bit more tedious due to poorer
readability
Unrolled loop may be followed by tail that
performs the last iterations1. for i=0:99 {body} // 100 iterations
2. for i=0:33 {body;body;body}; body // 3*33 +1
Copyright Tampere University of Technology Department of Computer Systems
#60/60
HW looping support
Some digital signal processor (DSP) families support looping with special hardware
Zero overhead from branching
Programmer sets special registers1. address of the 1st instruction in loop body
2. address of the last instruction in loop body
3. number of iterations
Of course, these cause small but constant overhead E.g. 3 instructions per 1M iterations
Copyright Tampere University of Technology Department of Computer Systems