Lecture02_SWDesignBasics
Lecture02_SWDesignBasics
1
Overview
Concurrency
How do we make things happen at the right times?
2
CONCURRENCY
3
MCU Hardware & Software for Concurrency
CPU executes instructions from one or
more threads of execution
4
Concurrent Hardware & Software Operation
Software Hardware Software Hardware Software
Time
Embedded systems rely on both MCU hardware peripherals and software to get
everything done on time
5
CPU Scheduling
MCU’s Interrupt system provides a basic scheduling approach for CPU
“Run this subroutine every time this hardware event occurs”
Is adequate for simple systems
How do we make the processor responsive? (How do we make it do the right things at the
right times?)
If we have more software threads than hardware threads, we need to share the processor.
6
Definitions
TRelease Other
processing
Ttask
Scheduler
Task or ISR Code
Latency
Response
Time
Time
TRelease(i) = Time at which task (or interrupt) i requests service/is released/is ready to run
TLatency (i) = Delay between release and start of service for task i
TResponse(i) = Delay between request for service and completion of service for task i
TTask(i) = Time needed to perform computations for task i
TISR(i) = Time needed to perform interrupt service routine i
7
Scheduling Approaches
8
Event-Triggered Scheduling using Interrupts
Basic architecture, useful for simple low-power devices
Very little code or time overhead
Leverages built-in task dispatching of interrupt system
Can trigger ISRs with input changes, timer expiration, UART data reception, analog input level crossing
comparator threshold
Function types
Main function configures system and then goes to sleep
◦ If interrupted, it goes right back to sleep
Only interrupts are used for normal program operation
Example: bike computer
Int1: wheel rotation
Int2: mode key
Int3: clock
Output: Liquid Crystal Display
9
Bike Computer Functions
ISR 1: ISR 2: ISR 3:
Reset
Wheel rotation Mode Key Time of Day Timer
Configure timer rotations++; mode++; cur_time ++;
inputs and if (rotations> mode = mode % lcd_refresh--;
outputs R_PER_MILE/10) { NUM_MODES; if (lcd_refresh==0) {
tenth_miles++; return from interrupt; convert tenth_miles
cur_time = 0; rotations = 0; and display
rotations = 0; } convert speed
tenth_miles = 0; speed = and display
circumference/ if (mode == 0)
while (1) { (cur_time – prev_time); convert cur_time
sleep; compute avg_speed; and display
} prev_time = cur_time; else
return from interrupt convert avg_speed
and display
lcd_refresh =
LCD_REF_PERIOD
}
10
A More Complex Application
11
Application Software Tasks
Dec: Decode GPS sentence to find current vehicle position.
Check: Check to see if approaching any pothole locations. Takes longer as the
number of potholes in database increases.
Rec: Record position to flash memory. Takes a long time if erasing a block.
Sw: Read user input switches. Run 10 times per second
LCD: Update LCD with map. Run 4 times per second
Dec
Check
Rec
Sw
LCD
Time
12
How do we schedule these tasks?
Task scheduling: Deciding which task should be run
Dec now
Check Two fundamental questions
Do we run tasks in the same order every time?
Rec ◦ Yes: Static schedule (cyclic executive, round-robin)
◦ No: Dynamic, prioritized schedule
Sw Can one task preempt another, or must it wait for
completion?
LCD
◦ Yes: Preemptive
◦ No: Non-preemptive (cooperative, run-to-completion)
13
Static Schedule (Cyclic Executive)
Dec Check Rec Sw LCD Dec
14
Static Schedule Example
GPS Data Arrives Checking
complete
Response Time
15
Dynamic Scheduling
16
Dynamic RTC Schedule
GPS Data Arrives Checking
complete
Response Time
17
Task State and Scheduling Rules
Scheduler chooses among Ready tasks for
execution based on priority
Scheduling Rules
If no task is running, scheduler starts the Ready
highest priority ready task Task is released
Once started, a task runs until it completes (ready to run)
Tasks then enter waiting state until triggered
or released again Start
highest
Waiting priority
ready task
18 18
Dynamic Preemptive Schedule
GPS Data Arrives Checking
complete
Response Time
19
Comparison of Response Times
Static
Rec Sw LCD Dec Check
Dynamic Run-to-Completion
Rec Dec Check
Dynamic Preemptive
Dec Check
Pros
Preemption offers best response time
◦ Can do more processing (support more potholes, or higher vehicle speed)
◦ Or can lower processor speed, saving money, power
Cons
Requires more complicated programming, more memory
Introduces vulnerability to data race conditions
20
Common Schedulers
21
Cyclic Executive with Interrupts
BOOL DeviceARequest, DeviceBRequest,
Two priority levels DeviceCRequest;
main code – background void interrupt HandleDeviceA(){
Interrupts – foreground /* do A’s urgent work */
Example of a foreground / background ...
DeviceARequest = TRUE;
system }
Interrupt routines run in foreground void main(void) {
(high priority) while (TRUE) {
Run when triggered if (DeviceARequest) {
FinishDeviceA();
Handle most urgent work
}
Set flags to request processing by main if (DeviceBRequest) {
loop FinishDeviceB();
Main user code runs in background }
Uses “round-robin” approach to pick if (DeviceCRequest) {
tasks, takes turns FinishDeviceC();
}
Tasks do not preempt each other
}
}
22
Run-To-Completion Scheduler
Use a scheduler function to run task functions at the right rates
Table stores information per task
◦ Period: How many ticks between each task release
◦ Release Time: how long until task is ready to run
◦ ReadyToRun: task is ready to run immediately
Scheduler runs forever, examining schedule table which indicates tasks which are ready to run (have been
“released”)
A periodic timer interrupt triggers an ISR, which updates the schedule table
◦ Decrements “time until next release”
◦ If this time reaches 0, set the task’s Run flag and reload its time with the period
Priority is typically static, so can use a table with highest priority tasks first for a fast, simple
scheduler implementation.
23
Preemptive Scheduler
Task functions need not run to completion, but can be interleaved with each other
Simplifies writing software
Improves response time
Introduces new potential problems
Worst case response time for highest priority task does not depend on other tasks,
only ISRs and scheduler
Lower priority tasks depend only on higher priority tasks
24
24
Task State and Scheduling Rules
Scheduler chooses among Ready tasks
for execution based on priority
Task needs
something Running
to happen
25 25
What’s an RTOS?
What does Real-Time mean?
Can calculate and guarantee the maximum response time for each task and interrupt service routine
This “bounding” of response times allows use in hard-real-time systems (which have deadlines which must
be met)
26
Comparison of Timing Dependence
Non-preemptive Non-preemptive Preemptive
Static Dynamic Dynamic
Device A ISR
Device A ISR Device A ISR
Device B ISR
Device B ISR Device B ISR
Device ... ISR
Device ... ISR
Device ... ISR
Device Z ISR Device Z ISR
Device Z ISR
Slowest Task
Task 1 Code
Task 5 Code Task 1 Code
Task 1 Code Task 4 Code
Task 2 Code Task 6 Code
Task 3 Code Task 2 Code
Task 2 Code
27
Task 3 Max S
Comparison of RAM Requirements
Non-preemptive Non-preemptive Preemptive
Static Dynamic Dynamic
28
SOFTWARE ENGINEERING FOR
EMBEDDED SYSTEMS
29
Good Enough Software, Soon Enough
How do we make software correct enough without going bankrupt?
Need to be able to develop (and test) software efficiently
Follow a good plan
Start with customer requirements
Design architectures to define the building blocks of the systems (tasks, modules, etc.)
Add missing requirements
◦ Fault detection, management and logging
◦ Real-time issues
◦ Compliance to a firmware standards manual
◦ Fail-safes
Create detailed design
Implement the code, following a good development process
◦ Perform frequent design and code reviews
◦ Perform frequent testing (unit and system testing, preferably automated)
◦ Use revision control to manage changes
Perform post-mortems to improve development process
30
What happens when the plan meets reality?
Successful software engineering depends on balancing many factors, many of which are
non-technical!
31
Risk Reduction
32
Software Lifecycle Concepts
Coding is the most visible part of a software development process but is not the only
one
The software will likely be enhanced over time - Extensive downstream modification and
maintenance!
Corrections, adaptations, enhancements & preventive maintenance
33
Product Development Lifecycle
Coding
Coding
Coding
Coding
Diagram: Phil Koopman,
Coding Carnegie Mellon
Coding University
With all this code development and modification, it is worth putting extra effort into
simplifying code development activities: understanding, maintaining, enhancing, testing
34
Requirements
Ganssle’s Reason #5 for why embedded projects fail: Vague Requirements
Types of requirements
Functional - what the system needs to do
Nonfunctional - emergent system behaviors such as response time, reliability, energy efficiency, safety, etc.
Constraints - limit design choices
Representations
Text – Liable to be incomplete, bloated, ambiguous, even contradictory
Diagrams (state charts, flow charts, message sequence charts)
◦ Concise
◦ Can often be used as design documents
Traceability
Each requirement should be verifiable with a test
Stability
Requirements churn leads to inefficiency and often “recency” problems (most recent requirement change is
assumed to be most important)
35
Design Before Coding
Architectural Detailed
Coding Test the Code
Design Design
36
Design Before Coding
How much of the system do you design before coding?
AD DD C T
AD DD C T
AD DD C T
AD DD C T
AD DD C T
AD DD C T
AD Prototyping DD C T
AD DD C T
AD DD C T
37
Development Models
How do we schedule these pieces?
38
Waterfall (Idealized)
Plan the work, and then
work the plan
BUFD: Big Up-Front Design
Model implies that we and the
customers know
All of the requirements up front
All of the interactions between components, etc.
How long it will take to write the software and debug it
39
Waterfall (As Implemented)
Reality: We are not omniscient,
so there is plenty of
backtracking
40
Agile Development: SCRUM
http://www.mountaingoatsoftware.com/topics/scrum
http://www.codeproject.com/KB/architecture/scrum.aspx
Diagram: Wikipedia
41
V Model Overview
Requirements
Analysis
Requirements Validation provided by testing Functional
Specification Testing
Review
Architectural Integration
Design Testing
Review
Detailed Integration
Design Testing
Review
S/W Unit
Coding
Testing
Review
Code
Themes:
Link front and back ends of life-cycle for efficiency
Provide “traceability” to ensure nothing falls through the cracks
42
1. Requirements Specification and Validation Plan
44
3. Detailed Design
45
State Machine for Parsing NMEA-0183
Any char. except *, \r or \n
$ Append char to buf.
Start Append char to buf. Talker + Inc. counter
*, \r or \n, Sentence
non-text, or Type
buf==$SDDBT, $VWVHW, or
counter>6 $YXXDR
Enqueue all chars. from buf
/r or /n
Sentence
Body Any char. except *
Enqueue char
*
Enqueue char
Checksum
1
Any char.
Save as checksum1
Checksum
2
Any char.
Save as checksum2
46
Flowcharts
47
Sequence of Interactions between Components
48
4. Coding and Code Inspections
49
Peer Code Review
50
5. Software Testing
Testing IS NOT “the process of verifying the program works correctly”
The program probably won’t work correctly in all possible cases
◦ Professional programmers have 1-3 bugs per 100 lines of code after it is “done”
51
Approaches to Testing
Incremental Testing
Code a function and then test it (module/unit/element testing)
Then test a few working functions together (integration testing)
◦ Continue enlarging the scope of tests as you write new functions
Incremental testing requires extra code for the test harness
◦ A driver function calls the function to be tested
◦ A stub function might be needed to simulate a function called by the function under test, and which
returns or modifies data.
◦ The test harness can automate the testing of individual functions to detect later bugs
Big Bang Testing
Code up all of the functions to create the system
Test the complete system
◦ Plug and pray
52
Why Test Incrementally?
53
Example Test Plan
54
6. Perform Project Retrospectives
Goals – improve your engineering processes
Extract all useful information learned from the just-completed project – provide “virtual
experience” to others
Provide positive non-confrontational feedback
Document problems and solutions clearly and concisely for future use
55
Example Postmortem Structure
Product Support
Bugs Tools
Software design Team burnout
Hardware design Change orders
Personnel availability
Process
Code standards
Code interfacing
Change control
How we did it
Team coordination
56