tkt-3500 microcontroller systems microcontroller systems lec 1 ... platform for exercises:...
TRANSCRIPT
TKT-3500
Microcontroller
systems
Lec 1 – Introduction to
Microcontrollers, Basics of debugging
Ville Kaseva
Department of Computer Systems
Tampere University of Technology
Fall 2009
#2/69
Copyright notice
Course slides originally prepared by
Erno Salminen
Part of the slides
adapted from slide set EE1A2 PIC Course by
Sandra I. Woolley, Univ. Birmingham
based on [B. Colwell, The power of most likely,
Computer, Vol. 35, Iss. 10, Oct. 2002, pp.12 –
14]
#3/69
Contents
What and where are microcontrollers
Basic features of microcontrollers
Embedded systems
Commercial microcontrollers, e.g. PIC-family
Platform for exercises: Multisensor node
Key components
Debugging: The power of most likely
#4/69
Microcontroller
Merriam-Webster dictionary:
microcontroller [\mī-krō\\-kən-trō-lər\ ]
Function: noun, Date: 1971
a microprocessor that controls some or all of
the functions of an electronic device (as a
home appliance) or system
micro - very small
controller - one that controls or has power or authority to control
control - to exercise restraining or directing influence over
#5/69
Microcontroller (2)
Microcontrollers are used in automatically controlled products and devices such as automobile engine control systems,
remote controls, office machines, appliances, power tools, and toys
i.e. in embedded systems
Microcontroller chip includes, for example an integrated microprocessor
memories (RAM, Flash, EEPROM etc.)
input and output peripherals
timers, event counters, PWM generators etc.
clock generator
many include analog-to-digital converters
in-circuit programming and debugging support
A PIC 18F8720
microcontroller in an
80-pin TQFP package.
#6/69
Microcontroller (2)
It emphasizes high integration, in contrast to
a microprocessor which only contains a CPU
(and cache)
functional computer system-on-a-chip
Difference between uproc and ukontr is blur
Modest processing capability
Adequate for simple control applications
Usually not meant for heavy number crunching
Low power consumption
Cheap unit price, high volumes
Programmable devices
#7/69
Classification of microprocessors
Number of bits 4,8,16,32,64...
Number of instructionsa) RISC (Reduced instruction-set computer)
b) CISC (Complex instruction-set computer) ASIP (Application-specific instruction-set processor)
Memory spacea) von Neumann – same for instr. and data
b) Harvard – separate addr spaces
Data path – where are the operandsa) Stack
b) Accumulator
c) Register-memory
d) Register-register (so called load-store)
Integrated peripherals, pipelining, num of ALUs...
#8/69
Where are the processors [Tennenhouse00]
Interactive 2% denotes PCs and
servers
98% of CPUs are elsewhere
Portable devices (cell phones
etc) have spread after 2000
[Tennenhouse, D. 2000. Proactive computing.
Commun. ACM 43, 5 (May. 2000), 43-50]
#9/69
What are embedded systems
#10/69
Embedded systems (1)
Application specific electronic sub-system used in a larger system such as an appliance, an instrument or a vehicle
Not User-Programmable
System needs to implement only a limited function whose characteristics are known at design time
The design can take advantage of the specification’s characteristics in ways that general-purpose computing systems cannot
Targeting certain performance level instead of maximum
Based on both hardwired and programmable components e.g. CPU, DSP, custom HW
#11/69
Embedded systems (2)
Fig: [Pinello, TVLSI08]
Hardware/Software co-design required
Resemble distributed systems multiple tasks are running on multiple processing
elements (PE)
interprocess communication and synchronization critical
Are subject to external timing constraints Hard real-time – missed deadlines are fatal
e.g. ABS brakes, safety system of nuclear plant
Soft real-time – missed deadlines cause degraded quality or inconvenience e.g. video frames are dropped
#12/69
Embedded systems (3)
Reactive Real-Time Systems
Continuous interaction with external
environment
Ideally never terminate
while (1) {
read the sensors
control the actuators
sleep()
}
Where would execution
go after main()?
#13/69
Examples of embedded systems
asdcar
digital
camera
mobile phone
harvester
robot
Figures from Wikipedia
network router
elevator
washing
machine
PDA
game console
printer medical
equipment
microwave oven
factory automation
#14/69
Commercial microcontrollers, especially
PIC
#15/69
Example microcontrollers
Atmel AVR 8- ja 32-bit RISC families
Over 80 models
Texas Instruments (TI) MSP430 – low power
TMS320 – high performance
TMS470 – ARM7-based
Renesas SuperH – High speed / performance
MR32 – 32-bit
H8 – low cost
ST microelectronics
And many others...
#16/69
PIC microcontrollers
Designed and sold by Microchip Corporation
http://www.microchip.com
PIC = initially Programmable Interface
Controller
then Programmable Intelligent Computer
Many configurations of 8-, 16- and 32-
microcontrollers
8-bit volume prices ~2$-12$
Minimalist basic ideology
#17/69
8-bit PIC Families
8-bit stands for width of data path
PIC10 (and some PIC12 and PIC16)
Baseline architecture, 12-bit program word
16-134 Bytes of SRAM
256- 2K Bytes of flash program memory
4-32 IO-Pins, 2 level deep stack
PIC12 and PIC16
Midrange architecture, 14-bit program word
64-368 Bytes of SRAM
1 -8 kBytes of flash program memory
6-53 IO-pins, 8 level deep stack
Images: www.microchip.com
#18/69
PIC18 family
High-tech 8-bit architecture, program word
16-bit
256 bytes – 4kBytes of SRAM
4-128 kBytes of program memory
15-70 GPIO-pins
Plenty of peripherals, for example:
USB, Ethernet, LCD,CAN
75 instuctions (some models have 83)
31 level deep stack
#19/69
PIC18LF8722
Used on this course
Symbol L stands for Low Power - Operating
voltage 2-5.5 V,
normally 4.2-5.5 V
F for Flash memory (?)
Accumulator machine
Accumulator= special register for storing results
Makes assembly and high level compiler writing
complicated
W-register= ALU’s working register (WREG)
Many operations can be done only in W-register
#20/69
PIC vs. Pentium roughly speaking
PIC
8-bit
1-50 MHz
5 mW
6 €
10-80 pins
Harvard arch.
1-10 MIPS
Few instructions
Accumulator
1 instr/4 cycles
no pipeline or very short
Pentium4
32-bit, 64-bit
2-4 GHz
150 W
150 €
~1000 pins
von Neumann arch.
60 000 MIPS
Zillions of instructions
Register bank, Superscalar/EPIC
Deeply Pipelined
#21/69
Platform for exercises –
Multisensor sensor network
node
#22/69
TUT Wireless Sensor Network (TUTWSN)
Very large research project in TUT/DCS since 2002
Sensor networks are emerging technology where the network consists of nodes that measure (‖sense‖) the
environment
communicate autonomously and wireleslly
self-organizing topology
may control actuators
Special courses TKT-2300 and TKT-2456
#23/69
TUTWSN Nodes
Multisensor node
Includes many sensors
Used in TKT-3500
Other nodes
Pipe Node
Long range pipe node
Badge node
Wrist node
Ethernet gateway
http://www.tkt.cs.tut.fi/research/
daci/ra_tutwsn_prototypes.html
#24/69
TUTWSN Multisensor node
#25/69
TUTWSN Multisensor node
#26/69
TUTWSN Multisensor node
Microcontroller: PIC18LF8722
256 kbyte external SRAM
Sensors and modules
GPS (Global Positioning System)
Radio
Temperature
Humidity
Accelerometer
Compass
Luminance
#27/69
TUTWSN Multisensor node
Add-on modules (not connected)
PIR (passive infrared, motion detector)
VGA Camera
Microphone
Interface
1 Pushbutton, 1 led
Input/Output
RS-232 serial port
MAX3226E is used to convert voltage levels
SPI (Serial peripheral interface), I2C
4 input/output pins
ADC (analog-to-digital converter)
#28/69
Power control
Possible power sources
a) DC power supply
b) 2 AA Batteries
c) Solar panel
All sensors can be turned off by uC
Voltage after regulation: 3 V/2 V and 2,7 V
2.7 V is used for GPS, 3V/2V (software
selectable) for other devices
#29/69
PIC18LF8722
8 bit RISC microcontroller with Harvard
architecture
High End 8-bit microcontroller
Accumulator…
Assembly programming complicated
128 kB program memory, 4 kB SRAM, 1kB
EEPROM
Operating voltage: 2.0 – 5.5 V
Max. Power dissipation 1 W
Min. Power dissipation (@1 Mhz): 3 mW
Compare: Normal red led 2V and max 20 mA
Image: www.futurlec.com
#30/69
PIC18LF8722
Plenty of peripherals
SPI, i2c, USART
16 channel 10-bit AD-converter
5 timers and capture/compare/PWM module
HW 8-bit multiplier
Watchdog, Brown-out
Max. Frequency: 40 Mhz
Many power management modes
Clock sources on platform:
Low frequency external clock
Internal clock
#31/69
C18 compiler and Programming
Microchip’s C-compiler for PIC18
microcontrollers
Not optimal but student version is free
Limitations in student version after 60 days:
No optimiztions
Processor works only in normal mode (77 instructions)
Microchip ICD2 - In-Circuit Debugger
Includes 5V Power supply
Not used with TUTWSN nodes due to lower
voltages -> External voltage source needed
Works fine with MPLAB IDE
Image: www.microchip.com
#32/69
GPS: iTrax03-s+GeoHelix–S
Fasttrax iTrax03-s
Includes lots of functionality: only few
extra components needed
Communication: USART with NMEA
(National Marine Electronics Association)
messages
Operating voltage: 2.7 – 3.3 V
Max power dissipation 500 mW
Sarantel GeoHelix-S
Active GPS antenna
Operating voltage: 2-3.5 V
Typical current 15 mA
#33/69
Radio: nRF24L01
Operating voltage: 1.9 – 3.6 V
Frequency: 2.400 – 2.4835GHz
Communication: SPI
Fully automated packet handling
Current consumption:
Power down 900 nA
Standby 22 uA or 320 ua (Two standby modes)
Transmission < 11.3 mA, Reception < 12.3 mA
Range about 15-30 meters indoors
Antenna dependable
Image: www.nordicsemi.com
#34/69
Temperature Sensor Maxim DS620
Operating voltage: 1.7 – 3.5 V
Communication: i2c
Selectable resolution:
LSB 0.5°C, 0.25°C, 0.125°C or 0.0625°C
Conversion time depends on accuracy
10 bit 25 ms, 13 bit 200 ms
Continuos conversion and one shot modes
Image: www.maxim-ic.com
#35/69
Humidity: Sensirion SHT1x
Humidity AND temperature sensor
Operating voltage: 2.4 – 5.5 V
Communication: ‖almost i2c‖ Not compatible with standard i2c interface
Conversion times: 11 ms (8 bit)
210 ms (14 bit)
Accuracy: Humidity 2 %, temperature 0.3 °K
Current consumption: Sleep 0,3 uA, measuring 550 uA
#36/69
Accelerometer: VTI SCA3000
3D accelerometer
Operating voltage: 2.35 – 3.6 V
Communication: SPI
Modes:
Free fall detection
Motion detection
Normal mode
Current consumption 120 uA in active mode
Image: www.vti.fi
#37/69
Compass: Hitachi HM55B
Operating voltage: 4.8 – 5.2 V
Communication: SPI
Transmission length 4 bits (normal SPI 8 bits)
Current consumption: Sleep 1 uA, Measuring
9 mA
Measuring time 30 ms
Resolution: 11 bits
Measures magnetic field strength
Min. value -180 uT max. 180 uT
Image: www.parallax.com
#38/69
Luminance: Agilent APDS-9002
Photosensor: Luminance is relative to current
Operating voltage: 2.4 – 5.5 V
Connected to uC’s analog-to-digital converter
Resolution equals AD-converter’s resolution
10 bit in PIC18LF8722
Sample rate = ADC’s sample rate
In PIC user selectable, but depends on clock
frequency. About 1 Mhz is theoretical maximum
PIC’s AD-converter operates also in idle
mode
Completion of conversion can cause an interrupt
Image: www.farnell.com
#39/69
PIR MS300
PIR = Passive Infra Red
Connected to uC’s ADC, but needs an operating
voltage
Used as motion detector
Operating voltage: 2.6 V – 5.5 V
Current consumption: ~35 uA
#40/69
VGA C328
Max. 640x480 pixels, 16 bit
Frames/s depends on image quality
JPEG still picture with best quality 0.75 fps
Camera + compression module + EEPROM
No extra components needed
Connection: RS-232
JPEG picture format
Operating voltage: 3.0 – 3.6 V
Operation current: 60 mA
Suspend current: 100 uA
Image: www.electronics123.net
#41/69
Microphone AOM-6746P-R
Capacitor microphone
Omnidirectional
Picks up sound evenly from all directions
Connection: ADC
PIC18LF8722 has 16 ADC channels, but one converter
Image: www.farnell.com
Image: www.farnell.com
#42/69
Debugging
#43/69
Colwell, Power of most likely
―Unquestioned assumptions are by far the
biggest time-waster for system debuggers‖
The reason why the word ―arrgh!‖ was coined.
When a system malfunctions, the most likely
causes get attention first
Checking simple things first is a good policy,
as anyone who has ever wasted time on a
computer or peripheral only to find it wasn’t
plugged in can testify.
After checking the simple things, attitude
matters
#44/69
Colwell (2)
Technicians and engineers generally have
fundamentally different and complementary
attitudes, both valuable in their own contexts.
1. Techs often develop an intuitive sense for how the
system behaves when it is running properly
Several sanity checks before diving into more intellectual
analyses
E.g. is system running hotter than normal or that a
subcomponent was swapped out just prior to the
malfunction?
Technician mindset also seems to encourage a general
willingness to just try things, to see what happens
Techs know that ―kicking the tires‖ of an errant system will
often yield important clues to what’s wrong
#45/69
Colwell (3)
2. Design engineers don’t usually kick tires unless
they have precalibrated the exact kicking force and
point of impact—which obviates the whole
approach
DEs often approach a malfunctioning system with the
same mindset they used when designing it in the first
place.
They know where all the difficult corners the design are;
it’s their job know where the product margins slimmest
That very knowledge may lead them to first check the
design rather than the actual machine
Fixing a design flaw is more important than just
getting one machine working
#46/69
Debug rules [Colwell]
1. Change one thing at a time
2. Don’t ignore the unexpected
3. Follow the bug trail
4. Reduce complex phenomena to simple absolutes
5. Keep accurate lab notes
6. Debug is an immersion activity
7. Bugs almost never live alone
8. Test your test equipment
9. Know when you’re stuck, and call in the cavalry
#47/69
Debug rules (2)
1. Change one thing at a time
Otherwise you won’t know what caused the change in system’s behavior
Even if you’re chasing down a systems issue that requires an hour to set up, the temptation can be very strong to ―try a couple of things‖ per run.
1. Don’t do it.
2. Spend the hour trying to find a way to get the system to the malfunction point more quickly.
However, don’t make irreversible changes to the system during debug
2. Don’t ignore the unexpected
Investigate all suspicious behavior
#48/69
Debug rules (2)
3. Follow the bug trail
You need to follow the bug trail wherever it leads,
not just where you wish it would go
4. Reduce complex phenomena to simple
absolutes
Strip the system down to the simplest configuration
that still shows the problem
This reduces the number of possibilities to consider
when generating hypotheses about what could be
wrong and what to try next
Faster compilation, synthesis, simulation, analysis
etc.
#49/69
Debug rules (3)
5. Keep accurate lab notes1. What you’re doing
2. why you’re doing it
3. what should be the result
4. the results you get
This way you must focus more deeply in what you are doing
Others can refer to your notebook and leverage your work instead of unknowingly replicating it.
If you forget the details, it becomes a virtual certainty that a related bug will appear several months down the road, and it will be déjà vu—all over again.
#50/69
Debug rules (4)
6. Debug is an immersion activity
Allocate several hours
1. to set up a system run
2. to run the experiment,
3. to analyze the result
Don’t allow distractions.
If you are interrupted, you’ll probably have to
start over
This is one reason serious debug often happens
wee hours of the morning.
#51/69
Debug rules (5)
7. Bugs almost never live alone
Where you find one bug, there are often others
1. Other problems in the same module Remember that 20% of code modules cause
80% of faults
While you’re in the neighborhood,check for them
2. Similar problems elsewhere Check buffer overflows in all places when you
encounter one
Ensure that the ‖fix‖ does not break anything
#52/69
Debug rules (6)
8. Test your test equipment
check instruments against one another
9. Know when you’re stuck, and call in the cavalry
Some people just are good at finding errors When you run across these people in your
career, be nice to them:
1. Give them things
2. Bow down and chant―I’m not worthy‖ when they walk by
3. Bake them chocolate chip cookies
4. Whatever it takes, it’s worth it.
#53/69
Further reading
Jakob Engblom, Debugging real-time
multiprocessor systems: Part 1 -Programming
parallel machines and Part 2 - Debugging
Parallel Programs, Embedded.com, March
2006 http://www.embedded.com/columns/technicalinsights/183701679?_requestid=345393
#54/69 Erno Salminen - Nov. 2008
Version control
Use version control (Git, SVN, ...)
Teaches one to take logically consistent steps
in a project
Helps backup process
Easy throw-away code prototyping
Keeps track of your work (how many changes
in a week?)
Keeps track who did what
One can go back to see any previous version
A must for all work
#55/69
Conclusions
#56/69
At first
Make sure that
simple things work
before even trying
more complex onesHUOM! OBS!
Muy importante!
#57/69
Two great truths in design
1.If it's not tested,
it's broken
2.If it's not simple,
it's broken[M. Keating, ISQED, 2006]
#58/69
Conclusions
Microprocessors/controllers are used practically everywhere
High volume necessitates cheap price per device
This allows only modest performance
Controllers integrate several peripherals into same chip with processor
In embedded systems, designers target certain performance level, not for max. perf.
System is optimized (made maximally cheap) while still meeting the requirements
Programmability allows faster development and upgrades also after shipping
Connectivity of components is the key in many projects
Exercise platform integrates many sensors. Extremely good for educational purposes
Portability and shorter dev.time favor using high-level languages (C/C++) instead of assembly
#59/69
Extra slides
Reminder: microprocessor basics
#60/69
Stored program concept
Program’s instructions (control statements) are
stored in memory
In contrast to e.g. ASIC, in which the control is hard-wired
during manufacturing
CPU repeats fetch-execute cycle for every instruction
Originates from Turing machine (1936) that
manipulates data based on the instructions and state
of the machine
The behavior can be programmed
An universal machine – it can simulate the behavior of any
other machine
Theoretical concept that assumes infinite memory capacity
#61/69
Memory types
Every microprocessor needs some memory May be internal (on the same chip), external, or
combination
1. Instruction memory Stores the program’s inctructions
Non-volatile – keeps the information when powered off mask-programmed read-only memory (ROM)
(electronically) erasable programmable ROM (EEPROM/EPROM)
flash memory
2. Data memory Stores the program’s variables and status
Most parts volatile – contents lost when powered off static random access memory (SRAM), dynamic RAM
(DRAM)
Some parts may be non-volatile EEPROM, Flash, (in principle also hard-disk)
#62/69
Memories (2)
Memory type affects cost, speed, area, and power
consumption notably
E.g. SRAM is expensive, fast, area- and power consuming
technology
The program may be copied from non-volatile mem
to faster RAM during initalization
The same RAM may contain both program and data
sections as well (classical von Neumann architecture)
Whereas Harvard architecture separates program and data
address spaces
‖Memory is guilty until proven innocent‖ –
E.Salminen
= They cause lots of headache in embedded world
#63/69
Microprocessor Programming
A program is a set of instructions written in a specific sequence for a processor to accomplish specified tasks
An instruction is defined as a simple task (such as addition) performed by the microprocessor
To the microprocessor, instructions must be supplied in binary, i.e., as machine language
Instruction-set is processor-specific (PIC, x86, MIPS…)
Assembly language is a symbolic language which represents machine-language instructions with short human-readable mnemonics
For example, in PIC assembler a null operation or ‘no operation’is represented by the mnemonic ‘NOP’
One-to-one correspondence between the assembly language mnemonics and the machine code instructions
An assembler is a software tool that converts assembler source programs into machine language object files
#64/69
Machine and assembly languages are referred to as low-level languages Generally faster and more
compact than higher-level language programs
Not portable to other processors, tedious to write
High-level languages are machine-independent E.g. C/C++, Java
Program’s source codes are translated by compilers or interpreters into machine language
The translated code is called object code
Easier to debug and port
CPU+mem+etc
compiler
assembler
interpreter
de
sig
n-tim
eru
n-tim
e
.c, .h
.asm
.java
.hex
Microprocessor Programming(2)
#65/69
CPU’s instruction-set architecture (ISA)
Defines the supported machine-instructions
Defines size of instruction word and its fields Operation codes (ADD, SUB, JMP...)
Parameters (src0, src0, dst)
Whther params are in registers or in memory
Addressing types (direct, indirect...)
add/sub/
AND/XO
R/OR...
src0 src1 dst
instr type 1
instr type 2
add/sub/
AND/XO
R/OR...
src0
(also dst)
immediate
add reg0, reg5, reg3
i.e. reg3 ← reg0 + reg5
and reg0, 0x500
i.e. reg3 ← reg0 & 0x500
instr type 3jmp address goto Nevada
i.e. PC ← address of label Nevada
...
015 347811
#66/69
Micro-architecture
Defines the HW resources that implement ISA arithmetic-logic unit (ALU) performs the actual computation
control logic fetches the instructions, decodes them and passes to ALU
registers store temporary data
(optional) internal memories store instructions and/or data
memory and IO buses provide connection to outisde world
Peripherals perform supplementary tasks
There may be several micro-architectures for the same ISA
digital IO
instr. fetch ext. mem IO
instr. mem
data mem
instr. decode
oscillator
register filepipeline ctrl ALU
timer
power ctrl analog IO
watchdog
CPU
peripherals
micro-
controller
multiplier
#67/69
Clock cycle and Instruction cycle
Machine operations are sequenced by clock signal
Provided by external or internal oscillator (RC circuit, INV-
loop, quartz crystal)
Oscillator signal may multiplied/divided by constant (e.g. 10
MHZ * 4 = 40 MHZ)
Execution of machine instruction may take more than
one clock cycle
4 clock cycles/instr. in PIC
40 MHz clock yields approx. 10 MIPS
Some instructions take over 4 cycles, e.g. operations
affecting program counter (PC)
Some CPUs pipeline the execution of instructions
E.g. instr takes 4 cycles but the next finishes after 1 cycle
#68/69
Program flow
CPU executes instructions step by step
Instructions are executed consecutively (addresses
0x0, 0x2, 0x4) until
a) Branch occurs – if-then-else, function call, goto
b) Exception occurs – interrupt, div-by-zero
The address of the next instruction is stored into
register program counter (PC)
Interrupts are function calls made from HW
a) Timer overflow (e.g. 1ms passed)
b) Peripheral device (e.g. serial IO transmit completed)
c) External pin (e.g. from button or sensor)
Extremely useful concept
#69/69
Program flow (2)
After reset, PC gets the value of reset
vector
Usually rst vec points to some sort of
(ccompiler-generated) initialization
function that will call the user’s main
function
Call graph shows which functions are
called and their order (nesting)
Interrupt service routine (ISR) may be
called ‖anywhere‖
After that execution continues from the
interrupted point
init(){
...
main()}
main(){
...
foo()
...
while(1){}
foo() {
...
bar() ...
return
bar(){
...
return
isr() {
....
return from int}
0x0rst vec