0% found this document useful (0 votes)
493 views35 pages

Dod Problems

This document contains 7 exercises related to modeling continuous and discrete dynamic systems. The exercises involve modeling systems such as a tuning fork, helicopter control system, DC motor, thermostat, and more using differential equations, block diagrams, and state machines. Parameters and behaviors are analyzed for properties such as linearity, stability, and hysteresis. Models are implemented and simulated in software.

Uploaded by

Quỳnh Nguyễn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
493 views35 pages

Dod Problems

This document contains 7 exercises related to modeling continuous and discrete dynamic systems. The exercises involve modeling systems such as a tuning fork, helicopter control system, DC motor, thermostat, and more using differential equations, block diagrams, and state machines. Parameters and behaviors are analyzed for properties such as linearity, stability, and hysteresis. Models are implemented and simulated in software.

Uploaded by

Quỳnh Nguyễn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

EXERCISES

Exercises

1. A tuning fork, shown in Figure 2.5, consists of a metal finger (called a tine) that
is displaced by striking it with a hammer. After being displaced, it vibrates. If
the tine has no friction, it will vibrate forever. We can denote the displacement of
the tine after being struck at time zero as a function y : R+ → R. If we assume
that the initial displacement introduced by the hammer is one unit, then using our
knowledge of physics we can determine that for all t ∈ R+ , the displacement
satisfies the differential equation

ÿ(t) = −ω02 y(t)

where ω02 is a constant that depends on the mass and stiffness of the tine, and where
ÿ(t) denotes the second derivative with respect to time of y. It is easy to verify that
y given by
∀ t ∈ R+ , y(t) = cos(ω0 t)
is a solution to the differential equation (just take its second derivative). Thus, the
displacement of the tuning fork is sinusoidal. If we choose materials for the tuning
fork so that ω0 = 2π × 440 radians/second, then the tuning fork will produce the
tone of A-440 on the musical scale.

displacement restorative force

tine

Figure 2.5: A tuning fork.

38 Lee & Seshia, Introduction to Embedded Systems


2. CONTINUOUS DYNAMICS

(a) Is y(t) = cos(ω0 t) the only solution? If not, give some others.
(b) Assuming the solution is y(t) = cos(ω0 t), what is the initial displacement?
(c) Construct a model of the tuning fork that produces y as an output using generic
actors like Integrator, adder, scaler, or similarly simple actors. Treat the initial
displacement as a parameter. Carefully label your diagram.

2. Show that if a system S : AR → B R is strictly causal and memoryless then its


output is constant. Constant means that the output (S(x))(t) at time t does not
depend on t.

3. This exercise studies linearity.

(a) Show that the helicopter model defined in Example 2.1 is linear if and only if
the initial angular velocity θ̇y (0) = 0.
(b) Show that the cascade of any two linear actors is linear.
(c) Augment the definition of linearity so that it applies to actors with two input
signals and one output signal. Show that the adder actor is linear.

4. Consider the helicopter of Example 2.1, but with a slightly different definition of
the input and output. Suppose that, as in the example, the input is Ty : R → R, as
in the example, but the output is the position of the tail relative to the main rotor
shaft. Specifically, let the x-y plane be the plane orthogonal to the rotor shaft, and
let the position of the tail at time t be given by a tuple ((x(t), y(t)). Is this model
LTI? Is it BIBO stable?

5. Consider a rotating robot where you can control the angular velocity around a fixed
axis.

(a) Model this as a system where the input is angular velocity θ̇ and the output
is angle θ. Give your model as an equation relating the input and output as
functions of time.
(b) Is this model BIBO stable?
(c) Design a proportional controller to set the robot onto a desired angle. That
is, assume that the initial angle is θ(0) = 0, and let the desired angle be
ψ(t) = au(t), where u is the unit step function. Find the actual angle as a
function of time and the proportional controller feedback gain K. What is
your output at t = 0? What does it approach as t gets large?

Lee & Seshia, Introduction to Embedded Systems 39


EXERCISES

6. A DC motor produces a torque that is proportional to the current through the wind-
ings of the motor. Neglecting friction, the net torque on the motor, therefore, is
this torque minus the torque applied by whatever load is connected to the motor.
Newton’s second law (the rotational version) gives

d
kT i(t) − x(t) = I ω(t), (2.15)
dt
where kT is the motor torque constant, i(t) is the current at time t, x(t) is the torque
applied by the load at time t, I is the moment of inertia of the motor, and ω(t) is
the angular velocity of the motor.

(a) Assuming the motor is initially at rest, rewrite (2.15) as an integral equation.
(b) Assuming that both x and i are inputs and ω is an output, construct an actor
model (a block diagram) that models this motor. You should use only prim-
itive actors such as integrators and basic arithmetic actors such as scale and
adder.
(c) In reality, the input to a DC motor is not a current, but is rather a voltage. If
we assume that the inductance of the motor windings is negligible, then the
relationship between voltage and current is given by

v(t) = Ri(t) + kb ω(t),

where R is the resistance of the motor windings and kb is a constant called the
motor back electromagnetic force constant. The second term appears because
a rotating motor also functions as an electrical generator, where the voltage
generated is proportional to the angular velocity.
Modify your actor model so that the inputs are v and x rather than i and x.

7. (a) Using your favorite continuous-time modeling software (such as LabVIEW,


Simulink, or Ptolemy II), construct a model of the helicopter control system
shown in Figure 2.4. Choose some reasonable parameters and plot the actual
angular velocity as a function of time, assuming that the desired angular veloc-
ity is zero, ψ(t) = 0, and that the top-rotor torque is non-zero, Tt (t) = bu(t).
Give your plot for several values of K and discuss how the behavior varies
with K.
(b) Modify the model of part (a) to replace the Controller of Figure 2.4 (the sim-
ple scale-by-K actor) with the alternative controller shown in Figure 2.6. This

40 Lee & Seshia, Introduction to Embedded Systems


2. CONTINUOUS DYNAMICS

K1

K2

Figure 2.6: A PI controller for the helicopter.

alternative controller is called a proportional-integrator (PI) controller. It


has two parameter K1 and K2 . Experiment with the values of these parame-
ters, give some plots of the behavior with the same inputs as in part (a), and
discuss the behavior of this controller in contrast to the one of part (a).

Lee & Seshia, Introduction to Embedded Systems 41


3. DISCRETE DYNAMICS

Exercises

1. Consider an event counter that is a simplified version of the counter in Section 3.1.
It has an icon like this:

This actor starts with state i and upon arrival of an event at the input, increments the
state and sends the new value to the output. Thus, e is a pure signal, and c has the
form c : R → {absent} ∪ N, assuming i ∈ N. Suppose you are to use such an event
counter in a weather station to count the number of times that a temperature rises
above some threshold. Your task in this exercise is to generate a reasonable input
signal e for the event counter. You will create several versions. For all versions,
you will design a state machine whose input is a signal τ : R → {absent} ∪ Z that
gives the current temperature (in degrees centigrade) once per hour. The output
e : R → {absent, present} will be a pure signal that goes to an event counter.

(a) For the first version, your state machine should simply produce a present out-
put whenever the input is present and greater than 38 degrees. Otherwise, the
output should be absent.
(b) For the second version, your state machine should have hysteresis. Specifi-
cally, it should produce a present output the first time the input is greater than
38 degrees, and subsequently, it should produce a present output anytime the
input is greater than 38 degrees but has dropped below 36 degrees since the
last time a present output was produced.
(c) For the third version, your state machine should implement the same hystere-
sis as in part (b), but also produce a present output at most once per day.

2. Consider a variant of the thermostat of example 3.5. In this variant, there is only one
temperature threshold, and to avoid chattering the thermostat simply leaves the heat
on or off for at least a fixed amount of time. In the initial state, if the temperature is
less than or equal to 20 degrees Celsius, it turns the heater on, and leaves it on for
at least 30 seconds. After that, if the temperature is greater than 20 degrees, it turns
the heater off and leaves it off for at least 2 minutes. It turns it on again only if the
temperature is less than or equal to 20 degrees.

Lee & Seshia, Introduction to Embedded Systems 73


EXERCISES

(a) Design an FSM that behaves as described, assuming it reacts exactly once
every 30 seconds.
(b) How many possible states does your thermostat have? Is this the smallest
number of states possible?
(c) Does this model thermostat have the time-scale invariance property?

3. Consider the following state machine:

Determine whether the following statement is true or false, and give a supporting
argument:

The output will eventually be a constant 0, or it will eventually be a


constant 1. That is, for some n ∈ N, after the n-th reaction, either the
output will be 0 in every subsequent reaction, or it will be 1 in every
subsequent reaction.

Note that Chapter 13 gives mechanisms for making such statements precise and for
reasoning about them.

4. How many reachable states does the following state machine have?

5. Consider the deterministic finite-state machine in Figure 3.14 that models a simple
traffic light.

74 Lee & Seshia, Introduction to Embedded Systems


3. DISCRETE DYNAMICS

Figure 3.14: Deterministic finite-state machine for Exercise 5

(a) Formally write down the description of this FSM as a 5-tuple:

(States, Inputs, Outputs, update, initialState).

(b) Give an execution trace of this FSM of length 4 assuming the input tick is
present on each reaction.
(c) Now consider merging the red and yellow states into a single stop state. Tran-
sitions that pointed into or out of those states are now directed into or out of
the new stop state. Other transitions and the inputs and outputs stay the same.
The new stop state is the new initial state. Is the resulting state machine de-
terministic? Why or why not? If it is deterministic, give a prefix of the trace
of length 4. If it is nondeterministic, draw the computation tree up to depth 4.

6. This problem considers variants of the FSM in Figure 3.11, which models arrivals
of pedestrians at a crosswalk. We assume that the traffic light at the crosswalk is
controlled by the FSM in Figure 3.10. In all cases, assume a time triggered model,
where both the pedestrian model and the traffic light model react once per second.
Assume further that in each reaction, each machine sees as inputs the output pro-
duced by the other machine in the same reaction (this form of composition, which
is called synchronous composition, is studied further in Chapter 6).

(a) Suppose that instead of Figure 3.11, we use the following FSM to model the
arrival of pedestrians:

Lee & Seshia, Introduction to Embedded Systems 75


EXERCISES

Find a trace whereby a pedestrian arrives (the above machine transitions to


waiting) but the pedestrian is never allowed to cross. That is, at no time after
the pedestrian arrives is the traffic light in state red.
(b) Suppose that instead of Figure 3.11, we use the following FSM to model the
arrival of pedestrians:

Here, the initial state is nondeterministically chosen to be one of none or


crossing. Find a trace whereby a pedestrian arrives (the above machine tran-
sitions from none to waiting) but the pedestrian is never allowed to cross. That
is, at no time after the pedestrian arrives is the traffic light in state red.
7. Consider the state machine in Figure 3.15. State whether each of the following is
a behavior for this machine. In each of the following, the ellipsis “· · · ” means that
the last symbol is repeated forever. Also, for readability, absent is denoted by the
shorthand a and present by the shorthand p.
(a) x = (p, p, p, p, p, · · · ), y = (0, 1, 1, 0, 0, · · · )
(b) x = (p, p, p, p, p, · · · ), y = (0, 1, 1, 0, a, · · · )
(c) x = (a, p, a, p, a, · · · ), y = (a, 1, a, 0, a, · · · )
(d) x = (p, p, p, p, p, · · · ), y = (0, 0, a, a, a, · · · )

76 Lee & Seshia, Introduction to Embedded Systems


3. DISCRETE DYNAMICS

(e) x = (p, p, p, p, p, · · · ), y = (0, a, 0, a, a, · · · )

8. (NOTE: This exercise is rather advanced.) This exercise studies properties of dis-
crete signals as formally defined in the sidebar on page 45. Specifically, we will
show that discreteness is not a compositional property. That is, when combining
two discrete behaviors in a single system, the resulting combination is not neces-
sarily discrete.

(a) Consider a pure signal x : R → {present, absent} given by

present if t is a non-negative integer



x(t) =
absent otherwise

for all t ∈ R. Show that this signal is discrete.


(b) Consider a pure signal y : R → {present, absent} given by

present if t = 1 − 1/n for any positive integer n



y(t) =
absent otherwise

for all t ∈ R. Show that this signal is discrete.


(c) Consider a signal w that is the merge of x and y in the previous two parts.
That is, w(t) = present if either x(t) = present or y(t) = present, and is
absent otherwise. Show that w is not discrete.
(d) Consider the example shown in Figure 3.1. Assume that each of the two
signals arrival and departure is discrete. Show that this does not imply that
the output count is a discrete signal.

Figure 3.15: State machine for Exercise 7.

Lee & Seshia, Introduction to Embedded Systems 77


EXERCISES

Exercises

1. Consider the extended state machine model of Figure 3.8, the garage counter. Sup-
pose that the garage has two distinct entrance and exit points. Construct a side-by-
side concurrent composition of two counters that share a variable c that keeps track
of the number of cars in the garage. Specify whether you are using synchronous or
asynchronous composition, and define exactly the semantics of your composition
by giving a single machine modeling the composition. If you choose synchronous
semantics, explain what happens if the two machines simultaneously modify the
shared variable. If you choose asynchronous composition, explain precisely which
variant of asynchronous semantics you have chosen and why. Is your composition
machine deterministic?

2. For semantics 2 in Section 5.1.2, give the five tuple for a single machine represent-
ing the composition C,

(StatesC , InputsC , OutputsC , updateC , initialStateC )

for the side-by-side asynchronous composition of two state machines A and B.


Your answer should be in terms of the five-tuple definitions for A and B,

(StatesA , InputsA , OutputsA , updateA , initialStateA )

and
(StatesB , InputsB , OutputsB , updateB , initialStateB )

3. Consider the following synchronous composition of two state machines A and B:

132 Lee & Seshia, Introduction to Embedded Systems


5. COMPOSITION OF STATE MACHINES

Construct a single state machine C representing the composition. Which states of


the composition are unreachable?

4. Consider the following synchronous composition of two state machines A and B:

Construct a single state machine C representing the composition. Which states of


the composition are unreachable?

5. Consider the following hierarchical state machine:

Construct an equivalent flat FSM giving the semantics of the hierarchy. Describe
in words the input/output behavior of this machine. Is there a simpler machine
that exhibits the same behavior? (Note that equivalence relations between state
machines are considered in Chapter 14, but here, you can use intuition and just
consider what the state machine does when it reacts.)

6. How many reachable states does the following state machine have?

Lee & Seshia, Introduction to Embedded Systems 133


EXERCISES

7. Suppose that the machine of Exercise 8 of Chapter 4 is composed in a synchronous


side-by-side composition with the following machine:

Find a tight lower bound on the time between events a and b. That is, find a lower
bound on the time gap during which there are no events in signals a or b. Give an
argument that your lower bound is tight.

134 Lee & Seshia, Introduction to Embedded Systems


EXERCISES

Exercises

1. Show how each of the following actor models can be transformed into a feedback
system by using a reorganization similar to that in Figure 6.1(b). That is, the actors
should be aggregated into a single side-by-side composite actor.

(a)

(b)

(c)

2. Consider the following state machine in a synchronous feedback composition:

172 Lee & Seshia, Introduction to Embedded Systems


6. CONCURRENT MODELS OF COMPUTATION

(a) Is it well-formed? Is it constructive?


(b) If it is well-formed and constructive, then find the output symbols for the first
10 reactions. If not, explain where the problem is.
(c) Show the composition machine, assuming that the composition has no input
and that the only output is y.

3. For the following synchronous model, determine whether it is well formed and
constructive, and if so, determine the sequence of values of the signals s1 and s2 .

4. For the following synchronous model, determine whether it is well formed and
constructive, and if so, determine the possible sequences of values of the signals s1
and s2 . Note that machine A is nondeterministic.

5. (a) Determine whether the following synchronous model is well formed and con-
structive:

Lee & Seshia, Introduction to Embedded Systems 173


EXERCISES

Explain.
(b) For the model in part (a), give the semantics by giving an equivalent flat state
machine with no inputs and two outputs.
6. Consider the following synchronous feedback composition:

Notice that the FSM A is nondeterministic.

(a) Is this composition well formed? Constructive? Explain.


(b) Give an equivalent flat FSM (with no input and no connections) that produces
exactly the same possible sequences w.

7. Recall the traffic light controller of Figure 3.10. Consider connecting the outputs
of this controller to a pedestrian light controller, whose FSM is given in Figure
5.10. Using your favorite modeling software that supports state machines (such
as Ptolemy II, LabVIEW Statecharts, or Simulink/Stateflow), construct the compo-
sition of the above two FSMs along with a deterministic extended state machine

174 Lee & Seshia, Introduction to Embedded Systems


6. CONCURRENT MODELS OF COMPUTATION

modeling the environment and generating input symbols timeR, timeG, timeY, and
isCar. For example, the environment FSM can use an internal counter to decide
when to generate these symbols.

8. Consider the following SDF model:

The numbers adjacent to the ports indicate the number of tokens produced or con-
sumed by the actor when it fires. Answer the following questions about this model.

(a) Let qA , qB , and qC denote the number of firings of actors A, B, and C, respec-
tively. Write down the balance equations and find the least positive integer
solution.
(b) Find a schedule for an unbounded execution that minimizes the buffer sizes on
the two communication channels. What is the resulting size of the buffers?

9. For each of the following dataflow models, determine whether there is an un-
bounded execution with bounded buffers. If there is, determine the minimum buffer
size.

(a)

Lee & Seshia, Introduction to Embedded Systems 175


EXERCISES

(b)

where n is some integer.


(c)

where D produces an arbitrary boolean sequence.


(d) For the same dataflow model as in part (c), assume you can specify a periodic
boolean output sequence produced by D. Find such a sequence that yields
bounded buffers, give a schedule that minimizes buffer sizes, and give the
buffer sizes.
10. Consider the SDF graph shown below:

In this figure, A, B, and C are actors. Adjacent to each port is the number of
tokens consumed or produced by a firing of the actor on that port, where N and
M are variables with positive integer values. Assume the variables w, x, y, and
z represent the number of initial tokens on the connection where these variables
appear in the diagram. These variables have non-negative integer values.

176 Lee & Seshia, Introduction to Embedded Systems


6. CONCURRENT MODELS OF COMPUTATION

(a) Derive a simple relationship between N and M such that the model is con-
sistent, or show that no positive integer values of N and M yield a consistent
model.
(b) Assume that w = x = y = 0 and that the model is consistent and find the
minimum value of z (as a function N and M ) such that the model does not
deadlock.
(c) Assume that z = 0 and that the model is consistent. Find values for w, x, and
y such that the model does not deadlock and w + x + y is minimized.
(d) Assume that w = x = y = 0 and z is whatever value you found in part
(b). Let bw , bx , by , and bz be the buffer sizes for connections w, x, y, and z,
respectively. What is the minimum for these buffer sizes?

Lee & Seshia, Introduction to Embedded Systems 177


EXERCISES

Exercises

1. Similar to Example 10.6, consider a C program for an Atmel AVR that uses a UART
to send 8 bytes to an RS-232 serial interface, as follows:
1 for(i = 0; i < 8; i++) {
2 while(!(UCSR0A & 0x20));
3 UDR0 = x[i];
4 }

Assume the processor runs at 50 MHz; also assume that initially the UART is idle,
so when the code begins executing, UCSR0A & 0x20 == 0x20 is true; further,
assume that the serial port is operating at 19,200 baud. How many cycles are re-
quired to execute the above code? You may assume that the for statement executes
in three cycles (one to increment i, one to compare it to 8, and one to perform the
conditional branch); the while statement executes in 2 cycles (one to compute
!(UCSR0A & 0x20) and one to perform the conditional branch); and the assig-
ment to UDR0 executes in one cycle.

2. Figure 10.9 gives the sketch of a program for an Atmel AVR microcontroller that
performs some function repeatedly for three seconds. The function is invoked by
calling the procedure foo(). The program begins by setting up a timer interrupt
to occur once per second (the code to do this setup is not shown). Each time the
interrupt occurs, the specified interrupt service routine is called. That routine decre-
ments a counter until the counter reaches zero. The main() procedure initializes the
counter with value 3 and then invokes foo() until the counter reaches zero.

(a) We wish to assume that the segments of code in the grey boxes, labeled A, B,
and C, are atomic. State conditions that make this assumption valid.
(b) Construct a state machine model for this program, assuming as in part (a)
that A, B, and C, are atomic. The transitions in your state machine should
be labeled with “guard/action”, where the action can be any of A, B, C, or
nothing. The actions A, B, or C should correspond to the sections of code in
the grey boxes with the corresponding labels. You may assume these actions
are atomic.
(c) Is your state machine deterministic? What does it tell you about how many
times foo() may be invoked? Do all the possible behaviors of your model
correspond to what the programmer likely intended?

284 Lee & Seshia, Introduction to Embedded Systems


10. INPUT AND OUTPUT

#include <avr/interrupt.h>
volatile uint16_t timer_count = 0;

// Interrupt service routine.


SIGNAL(SIG_OUTPUT_COMPARE1A) {

if(timer_count > 0) {
timer_count--; A
}
}

// Main program.
int main(void) {
// Set up interrupts to occur
// once per second.
...

// Start a 3 second timer.


timer_count = 3; B

// Do something repeatedly
// for 3 seconds.
while(timer_count > 0) {
foo(); C
}
}

Figure 10.9: Sketch of a C program that performs some function by calling proce-
dure foo() repeatedly for 3 seconds, using a timer interrupt to determine when to
stop.

Lee & Seshia, Introduction to Embedded Systems 285


EXERCISES

Note that there are many possible answers. Simple models are preferred over elab-
orate ones, and complete ones (where everything is defined) over incomplete ones.
Feel free to give more than one model.

3. In a manner similar to example 10.8, create a C program for the ARM CortexTM -
M3 to use the SysTick timer to invoke a system-clock ISR with a jiffy interval of
10 ms that records the time since system start in a 32-bit int. How long can this
program run before your clock overflows?

4. Consider a dashboard display that displays “normal” when brakes in the car operate
normally and “emergency” when there is a failure. The intended behavior is that
once “emergency” has been displayed, “normal” will not again be displayed. That
is, “emergency” remains on the display until the system is reset.
In the following code, assume that the variable display defines what is displayed.
Whatever its value, that is what appears on the dashboard.
1 volatile static uint8_t alerted;
2 volatile static char* display;
3 void ISRA() {
4 if (alerted == 0) {
5 display = "normal";
6 }
7 }
8 void ISRB() {
9 display = "emergency";
10 alerted = 1;
11 }
12 void main() {
13 alerted = 0;
14 ...set up interrupts...
15 ...enable interrupts...
16 ...
17 }

Assume that ISRA is an interrupt service routine that is invoked when the brakes
are applied by the driver. Assume that ISRB is invoked if a sensor indicates that the
brakes are being applied at the same time that the accelerator pedal is depressed.
Assume that neither ISR can interrupt itself, but that ISRB has higher priority than

286 Lee & Seshia, Introduction to Embedded Systems


10. INPUT AND OUTPUT

ISRA, and hence ISRB can interrupt ISRA, but ISRA cannot interrupt ISRB.
Assume further (unrealistically) that each line of code is atomic.

(a) Does this program always exhibit the intended behavior? Explain. In the
remaining parts of this problem, you will construct various models that will
either demonstrate that the behavior is correct or will illustrate how it can be
incorrect.
(b) Construct a determinate extended state machine modeling ISRA. Assume
that:
• alerted is a variable of type {0, 1} ⊂ uint8 t,
• there is a pure input A that when present indicates an interrupt request for
ISRA, and
• display is an output of type char*.
(c) Give the size of the state space for your solution.
(d) Explain your assumptions about when the state machine in (b) reacts. Is this
time triggered, event triggered, or neither?
(e) Construct a determinate extended state machine modeling ISRB. This one has
a pure input B that when present indicates an interrupt request for ISRB.
(f) Construct a flat (non-hierarchical) determinate extended state machine de-
scribing the joint operation of the these two ISRs. Use your model to argue
the correctness of your answer to part (a).
(g) Give an equivalent hierarchical state machine. Use your model to argue the
correctness of your answer to part (a).

5. Suppose a processor handles interrupts as specified by the following FSM:

Lee & Seshia, Introduction to Embedded Systems 287


EXERCISES

Here, we assume a more complicated interrupt controller than that considered in


Example 10.12, where there are several possible interrupts and an arbiter that de-
cides which interrupt to service. The above state machine shows the state of one
interrupt. When the interrupt is asserted, the FSM transitions to the Pending state,
and remains there until the arbiter provides a handle input. At that time, the FSM
transitions to the Active state and produces an acknowledge output. If another inter-
rupt is asserted while in the Active state, then it transitions to Active and Pending.
When the ISR returns, the input return causes a transition to either Inactive or Pend-
ing, depending on the starting point. The deassert input allows external hardware
to cancel an interrupt request before it gets serviced.
Answer the following questions.

(a) If the state is Pending and the input is return, what is the reaction?
(b) If the state is Active and the input is assert ∧ deassert, what is the reaction?
(c) Suppose the state is Inactive and the input sequence in three successive reac-
tions is:
i. assert ,
ii. deassert ∧ handle ,
iii. return .

288 Lee & Seshia, Introduction to Embedded Systems


10. INPUT AND OUTPUT

What are all the possible states after reacting to these inputs? Was the interrupt
handled or not?
(d) Suppose that an input sequence never includes deassert. Is it true that every
assert input causes an acknowledge output? In other words, is every interrupt
request serviced? If yes, give a proof. If no, give a counterexample.

6. Suppose you are designing a processor that will support two interrupts whose logic
is given by the FSM in Exercise 5. Design an FSM giving the logic of an arbiter
that assigns one of these two interrupts higher priority than the other. The inputs
should be the following pure signals:

assert1, return1, assert2, return2

to indicate requests and return from interrupt for interrupts 1 and 2, respectively.
The outputs should be pure signals handle1 and handle2. Assuming the assert
inputs are generated by two state machines like that in Exercise 5, can you be sure
that this arbiter will handle every request that is made? Justify your answer.

7. Consider the following program that monitors two sensors. Here sensor1 and
sensor2 denote the variables storing the readouts from two sensors. The actual
read is performed by the functions readSensor1() and readSensor2(), re-
spectively, which are called in the interrupt service routine ISR.
1 char flag = 0;
2 volatile char* display;
3 volatile short sensor1, sensor2;
4
5 void ISR() {
6 if (flag) {
7 sensor1 = readSensor1();
8 } else {
9 sensor2 = readSensor2();
10 }
11 }
12
13 int main() {
14 // ... set up interrupts ...
15 // ... enable interrupts ...
16 while(1) {
17 if (flag) {
18 if isFaulty2(sensor2) {
19 display = "Sensor2 Faulty";
20 }

Lee & Seshia, Introduction to Embedded Systems 289


EXERCISES

21 } else {
22 if isFaulty1(sensor1) {
23 display = "Sensor1 Faulty";
24 }
25 }
26 flag = !flag;
27 }
28 }

Functions isFaulty1() and isFaulty2() check the sensor readings for any
discrepancies, returning 1 if there is a fault and 0 otherwise. Assume that the vari-
able display defines what is shown on the monitor to alert a human operator
about faults. Also, you may assume that flag is modified only in the body of
main.
Answer the following questions:

(a) Is it possible for the ISR to update the value of sensor1 while the main
function is checking whether sensor1 is faulty? Why or why not?
(b) Suppose a spurious error occurs that causes sensor1 or sensor2 to be a
faulty value for one measurement. Is it possible for that this code would not
report “Sensor1 faulty” or “Sensor2 faulty”?
(c) Assuming the interrupt source for ISR() is timer-driven, what conditions
would cause this code to never check whether the sensors are faulty?
(d) Suppose that instead being interrupt driven, ISR and main are executed con-
currently, each in its own thread. Assume a microkernel that can interrupt
any thread at any time and switch contexts to execute another thread. In this
scenario, is it possible for the ISR to update the value of sensor1 while the
main function is checking whether sensor1 is faulty? Why or why not?

290 Lee & Seshia, Introduction to Embedded Systems


EXERCISES

Exercises

1. Give an extended state-machine model of the addListener procedure in Figure


11.2 similar to that in Figure 11.3,

2. Suppose that two int global variables a and b are shared among several threads.
Suppose that lock a and lock b are two mutex locks that guard access to a and
b. Suppose you cannot assume that reads and writes of int global variables are
atomic. Consider the following code:
1 int a, b;
2 pthread_mutex_t lock_a
3 = PTHREAD_MUTEX_INITIALIZER;
4 pthread_mutex_t lock_b
5 = PTHREAD_MUTEX_INITIALIZER;
6
7 void procedure1(int arg) {
8 pthread_mutex_lock(&lock_a);
9 if (a == arg) {
10 procedure2(arg);
11 }
12 pthread_mutex_unlock(&lock_a);
13 }
14
15 void procedure2(int arg) {
16 pthread_mutex_lock(&lock_b);
17 b = arg;
18 pthread_mutex_unlock(&lock_b);
19 }

Suppose that to ensure that deadlocks do not occur, the development team has
agreed that lock b should always be acquired before lock a by any thread that
acquires both locks. Note that the code listed above is not the only code in the pro-
gram. Moreover, for performance reasons, the team insists that no lock be acquired
unnecessarily. Consequently, it would not be acceptable to modify procedure1
as follows:
1 void procedure1(int arg) {
2 pthread_mutex_lock(&lock_b);
3 pthread_mutex_lock(&lock_a);
4 if (a == arg) {
5 procedure2(arg);
6 }
7 pthread_mutex_unlock(&lock_a);

318 Lee & Seshia, Introduction to Embedded Systems


11. MULTITASKING

8 pthread_mutex_unlock(&lock_b);
9 }

A thread calling procedure1 will acquire lock b unnecessarily when a is not


equal to arg. 2 Give a design for procedure1 that minimizes unnecessary
acquisitions of lock b. Does your solution eliminate unnecessary acquisitions of
lock b? Is there any solution that does this?
3. The implementation of get in Figure 11.6 permits there to be more than one thread
calling get.
However, if we change the code on lines 30-32 to:
1 if (size == 0) {
2 pthread_cond_wait(&sent, &mutex);
3 }

then this code would only work if two conditions are satisfied:
• pthread cond wait returns only if there is a matching call to
pthread cond signal, and
• there is only one consumer thread.
Explain why the second condition is required.
4. The producer/consumer pattern implementation in Example 11.13 has the draw-
back that the size of the queue used to buffer messages is unbounded. A program
could fail by exhausting all available memory (which will cause malloc to fail).
Construct a variant of the send and get procedures of Figure 11.6 that limits the
buffer size to 5 messages.
5. An alternative form of message passing called rendezvous is similar to the pro-
ducer/consumer pattern of Example 11.13, but it synchronizes the producer and
consumer more tightly. In particular, in Example 11.13, the send procedure re-
turns immediately, regardless of whether there is any consumer thread ready to
receive the message. In a rendezvous-style communication, the send procedure
will not return until a consumer thread has reached a corresponding call to get.
Consequently, no buffering of the messages is needed. Construct implementations
of send and get that implement such a rendezvous.
2
In some thread libraries, such code is actually incorrect, in that a thread will block trying to acquire a
lock it already holds. But we assume for this problem that if a thread attempts to acquire a lock it already
holds, then it is immediately granted the lock.

Lee & Seshia, Introduction to Embedded Systems 319


EXERCISES

6. Consider the following code.


1 int x = 0;
2 int a;
3 pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER;
4 pthread_cond_t go = PTHREAD_COND_INITIALIZER; // used in part c
5
6 void proc1(){
7 pthread_mutex_lock(&lock_a);
8 a = 1;
9 pthread_mutex_unlock(&lock_a);
10 <proc3>(); // call to either proc3a or proc3b
11 // depending on the question
12 }
13
14 void proc2(){
15 pthread_mutex_lock(&lock_a);
16 a = 0;
17 pthread_mutex_unlock(&lock_a);
18 <proc3>();
19 }
20
21 void proc3a(){
22 if(a == 0){
23 x = x + 1;
24 } else {
25 x = x - 1;
26 }
27 }
28
29 void proc3b(){
30 pthread_mutex_lock(&lock_a);
31 if(a == 0){
32 x = x + 1;
33 } else {
34 x = x - 1;
35 }
36 pthread_mutex_unlock(&lock_a);
37 }

Suppose proc1 and proc2 run in two separate threads and that each procedure
is called in its respective thread exactly once. Variables x and a are global and
shared between threads and x is initialized to 0. Further, assume the increment and
decrement operations are atomic.

320 Lee & Seshia, Introduction to Embedded Systems


11. MULTITASKING

The calls to proc3 in proc1 and proc2 should be replaced with calls to proc3a
and proc3b depending on the part of the question.

(a) If proc1 and proc2 call proc3a in lines 10 and 18, is the final value of
global variable x guaranteed to be 0? Justify your answer.
(b) What if proc1 and proc2 call proc3b? Justify your answer.
(c) With proc1 and proc2 still calling proc3b, modify proc1 and proc2
with condition variable go to guarantee the final value of x is 2. Specifically,
give the lines where pthread cond wait and pthread cond signal
should be inserted into the code listing. Justify your answer briefly. Make the
assumption that proc1 acquires lock a before proc2.
Also recall that
pthread cond wait(&go, &lock a);
will temporarily release lock a and block the calling thread until
pthread cond signal(&go);
is called in another thread, at which point the waiting thread will be unblocked
and reacquire lock a.

(This problem is due to Matt Weber.)

Lee & Seshia, Introduction to Embedded Systems 321


12. SCHEDULING

Exercises

1. This problem studies fixed-priority scheduling. Consider two tasks to be executed


periodically on a single processor, where task 1 has period p1 = 4 and task 2 has
period p2 = 6.

(a) Let the execution time of task 1 be e1 = 1. Find the maximum value for the
execution time e2 of task 2 such that the RM schedule is feasible.
(b) Again let the execution time of task 1 be e1 = 1. Let non-RMS be a fixed-
priority schedule that is not an RM schedule. Find the maximum value for the
execution time e2 of task 2 such that non-RMS is feasible.
(c) For both your solutions to (a) and (b) above, find the processor utilization.
Which is better?
(d) For RM scheduling, are there any values for e1 and e2 that yield 100% utiliza-
tion? If so, give an example.

2. This problem studies dynamic-priority scheduling. Consider two tasks to be exe-


cuted periodically on a single processor, where task 1 has period p1 = 4 and task
2 has period p2 = 6. Let the deadlines for each invocation of the tasks be the end
of their period. That is, the first invocation of task 1 has deadline 4, the second
invocation of task 1 has deadline 8, and so on.

(a) Let the execution time of task 1 be e1 = 1. Find the maximum value for the
execution time e2 of task 2 such that EDF is feasible.
(b) For the value of e2 that you found in part (a), compare the EDF schedule
against the RM schedule from Exercise 1 (a). Which schedule has less pre-
emption? Which schedule has better utilization?

3. This problem compares RM and EDF schedules. Consider two tasks with periods
p1 = 2 and p2 = 3 and execution times e1 = e2 = 1. Assume that the deadline for
each execution is the end of the period.

(a) Give the RM schedule for this task set and find the processor utilization.
How does this utilization compare to the Liu and Layland utilization bound of
(12.2)?
(b) Show that any increase in e1 or e2 makes the RM schedule infeasible. If you
hold e1 = e2 = 1 and p2 = 3 constant, is it possible to reduce p1 below 2

Lee & Seshia, Introduction to Embedded Systems 351


EXERCISES

and still get a feasible schedule? By how much? If you hold e1 = e2 = 1


and p1 = 2 constant, is it possible to reduce p2 below 3 and still get a feasible
schedule? By how much?
(c) Increase the execution time of task 2 to be e2 = 1.5, and give an EDF sched-
ule. Is it feasible? What is the processor utilization?

4. This problem, formulated by Hokeun Kim, also compares RM and EDF schedules.
Consider two tasks to be executed periodically on a single processor, where task 1
has period p1 = 4 and task 2 has period p2 = 10. Assume task 1 has execution
time e1 = 1, and task 2 has execution time e2 = 7.

(a) Sketch a rate-monotonic schedule (for 20 time units, the least common multi-
ple of 4 and 10). Is the schedule feasible?
(b) Now suppose task 1 and 2 contend for a mutex lock, assuming that the lock
is acquired at the beginning of each execution and released at the end of each
execution. Also, suppose that acquiring or releasing locks takes zero time
and the priority inheritance protocol is used. Is the rate-monotonic schedule
feasible?
(c) Assume still that tasks 1 and 2 contend for a mutex lock, as in part (b). Sup-
pose that task 2 is running an anytime algorithm, which is an algorithm that
can be terminated early and still deliver useful results. For example, it might
be an image processing algorithm that will deliver a lower quality image when
terminated early. Find the maximum value for the execution time e2 of task
2 such that the rate-monotonic schedule is feasible. Construct the resulting
schedule, with the reduced execution time for task 2, and sketch the schedule
for 20 time units. You may assume that execution times are always positive
integers.
(d) For the original problem, where e1 = 1 and e2 = 7, and there is no mutex
lock, sketch an EDF schedule for 20 time units. For tie-breaking among task
executions with the same deadline, assume the execution of task 1 has higher
priority than the execution of task 2. Is the schedule feasible?
(e) Now consider adding a third task, task 3, which has period p3 = 5 and ex-
ecution time e3 = 2. In addition, assume as in part (c) that we can adjust
execution time of task 2.
Find the maximum value for the execution time e2 of task 2 such that the
EDF schedule is feasible and sketch the schedule for 20 time units. Again,

352 Lee & Seshia, Introduction to Embedded Systems


12. SCHEDULING

you may assume that the execution times are always positive integers. For
tie-breaking among task executions with the same deadline, assume task i has
higher priority than task j if i < j.)

5. This problem compares fixed vs. dynamic priorities, and is based on an example by
Burns and Baruah (2008). Consider two periodic tasks, where task τ1 has period
p1 = 2, and task τ2 has period p2 = 3. Assume that the execution times are e1 = 1
and e2 = 1.5. Suppose that the release time of execution i of task τ1 is given by

r1,i = 0.5 + 2(i − 1)

for i = 1, 2, · · · . Suppose that the deadline of execution i of task τ1 is given by

d1,i = 2i.

Correspondingly, assume that the release times and deadlines for task τ2 are

r2,i = 3(i − 1)

and
d2,i = 3i.
(a) Give a feasible fixed-priority schedule.
(b) Show that if the release times of all executions of task τ1 are reduced by 0.5,
then no fixed-priority schedule is feasible.
(c) Give a feasible dynamic-priority schedule with the release times of task τ1
reduced to
r1,i = 2(i − 1).

6. This problem studies scheduling anomalies. Consider the task precedence graph
depicted in Figure 12.16 with eight tasks. In the figure, ei denotes the execution
time of task i. Assume task i has higher priority than task j if i < j. There is no
preemption. The tasks must be scheduled respecting all precedence constraints and
priorities. We assume that all tasks arrive at time t = 0.

(a) Consider scheduling these tasks on two processors. Draw the schedule for
these tasks and report the makespan.
(b) Now consider scheduling these tasks on three processors. Draw the schedule
for these tasks and report the makespan. Is the makespan bigger or smaller
than that in part (a) above?

Lee & Seshia, Introduction to Embedded Systems 353


EXERCISES

e1= 3 e8= 5

e2= 2 e7 = 10

e3= 2 e4 = 5

e5 = 5

e6 = 5

Figure 12.16: Precedence Graph for Exercise 6.

(c) Now consider the case when the execution time of each task is reduced by
1 time unit. Consider scheduling these tasks on two processors. Draw the
schedule for these tasks and report the makespan. Is the makespan bigger or
smaller than that in part (a) above?

7. This problem studies the interaction between real-time scheduling and mutual ex-
clusion, and was formulated by Kevin Weekly.
Consider the following excerpt of code:
1 pthread_mutex_t X; // Resource X: Radio communication
2 pthread_mutex_t Y; // Resource Y: LCD Screen
3 pthread_mutex_t Z; // Resource Z: External Memory (slow)
4
5 void ISR_A() { // Safety sensor Interrupt Service Routine
6 pthread_mutex_lock(&Y);
7 pthread_mutex_lock(&X);
8 display_alert(); // Uses resource Y
9 send_radio_alert(); // Uses resource X
10 pthread_mutex_unlock(&X);
11 pthread_mutex_unlock(&Y);
12 }
13
14 void taskB() { // Status recorder task
15 while (1) {
16 static time_t starttime = time();
17 pthread_mutex_lock(&X);
18 pthread_mutex_lock(&Z);
19 stats_t stat = get_stats();
20 radio_report( stat ); // uses resource X

354 Lee & Seshia, Introduction to Embedded Systems


12. SCHEDULING

21 record_report( stat ); // uses resource Z


22 pthread_mutex_unlock(&Z);
23 pthread_mutex_unlock(&X);
24 sleep(100-(time()-starttime)); // schedule next excecution
25 }
26 }
27
28 void taskC() { // UI Updater task
29 while(1) {
30 pthread_mutex_lock(&Z);
31 pthread_mutex_lock(&Y);
32 read_log_and_display(); // uses resources Y and Z
33 pthread_mutex_unlock(&Y);
34 pthread_mutex_unlock(&Z);
35 }
36 }

You may assume that the comments fully disclose the resource usage of the proce-
dures. That is, if a comment says ”uses resource X”, then the relevant procedure
uses only resource X. The scheduler running aboard the system is a priority-based
preemptive scheduler, where taskB is higher priority than taskC. In this problem,
ISR A can be thought of as an asynchronous task with the highest priority.
The intended behavior is for the system to send out a radio report every 100ms and
for the UI to update constantly. Additionally, if there is a safety interrupt, a radio
report is sent immediately and the UI alerts the user.

(a) Occasionally, when there is a safety interrupt, the system completely stops
working. In a scheduling diagram (like Figure 12.11 in the text), using the
tasks {A,B,C}, and resources {X,Y,Z}, explain the cause of this behavior.
Execution times do not have to be to scale in your diagram. Label your dia-
gram clearly. You will be graded in part on the clarity of your answer, not just
on its correctness.
(b) Using the priority ceiling protocol, show the scheduling diagram for the same
sequence of events that you gave in part (a). Be sure to show all resource locks
and unlocks until all tasks are finished or reached the end of an iteration. Does
execution stop as before?
(c) Without changing the scheduler, how could the code in taskB be reordered to
fix the issue? Using an exhaustive search of all task/resource locking scenar-
ios, prove that this system will not encounter deadlock. (Hint: There exists

Lee & Seshia, Introduction to Embedded Systems 355


EXERCISES

a proof enumerating 6 cases, based on reasoning that the 3 tasks each have 2
possible resources they could block on.)

356 Lee & Seshia, Introduction to Embedded Systems

You might also like