Lecture #5 Intro. to Engineering Process and Design Techniqueskoopman/lectures/ece348/...•...
Transcript of Lecture #5 Intro. to Engineering Process and Design Techniqueskoopman/lectures/ece348/...•...
Lecture #5
Intro. to Engineering Process and
Design Techniques18-348 Embedded System Engineering
Philip KoopmanWednesday, 27-Jan-2016
© Copyright 2006-2016, Philip Koopman, All Rights Reserved
&Electrical ComputerENGINEERING
2
Real embedded projects aren’t just about the CPU! http://www.youtube.com/watch_popup?
v=PKaNyvOgMA0&vq=medium#t=52 Digital Hardware Software
… but also …
Mechanical Electrical Fluids Environmental control Food Safety Security Lots of engineering considerations
What happens if a software defect causes temperature problems? [Moobella06]
3
Where Are We Now? Where we’ve been:
• Hardware & assembly language
Where we’re going today:• Is there more to embedded systems than just slapping together hardware and
hacking out the code?
Where we’re going next:• Embedded C and language use• Embedded programming techniques• Memory bus• Economics / general optimization• Serial ports• Debug & Test
• Exam #1
4
Preview Engineering projects have phases
• Marketing, product definition, requirements, architecture, design, implementation, test, V&V, support, evolution
Requirements• Shall vs. should• Keep an eye on these in projects
Design• Flowcharts• Statecharts• Sequence Diagrams
Implementation• Basic coding style• Good & Bad practices
5
Embedded System Engineers Need Perspective How does what I do fit into the bigger picture?
• What outside constraints do I have to meet (e.g., limited battery life)• How can I exploit the non-computer aspects of the system?
How can I contribute toward the product, not just my piece?• Ask how your company makes money from the product• Advocate a decent engineering process (what this lecture is about)
Important embedded skills perspective:• Knowing how to solder doesn’t make you a hardware engineer• Knowing how to write lines of code doesn’t make you a software engineer• Knowing how to do both isn’t enough to be an embedded systems engineer
6
Typical project life cycle:
Engineering phases:
Marketing Product definition Requirements Architecture Design Implementation Test Verification &
Validation Support Evolution
General System Life Cycle
7
Marketing & Product Definition What is the need?
• Personal communication device• More selection in TV programs• Better energy efficiency in a home
What can we design or otherwise provide to satisfy the need?• Cell phones• On-demand TV, TiVO, etc.• “Smarter” water heaters, thermostats
• Usually, product definition has a list of high level features to be provided– E.g., not just a “thermostat”, but “setback thermostat with four time bands for
weekdays and two time bands for weekends; able to control both heating and cooling”
8
Specification (Requirements) – What Does It Do? Sometimes marketing provides guidance on what it does
• Based on customer preferences• Based on competition
Generally, marketing decides what and why; engineers decide how
Specification – precise, detailed list of how the system works• “Shall” means must do it• “Should” means it would be nice, but might not happen in some situations
1. The program shall compute the hash value of the string in memory and store the lowest byte of the value in memory.
2. When PB1 (on the project board) is pressed, the program shall display the stored hash value on the bar graph LED.
3. When PB1 is not pressed, all elements of the bar graph LED shall be turned off.4. Values written to the display shall use the following convention:
» * A "1" bit shall be indicated by the corresponding LED being lit.» * A "0" bit shall be indicated by the corresponding LED being unlit.
9
Architecture – How Do The Pieces Fit Together? Architectures are all about “boxes and arrows”
• Boxes are the pieces• Arrows are how they fit together
Software architecture
Hardware architecture
CPU
A S A S
CPU
S A S
CPU
S A
A
A
A S
METHODS
DATA
OBJECT "BUS"
METHODS
DATA
METHODS
DATA
10
Architecture Examples From [Valvano]
CALLSCALLS CALLS CALLSCALLS
I/O I/O I/O I/O
11
Design – Working Out High Level Details(Is “High Level Details” an oxymoron? – Not in computer abstractions!)
Hardware: “design” level is usually schematics• Which devices are connected and how• BUT NOT: how wires are routed on printed circuit board• BUT NOT: not package selection and placement• Maybe you can synthesis implementation from there; depends on tool chain
Software: “design” is high level description• Pseudocode, algorithms• Flow charts, state charts, most UML diagrams, …• BUT NOT: actual lines of code (either C or assembly language)
The point of design is to hide messy details so you can do the hard stuff• Circuit board routing doesn’t (usually) affect how registers are connected• Software design shouldn’t worry about the name of a variable used as the index
in a switch statement
12
Implementation – The Gory Details Hardware
• Component placement• Circuit board routing• Decoupling capacitors• Connector locations• Etc.
Software• Source code• Header files• Etc.
13
Test – Executing Code To Check Its Operation How many of you write perfect code all the time?
• If you play around with code a few minutes, was that perfect testing?
Testing is one way to gain confidence the code is correct• Involves actual execution of code (or executing with a CPU simulator)• Testing includes:
– The program you are testing– Support framework to provide inputs/outputs– The workload (data inputs, etc.) you are testing it with– A set of expected outputs – passing the test means program performs to expectations
You all do some form of testing• Most engineers don’t do very good testing without some training
(later lecture to cover the basics)• Some engineers are “born testers” – they are good at breaking things!
14
Verification and Validation Testing is not the only way to know you got it right
• Verification – did you produce what you planned to produce?– e.g., does the implementation actually implement what the design says?
• Validation – does it actually do the Right Thing?– e.g., does the implementation make the customer happy?
Simple verification and validation techniques• Have someone grade your work (e.g., TAs grading labs)
– But generally this doesn’t happen in the Real World– There is usually no “solution sheet” in the Real World either!
• Have a buddy look over your stuff (“peer reviews”)• Have an outsider look over your stuff (“external reviews”)• Have a testing agency exercise your stuff (“FAA flight certification”)
– This is close to grading – but they don’t have a true answer sheet– They expect you to give them an answer sheet and then convince them it is right
15
Version Control What happens if you need to go back to an old version?
• The new version doesn’t work, and you don’t remember what you changed• The new version doesn’t work, and you can’t figure out why• Your computer crashed and you need to restore some recent version• Someone messed up the code base before quitting• There is a bug in an old deployed version and you need to test small fixes• …
Use some sort of version control – always• Simplest versions: copy directories to temp directory once in a while• Better: keep old versions around for a long time (Prog.c, Prog.save1.c,
Prog.save2.c, …) or do this at directory level• Best: use a version control system
– SVN– Sourcesafe– …. lots more– For this course (and others) don’t use one that makes your code publicly visible to
avoid problems with someone else copying your stuff
16
Lifecycle Support What happens after you ship version 1.0?
• Version 1.1, Emergency Bug Patch 1.1.035, and Version 2.0 happen• You get calls at 3 AM because there is a bug in version 1.7.3.2
– … but you can’t even remember what is in that particular version!– … and you can’t find, or even recreate the source code for it!
• You get calls at your new job from desperate people at your old job• …
Good engineering is more than making it work.You need to make sure:• Other people can understand it
– For that matter, you can understand it a few years later!• You/others can modify it, both in small and large ways• You can demonstrate your part of the design isn’t where the bug is (if true)
– It is always your fault unless you can demonstrate otherwise• It isn’t brittle to changes in operating conditions, technology, users, …
17
DESIGN
Would you start building a house without a floorplan?
Would you just start bending sheet metal without a drawing?
Would you start fabricating a chip without a layout?
Would you just start soldering or protoboarding without a schematic?
Would you just start writing code without a software design?
The answer to all these questions is (or should be) NO!
18
Flowchart Basics
19
Flowchart Pro/Con Pro:
• Good at describing a lot of classical software…… especially if its job is to execute a sequence of steps in mostly linear order
• Everyone seems to know how to create one• Better than nothing
Con:• Easy to get caught in trap of one line of code per box – pretty much useless
– Each box should be a high level operation, not just a line of code• Subroutine calls are the only way to manage complexity – but not enough• Usually get out of date with software, because aren’t that useful for
maintenance
But, still can be pretty useful for some situations• For object-oriented systems, generally use UML sequence diagrams instead
20
Exercise – Flow Chart For Doing An 18-348 Lab
21
Statechart Basics Statecharts are a software finite state machine diagram
• “Bubbles” are states of a state machine– While in each box, perform some action
• “Arrows” between bubbles are guarded state transitions– Take an arrow of the “guard” condition is true
• Has a “reset” or initialization state• Can be implemented via switch statements in software
22
Example StatechartThis is a controller for a multi-speed motor or other similar application Inputs: SPDBUTTON and ONOFF Outputs: Speed = {Stop, Slow, Med, Fast} State names (arbitrary labels): {OFF, SLOW, MEDIUM, FAST} System Reset is to state s1
[Koopman10]
23
Example Statechart Implementation – 1
24
Example Statechart Implementation – 2
25
Statechart Pro/Con Pro:
• If you had 18-240, you already know how to do these!– They are the software version of FSM state diagrams
• Many embedded systems have a lot of modes; great for that– What common embedded systems have modes?
• Forcing designers to look for states generally improves designs– Lots of duplicative nested “if” statements usually means it should have been
designed as a state machine with a “switch” statement instead
Con:• Not every system is reducible to states• Not good at representing flows of control (long lists of steps)
Other considerations• Use a switch statement to convert to code, with integer state numbers
26
Exercise: State Chart For Traffic Light (one direction)
27
On Clarity in Requirements A wife asks her software engineer husband, “Could you
please go shopping for me and buy one carton of milk? And if they have eggs, get six.”
A short time later the husband comes back with 6 cartons of milk and no eggs. The wife asks him, “Why did you buy six cartons of milk?!”
He replied, “They had eggs.”
www.ganssle.com/jokes.htm.
28
Sequence Diagram Basics Sequence diagrams show the interactions between components
• Each component is a box at the top of the diagram• Time extends downward from the component• Arcs go between timelines to show messages/method calls/etc.
29
Example Sequence Diagram
Customer CoinOutControlButtonControl
1. Button[s](True)
VendControl
1. mButton[s](True)
VendButton_Light
2. Light[s](True)
3. mVend[s](True)Vend[s](True)
5. Button[s](False)
5. mButton[s](False)
4. Light[s](False)
COUNTER > 0
COUNTER = 0COUNTER = 0
COUNTER > 0
3. mVend[s](False) Vend[s](False)
3. Dispense Soda
30
Sequence Diagram Pro/Con Pro:
• Well suited to object-oriented designs (one box per object)• Lets you emphasize interactions rather than in-line order of steps• Very useful for distributed embedded systems (18-649 course)
Con:• Only works if you have organized code into multiple objects
(Learn more about sequence diagrams & state charts in 18-649)
31
Exercise: Sequence Diagram For Getting Voice Mail
32
Good & Bad Design Practices Some GOOD practices
• Make tradeoffs and decisions at a high level – before writing code• Keep design documents in synch with implementation• Get design documents reviewed by someone else before spending time on
implementation
Some BAD practices• Starting writing design documents
after the implementation is completed(design documents as “documentation”rather than “design steps”)
• Overly detailed designs– One line of code per box is bad
• Ignoring design and jumping right to implementation
33
IMPLEMENTATION How long does software last?
• Many people act as if their software will be thrown away next week• But cars typically live 10-15 years after sale• Houses last up to 100 years• Example: SAGE air defense system
– Started 1954– Deployed 1963 – vacuum tube hardware (500,000 lines of code)– In operation until 1983 – (IBM PC came out in 1982)
• Example: MS-DOS. Released 1981. Still runs as command line for Windows.• 1AESS telephone switch: 1976 through 2008+ (maybe some still working)
[http://history.acusd.edu/gen/20th/sage.html]
34
35
Why Do You Need Coding Style Sheets? So others can understand your software quickly and accurately
• Your design colleagues• YOU – when you look at it years later• People who have to maintain and expand it• Your successors, when you move on but the software stays behind
How can you make your code understandable?1. Document the architecture and design, not just the code2. Use a consistent style of programming, with good practices
This is a partial step toward hard-to-get wrong code• Coding rules can avoid the dark, scary corners of languages• Avoid static analysis problems (compiler warnings)
36
18-348 Code Style OverviewEvery file shall have: Title block
• Programmer’s name and revision history of software• Summary of externally visible items (e.g., variables visible to other modules)• Tool chain specification (e.g., codewarrior version and target chip)
Global variable and constant definitions• RAM variables• ROM constant values
“Main” routine• Must initialize stack pointer, interrupts, and so on
Major routines/procedures/methods (one page each, max) Support routines
37
Important Practices Avoid “magic numbers”
• If a value is used repeatedly or could possibly change, use an EQU value– or #define– or C++ const
Almost every line of code should have a comment• Describe why something is happening and end goal…
… not just what the instruction is doing to the machine• BAD: CLC ; Clear Carry Bit• GOOD: CLC ; Set return status flag (cy bit) to False
• Also include higher level comments about what is happening
Code should compile “clean”• No warnings at all – otherwise you will miss a new warning if it gets lost in all
the “false alarm” warnings
38
39
Avoid Global Variables In Real Code• Global variables can be read/written from any module in the system
– In contrast, local variables can only be seen from a particular software module• Excessive use of globals tends to compromise modularity
– Changes to code in one place affect other parts of code via the globals– In other words: Global Variables are Considered Harmful
(McConnell 1993, p. 90; book on accepted practices)
(Wulf 1973, pp. 28,32)
39
40
Other Good Ideas For Product Development Version number
• Store the version number of the software in ROM• What if a PROM label comes off? You won’t know which version it is• Also, ROM-based version number makes diagnosis easier
Make variables distinct in the first 6 characters• Some assemblers think FOOBAR1 and FOOBAR2 are the same – because they
just look at length and first 6 characters!!
Set “unused” resources to something safe• E.g., unused ROM should be set to a “halt” instruction and not random junk• E.g., unused interrupt vectors should go to an error recovery routine
Uniform naming conventions across project(s)
Copyright and proprietary information• Is this module a trade secret?
41
Gas Pump Startup Printout Example (Aug 2009)
42
Embedded Design Review Checklist Areas based on doing many design reviews in industry
• Function – does the code do the right thing and not the wrong thing?• Style – is the code structured in a way that makes bugs less likely?• Architecture – is code modular, cleanly nested, and without complex
dependencies?• Exception handling – does the code fall over if something goes worng?• Timing – are real time deadlines and concurrency handled appropriately?• Validation and Test – is test coverage high?• Hardware – are timing, power, and other hardware problems addressed?
Source: http://betterembsw.blogspot.com/2011/11/embedded-system-code-review-checklist.html(See the detailed checklist in these handouts)
We’ll talk more about design reviews in a later lecture• This checklist is for information, not a course requirement
A good way to use a checklist this complex:• Have 3-4 reviewers in a joint session• Assign different sections to each reviewer for primary responsibility
43
Conclusions Engineering projects have phases
• Marketing, product definition, requirements, architecture, design, implementation, test, V&V, support, evolution
Requirements• Shall vs. should• Keep an eye on these in projects
Design• Flowcharts• Statecharts• Sequence Diagrams
Implementation• Basic coding style• Good & Bad practices• Read the course coding style sheet before recitation!• Read the style sheet attached to this lecture and understand what it is talking about
– Not required to follow this style sheet for course projects, but might be a good idea
44
Lab Skills State chart
• Create a state chart for a moderately complex system
Implementation• Assembly language implementation of a state machine• Follow course coding style for all labs after this point