Você está na página 1de 3

EMBEDDED SYSTEMS EXAM 2006

Q1.) There are 2 distinct categories of computer


system designated as re-programmable & embedded
systems. Describe the basic characteristics of each
type & give examples of their application.
Reprogrammable systems are designed for general
purpose computing in moderately controlled environ./
peripherals include humans (mice), communication
(modem), storage (disk)/controlled by powerful
operating system/hierarchical memory possible/ mainly
32-64 bit processors/ wide range of available software/
subject to evolutionary constraint due to heavy software
investment requiring upwards compatibility. Embedded
systems are designed primarily for industrial use,
system integration, consumer products/ designed to
interface easily with peripherals for data acquisition &
industrial control/ minimal operating system/
programmed once for life/ limited unsophisticated
memory/ variety of architecture available/ processor is
strongly I/O orientated/ many units are 4-8 bit based.
Q2.) Describe 2 ways of interrupt configuration on a
68HC11 which will support maintenance of elapsed
time or time of day & for 1 of these code or pseudo
for a service routine to update secs, mins & hrs as
necessary. Provide sufficient documentation &
declarations to ensure the code is readable.
2 interrupt facilities: Real Time Interrupt (RTI) &
Output compares (OC). For RTI, a limited choice of
interrupt periods is available. For OC, the user defines
the period in terms of the system clock cycles & often
this is chosen to fit in with time of day clock
functionality.
Interrupt update time {
Describe what is sec & when to change;
Describe what is min & when to change;
Describe what is hr & when to change; }
Set time zone {
Get the current hrs of the time;
Adjust for the new time zone;
Adjust for daylight saving time;
Save the new hrs of time; }
Q3.) Name one of the reference articles & author
specified during the course. Name the magazine
from which most are taken!
Magazine most taken from is Embedded Systems
Programming. Authors include Miro Samek (Dec
1997) and Integer Square Roots from Embedded
Systems Engineering by Jack Crenshaw (Feb 98).
Q4.) The use of interrupt facilities & sophisticated
peripheral subsystems in embedded
microcontrollers reduce the time critical aspects
which are important in many applications. Describe
1 peripheral subsystem which may be found in
embedded systems & discuss the most appropriate
type of interrupt facility & the advantages which
would accrue from the provision of interrupt
capabilities for this system.
The peripheral subsystem is the timer subsystem. The
interrupt configuration facility is OC. It is flexible as it
would be possible to limit the time of a certain task,
this would make sure the system was not waiting for a
task to complete indefinitely & could move on the next
task. It would also be possible to shutdown the system
after a certain time of inactivity or many other
situations. This is good since it wont affect the
interrupt.
Q5.) For any microprocessor other than the 68HC11
describe the basic processor configuration & give 1
example of a facility which distinguishes this
processor from its competition.
One example is the Intel 8051. This has a separate
program & data memories which cannot overlap in any
circumstance as it is a distinguishable property. The
first 32 bytes of RAM provide the register banks; the
next 16 provide a 128 bit addressable space.
Q6.) Describe with an example the concept of Finite
State Software (FSS) & its significance in the
development of embedded systems.
FSS deals with finite state. When developing the
embedded systems, there may only be a certain number
of states that need to be addressed. By using
appropriate variables, a table can be produced sharing
the different input combination & the resulting state.
This can help make the programmers job easy for
debugging as all input combinations are covered &
resulting states are known. Example: Finite input,
Finite output, with password COOL
Input/State 1 2 3 4
C fail-2 fail-1 fail-1 fail-1
L fail-1 fail-1 fail-1 success-1
O fail-1 fail-3 fail-4 fail-1
Q7.) (i) Describe the finite state machine
approach to software structuring. (ii) A system
represented by the state table is to be implemented
by software within an embedded system. Using your
preferred hi-level language, shown a corresponding
software implementation. If appropriate use
variables: input, output & state.
|Input |00 01 11 10 00 01 11 10
---------+--------+--------------------------------------
Coding | State | Output
00 | s1 |s1 s2 s2 s3 1 0 0 0
01 | s2 |s3 s2 s3 s3 0 0 0 0
11 | s3 |s1 s2 - s4 0 0 - 0
10 | s4 |s3 s1 s2 s4 0 0 0 0
(i) FSM in digital design is where it designs a basic
system which responds to changes to its inputs by
changing its internal states & updating its outputs. It
develops code through state charts & software
templates by using case.
(ii)
#define s1 0 #define s3 3
#define s2 1 #define s4 2
//define valid state_input combinations
#define s1_00 0x0000 #define s2_00 0x0100
#define s1_01 0x0001 #define s2_01 0x0101
#define s1_10 0x0002 #define s2_10 0x0102
#define s1_11 0x0003 #define s2_11 0x0103
#define s3_00 0x0300 #define s4_00 0x0200
#define s3_01 0x0301 #define s4_01 0x0201
#define s3_10 0x0302 #define s4_10 0x0202
#define s3_11 0x0303 #define s4_11 0x0203
#define ST_INP m.s_i //state & input combine
#def STATE m.byte.st //current Machine state
#define INPUT m.byte.inp //last input
Static union {
unsigned int s_i;
struct {
unsigned char inp; //input in LO order
unsigned char st; //state in HI order
} byte;
} m={s1_00} //initialise to state one
Newstate(char, input_char) {
INPUT = input_char;
switch (ST_INP) {
case s1_00:STATE=s1;return(1);break;
case s1_00:STATE=s2;break;
case s1_10:STATE=s2;break;

default:STATE=0;
}
return (0); }
Q8a.) Describe the basic facilities provided by the
timer subsystem of the 68HC11 peripheral
subsystem. In particular discuss the output compare
configuration functions provided & the associated
interrupt facilities.
When it is equal, it carries out the operations. It may
also do nothing. Need to set the toggle pin.
Q8b.) Describe the basic facilities provided by the
timer subsystem of the 68HC11 peripheral
subsystem. In particular, discuss the input capture
configuration functions provided & the interrupt
facilities.
- Input capture function = allows the user to measure
the width or period of an unknown signal & also can be
used as a time reference for triggering other operations.
- Output capture function = used to create a delay or
generate a digital waveform with a specified frequency
& duty cycle.
- RTI function = used to generate periodic interrupts;
ideal for applications that needs to be performed within
a specific time limit.
- Computer Operating Properly (COP) / Watchdog
Timer function = used to reset a computer system if a
software program has bugs in it & fails to take care of
the COP system within the time limit. It detects
software processing errors by detecting that the normal
processing sequence has not been completed.
- 8bit Pulse Accumulator function = used to count
events occurring within some time limit or to measure
the duration of a pulse.
Input Capture
- Capture signal from external source (PORTA) that
triggers the interrupt.
- If the appropriate ISR is enabled, then the ISR is
enabled.
- input capture pins on PORTA.
- Capture signal as TCNT value.
- Time between 2 events may be calculated as using
overflow to time long events.
- IC operation:
- edge detected determined by edge bits in TCTL2.
- TCNT copied to appropriate TICX register.
- ICx flag set in TFLG1.
- interrupt operated if matching ICxI bit set in
TMSk1.
Q9.) Discuss the use of volatile & static in embedded
C code. Give examples where these type qualifiers
are necessary.
Static= Fixed location in memory & it is shared by any
task that happens to call the function. It also has faster
execution & is not stored in a stack but only available
on the created function.
Volatile= Keyword that is used to warn the compiler
that certain variables may change due to interrupt
routines or other things that the compiler doesnt know
about. The compiler cant do assumptions about the
current value.
Status registers for I/O & incoming measured values
are cases where this is necessary.
Examples are peripheral registers & anything which
can be changed by an ISR.
Q10.) The 8051 family of MCs incorporate a bit
processor. Indicate what is meant by this term &
give examples of how it would be useful in an
embedded processor application.
The 8051 instruction set is optimised for the one-bit
operations so often desired in the real world, real-time
control applications. The Boolean processor provides
direct support for bit manipulation. This leads to more
efficient programs that need to deal with binary input &
output conditions inherent in digital-control problems.
Bit addressing can be used for test pin monitoring or
program control flags.
The 8051 is an 8-bit processor with an 8-bit internal
bus. It supports:
ALU = Supports unsigned 8-bit integer additions,
subtractions, multiplication, division
& BCD additions. Supports 1bit logical operations.
Interrupt = MC supports a 2-lvl interrupt system
with 5 sources & 2 externals.
I/O = the basic 8051 has 4 8-bit parallel ports, each
of which can be treated as 8 1-bit lines, plus a full
duplex serial port.
Q11.) What is a Frame Pointer & what role does it
play in the compilation & execution of high level
language code?
Frame pointer = points to an address of stack used to
pass more than 1 parameter. Where, Frame is the area
of stack defined by the user.
Role: -Same purpose as stack pointer except it points to
an area defined by the pointer.
- Pointer to base address of stack frame for a routine for
which control is transferred.
- Useful for interrupt service routines.
- Gives access to local variable & parameters passing
by the stack. - Works like a C array.
- Acts as an offset base to point to the stack.
Q12.) There is a lot of publicity about the concepts
of hardware/software codesign. Describe what is
meant by this term & what are the implications for
the design of embedded systems.
Hardware/Software Codesign is the ability to design
both parts of the system in parallel & to use the best
advantages of both. It works together because of scale
factor.
Choices include:
- Do we use DAC chips or simply use software to drive
a single pin output onto a simple PC network?
- What are the peripheral facilities required & how do
we get what we need from the microcontroller
families?
- What software driver facilities are needed to support
the specific peripheral functionality?
Hardware/Software Codesign refers to the balance &
interaction between hardware & software in the design
process. The use of COCOMO ideas from Boehm
provides costing for microprocessor implementation,
strongly suggests that the cooperative development
process is by far the most effective.
Q13.) Assembly language is still used for the design
of embedded systems. Describe which system
aspects are generally encoded this way.
A system that is performance sensitive & needs to
access a lot of I/O & memory, is generally coded in
assembly language as it provides better control & faster
execution time. Assembly language is used in the
following situations such as critical speed problem,
interface software for hardware drivers & interrupt
service routines.
Q14.) The passing of parameters between assembly
functions & high level code requires a detailed
understanding of the order & process of routine
linkage. Describe how this may be done & indicate
the method of accessing the parameters.
The order of parameter storage on the stack is
important.
- Pascal parameters are pushed onto the stack in the
order of the calling procedure.
- C parameters are pushed onto the stack in the reverse
order of the calling procedure.
- Forth parameters are located on the stack in the order
in which they are created (similar to Pascal).
Access to assembly language in Forth:
- CODE-ENDCODE pair delimit = Assembly code is
directly accessible as a Forth word.
- PROC-ENDPROC pair delimit = Assembly code is
called as a procedure in assembly language routines.
(Through JSR instruction).
Q15.) Describe the Analogue to Digital Converter on
the 68HC11 & what advantages there are to
averaging the results in the 4 registers provided
when only 1 input is being monitored.
The 68HC11 has an A/D based on successive
approximations using a capacitor charge redistribution
network. It has 8 analogue inputs called channels at
portE. The subsystem can convert data from channel 4
times or from a group of four once each. To use the
A/D, the software must enable the charge pump for the
capacitor network & specify the clock source. It does
this by setting up bits ADPU & CSEL in OPTION
register. Control register ADCTL specifies other
options, such as single-or-multiple-channel (bit MULT)
operations & single or continuous conversions (bit
SCAN). The channel select bits (bits CA,CB, CC, CD)
and determines which analogue channels can be read.
Averaging reduces the amount of noise.
Q16.) The use of lookup tables for standard
functions like sq root is generally based on
normalised values. Why? In particular discuss the
difference between the possible values of an 8bit
integer sq root & an 8bit normalised lookup table
for sq roots.
Normalised values tend to be more accurate when
performing functions such as sq root (to ascertain the
result is within the desired range.) Therefore, they will
be used in the lookup table. When using the table, there
is no need for calculations. In the normalised table, all
that we would need to show are the hexadecimal &
decimal values of each number between 0 & 255 (256
integers). Sq root in lookup table can be precise & sq
root integer returns an integer.
An 8bit unsigned char has only 16 possible integer sq
roots while an 8bit normalised value has 256 (63
duplications) = 193 distinct values.
Q17.) Describe the various approaches to interrupt
service routine entry & how these relate to the areas
of application of the microprocessor. Indicate the
advantages & disadvantages of the various methods.
Software = Save program counter, then registers are
saved by the ISR once executed. This method must use
push & pull to remove stored data.
Hardware = Store registers.
- Uses any registers freely as it will be restored at the
end.
- Does not need to execute instructions to use registers
as it is already stored.
- Can put any or all registers in 1 instruction.
- Masking is used to point to a register.
- It stores return address -> routine is responsible to
free up space.
Q18.) Describe how to interface a 68HC11 to an
external memory interface. Can this method be used
for peripheral connection as well? Justify your
decision.
The MCU must be operating in expanded mode. Here,
the MCU can access the full 64kb address space which
includes: (1) the same on chip memory address used for
single chip mode & (2) addresses for external
peripherals & memory devices.
The expansion bus is made up of ports B & C & control
signal AS (Address Strobe) & R/W (read/write). R/W
& AS allows the low-order address & the 8bit data bus
to be multiplexed on the same pins. During the 1
st
half
of each bus cycle, the pins become the bidirectional
data bus. AS is an active-high latch enable signal for an
external address latch. Address information is allowed
through the transparent latch while AS is high & is
latched when AS drives low.
The address, R/W & AS signals are active & valid for
all bus cycles including accesses to internal memory
locations. The E clock is used to enable external
devices to drive data onto the internal data bus during
the 2
nd
half of a read bus cycle (E clock high). R/W
controls the direction of data transfer. R/W drives low
when data is being written to the internal data bus. R/W
will remain low during consecutive data bus write
cycles such as when a double-byte store occurs.
Q19.) Describe the process & use of double & single
level solutions to the finite state software process.
Double level solution = In FSP, it is simply shown by
using the state table. This state table shows the state
input, next state & the outputs.
Single level solution = It is often used where input
choices are global within the system.
Q20.) Describe the use of series solutions to the
generation of trigonometric quantities. In particular
discuss the generation of an integer solution to the
sine & cosine values.
Both sine & cosine can be represented by an infinite
series involving factorials & indices of the angle:
sin(x) = x (x^3/3!) + (x^5/5!) +
cos(x) = 1 (x^2/2!) + (x^4/4!) +
Trigonometric values are found by knowing that the
terms become smaller & smaller. We can approximate
the solution to be only the first few terms of the above
equations. This is known as convergence.
Due to the recursive nature of these functions & using
trigo identities, all possible output values can be
produced from using angles from +45 to -45 degrees
sin(90-x) = cos(x).
The quadrant the angle lies in can be computed:
n = round (x/90)
x(angle from reference of quadrant) = x 90n
It is best that the angle to be represented as BAM
(binary angular measure). With this value:
n = (x - $2000) >> 14
x = x (n << 14)
Where x has a range of -45 to +45 degrees.
Scale factors are then used to determine the output of
this angle by referring back to the reverse polish
notation of the functions.
Q21.) Scaling is an important part of computing in
integer only processor environments. Describe what
it is & how it is used.
With integers only, processes scaling would help in
reducing the number of operations needed to perform
calculation. By reducing the size of integers used for
the calculation, we still end up with a correct answer.
This improves the processing time & memory space of
the instructions. Floating points need a lot of support
=> solution is to use scaling!
Scaling by power of 2 only requires shift to work. Eg. 2
000 000 / 40 000 is the same as 1 000 000 / 20 000
(Using scale factor of 2).
Division of x by 32 is the same as shifting right of x 5
times: X >> 5 equals x / 32. Scale factor is 32.
20 000 000 / 40 000 becomes 62500 / 1250 & do shift
operation (which is faster) instead of division.
Q22.) Pulse Width Modulation (PWM) is an
important technique for generation of analogue
outputs from MCs. How would you convert such an
output to an actual analogue output? Describe 3
methods of generating PWM waveforms. Write code
or pseudo code for one of these methods.
PWM can be converted to analogue using both
capacitors & inductors to smooth output waveforms.
PWM is generally created using the TOC registers &
the timer. TCNT increments according to the clock
cycle and when it overflows, a flag is set. With TCNT
incrementing linearly with time, the TOCR is compared
with the TCNT. When one TOCR is equal to TCNT,
the output will toggle high & when the other TOCR is
equal to TCNT, the output will trigger low, creating a
PWM waveform. One of the TOCR can be altered in
order to achieve different duty cycles. This is assumed
that the TCNT has already been programmed to
increment.
Pseudo Code:
Generate PWM {
- TOC1 = TCNT + wave period
- TOC2 = TOC1 + (1 DC) * wave period
- loop to top. }
Q23.) Discuss the problems of contact bounce in
switches & how this may be overcome by software.
Indicate some of the difficulties which may be
implicit in implementation.
When a mechanical switch is pressed or released, it
bounces microscopically for a period of a few
milliseconds. Hence, the MCU will have many
occurrence of make & break instead of one occurrence.
A mechanical key requires a debouncer when used with
logic circuits or MC hardware. The MCU should see
only one break-to-make transition when a key is
pressed & only one make-to-break transition when a
key is released. This may be overcome by software by
using a time delay after detecting a transition to check
if the key condition has stayed the same. Basically, the
key is debounced if the key codes before & after the
time delay are identical.
Q24.) Digital filtering of analogue inputs is a
common function in control systems. Describe how
to create a simple low pass filter in an embedded
system. Discuss the limitations of your solution.
Mean filter (integration, low-pass filter) = the mean
filter or averaging filter is a simple low-pass filter or
smoothing filter. Its main function is to smooth
sampling jitter in time functions, often in visual
displays. For generating filtering, however, more
complex filter types are used. The mean filter like the
median filter, is represented by a moving window of
length n & the mean of the values at all positions in
the window is selected:
y(t) = sum_i = t (w+1)[x(i)] / n
Where w = length of the window.
Q25.) Under what conditions can you use a shift
right operation to replace a divide by 2. Why is
there a potential problem?
Condition is when the values are positive. Potential
problem occurs when negative numbers are used.
For a signed positive integer, a right shift operation is
perfectly ok because an integer divide should always
truncate towards - & leave a +ve remainder if there is
one. This agrees with most people's interpretation of
division for a +ve integer but not for a -ve one. Eg 000
0101 goes to 000 0010 (5 goes to 2) and 111 1011 goes
to 111 1101 (-5 goes to -3). From a mathematical
viewpoint, there should be no difference between the
results of operations on any numbers throughout the
integer spectrum. Zero should have no special
privileges. Consider calculation of the midpoint
between two integers sequence of results. The integer
division gives zero a special place whereas the shift
does not. Division of -ve integers is actually interpreted
as "remove the sign, perform the division and then add
the sign back in" which is not formally correct as it
results in -ve remainders for -ve numbers which are not
acceptable. The MISRA C guideline is only to
minimize human ambiguity about what will result from
the operation.
Q26.) Microcontroller manufacturers often have
several families on the market at the same time.
Give reasons why they would do this.
Each family targets a different market. Many of the
products are mature & designer familiarity keeps them
in use for new designs. When there is a need to upgrade
to higher power processors, then the designer is
inclined to stick to the same manufacturer &
particularly where there is a viable family upgrade
route. To stop support, it may lead to designer
uncertainty of the future & a rapid decline in market
share.
The range of families is there to support the wide range
of embedded system requirements. They may remain
due to contractual requirements & a need to be seen as
consistent in the market place.
Q27.) MISRA C provides guidelines for many
aspects of C in embedded systems. Describe the
recommendations for the standard types such as int.
The basic types of char, int, short, long, float & double
should not be used, but specific - length equivalents
typedefd for the specific compiler & these type names
used in the code. The basic C types are implemented
differently on different processors & different
compilers. Making an explicitly portable set is very
important for embedded development as type size has a
critical impact on implementation on processors with
limited register sizes. In porting code, you only need to
rematch the typedefs to the new compilers own
implementations to get correct porting.
Q28.) Safety concerns in embedded systems can be
significant in medical & hazardous areas. Describe
techniques used to help reduce potential problems
associated with errors in software &/or hardware.
Use COP (Computer Operating Properly)/ watchdog
timer:
- A watchdog timer is incorporated into a system to
provide detection of software failure & to provide a
mechanism to restore operations.
- Timeouts 16ms, 66ms, 262ms, 1s.
- The COPRST register is used for arming the
watchdog & requires multiple wires of different
patterns to activate.
- Very dependant on the clock so a clock failure
sensing mechanism is also included.
Q29.) A 68HC11 microprocessor is used as part of a
power monitoring system. (a) Describe the basic
facilities necessary to implement such a system. (b)
Discuss any difficulties in the measurements
required & how to overcome them.
(a) Basic facilities: Sensors, signal conditioning, A/D
conversion, display (eg. LCD), MCs.
(b) In general case, the waveform is not sinusoidal so
the measuring of the system needs to be able to handle
this & still determine voltage, current & phase etc. To
do this, one can use the 12 point method & harmonic
analysis which allows one to extract the fundamental
magnitude & phase of voltage & current. It has the
advantage that there is no synchronization requirement
for the monitoring provided it performs 12 equally
same spaced samples over a waveform of the mains.
The major difficulty is accuracy & the likely need to go
better than an 8bit A/D converter.
Q30.) The 68HC11 incorporates a pulse
accumulator subsystem. Describe 2 of its modes of
operation.
Event counting mode: The counter is docked by the
source each detection of a specific edge at the input pin
will increment the counter. The processor is
accumulating info from an external source.
Gated time accumulation mode: The input signal
opens a gate which allows dock pulses derived from the
processor dock to increment the counter. Used to
measure duration of single pulses.
Q31.) What is a simple approxi. for cos(30) in a
system w/o floating point arithmetic? How may the
accuracy of this approximation be improved upon?
Provide pseudo code for the correction routine.
A simple reasonable approximation for cos(30) is 7/8
(ie. 0.875). It over estimates by 1.04% (ie. error =
1.04%). Original value is cos(30) = 0.866.
1
]
1

+
y
x
factor Correction 1
8
7
_
With an appropriate choice of x & y can be used. A
starting point is to set x = -1 & find y (y = 97.5). It
would be preferred if y were to come out as a binary
number to maximise arithmetic manipulation.
(Correction factor CF)
Pseudo code of the correction routine:
- Take a copy of the original.
- Shift left once & adds the original. You have three
times the original.
- This is now 256 times more than you wanted for the
correction so the upper byte is now the CF to be
subtracted from the original value.
- This reduces the error by a factor of about 7.
Q3) It is often useful to use extreme values from an
A/D converter to indicate out of range information.
What is the implication of this when doing data
conversion?
We need to subtract one to the value from the AD
before scaling it or performing any other operation. If 0
from A/D signifies data below range, then 1 signifies 0.
Hence 1 needs to be subtracted.
Q4) Describe how the keyboard interface is
implemented in the CLIC2 system. Indicate how the
use of PLDs helps reduce software complexity in this
case.
Keyboard Interface- How is it implemented onto the
clic2 board.???
The advent of programmable logic devices (PLDs)
enabled engineers to implement more functions in a
given unit area of the circuit board while also reducing
time to market. The number of components used in a
system was reduced, resulting in a lower overall system
cost. The same PLD device could be used across
multiple designs, reducing the number of devices used
in a system. Companies standardized on a few PLD
devices without compromising the functionality
required for each circuit board. Managing fewer PLDs
was a lot easier than managing a large number of TTL
gates. The same PLD device could be used across
multiple board designs, reducing or even eliminating
the need for second sourcing. Designers could simulate
the design in software before committing it to the
circuit board, increasing the likelihood of first time
success.
Q5) The 68HC12 responds to a number of
exceptions indicate how the system responds to an
IRQ and to a COP timeout. The 68HC12 responds to
a number of exceptions. The maskable interrupts which
includes IRQ pin and all peripheral function interrupts.
The IRQ is only external maskable interrupt for the
68HC12. IRQ interrupt can be edge-triggered or level-
triggered and has a local enable mask in the interrupt
control (INTCR) register. The IRQ interrupt may be
delayed for 4096 E clock cycles after exiting the stop
mode. The IRQ interrupt is configured by programming
the INTCR register.
Resets: including the power-on reset, reset pin manual
reset, the COP reset(computer operate properly), and
clock monitor reset. The computer operate properly
(COP) system is designed to protect against software
failure. If software was written correctly, it should
follow certain sequence of execution and the execution
time can also be predicted. When the COP is enabled,
software must write $55 and $AA (in this order) to the
COPRST register to keep a watchdog timer from timing
out. If the software was not written properly, then it
may not write $55 and $AA to the COPRST (located at
$17) before the COP times out and the CPUwill
bereset. The software problems can therefore be
detected.
Q6)Why do companies developing embedded
systems need a Firmware Development Standard.
Indicate three topics expected to be covered. The
reason for the Firmware Development Standard is to
ensure all Company-developed firmware meets
minimum levels of readability and maintainability.
Source code has two equally-important functions: it
must work, and it must clearly communicate how it
works to a future programmer. Part of every code
review is to ensure the reviewed modules and functions
meet the requirements of the Standard. Code that does
not meet this Standard will be rejected.
TOPICS expected to be covered: 1)Projects 2)Modules
3)Variables 4)Functions 5)Interrupt Service Routines
6)Coding conventions 7)C formatting.
Q7)Defensive programming is a form of defensive
intended to ensure the continuing function of a piece of
software in spite of unforeseeable usage of said
software. Defensive programming techniques are used
especially when a piece of software could be misused
mischievously or inadvertently to catastrophic effect
Improve software in term:
-general quality; reducing the number of software bugs
-making the source code comprehensive
-making the software behaves in a predictable manner
despite unexpected input or user action
8. In C parameters are passed to functions with the
right hand parameter placed on the stack first.
Give the reason for this and indicate whether this
facility is considered good programming in the
context of new code for embedded systems.
Passing parameters on the stack is slightly less efficient
than passing these parameters in registers. The
functions of the registers set is very limited and can
only pass a few values or reference parameters. The
stack can pass large amount of parameters without any
difficulty. In embedded systems we want as much
efficiency as possible therefore passing to registers is a
better way even though only a few values can be
passed.
Q9) PWM waveforms can be specified using a
number of terms. Explain each of the following in
the context of a PWM waveform. Mark to Space
Ratio, Pulse width, period, left aligned, centre
aligned. Some systems do not allow the PWM
waveform to take the extreme values of Full on or
full off. Explain the reasoning behind this and
indicate for an 8 bit system the maximum and
minimum mark space ratios allowed. Period-when
using the PWM, we need to choose a period. To set the
period for a PWM channel you need to write to the
PWMPER register for that channel. PWM Period =
(PWMPERn) x Period of PWM Clock n
Left-aligned- To select left-aligned mode, write a 0 to
Bit n of PWMCAE register
Centre-aligned-to select centre-aligned mode,write a 1
to Bit n of PWMCAE register. If all channels are
programmed to mode 1,center-aligned PWM signals
will be generated.A duty cycle from 0 to 100% is
programmable.
Mark to space ratio- By varying the mark-space ratio of
the signal over the full range, it is possible to obtain
any desired average output voltage from 0V to 12V.
Space ratio allowed for a 8-bit system is 0-255 clock
ticks[(2^8)-1].
10.Timer subsystems often have a prescaler
function to reduce the frequency of the clock used
for the internal functions. Usually this is intended
to provide a divide by 2
x
function where x is the
setting of a 2 or 3bit prescaler. Explain.
ANS: This is done by using a compare operation. Each
time the main clock reaches the value of the prescaler,
it generates a cycle (Not sure about this)
Q11)ANSI C does not specify how interrupt routines
should be handled but provides a #pragma facility
to extend the language as required but this is not
always used by compilers. Indicate how the IAR
compiler meets the needs for interrupt service.
An interrupt service routine that does not cause a
context switch has no special requirements and can be
written as per the normal IAR syntax. Often you will
require an interrupt service routine to cause a context
switch. For example a serial port character being
received may wake a high priority task that was
blocked waiting for the character. If the ISR interrupted
a lower priority task then it should return immediately
to the woken task. Limitations in the IAR inline
assembler necessitate such interrupt service routines
include an assembly file wrapper.
Q12) Some C compilers for the HC12 use functions
such as __enable_interrupt() while others may use
CLI() etc. From where has the second function
name been derived. Discuss the portability of these
functions to other processor families. The CLI()
[command line interface] is the macro function which
uses assembly language program instructions cli
respectively. eg,#define CLI() asm(cli\n) where the
symbol asm simply commands a compiler to place
enclosed assembly instruction immediately into the
compiled code. The CLI() command is used to clear the
I bit in the CCR to a logic 0 as well as enables the
interrupt.
Q13) The declarations shown below provide the
basis for access to the keypad in the CLIC2 system.
Explain how the expression for Keypad works and
all implications for its use in a program.
#define Extport (0x4000) // Peripheral Base
Address
#define CLIC2Offset (0) // Local peripheral
offset - Jumper 0
#define Keypad ( * (volatile UI_8 *) (Extport +
CLIC2Offset + 0x04))
The Keypad is memory mapped. Its memory location is
defined by the expression Extport+Clic2Offset+0x04.
This value is casted to an 8 bit integer pointer. The
additional pointer qualifier dereferences the
declaration. This causes the value stored in location
0x4004 to be defined by Keypad.If a key is pressed,
the column and row ID of that key can be accessed by
accessing Keypad. A lookup table can then be used to
determine the value of the key pressed.
PAST PAPERS SOLUTIONS (2005)
Q1a.) The 13
th
rule of the MISRA C guidelines:
The basic types of char, int, short, long, float &
double should not be used, but specific - length
equivalents typedefd for the specific compiler &
these type names used in the code.
Discuss the need for this rule & indicate why it is
considered necessary.
There is no requirement under ANSI C for these types
to have the same implementation on different
machines. This has significant implications in an
embedded environment where it is often critical to
know how variables will be treated. Creating specific
length equivalents typedefd means that your code has
explicit representation of types & by changes in one
place only can be matched to specific processor
environments.
Q1b.) It is recommended that an integer variable
division by 2 be achieved by the divide operator
rather than the shift right operator. Explain this
recommendation & the conditions under which it
applies.
The shift right operator does an integer divide by 2 but
referenced to infinity (not 0 as most people expect). If
the value to be divided is guaranteed to be positive, the
result will always be as expected, but for negative
numbers, the result may be one lower than the
expected.
Q2.) The following code initiates a PWM waveform
using OC1 & OC3 of the 68HC11. It has been
configured so that an independent function under
interrupt control may return a value to the byte
variable control. This interrupt function has not
been shown.
Assume the 68HC11 has been configured with the E
clock @ 2MHz & the timer prescaler set to divide by
1.
Analyse the code & answer the following qns:
(a) What is the period of the PWM waveform?
(b) What is the min. pulse time generated?
(c) What is the max pulse time generated?
(d) If control contains the value 0x50, what is the
pulse time generated?
(e) Under what system environmental conditions
would this config. be appropriate?
(a) TOC1 provides the period & is fixed to the value of
0 for TCNT so period is 32.768msec.
(b) The min time is with time.bytes.hi = 0 &
time.bytes.lo = 0x080. 128 cycles of the system clock
@ 2MHz or 64 microsec.
(c) The max time is when time.bytes.hi is 0x0FF &
time.bytes.lo = 0x080 so the time is 32.768 msec 64
microsec or 32.704 msec.
(d) If control is 0x050 & time.bytes.lo =0x080, the
composite pulse length is 0x05080 @ 2MHz or 10.304
msecs.
(e) When the system is capable of switching @ speeds
commensurate with the pwm & where response time is
slow compared to the PWM period.
Q3.) Describe the differences between the Motorola
& Intel approaches to peripheral interfacing. How
would you operate an Intel peripheral in a Motorola
environment?
Intel uses RD* & WR* strobes while Motorola uses the
RD/WR* line together with the system clock. The
result is that it is easy to generate Intel signals from
Motorola but not vice versa. Requires 2 NAND gates &
inverter.
Q4.) The series solution for a sine function is:
...
! 9 ! 7 ! 5 ! 3
) sin(
9 7 5 3
x x x x
x x + +
(a) Given that x may be as large as 1 radian
determine the equation where it is required that the
last term is the first that contributes less than 1% to
the sine function value.
(b) Use Horners factorisation method & reverse
Polish Notation to reorder the solution for an
embedded system evaluation.
Show how you would calculate the sine value for
x=1.00 when scaled by 128 using 16bit signed
integer arithmetic.
ENSURE you fully consider and state all the scaling
effects. Compare your answer with the actual value
of the sine for an angle of 1 radian. Specify the final
scaling factor of sin(x) generated by your function.
Write a function in C (or pseudo) which accepts as
input (x) a signed integer representation of the
radian measure ranging from 0 to 1.00 which has x
scaled by 128 & returns a value for sin(x).
i.e. When x = 1.00, the input value to the function is
128. Assume the size of an int in this version of C is
16bits & that integer division can be used.
(a) Term 1 -> 1.0
Term 2 -> 1/3! = 0.167
Term 3 -> 1/5! = 0.008
Term 4 -> 1/7! = 1.984*10^- 4
Term 3 provides less than a 1% chance.
Horners factorisation method gives:

'

'


20
1 1
6
1 ) sin(
2 2
x x
x x
Reverse Polish Notation:
x
x x
x

'

'

1
6
1
20
) sin(
2 2
As the largest input value is 128, the largest value
calculated by the function will be 16384 which is well
within the representation of a signed integer. Use
rounding on the division so
Left hand term returns maximum rounded value of
(1.0*1.0*128*128+10)/20 which is the term scaled by
128*128 = 819.
Reduce to scaling by 128 -> 6.
Subtract 1*128 for the first {} term = -122 which is the
actual value scaled by 128.
The next term gives (1.0*1.0*128*128+3)/(6) = 2731
which is the term scaled by 128*128. Reduce scaling
by 128 -> 21.
Multiply terms gives -2562 which is scaled by 16384.
Add 16384 which is 1*16384 -> 13822
Multiply by 128 & divide by scale of 128 give answer
of 13824 rounded which represents 13824/16384 =
0.844 within 0.4%.
The scale factor is 16384 corresponding to a sine value
of 1.00.
sin(1.00) = 0.841
Direct calculation using the expression above gives
0.842, so this is well within the 1% limit.
Code:
#define halfscale (64)
#define scale (128)
#define fullscale (16384)
#define realscale (128.)
#define realfullscale (16384.)
int mysin(int x) {
}
The function has been deliberately written step by step
to correspond to the parts of the RPN equation & to
deal with the scaling requirements.
PAST PAPER SOLUTIONS (2004)
Q1.) A partial circuit schematic of the CLIC board
as used in the labs of this unit is shown below. It
represents the interface between the keypad & the
rest of the system.
(a) The signal line entering the image @ the top left
is the decoded keypad selection address. Describe
how the write & read operations will provide signals
to the keypad connections.
(b) The keypad connections are graphically shown
on the following page:
With the intersection points corresponding to the
keys on the keypad, write pseudo code for an
algorithm to determine which key has been pressed.
(a) When the write operation is performed, the data on
lines D is latched into the quad latch 74HC75. This data
is then the source signal to the rows of the keypad.
Generally, only one of these lines should be held high
at any one time. When the read operation is performed,
the signals on lines 4-1 are placed onto the data bus via
the tristate buffers & will show a 1 if the equivalent
row is high enough.
(b)
Initiate check with data 0x01
while (more rows) {
write pattern
read column values
if a 1 detected then exit with keypad code
update check pattern by ASL operation }
Q3.) Fixed point & Scaled arithmetic are used
extensively in embedded systems. Describe these &
give reasons for their use.
Fixed point arithmetic depends on the ability to save &
use the position of the decimal or binary point so that
the final results of a calculation are correct.
Eg. 10.5x3.6=37.80 with the initial values having one
place after the decimal point (dp) & the result having 2.
The user must determine when to retain the max dp
value & when to reduce it. The user must decide
whether truncation or rounding is appropriate. For
scaled arithmetic, the only difference is that the system
needs to retain information about the scaling used
rather than the dp position. This approach may be
useful where a scale factor can be usefully retained
through a significant set of calculations only to be
absorbed or used once at the end to finalise a result. An
example here would be where there is an inherent
divide by 6 in a calculation and at the same time, there
is a physical I/O scaling factor which relates simply to
6 so that completion of the calculation may involve
minimal operations.
The use of fixed point or scaled arithmetic in embedded
systems is based on the lack of a floating point unit &
the often excessive time taken for software floating
point calculations to execute.
It should be noted that it is generally rational to use
these techniques as the accuracy of calculation is
normally adequate & their speed of execution will often
result in the chance to use a cheaper MC or run on a
slower clock for reduced power consumption.
Q4a.) The use of an Assert mechanism is
recommended for general C programming. Discuss
what it is used for & then indicate how an
equivalent function can be used in an embedded
development.
Asserts are used to detect illegal information & to
ensure that the programmer/developer becomes aware
of such situations. It is not intended to detect situations
which should be handled by the normal code.
The normal assert returns information about the
location of the original code in the original file but this
is not feasible in the embedded environment so the
equivalent function should activate some visual
mechanism such as a flashing LED to indicate the
detection of a problem.
Q4b.) A common requirement in measurement &
computation of waveforms is the need to compute a
square root value. Consider the needs for such a
function & describe one method for its
implementation where the data is a 16 bit unsigned
integer & the square root an unsigned char.
The solution is in some iterative form.
PAST PAPER SOLUTIONS (2003)
Q1.) A partial circuit schematic of the Heater
Accessory Board is shown. (a) With reference to
the partial schematic diagram, describe how the
addressing for the D/A converter (U11) is obtained.
The onboard jumper (J2J3) selection may be
referred to as the Block number. Give an
expression which may be used to obtain the
resulting address.
Peripheral chips attached to the 68HC11 are memory
mapped so the decoding process is effectively the
same as for memory chips though generally to a much
smaller address range as described in the lecture. The
lower byte of the address bus & the 8bit data bus are
multiplexed onto the same lines & so the 74HC373 8bit
Dtype latch is the source of Address bits 7-0 on outputs
8Q-1Q & it is latched by the Address Strobe AS.
The 74HC138 chip decodes the 3 most significant
bits of the lower address bus when activated by the
active low interface line *EXTPORT. The actual
selected block is determined by the jumpers
corresponding to BLOCKs 1 to 8 we have address
additions of 0 through 7 in increments of 0x020. The
result is that an active low select signal is created at the
output of the jumper block corresponding to an address
of EXTPORT + (BLOCK 1)*0x020. This active low
selection signal is inverted by U9A & NANDed with
the low order address bit A0 to produce the active low
chip select signal *CS for U11. The corresponding
address is active for U11 if Address line A0 is 1. The
resulting expression for the address of U11 is:
EXTPORT + (BLOCK 1) *0x020+1.
Q1b.) The LM335 is a temperature sensor which has
an output of 10mV/degree K.
Given the amplifier circuit shown in the diagram
above, obtain the temp in degrees Celsius
corresponding to 0V & 5V inputs to the A/D
converter. Note that the reference point for the
amplifier output is offset to 2.5V relative to ground
at pin 14 of U1D that the inverting input to the
instrumentation amplifier configuration is at pin 5
of U1B & e non-inverting input @ pin 10 of U1C.
1
2
2
1
5
3
4
1 3
1
2
1
R
R
R
R
R
R
R
R R
Gain
1
1
]
1

,
_

+ +
+

(b.) The temp sensed for the LM355 which is thermally


linked to the high power resistor. This precision temp
sensor has a linear output of 10mV/degree K which is
coupled through the AD8544 amplifier configuration.
To Port E bit 5. (0 degrees Celsius = 273 degrees
Kelvin.)
The amplifier gain is 4.2 to 1 decimal place so the
output changes at 42mV/ degree K.
0 & 5 V correspond to outputs of -2.5 & +2.5 relative
to the specified reference point (Vref = 2.5V).
The composite amplifier has a gain expression of:
Vout = Gain * (Vnon Vinv)
The inverting input has a fixed value of 5.0*(20k/(20k
+10k)) or 3.33 V.
Vout = 4.2(10mV(273+C) 3.33)
When Vout = -2.5:
-2.5 = 4.2(C/100 0.6) C = 0.48 degrees
When Vout = 2.5:
2.5 = 4.2(C/100 0.6) C = 119.52 degrees
(c.) The A/D converter on the 68HC11 provides an
8bit resolution over the range of converter voltages.
What is the temperature resolution of the system?
The converter does 255 steps over the temperature
range so the resolution is 0.4668 degrees Celsius. From
(119.520.48)/255.Approx 0.5 deg. per step.
Q2a.) MISRA C guidelines include as the first rule:
All code shall conform to ISO 9899 standard C,
with no extensions permitted. Discuss the need for
this rule & indicate any deviations from this which
may be permitted & why.
It is essential to only use those definitions which are
portable to different MCs so sticking to the standard
ensures this.
Deviations should only be applied when explicit control
of hardware is required & this needs use of defined
extensions. Occasionally some explicit optimisation
may be useful where timing is significant and/or when
C does not produce the information required (eg.
Overflow). Any deviations MUST BE fully
documented.
Q2c.) The MISRA C guidelines recommend that the
basic C types should not be used (Rule 13). Explain
why. Where would the replacement definitions be
placed before use? For the 68HC11 a useful type
definition set is shown below:
(c.) The basic C types are implemented differently on
different processors & different compilers. Making an
explicitly portable set is very important for embedded
development as type size has a critical impact on
implementation on processors with limited register
sizes.
In porting code, you only need to rematch the typedefs
to the new compilers own implementations to get
correct porting.
Q3.) The C prototype & assembly language coded
function is designed to add 2 signed 16bit integers
on a 68HC11 MC & to return the result of the
addition in the required location & a true flag if
Overflow has occurred.
(a.) Explain why you may wish to implement such a
function in C.
The designers of the C language assumed that the user
would use variable types which are guaranteed to be big
enough for the data being manipulated, therefore, C
does not check for overflow conditions when it
implements arithmetic operations. If there is any
concern that the result of a calculation may overflow
then implementing a function which returns a flag
indicating when overflow has occurred is of
considerable value. This cannot be done satisfactorily
in C as you need access to the condition code register.
The best you can do at the C level is test each incoming
value to an addition to ensure it is less than half the
limit so that the sum is less than the limit. In MCs, it is
necessary to use the full range of a variable type &
ensure we are in range or detect whenever results are
out of range so that effective measures may be
implemented.
(b.) Discuss the responsibilities of the C language
specification & the programmer in C with regard to
the potential error conditions, which may arise from
arithmetic operations.
The C specification takes NO responsibility for error
condition detection making it the programmers
responsibility. The programmer must ensure that his
code cannot generate an error condition OR arrange to
detect & respond to the problem. Such a situation is
where creation of an assembly function to replace the C
level operator becomes appropriate.
(c.) Explain the use of the tsx instruction in the
code shown & its value when creating re-entrant
code as shown in the example.
The tsx instruction is used to establish a frame
pointer. It is used to transfer the stack pointer contents
to the X register plus one.
All data associated with the function may be accessed
relative to this address pointer. This allows indexed
addressing to access the contents of the stack, which is
where we have placed the incoming parameters & the
local variables. For example, one of the parameters is
located @ 5,X or starting at the 5
th
byte above the
location pointed to be the frame pointer in X.
The value of this operation is that provided all data
storage associated with a function is in registers or on
the stack, then the code may be used in re-entrant code.
Q4a.) The Real Time Interrupt (RTI) on the
68HC11 has been provided as the basis for a system
tick or periodic interrupt. This is very useful for
organising the execution of code at regular intervals.
It does not, however, directly provide a convenient
time base for an elapsed time clock. One of the
possible periods for execution of the RTI is 16.384
msec. Use pseudo code, C or assembly code to define
an algorithm, which may be used by the RTI
interrupt service routine called at this interval to
create an incrementing 1 sec based elapsed time
clock.
1 second = 1,000,000 micro sec, & this is being divided
up into 16384 microsec chunks by the RTI. These
values are outside of the integer representational range
for 16bit integers but are equivalent to 15625 & 256
when scaled down by 64 w/o any loss if information.
These are within the 16bit int representation so in the
code, it can be defined:
(code written in C)
Q4b.) Determine the tolerance (in milisec) on the
registration of a 1 second time duration & indicate
any (short or long term) time drift that your system
will experience using your algorithm.
This has short term tolerance of magnitude plus/minus
half of the interrupt period (8.192 msec) but no long
term drift as it is self correcting. Note that this is all
relative to the starting time & the initialisation provides
a half interrupt offset. The overall drift is limited to that
of the crystal clock.
Tutorial 3
2. Find out about bus alignment and structures in C.
This is critical for larger bus
systems BUS16, BUS32 and BUS64.
The influence of embedded processor bus organisation
on structures in C
Structure Layout An embedded requirement
In general one needs fine grain control of the way in
which data is stored in structures (or classes in C++)
BUS16 has a 16bit data bus width so it access 2bytes in
one cycle provided they start on an even address. If
they start on an odd address it causes an exception so
compilers must avoid the situation by accessing
misaligned data in a byte wise, piecemeal fashion.
BUS32 have a 32bit data bus. Multibyte values can be
accessed at any address but if not properly aligned will
degrade performance with multiple accesses required.
BUS64 has similar characteristics but based on 8byte
multiples.
Each C type has a natural boundary (N) by which we
mean that access is best if the address is a multiple of
N. As a rule we consider that
N = min(buswidth,data size)
This becomes important in relation to the packed
keyword. If packed the storage is more efficient but
access may be slower. If enough memory is available
unpacked storage is preferred.
Unpacked storage has to meet certain conditions:
Rule 1: The natural boundary for an unpacked structure
is the natural boundary of its most demanding member.
Padding bytes may be needed between members to
guarantee proper alignment.
Rule 2: The size of an unpacked structure must be a
multiple of its natural boundary. Trailing bytes may be
needed at the end of the structure to satisfy this rule.
Rule 3: The size of a structure cannot depend on its
context.
These rules guarantee that should a structure become a
substructure or a component of an array the natural
alignment of its members is preserved.
Examples:
struct simple
{ char A;
int B;
char C;
};
struct simple vector[2];
struct outer
{ char X;
struct simple Y;
};
struct point
{
char C;
double X, Y;
};
Notation A-Z represents bytes in the structure.
represents .. a padding byte.
BUS16 memory layout:
struct simple {A..BBBBC..}
array vect [{A..BBBBC..}{A..BBBBC..}]
struct outer {X..{A..BBBBC..}}
struct point {C..XXXXXXXXYYYYYYYY}
BUS32 memory layout:
struct simple {A......BBBBC......}
array vect [{A......BBBBC......}{A......BBBBC......}]
struct outer {X......{A......BBBBC......}}
struct point {C......XXXXXXXXYYYYYYYY}
BUS64 memory layout:
struct simple {A......BBBBC......}
array vect [{A......BBBBC......}{A......BBBBC......}]
struct outer {X......{A......BBBBC......}}
struct point {C..............XXXXXXXXYYYYYYYY}
3. What is the relationship between arrays and
pointers? Is there any difference
between the following expressions:
z[2] = 99;
*(z+2) = 99;
z[2]=99 is taking z, using 9 as reference and storing in
99, it is taking location of z as pointer
*(z+2)=99 is taking z+2 and storing 99, taking location
of z as pointer provided z is byte based theory
4. What is the use of the #pragma inline in C code?
When interrupt handlers are written in C, the interrupt
service routine must be preceded by an interrupt
handler #pragma. A #pragma is a pre-processing
directive used for implementation-specific guidance to
the compiler
7. What are the two meanings of the symbol * in the C
programming language?
1. Multiply
2. Location of pointer
7.Short floating point routines for trig functions
can be written rather than use the built in functions
provided by the C libraries. Why would you use
them?
ANS: Requires less resources. Library functions are
written for reprogrammable systems, which usually
have much more resources.
Textbook:
Ganssle J. Newnew, The Firmware Handbook.
Other texts:
- Spasov P Prentice Hall Microcontroller Technology:
68HC11 & 68HC12
- Simon D Addison Wesley An Embedded Software
Primer

Você também pode gostar