ECNG2006 (EE25M) Introduction to microprocessors Course Notes Contributors: K. Hall F. Mohammed C. Radix A. Sinanan A. Williams K. Edwards A. Joseph O. Regalado K. Narine I. Mohammed Y. Panchu S. Patrick A. Abdool C. Arneaud N. Harrichand H. Lawrence D. Caberrea P. Pollucksingh c Dept. of Electrical and Computer Engineering, U.W.I. , St. Augustine March 11, 2008 ECNG2006 (EE25M) March 11, 2008 2 Contents Course Outline 8 Coursework Portfolio 20 Course Perceptions Questionnaire 21 Prerequisite Skills Questionnaire 23 I Microprocessor Overview 1 1 Microprocessor Basics 1 2 Microprocessor System Basics 11 3 Microprocessor support circuitry 21 4 Microprocessor architecture 30 5 Typical Microprocessor instructions 39 II Microprocessor-based system development 1 6 Software tool chain 1 7 Development support (hardware) 9 8 Microprocessor families and forms 17 III PIC16 Introduction 1 9 PIC16F877 Overview 2 10 MPLAB Overview 13 IV Numbers & Data 1 11 Real numbers 1 12 Integer arithmetic 13 13 Real number arithmetic 22 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 3 14 Data structures 27 V Algorithms on PIC16 1 15 Basic operations 1 16 Code comparison 41 17 Compiler limitations 57 VI Interfacing Peripherals 1 18 Interfacing Idioms 1 19 Interrupt Basics 14 20 Typical peripherals 28 21 Digital troubleshooting 37 22 PIC16 peripherals 45 VII System Issues 1 23 Interrupt issues 1 24 P interface/timing issues 24 25 Power/Signal issues 35 26 P choice/comparison 42 27 Case study 50 28 Design guidelines 57 VIII Communication 1 29 Communication protocols 1 30 Bit-banging vs. hardware 12 31 I/O on the PC 17 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 4 32 PC to P serial link 20 33 P Parallel Interface 46 IX Appendices 1 A Data Sheets 1 B Glossary 3 C Study tips 15 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 5 References Dictionary.com. Internet. Http://dictionary.reference.com/. Mathworld. Internet. Http://mathworld.wolfram.com/. 1991. Can speci cation version 2.0. Http://www.interfacebus.com/CAN 2 Spec.pdf. 1993. The free on-line dictionary of computing. Internet. Http://www.foldoc.org/. 1994-2000. PCW Compiler Help les. 1995. 80C51 family architecture. http://www.semiconductors.philips.com/acrobat/various/80C51 FAM ARCH 1.pdf; http://www.grifo.com/press/DOC/Philips/FAMARCH.PDF. 1997. PICmicro Mid-Range MCU Family Reference Manual. Technical Reference Document 33023a, MicroChip Technology Inc. 1999. HD44780U (LCD-II) (Dot Matrix Liquid Crystal Display Controller/Driver). Datasheet, Hitachi. 1999. MPASM USERS GUIDE with MPLINK and MPLIB. Manual DS33014G, MicroChip Tech- nology Inc. 2000. MPLAB ICD USERS GUIDE. Manual DS51184D, Microchip Technology Inc. 2000. MPLAB IDE, SIMULATOR, EDITOR USERS GUIDE. Manual DS51025D, Microchip Technology Inc. 2000. The I2C-bus speci cation. http://www.semiconductors.philips.com/acrobat/various/I2C BUS SPECIFICATION 3.pdf. 2001. At90s8535 summary. Available at www.atmel.com. Rev. 1041HS - 11/01. 2001. Atis telecom glossary 2000. Internet. Http://www.atis.org/tg2k/t1g2k.html. 2001. PIC16F87X Data Sheet: 28/40-Pin 8-Bit CMOS FLASH Microcontrollers. Technical Refer- ence Document 30292c, MicroChip Technology Inc. Arnold, Ken. 2001. Embedded controller hardware design. LLH Technology Publishing. Awtrey, Dan. 1997. Transmitting data and power over a one-wire bus. Sensors Reprint downloaded from www.dalsemi.com. Ball, Stuart R. 2000. Embedded microprocessor systems. Butterworth-Heinemann. Barr, Michael. 1999. Choosing a compiler: The little things. WebPage: http://www.netrino.com/Articles/CrossCompilers/. |||. 2000. Language lessons. WebPage: http://www.netrino.com/Connecting/2000- 03/index.html. Buchanan, William, and Austin Wilson. 2001. Advanced pc architecture. Addison-Wesley. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 6 Cady, Fredrick M. 1997. Microcontrollers and microcomputers: Principles of software and hardware engineering. Oxford University Press, Inc. Fisher, Matt. 2000. Protecting binary executables. Webpage: http://embedded.com/2000/0002/0002feat1.htm. Hartman, Hope J. 2001. Developing students’ meta-cognitive knowledge and skills, chap. 3, 33{68. Kluwer Academic Publishers. Horowitz, Paul, and Win eld Hill. 1989. The art of electronics. 2nd ed. Cambridge University Press. Katzen, Sid. 2003. The quintessential pic microcontroller. Springer. 2nd printing. Kernighan, Brian W., and Dennis M. Ritchie. 1988. The C Programming Language Second Edition. Prentice-Hall, Inc. Mazidi, Muhammed Ali, and Janice Gillespie Mazidi. 1995. The 80x86 ibm pc & compatible com- puters volumes i & ii: Assembly language design and interfacing. Mitra, Sumit. 1997. Power-up considerations. Application Note AN522, DS00522E, Microchip Technology Inc. Noergaard, Tammy. 2005. Embedded systems architecture. Newnes. Palmer, Mark. 1997a. An520: A comparison of 8-bit microcontrollers. Application Note DS00520D, Microchip Technology Inc. |||. 1997b. Power-up trouble shooting. Application Note AN607, DS00607B, Microchip Tech- nology Inc. Contributions: Richard Hull & Randy Yach. Peri, Vamsi, and Dan Simon. 2005. Fuzzy logic control for an autonomous robot. In Annual meeting of the north american fuzzy information processing society (na ps 2005) 26-28 june 2005, 337{ 342. Downloaded from http://academic.csuohio.edu/simond/pubs/Vamsi.pdf on March 7th 2007. Predko, Myke. 2000a. Debugging your applications, chap. 12, 561{569. In Predko (2000d). |||. 2000b. Designing your own picmicro R mcu application, chap. 11, 547{560. In Predko (2000d). |||. 2000c. Picmicro R mcu application design and hardware interfacing, chap. 6, 253{316. In Predko (2000d). |||. 2000d. Programming and customizing picmicro R microcontrollers. McGraw-Hill. |||. 2001. Picmicro R microcontroller pocket reference. McGraw-Hill. Stallings, William. 1996. Computer architecture and organization. 4th ed. Prentice-Hall, Inc. |||. 2000. Computer architecture and organization. 5th ed. Prentice-Hall, Inc. Vahid, Frank, and Tony Givargis. 2002. Embedded system design. John Wiley & Sons, Inc. Wakerly, J. F. Digital design principles and practices. 3rd ed. Prentice-Hall. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 7 Wilmhurst, Tim. 2001. An introduction to the design of small-scale embedded systems. Palgrave. Wolf, Wayne. 2000. Computers as components:principles of embedded computing system design. Morgan Kaufmann. c DECE, UWI, St. Augustine, Trinidad ECNG2006(EE25M) – Introduction to Microprocessors The University of the West Indies Department of Electrical and Computer Engineering Last Review: December 2, 2005 Course Instructor: Name: Ajay Joshi Email: ajoshi@eng.uwi.tt Phone: ext. 3144 Office: Room 325 Office Hours: as posted on door Course Support Name: Aaron Joseph Email: Given at Later Date Phone: ext. 3156 Office: Room 329 Office Hours: Tuesday and Thursday 1pm-3pm Aims To cultivate the student’s ability to utilize, comprehend the operation, and criticize the efficacy of, a microprocessor in an applied context. Objectives At the end of this course the student will be able to: • in general, or (given relevant diagrams and specifications) for a particular system, identify, and describe the role of, the components of (a) a microprocessor, (b) a microprocessor-based system, (c) a development suite (hardware, software) for a microprocessor-based system. • illustrate how data can be represented in (and accessed from) memory, implement arithmetic and data manipulation operations in assembly language, and assess how well code will perform in a given context, given the architecture and instruction set of a microprocessor • design and implement an appropriate interface between a microprocessor-based system and a peripheral device (or another microprocessor-based system), given relevant datasheets and suitable parts • select (and critique the selection of) a microprocessor-based system for an application, given relevant datasheets and application requirements Course Overview Microprocessors have been one of the most widely used methods of incorporating flexibility and intelligence into automated devices. Their general-purpose nature, speed and size have made them one of the most common components in Electrical Engineering. It is therefore necessary to develop a good understanding of their operation and how they can be used as building blocks for automated systems and control applications. This course explores the inner workings of a microprocessor from the programmer's perspective, as well as treating with external hardware issues such as interfacing, and ECNG2006 (EE25M) March 11, 2008 8 c DECE, UWI, St. Augustine, Trinidad selection criteria for microprocessors. Exercises and examples are based on the PIC 16F877 microcontroller. The syllabus follows: Microprocessor architecture (PIC16F877); Microprocessor development and support systems(MPLAB); Binary, integer and floating point arithmetic operations; (PIC16Cxxx) assembly language programming; Interfacing (PIC16F877): I/O ports, Timers, Interrupts, A/D conversion, PWM; System Issues; Serial/Parallel Communication. ECNG2006 (EE25M) March 11, 2008 9 c DECE, UWI, St. Augustine, Trinidad Prerequisites There are no departmental pre-requisites, however, it is presumed that the student has acquired the necessary pre-requisite skills in the preceding electronics and computer systems courses. It is presumed that the student is able to: • correctly interpret syntax of simple C programs, representation of different numeric bases in C, and utilize an ANSI C compiler/IDE. • treat with the concept of numeric bases, and perform translation between binary, decimal and hexadecimal bases. • predict the operation of simple digital/analog circuit components, in particular resistors, capacitors, latches and operational amplifiers. • interpret pin-out diagrams, functional block diagrams, and timing diagrams as found on datasheets. • effectively use basic lab equipment: meters, oscilloscopes, power supplies, breadboards. • troubleshoot basic signal problems in a circuit (i.e. no/low voltage, intermittent signals, different grounds, noise). Weighting 3 credits requires 12 teaching weeks; week 13 activities/mock exam not compulsory each teaching week: 3 hrs lecture; 3 - 6 hrs self-study; 1 hr tutorial additional time for group project 6-9 hours. associated labs in ECNG2005 (EE24D): 6 labs @ 3hrs/lab; individual project @ 6 hours Evaluation Type of Evaluation Description % of Course Grade End of Semester Exam: 3 hours – compulsory pass Short answer/design (cover major learning objectives) 60% In-semester Exam: Mid-term exams in Wk 6 and 12 @ 6% Mock Exam in Wk 13; not assessed 12% Laboratory: Lab exercises & individual project contribute to grade in ECNG2005 (EE24D) 0% Mini-Project: Group lab exercise (5-6 people per group) 6% Research Paper: Reading Assignment in Wk 12 2% Other: Online Tutorials (10 % ) 5 Assignments (2% each) Optional participatory activities (1% each contribution; total not exceeding 4%; category total not exceeding 20%) 20% TOTAL: 100% ECNG2006 (EE25M) March 11, 2008 10 c DECE, UWI, St. Augustine, Trinidad 2007/08 Semester II Calendar Mon Tue Wed Thu Fri Sat Sun Wk 1 14 Jan 15 16 17 18 19 20 Wk 2 21 22 23 24 25 26 27 Wk 3 28 29 30 31 1 Feb 2 3 Wk 4 4-Carnival 5- Carnival 6 7 8 9 10 Wk 5 11 12 13 14 15 16 17 Wk 6 18 19 20 21 22 23 24 25 26 27 28 29 1 Mar 2 Wk 7 3 4 5 6 7 8 9 Wk 8 10 11 12 13 14 15 16 Wk 9 17 18 19 20 21-Good Friday 22 23 Wk 10 24-Easter Monday 25 26 27 28 29 30-Baptist Liberation Wk 11 31 Bap Lib Holiday 1 Apr 2 3 4 5 6 Wk 12 7 8 9 10 11 12 13 Wk 13 14 15 16 17 18 19 20 Exams 21 22 23 24 25 26 27 Exams 28 29 30 1 May 2 3 4 Exams 5 6 7 8 9 10 11 Exams 12 13 14 Coursework Laboratory Exercises: Marks towards ECNG2005 (EE24D) Mini Project: Group must choose one of the assigned projects 4-6 people per group w/up to 5 groups per topic Marks: Design 2%; Implementation 2%; Report 1%; Demo/Presentation 1% Weighted by individual contribution to group Assignments Research Paper/s: Submit an informative abstract about an article chosen/assigned from IEEE Magazines 2002-7. Item should be a 5-7 page article on a topic of relevance to microprocessor-based systems. Presentation/s: Associated with the Group Project – 1 minute Problem Set/s: 5 Assignments; written, 2 weeks to submit Other: tutorial questions online; 30 minute completion time ECNG2006 (EE25M) March 11, 2008 11 c DECE, UWI, St. Augustine, Trinidad Resources Textbooks: Category A: Essential Texts 1) An introduction to the design of small-scale embedded systems, T. Wilmhurst. Category B: Highly Recommended Texts 1) The Quintessential PIC Microcontroller, S. Katzen. 2) Embedded Systems Architecture, T. Noergard Category C: Recommended Texts 1) Programming and customising PICmicro microcontrollers, M. Predko (2nd Edition). 2) Microcontrollers and microcomputers, F. Cady. General Reference: 1) Computer Organisation & Architecture, W. Stallings, (5th Edition or later) 2) Embedded System Design: A Unified Hardware/Software Introduction, F. Vahid, & T. Givargis 3) Logic and Computer Design Fundamentals, M. Mano & C. Kime 4) Digital Design: Principles & Practice by J. Wakerly, (3rd Edition or later) Course Notes: will be distributed in class and/or made available online On-Line Resources: Topical Videos: http://murl.microsoft.com/default.asp Course site: http://www.eng.uwi.tt/depts/elec/staff/cradix/ee25m/ Study Tips: http://www.iss.stthomas.edu/studyguides PIC Micro WebRing: http://www.webring.org/cgi-bin/webring?ring=picmicro;list Simulation Tools: (in microprocessor and shared labs) MPLAB/CCS compiler Laboratory Tools: 20 seat lab. Per seat: LED's, resistors, potentiometers, ICD header + RJ12 cable + ICD debug module + serial cable, Breadboard, wire and 5V power supply, 7 segment LCD display, transistors, LCD text display, DS1821 temperature sensor, additional serial cable, DC motor, stepper motor, encoder disc/IR led/detector, keypad. Additional components for group projects. Other: --none-- ECNG2006 (EE25M) March 11, 2008 12 c DECE, UWI, St. Augustine, Trinidad Lecture/Tutorial Schedule Course has: 33 learning units; each unit 1 hr lecture + coursework In addition to learning units there is: 1 hr overview + 1 hr mid-term + 1 hr mid-term Tutorial activities include 4 hours topic review 2 hours guest lecture – informative abstract; 2 hours midterm review 4 hours group project work No. Unit #: Topic Notes/Delivery/Comments 1 Text 2 Associated C'work Deadline 1. Course Overview Survey 2. 1: ?P basics Tutorial 1:a Ch. 1 3. 2: ?P system basics Tutorial 1:b Ch. 1/2/4 4. 3: ?P support circuitry Tutorial 2:a Ch. 2/4 5. 4: ?P architecture Tutorial 2:b Ch 1 6. 5: Typical instructions Assignment 1 Ch. 3 7. 6: Software tool chain Tutorial 3:a Ch 3/7 8. 7: Development support Tutorial 3:b Ch 3/7 9. 8: Families & forms Tutorial 4:a Ch. 1 10. 9: PIC16F877 overview Tutorial 4:b Ch. 1/2/3 11. 10: MPLAB overview Lab 1 Ch. 3 12. 11: Real numbers Assignment 2 Ch. 11 13. 12: Integer arithmetic Tutorial 5:a Ch. 11 14. 13: Real number arithmetic Tutorial 5:b Ch. 11 15. 14: Data structures Tutorial 6:a Ch 3 16. 15: Basic operations Lab 2 Ch 3 17. 16: Code comparison Assignment 3 18. 17: Compiler limitations Tutorial 6:b Ch 7 19. 18: Interfacing Idioms Tutorial 7:a Ch. 2/9 20. 19: Interrupt Basics Tutorial 7:b Ch. 3 1 Whichever applicable 2 Specify ECNG2006 (EE25M) March 11, 2008 13 c DECE, UWI, St. Augustine, Trinidad No. Unit #: Topic Notes/Delivery/Comments 1 Text 2 21. Mid-term 22. Midterm review+ Stud't Feedback Grp. Project 23. Guest Lecture – H. Lawrence 24. Guest Lecture – H. Lawrence Reading Assignment 25. Topic Review 26. Topic Review 27. 20: Typical peripherals Tutorial 8:a Ch. 5/9 28. 21: Digital troubleshooting Tutorial 8:b Ch. 3 29. 22: PIC16 peripherals Lab 3 Ch. 2/4/5 30. Group Project 31. 23: Interrupt issues Assignment 4 Ch. 8 32. 24: ?P interface/timing issues Tutorial 9:a Ch. 9 33. 25: Power/Signal issues Tutorial 9:b Ch. 10 34. Group Project 35. 26: ?P choice/comparison Tutorial 10:a Ch. 12 36. 27: Case study Tutorial 10:b Ch. 12 37. 28: Design guidelines Assignment 5 Ch. 12 38. Group Project 39. 29: Communication protocols Tutorial 11:a Ch. 6 40. 30: Bit-banging vs. hardware Tutorial 11:b Ch. 6 41. 31: I/O on the PC Lab 4 Ch. 2 42. Group Project 43. 32: PC to ?P serial link Lab 5 Ch. 6 44. 33: ?P Parallel Interface Lab 6 Ch. 2 45. Topic Review 46. Topic Review 47. Mid-Term 48. Stud't F’back;+ Midterm Review 49. Group Demos/Presentations 50. Mock Exam (3 hours; proctored) ECNG2006 (EE25M) March 11, 2008 14 c DECE, UWI, St. Augustine, Trinidad Unit objectives At the end of this course the student will be able to: Section I: ?P Overview 1. identify the components of a typical microprocessor (ALU, registers, stack), describe the operation of the components of a typical microprocessor, and describe the representation of instructions in the operation of the instruction cycle. 2. identify the components of a microprocessor-based system (CPU, bus, memory/layout, peripherals), describe the operation of typical components of a microprocessor-based system, and discuss issues involved in the design/choice of the various components of the microprocessor(-based system) 3. describe (and/or illustrate) how bus addressing, conflict resolution and memory maps may be implemented, and explain the function of basic support circuitry for microprocessors such as clocks, reset circuitry, watch dog timer, capacitors to ground etc. . 4. differentiate between organization and architecture, and relate instruction set design to the programmer’s model of the microprocessor,. 5. explain the operation of typical machine instructions, addressing modes, status bits, and infer the consequences of sequences of generic instructions. Section II: ?P development 6. explain the roles of the compiler, linker, assembler, simulator, emulator, debugger in the software development tool chain, and the role of scripting languages, make/configure-like utilities and IDE’s in the software development process. 7. explain the role of firmware, operating systems, oscilloscopes, logic probes/analyzers, terminals, disk drives, external memory, debug protocols e.g. JTAG and host computers in the development and support of microprocessor based systems. 8. recognize and differentiate between the different commercially available families/forms of microprocessor based systems (Motorola, AVR, PIC – chip/component packages -- SOC, microcontroller, PC, back-plane bus, PC104, standalone, embedded) based on their pictures/properties/descriptions and supported development tools. Section III: PIC16 Introduction 9. explain the memory layout, operation of the instruction cycle, and the basic instructions (move, add, subtract, shifts) for the PIC16F877 microcontroller. 10. utilize the MPLAB IDE , CCS compiler, and other software tools, to develop software, for the MicroChip PIC16xxx series of microcontroller, in C, C++ and assembly language. Section IV: Numbers & Data 11. represent real numbers using fixed and floating point binary representations. 12. perform integer arithmetic operations using binary representations of the operands. 13. perform fixed/floating point arithmetic operations using binary representations of the operands. 14. describe how data (and data structures) can be represented and manipulated, with reference to alignment and byte/bit ordering issues. ECNG2006 (EE25M) March 11, 2008 15 c DECE, UWI, St. Augustine, Trinidad Section V: Algorithms on PIC16 15. implement basic programming operations (loops, swaps, lookups), integer arithmetic, and other computation/numerical methods, in assembly language on the PIC16Cxxx series of microcontrollers. 16. contrast alternate programming techniques in terms of size/speed of the code produced for the PIC16Cxxx series of microcontrollers. 17. give examples of the limitations placed on compiler-generated code, for the PIC16Cxxx series of microcontrollers, by the need for generality. Section VI: Interfacing Peripherals 18. identify alternate ways in which components may be interfaced with a microprocessor (i.e. common idioms for interacting with hardware): single bit (with debounce), matrix, map into memory space, etc. . 19. explain the operation of interrupts, the different types of interrupts (h/w, s/w), how interrupts may be prioritized (peripheral interrupt controller), and identify common applications of interrupts. 20. explain the operation of commonly used peripherals: PPI/PIA, A/D, Timers/Counters, PWM, D/A. 21. select and apply techniques for troubleshooting digital circuitry using standard laboratory equipment. 22. utilize built-in peripherals of the PIC16F877 microcontroller in simple applications. Section VII: System Issues 23. understand the implications of (nested/multiple) interrupts for execution times, and the need for context saving. 24. interpret and recognize the implications of, microprocessor timing and interfacing requirements. 25. determine the noise, voltage, current and power considerations due to microprocessors and peripheral fan-in/out and how different logic families (as well as inverted voltage logic) may be used in conjunction in a design. 26. compare alternate microprocessors in terms of the instruction set, and features(such as cache pipelining etc.) and the best performance, which may be facilitated by the instruction set and features. 27. recognize the issues and tradeoffs involved in the design of a microprocessor based (embedded) system, and justify the role of a microprocessor(-based system) in an applied context. 28. remember and follow a checklist of design guidelines, in order to perform a simple design for a microprocessor based system. ECNG2006 (EE25M) March 11, 2008 16 c DECE, UWI, St. Augustine, Trinidad Section VIII: Communication 29. understand commonly used parallel and serial communication protocols (I2C, CAN, RS232, USB, Firewire) and interpret descriptions of proprietary protocols (Dallas 1- wire). 30. differentiate between bit-banging and dedicated hardware interfaces for serial/parallel communication (PPI/PIA vs ACIA/UART, PPC) 31. perform I/O programming on the PC in C/Assembly using the Visual C++ compiler 32. produce assembly language programs for communication between a microprocessor and a PC using the parallel and/or serial port, given UART and PPC datasheets/details, and respective instruction sets. 33. interface external peripherals/devices to the PIC16F877 microcontroller using a parallel bus, and interface the PIC16F877 microcontroller as an external device on a parallel bus (memory mapped). ECNG2006 (EE25M) March 11, 2008 17 c DECE, UWI, St. Augustine, Trinidad Course Rules: your rights and responsibilities You have the right to receive a fair mark for any assessed coursework which you produce. • Weighting of individual assignments will be issued at the beginning of the semester. • Marking schemes will be issued with each piece of assessed coursework. • You may request clarification of marking schemes at any time prior to submission. • You should receive feedback (individual, general or both) on coursework within 1 week. • You may query the mark assigned to your coursework, if it has been totaled incorrectly, or is not consistent with the published marking scheme. You have the right to know the examination format, as well as the requirements for passing the final examination, and the course. You are entitled to lectures, which start and finish on time. You are entitled to appropriate notice of lecture/lab cancellation. You are entitled to have any concerns about the course heard. Individual queries should be addressed to the lecturer (or TA) in the first instance and the HoD in the next instance. Anonymous or group queries should be directed to the student representative or your tutor in the first instance, who is obliged to bring it to the attention of the lecturer and/or HoD. You are responsible for checking posted examination schedules and arriving on time for exams with your examination and/or ID cards, and writing implements. You are responsible for arriving to lectures/labs on time, and participating in all course activities. You are responsible for submitting coursework by the posted deadline, and for securing a receipt (or signing a submission sheet) for all submitted coursework. You are responsible for seeking assistance from or notifying staff if you any difficulties (academic, personal or health-related). You will be held at fault if you do not comply with all university, departmental and faculty regulations, as well as with the course policy on collaboration. Ignorance is not a valid excuse. ECNG2006 (EE25M) March 11, 2008 18 c DECE, UWI, St. Augustine, Trinidad Policies on plagiarism, collaboration and late submission Late submissions may fall into one of two categories, late submissions for online coursework and late submission for written coursework. All online coursework will be due at 11:59PM on the submission date and all written coursework will be due at 4PM on the submission date. For online coursework, once the submission time has passed, the coursework will no longer be accepted; and you will receive a grade of zero for the piece of coursework. For written coursework, will be assessed in accordance with the published marking scheme, but 0.5% of your course mark will be deducted for each 24 hour period (or part thereof) a piece of coursework is late. The minimum mark awarded will be 0%. e.g. an assignment graded at 8 marks out of 10, which translates to 1.6% towards the course mark. If the tutorial was handed in at 8am (16 hours late), 0.5% would be deducted, leaving 1.1% towards the course mark. Written coursework must be in the possession of the Course Lecturer or Support Team Leader to have been submitted. The ONLY exception to this rule is if you have a valid medical/sick leave for the days in question, which you have submitted to the Electrical office/Registry; or if an unforeseeable national/personal emergency prevented you from getting here. In either case, I need to get formal notice from the Head. "Plagiarism is using others' ideas and words without clearly acknowledging the source of that information" -- from Plagiarism: What It is and How to Recognize and Avoid It, http://www.indiana.edu/~wts/wts/plagiarism.html Plagiarism can occur in many different ways: • using someone else's words/work without quotes or acknowledgement • using someone else's ideas without acknowledgement • using information gathered or collected by someone else without acknowledgement -- from Plagiarism: What It is and How to Recognize and Avoid It, http://www.indiana.edu/~wts/wts/plagiarism.html ``Plagiarism is the presentation by a student of an assignment which has in fact been copied in whole or in part from another student's work, or from any other source (e.g. [solutions,] published books or periodicals), without due acknowledgement in the text.'' -- EE26A policy on plagiarism Collaboration on assignments is often helpful, and has been shown to increase understanding of all parties involved in the collaboration. It is OK to ask someone else if they think your work is correct, and if not, they can point out where you made a mistake, and give an explanation of the error. If you give (or are given) a worked example to improve understanding, the example should be as unrelated to the assignment as possible. Inappropriate collaboration (for the purposes of this course) includes: • for individual or group assignments allowing your assignment to be copied, or copying someone else's assignment, either electronically, manually or by photocopy. Ignorance of the copying is no excuse -- you are advised to secure all coursework material. ECNG2006 (EE25M) March 11, 2008 19 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 20 Coursework Portfolio AIM: to promote re ective learning of both students and lecturer O ine Version1 Students are asked to keep a manila folder with all coursework and feedback forms. Items should be fastened into the folder using a single hole and a treasury tag. Your ID# should be placed on the folder tab. Your name is not required. You should use this folder to review your progress throughout the semester. The folder should be submitted to the lecturer after the nal exam, who will use the information to determine appropriate course adjustments. Please feel free to make frank observations, constructive criticism, and realistic suggestions in the feedback sections. Feedback will not adversely a ect your course grade. Any students who have reservations about how such feedback is being used may withhold feedback until after the coursework is marked, or omit feedback entirely. Please start your folder with the Course Perceptions and Skills Questionnaires within the rst 2 weeks of the semester. Online Version Students are asked to keep a Wiki containing scans of/re ections on all coursework and feedback forms. You should use this Wiki to review your progress throughout the semester. The Wiki will be viewed by the lecturer, who will use the information to determine appropriate course adjustments, and o er correction or advice. Please feel free to make frank observations, constructive criticism, and realistic suggestions. These will not adversely a ect your course grade. Any students who have reservations about how such information is being used may withhold comments until after the coursework is marked, or until the end of term. Please start by executing the online Pre-Test and making a Wiki entry reviewing your course preparedness within the rst 2 weeks of the semester. 1Students are advised that O ine versions are to be used either with the explicit permission of the course lecturer OR at times when the electronic course support site is unavailable for more than 48 hours. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 21 Course Perceptions Questionnaire O ine Version2 Please read the course outline and/or the course web page before attempting this questionnaire. The questionnaire should require about 30 minutes to complete. It is not a test, and will not contribute to your course grade. What do you think this course is about? What do you want to get from this course? What do you think you will have to do in this course? What skills do you think you need in order to do well in this course? Fill in the blanks in the following statements: 1. Each week, I expect to do hours of self-study for this course. 2. The coursework for this course is worth % of my nal grade. 3. There are learning units in this course. 4. Open Hours will be held on from to . Label each of the following statements as either True(checked)/False: { Week 13 classroom activities are all voluntary. { I need to pass the exam in order to pass this course. { If I cannot make the tutorial, then the deadline doesn’t apply to me. { Ignorance of departmental, faculty or university regulations is a valid excuse for violating them. 2Students are advised that O ine versions are to be used either with the explicit permission of the course lecturer OR at times when the electronic course support site is unavailable for more than 48 hours. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 22 Label each of the following statements, concerning student behaviour in the course, as either Acceptable (checked) or Unacceptable: { Student A copies Student B’s program onto a diskette with Student B’s permission. { Student A copies Student B’s program onto a diskette without Student B’s permis- sion. { Student A does Student B’s coursework. { Student A does a tutorial set individually and compares answers with Student B. { Student A has a problem with an assignment, and reads Student B’s answer. { Student A has a problem with an assignment, and uses "draft" for assistance. { Student A has a question about a lab, which Student B answers. { Student B reads, and points out an error in, Student A’s code. { Student B steals Student A’s printout o the printer. { Student B submits a program that contains code taken from the Internet, and does not acknowledge his source. { Students A and B submit identical assignments. { Students A and B work together to understand an assignment, and then complete it individually. { Students A and B work together, and submit identical assignments. For each of the following questions, select the most appropriate answer. 1. The penalty for late submission of coursework is: (a) 1.25 marks per hour. (b) 0.125% per 3 hours. (c) 0.125% per day. (d) there is no penalty for late submission. 2. The purpose of all these feedback forms, and tutorials is to: (a) stress me out. (b) catch cheaters. (c) make sure that I am doing the work. (d) provide continuous feedback about my performance in the course. 3. In order to learn how to program microprocessors in assembly, which of the following is MOST e ective: (a) read books about assembly. (b) practice writing assembly programs on paper. (c) test assembly programs in simulation. (d) test assembly programs on microprocessors. 4. Which of the following is NOT a prerequisite skill for this course: (a) I must be able to program in C++. (b) I must understand hexadecimal and binary number representations. (c) I must be able to predict how simple digital/analog circuits will work. (d) I must be able to read/understand diagrams typically found on datasheets. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 23 Prerequisite Skills Questionnaire O ine Version3 The questionnaire should require no more than 60 minutes to complete. If you are unable to answer a question please write ‘Unable to answer’ in the space provided. It is not a test, and will not contribute to your nal grade. 1. Indicate which of the following courses you have already registered for, and the last grade you obtained in each course analog electronics digital electronics introduction to computers computer systems / C++ 2. Name any C/C++ compilers/IDE’s which you are familiar with/have used. 3. Write down the screen output of the following program: int main() { int i; for (i=0; i<5;i++) { cout<<"The number is "< on; on > o ) bitwise-xor the status register with the bit mask. To clear a bit, bitwise-and the status register with the inverted bit mask (you can invert the mask using bitwise-xor rst). c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 45 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 46 Review Exercises 1. Label the following statements True/False: (a) Immediate addressing requires no memory referencing, but the range of values is limited by the operand space in the instruction. (b) Indirect addressing potentially allows access to a large addressing space, but requires multiple memory references. (c) The branch (jump, goto) instruction changes the program counter value, only after storing the previous value. (d) The noop instruction has no e ect other than incrementing the program counter. (e) Register addressing requires two memory references. (f) The push and pop instructions are used to manipulate the accumulator. (g) The skip instruction is the same as the call (subroutine) instruction. (h) The range of addresses which are accessible using Direct Addressing, is limited by the operand space in the instruction. 2. The following values are in the data memory of a Harvard machine with an accumulator. Address 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2A Data 0x44 0x10 0x02 0x53 0x43 0x23 0x11 0x34 0x23 0x38 0x22 What value is in the accumulator after each of the following instructions are executed in sequence: LOAD IMMEDIATE 22 LOAD DIRECT 25 ADD IMMEDIATE 27 ADD INDIRECT 2A Your answer should show your reasoning. 3. The question refers to the following program which runs on a machine with an accumulator: Line 1 load 5 Line 2 begin: sub 1 Line 3 jumpnz Begin Write down the line numbers, and accumulator values as the program executes. 4. (a) What is the di erence between a program branch, and a subroutine call? (b) Branch instructions move to the speci ed instruction if the test condition is ful lled. Skip instructions miss the next instruction if the test condition is ful lled. Why do we have a skip instruction when we already have a branch? (c) Add instructions add a value to the speci ed register. The increment instruction simply adds one to a register. Why do we need an increment instruction when we have an add instruction? c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 47 (d) The nop(no operation) instruction has no e ect other than incrementing the program counter. Suggest some uses of the nop instruction. (Stallings 2000; 9.5) (e) How can CPU use a stack for any purpose, if there are no push and pop operations in the instruction set? (Stallings 2000; 9.7) (f) \The number of machine instructions in an instruction set is limited by the number of bits used to encode the instruction, and the instruction format." Is this statement true or false? Explain your answer. (g) How would you perform an indirect addressing operation, using direct and immediate addressing mode instructions? 5. Assuming a single address instruction, and a processor with an accumulator, use the "stan- dard" instructions you have learned here to convert the following piece of C code into machine instructions. a=4; do { a=a+5; }while (a<25); You should check your answer by writing down the output from the C code, and your assembly language code. 6. Convert the following machine language instructions into C code. load #0 store c load a loop: inc c sub b jmpovf end goto loop end: dec c Your answer should explain what this piece of code does. 7. Assuming a single address instruction, and a processor with an accumulator, use the "stan- dard" instructions you have learned here to convert the following piece of C code into machine instructions. a=0; for (i=0;i<5;i++) { a=a+i; } c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 48 8. Convert the following machine language instructions into C code: loop: load a add b store a jmpc end goto loop end: .... 9. Role Play: (a) What are the relative advantages and disadvantages of each of the addressing modes? (Hint see: (Stallings 2000; Table 10.1)) (b) Di erentiate between xed length and xed format instruction sets. What are their respective implications for CPU organisation, architecture and operation? (c) Assume an instruction set that uses a xed 16 bit instruction length. Operand spec- i ers are 6 bits in length. There are K two-operand instructions and L zero-operand instructions. What is the maximum number of one-operand instructions that can be supported? (Stallings 2000; 10.9) (d) Is there any possible justi cation for an instruction with two opcodes? (Stallings 2000; 10.12) 10. Role Play/Challenge question:(Stallings 2000; 9.4) \Consider a hypothetical computer with an instruction set of only two n-bit in- structions. The rst bit speci es the op-code, and the remaining bits specify one of the 2n 1 n-bit words of main memory. The two instructions are as follows: SUBS X Subtract the contents of location X from the accumulator, and store the result in location X and the accumulator JUMP X Place address X in the program counter A word in main memory may contain either an instruction or a binary number in twos complement notation. Demonstrate that this instruction repertoire is reason- ably complete by specifying how the following operations can be programmed: (a) Data transfer: Location X to accumulator, accumulator to location X (b) Addition: Add contents of location X to accumulator (c) Conditional branch (d) Logical OR " c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 49 Assignment A 12 ID# 1. An 8-bit processor-status register is con gured so that bit-2 is the carry ag, and bit-7 is the zero ag. Write down the bit mask for each ag, and explain how they can be combined, and then used, to simultaneously detect if both bits in the status register are clear. Use examples, and counter-examples, to support your answer. 8 marks 2. The binary number 111000102 is subjected to the following operations on an 8-bit processor core: 4 marks arithmetic shift right bit-wise xor $0011 1110_2$ rotate left logical shift left What is the resulting value? Show all working. 12Students are advised that there is no online version of this assignment, and that electronic submissions will not be accepted without the explicit permission of the course lecturer. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 50 3. A CPU designer has decided that his new CPU core will use an 6-bit wide instruction memory, and have a variable-width instruction format, with single operand instructions. The CPU core will have a internal stack, and will be supplied in a 14-pin IC package. (a) The support pins required to allow the IC to function include all of the following EX- CEPT: 1 mark i. 1 pin for clock signal ii. 2 pins for power supply iii. 1 pin for reset line iv. 1 pin for watchdog timer (b) The decision to have an 8 bit wide instruction memory, is a decision about: 1 mark i. CPU architecture ii. CPU manufacturing iii. CPU organization iv. none of the above (c) The instruction format MUST: 1 mark i. contain an operand which requires less than 6 bits. ii. include push and pop instructions for the stack. iii. specify a maximum of 26 unique instructions. iv. support at least one form of addressing. (d) Assuming that operands are at least 5 bits wide, and that instructions never require more than 2 instruction memory words, calculate the maximum number of op-codes that can be included in the instruction set. Show all working. 4 marks c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 51 4. The following values are in the data memory of a CISC machine with an accumulator. Address 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2A Data 0x44 0x10 0x02 0x53 0x43 0x23 0x11 0x34 0x23 0x38 0x22 What value is in the accumulator after each of the following instructions are executed in sequence: load direct 0x22 add immediate 0x27 store indirect 0x25 load immediate 0x20 add indirect 0x28 Your answer should show your reasoning. 5 marks c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 52 5. The question refers to the following program which runs on a stack-based machine, that has a carry- ag. Labels are used to refer to the address of the instruction.: Address Label Instruction 0x00 push 11102 0x01 label begin: push 01002 0x02 add 0x03 push label end 0x04 jump-if-carry-set 0x05 push label begin 0x06 jump 0x07 label end: pop As the program executes, write down the address of the instruction executed, line numbers, the state of the carry ag (if known) and the values stored on the stack, Your answer should show your reasoning. 6 marks c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 53 6. The instruction set for an accumulator-type Harvard-architecture microprocessor with 8- bit instructions, 6-bit addresses, and 4-bit data is supplied. The C/C++ subroutine, to calculate base-2 logarithms, must be compiled so that the nal assembly language routine starts executing from address 0x12. Instruction set: Description Format add Add the contents of the accumulator to the operand; Result in accumulator; Sets/Clears zero and carry ags 0010 nnnn clf Clear all ags 0001 0010 jnc Jump to the speci ed INSTRUCTION address if the carry ag is not set 01qq qqqq lod Load the number from the speci ed DATA address into the accumulator 10qq qqqq nop No operation 0000 0000 rtn Return to the calling routine (return value should already be in accumulator) 0001 1100 sbt Subtract the operand from the contents of the accumulator; Result in accumulator; Sets/Clears zero and carry ags 0011 nnnn shl Logical shift left contents of accumulator; result in accumulator 0001 1011 shr Logical shift right contents of accumula- tor; results in accumulator 0001 1010 str Store the number from the accumulator to the speci ed DATA address 11qq qqqq zer Zero the contents of the accumulator; Clears the zero ag 0001 1000 NIBBLE base2log_routine(NIBBLE c) { BYTE a,b; b=0; a=c; while (a>=2) { a=a/2; b=b+1; } return b; } (a) Manually translate the C/C++ code into assembly language: 5 marks c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 54 (b) Encode your assembly language using the op-codes supplied. Indicate the memory loca- tions used for variables and branch destinations using labels. Place the nal values into the data memory locations, presuming that routine was called with the value 0x9 as the function argument. 5 marks Data memory 0x10 0x11 0x12 0x13 0x14 Instruction memory 0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17 0x18 0x19 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2A This assignment is worth 2% of the 40% assigned for the ECNG2006 coursework mark. It contains a total of 40 marks. PLAIGIARISM DECLARATION: For the purposes of this exercise, unauthorised collaboration is any form of collaboration which does NOT fall into one of the following categories: verbal or written discussion/clari cation of question and/or related concepts Department of Electrical and Computer Engineering PLAGIARISM Plagiarism is the presentation by a student of an assignment which has in fact been copied in whole or in part from another student’s work, or from any other source (e.g. published books or periodicals), without due acknowledgement in the text. COLLUSION Collusion is the presentation by a student of an assignment as his or her own which is in fact the result in whole or part of unauthorised collaboration with another person or persons. DECLARATION I declare that this assignment is my own work and does not involve plagiarism or collusion. I have read and understood University Examination Regulations 73,75,76 and 79 regarding cheating. Signed: Date: (Department of Electrical and Computer Engineering) c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 55 A S S T AUnit 5 Write the letter you have been assigned here . Answer the following questions for ONE instruction whose letter you were assigned. 1. The instruction is . 2. The instruction has operands. 3. The format of this instruction is: . 4. Write a sentence which explains what the CPU does in response to this instruction. 5. Write a short program to demonstrate how the instruction can be used by the programmer of an embedded system. Re ection & Feedback Indicate the objectives that you feel you have achieved in this unit. { explain the operation of typical machine instructions, addressing modes, status bits; { predict the results of sequences of generic instructions; Which aspect of this unit did you have the most di culty understanding? Which aspect of this unit did you like best? Why did you like it? Identify one thing (if any) that you learned while doing this unit/tutorial. Identify one way in which this unit/tutorial could be improved. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 I 56 Microprocessor Overview This section presented a highly simpli ed view of microprocessors and microprocessor-based sys- tems. The more astute student will recognise that the text contains several statements which were never, or are no longer, strictly true. Among the more obvious: The RISC{CISC border has blurred; in most cases features from both are merged. In fact RISC processers are rapidly being outstripped by superscalar and parallel(e.g Dual core) architectures. We have not mentioned SIMD (Single Instruction Multiple Data) or MIMD (Multiple In- struction ...) processors Arbiters and DMA controllers have merged. In fact burst mode DMA, utilises the DMA mechanism for sending data over more than one bus cycle. Memory is no longer directly accessed over the system bus: it may have a dedicated bus, (e.g. RAM Bus) or Level I/II cache may be used (faster, smaller memory banks \closer" to the microprocessor) Peripherals are becoming more intelligent, with a variety of peripheral buses (w/ controllers) being used to transmit data independently of the system bus. Due to increasing performance demands, and shrinking transistor size, CPU design is now an extremely complex eld. The average chip designer is resorting to the use of prede ned CPU parts in a custom SoC (system-on-chip), which includes other circuitry. The purpose of this section was to address part of the rst course objective; i.e. \identify, and de- scribe the role of, the components of a microprocessor, a microprocessor-based system," and as such it is su cient, if you the student possesses su cient appreciation of the parts/mechanisms to facilitate assembly-language programming/debugging. The following section will further address the rst course objective. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) Introduction to microprocessors c DECE, UWI, St. Augustine, Trinidad original author: Feisal Mohammed; updated: March 11, 2008{ CLR Part II Microprocessor-based system development The previous section talked about the hardware components which make up a microprocessor, and a microprocessor based system, and the ways in which they interact. However, there are other issues to choosing/designing a microprocessor; primarily, the issue of developmental support. This support manifests itself in several ways: documentation, software development tools and hardware development tools. This part gives a brief introduction to these topics, to familiarise the reader with the terminology, as well as common features and techniques. 6 Software tool chain At the end of this unit the student will be able to: explain the roles of the compiler, linker, assembler, simulator, emulator, debugger in the software development tool chain, explain the role of scripting languages, make/con gure-like utilities and IDEs in the software development process. When a program is written as text, it must rst be compiled (high level language) or assembled (assembly language). The compiler(or assembler) is a special program which converts the text into relocatable machine instructions. Compilers and assemblers understand two types of commands: programming statements, and pre-processor directives. Programming statements are code i.e. what you want the microprocessor to do. Preprocessor directives are simple instructions which run prior to the actual compiler(assembler); they make the programmer’s life easier. For example, the "#de ne" in a C program is a preprocessor command, which replaces the speci ed text string throughout the le. The microprocessor-based system developer must decide which language, assembly or one of the higher-level languages to program in: \The factors relevant to a language decision probably include at least: E ciency of compiled code Source code portability Program maintainability Typical bug rates (say, per thousand lines of code) The amount of time it will take to develop the solution The availability and cost of the compilers and other development tools ECNG2006 (EE25M) March 11, 2008 II 2 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 3 Your personal experience (or that of the developers on your team) with speci c languages or tools " (Barr 2000; { from Language Lessons by Michael Barr, Copyright 2000 by CMP Media, Inc.) If the host and target are not the same type of microprocessor, a special cross-compiler or cross- assembler must be used (because the host will not understand target instructions and vice versa). The compiled (assembled) le from must be linked before it can be used by the target. Linking is used to provide several facilities, namely multi- le programming and/or use of libraries/pre-written routines. The Run Time library is a collection of standard C functions e.g. printf compiled for the particular tool-chain/target platform. The linker takes the various sets of relocatable code, and generates the nal executable which can be loaded into memory, or run by a simulator/emulator. To do so, the linker decides where code and variables will be placed in memory, and resolves addresses for items referenced in multiple modules. The linker must be aware of the target’s memory map, in order to produce a valid executable or binary le. Information about the memory map is often speci ed in an additional text- le which is speci ed when the linker is invoked. The nal binary le will contain machine instructions, and information about the speci c locations in memory to which they are to be loaded. Because the le contains code for the target processor, it cannot be run on the host, unless we use another program to interpret the target code. Instruction SetSimulators, and emulators are similar in that they may both run on the host processor, and accept code produced for the target processor. However, simulators do not interact with hardware, they run within a \virtual target" environment on the host. Whilst emulators, possess a hardware interface, so that they may physically replace the target \in-circuit". In both cases (simulator and emulator), the objective is to be able to \view" what is going on \within" the target during program execution; this assists the programming in \debugging" i.e. lo- cating portions of code which do not perform as expected/speci ed. Techniques typically employed in debugging include: use of breakpoints to pause the program single stepping through program \watch"ing or setting speci c values in memory An alternative to simulators, and emulators, is to actually build support for debugging into the target software. When the program code is downloaded to memory, additional code (debug kernel) is also downloaded. Using this additional code, the target will communicate with a program on the host (debugger) via serial or network connections, and report the state/change of state in the target as code executes. The advantage of using standard debug kernels, is that the same host debugger software may be used for mutliple target microprocessors. Examples of debug kernels include: the Angel debug monitor, and the gdb debug stub. All three options have their relative advantages and drawbacks. Simulators (because they run much more slowly), cannot cope with or be used to troubleshoot problems due to interaction with external devices/timing. They can however be used to debug/predict execution times of particular pieces of code which have no external interaction. Emulators also tend to run at lower speeds than the physical target; emulators which can match target speeds are expensive compared to other development tools. Both emulators and simulators are designed to match the target speci cations and cannot identify problems which arise from targets which somehow violate their c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 4 speci cations (hardware or software). In-circuit debugging, will take CPU time and other resources (e.g. interrupts), and cannot be performed without a ecting the performance of the code under test. In practice, each method is applied (as appropriate) to deal with a sub-set of problems, and any remaining problems must be dealt with using hardware-based troubleshooting methods. Microprocessor software development tools are generally designed to work in conjunction with each other. The term tool chain is often used to collectively refer to assemblers, compilers, linkers, libraries, simulators, emulators and debuggers. These are all command-line tools, i.e. in order to run the tool, you must type the name, and provide it with a list of options before it will run. Repeatedly typing in command lines can become tedious, thus many tool chains also include other programs to facilitate the development process. These \helper" programs can be roughly subdivided into: scripts or batch les, make les, window- based IDE’s . Scripts or batch les are simply sequences of commands, which could have been typed in at an interpreter prompt. Often they support replacement of wildcards by parameters speci ed when the script is invoked. They can be con gured to stop if any command gives an unexpected result. In this context, the script le would contain a sequence of tool-chain commands, with wildcards used for the program name(s). One popular tool coming from the UNIX development environments is the make le. Make les operate on a similar principle to scripts, except that they are especially designed for software devel- opment, and are executed by the make utility. Make les consist of a list of rules and dependencies for individual make le-targets. If a make le-target does not exist, then make checks whether all the dependencies exist. If a dependency does not exist, it looks for a rule/depedency list to make the dependency. Once all dependencies exist, the rule is executed. Make also checks the date/time- stamps on les; if the dependencies are time-stamped later than the make le-target, then the rule is executed. Make is invoked with a single make le-target By listing all the required make le-targets as dependencies of a single make le-target, we can cause all les to be built in the required order. Integrated Development Environments(IDEs) are window-based software packages designed to ease the use of the various software tools required to perform program development. They generally provide text editing (tailored with highlighting/syntax checking), project les to keep track of all the contributing les, and their relevant tool settings, and launch menus for the various items in the tool chain. They may also present the results of these tools for easy correction/review of the text program. For example, after compilation, a window with the errors comes up to prompt the user for changes. Additional features may include a (make-like) build, version control, and code generation from software design tools. When choosing a compiler or tool-chain (tool-set), the following issues must be considered: \ Target Platform The rst step in selecting a cross compiler is nding one that will produce code for your target processor. Host Platform The next step is to decide on a development platform. If there are several platforms available, you may want to check some of the other items in this list before making a decision about the host. Integration with Other Tools Is the compiler compatible with any debugging environments? Is a make utility included? If the compiler is shipped with an IDE, is it extensible so that you can integrate your version control tool? Standard Libraries Will you need functions from the standard C library, math library, or C++ classes? If so, are they provided with the compiler? Are all of the functions in those libraries reentrant? c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 5 Startup Code Is startup code for embedded systems provided? Are the code and its use well documented? If you can’t nd any mention of startup code in the user’s manuals for a potential cross compiler, consider that a bad sign. Execution Speed Optimizations If your program is too slow, you’ll want the compiler to try to speed it up. Will the compiler do this? If so, what speci c optimizations are supported? Can they be individually enabled or disabled? Program Size Optimizations If your program is too big for your target memory, you’ll want the compiler to attempt to reduce the amount of code space used. Will the compiler do this? If so, what speci c optimizations are supported? " { (Barr 1999; Extracted from Table 1. Checklist for Cross Compiler Selection Target Processor) Review Exercises 1. Write a de nition for all italicised terms in this unit. 2. Di erentiate between: (a) an emulator and a simulator. (b) an interpreter and a compiler. (c) a script and a make le. (d) a library and a linker. 3. Label the following statements about the software tool-chain as True/False: (a) The IDE provides provide a common editor/interface for other elements of the software development tool chain. (b) The assembler takes assembly language text and optionally produces object les. (c) The compiler only runs on the target platform, and generates code for the host platform to run. (d) The compiler takes output from the assembler, and produces the executable le. (e) The debugger runs on the host, and communicates with the target debug kernel code. (f) The di erence between the simulator and the emulator is that the simulator runs on the host, and the emulator runs on the target. (g) The host and target platforms are always di erent. (h) The linker is never used when the host and target platforms are di erent. (i) The simulator runs on the host platform, and executes code compiled for the target platform. (j) The simulator takes assembly language text as input, and runs on the target. (k) The tool-chain is a group of programs used to facilitate the development of programs for a particular target(s) on a particular host. 4. From (Wilmhurst 2001; 12.3) c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 6 \ You are employed in a small company whose products incorporate PIC microcontrollers. You are the company’s only development engineer, and you wish to persuade your manager to agree to the purchase of an in-circuit emulator. Your manager, however, knows that you have ...[a simulator] already, and believes (perhaps wrongly) that if you can simulate a program then you don’t need the emulator. Write a justi cation for your proposed purchase stating clearly the advantages that an emulator would give. " 5. In addition to pre-processor directives, C compilers often support special keywords, which are not part the standard C. One example is the asm/endasm keyword pair used to delimit blocks of assembly language code within a C program. What possible advantage could this non-standard keyword o er? 6. \Decompiling is the process of generating source-level code from the executable object code embedded in a product’s memory". (Fisher 2000) This can be a serious problem for developers of proprietary systems. Investigate this issue, and identify one way in which code can be protected from being decompiled. 7. In your own words, explain why the same C code, when compiled by di erent compilers may generate di erent size/speed executables. 8. (a) Explain how scripts may be used to automate testing of the software, as dictated by the client, both in the absence of the hardware, and after the hardware becomes available. (b) Investigate and identify 2 scripting languages commonly used in software development. 9. Explain what a debug kernel is. Your answer should mention ways in which a debug kernel can facilitate testing/ xing a micro-processor-based system. 10. Role play: Assembly language programming skills are often valued, because of the perception that the assembly language programmer will always generate more e cient code. Form teams which will debate this issue from the following viewpoints: In (Barr 2000), Michael Barr describes a case where the C program was faster than the assembly language program: \The speedup was actually the result of a better design." \Assembly will always be at least as fast as C when executing the same algorithm." (Barr 2000) c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 7 Tutorial Exercise 3A O ine Version13 ID# Congratulations! You have been assigned to the NOVATE company as a summer trainee in the software development division. NOVATE has recently been granted a contract to develop an embedded system which monitors oil ow in pipelines. The system will provide an estimate of the oil transported via the pipeline, as well as automatically detect changes in ow (e.g. pipeline breaks). The sensor and microprocessor hardware must be specially developed for solar power consumption, and adverse environmental conditions, and will not be available for several months, although a functional/circuit diagram for the system is currently available. You must develop the software and verify that it operates correctly in di erent (contract-speci ed) scenarios. 1. At this time, in this project, which of the following items could you use to DEVELOP your software? 5 marks (a) compiler (b) IDE (c) libraries (d) linker (e) loader 2. Choose the word combination which best completes the following sentence: 1 mark Within the development tool chain, the simulator runs on the 2I and takes 2II as input, while the online debugger runs on the host, and communicates with the 2III . (a) 2I: host 2II: assembly language text 2III: target emulator (b) 2I: host 2II: binary le (hex le or executable)2III: target debug kernel (c) 2I: host 2II: binary le (hex le or executable)2III: target emulator (d) 2I: target 2II: assembly language text 2III: target debug kernel (e) 2I: target 2II: binary le (hex le or executable)2III: target emulator 3. For this project, how much development and testing can take place before the hardware be- comes available? You may use drawings/diagrams to express your answer, if you prefer. 4 marks PLAIGIARISM DECLARATION: For the purposes of this exercise, unauthorised collaboration is any form of collaboration which does NOT fall into one of the following categories: verbal or written discussion/clari cation of question and/or related concepts Department of Electrical and Computer Engineering PLAGIARISM Plagiarism is the presentation by a student of an assignment which has in fact been copied in whole or in part from another student’s work, or from any other source (e.g. published books or periodicals), without due acknowledgement in the text. COLLUSION Collusion is the presentation by a student of an assignment as his or her own which is in fact the result in whole or part of unauthorised collaboration with another person or persons. DECLARATION I declare that this assignment is my own work and does not involve plagiarism or collusion. I have read and understood University Examination Regulations 73,75,76 and 79 regarding cheating. Signed: Date: (Department of Electrical and Computer Engineering) 13Students are advised that O ine versions are to be used either with the explicit permission of the course lecturer OR at times when the electronic course support site is unavailable for more than 48 hours. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 8 T U T 3 AUnit 6 Your lecturer will put up a diagram with several parts of the software development tool- chain labeled with letters. Answer the following questions for the part whose letter you were assigned. Write the letter you have been assigned here . 1. The part is called the . 2. Circle the correct answer. The primary function of the part is: (a) to convert assembly language text to relocatable machine code . (b) to convert high level language text to relocatable machine code . (c) to convert relocatable machine from many les into a single binary/executable le . (d) to store relocatable machine code for commonly used functions, speci c to a tool-chain, high-level language and/or target. . 3. Write a sentence which explains how this part of the software tool-chain operates, with ref- erence to the host and target machines. Re ection & Feedback Indicate the objectives that you feel you have achieved in this unit. { explain the roles of the compiler, linker, assembler, simulator, emulator, debugger in the software development tool chain, { explain the role of scripting languages, make/con gure-like utilities and IDEs in the software development process. Which aspect of this unit did you have the most di culty understanding? Which aspect of this unit did you like best? Why did you like it? Identify one thing (if any) that you learned while doing this unit/tutorial. Identify one way in which this unit/tutorial could be improved. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 9 7 Development support (hardware) At the end of this unit the student will be able to: explain the role of rmware, operating systems, oscilloscopes,logic probes/analyzers, terminals, disk drives, external memory, host computers debug protocols e.g. JTAG in the development and support of microprocessor based systems. In the previous unit, we looked at the software needed to perform microprocessor-based system development. Some of that software, (for example emulation) works in conjunction with specialist hardware. In this unit we examine some of the more hardware-related items required to support development. The rst two items rmware and operating system kernels while software, are strongly tied to the hardware upon which they run. Firmware is software stored in a non-volatile medium e.g. EPROM, and is typically where the self-test, boot-loader and/or BIOS code is stored i.e. software that needs to run when the system is rst powered up. For EPROM/ ash media, rmware may be programmed using a dedicated universal or chip programmer, and then the media may be placed in circuit; the newer ash chips support serial programming while the chip is in circuit. Operating system kernels may be stored as rmware, or may be stored on volatile media, and loaded into memory by the rmware. Both rmware and operating systems are written for spe- ci c platforms, with known memory maps. They will not work on di erent platforms. A target microprocessor-based system, need not necessarily have an operating system installed. In dedicated single function applications, the program is compiled down to a an absolute binary which is placed in memory starting at the reset vector. Where the operating systems on the host and target di er, we must ensure that they both interpret le(s) in the same manner. e.g. UNIX and Windows operating systems interpret ASCII control characters di erently. Development boards, are circuit boards tted with a microprocessor, support circuitry for the more commonly used peripherals, and expansion space for customisation. They are useful to the microprocessor-based system software developer, as they give the programmer something to test code on/with prior to obtaining the custom board being developed for the application. This means that application hardware and software can be developed in parallel reducing overall development time. In order to troubleshoot timing and signal problems involving a microprocessor, it is necessary to examine the signals at the pins (Note: we cannot get inside) using an oscilloscope or logic analyser. Generally, an oscilloscope can show only 2 channels (2 pins) simultaneously. The logic analyser however allows the user to capture either timing (continuous sampling at the logic analyser frequency) or state information (sampling at the system clock frequency) on multiple pins. Because of the quantity of information that the logic analyser captures, it needs to have large data bu ers, and provide facilities to capture selective data (trigger conditions), lter the captured data, and/or download to a PC for analysis. Some logic analysers can even list the program begin executed, simply by recording the data passing across the microprocessor bus lines, and disassembling the instructions. Logic analysers have two main drawbacks. The rst is the physical di culty of making multiple connections on dense pin packages. Special connectors are often delicate, and accidental shorts are c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 10 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 11 always possible. The second is the fact that signals within the IC cannot be examined. This may not be an issue for microprocessor-only IC’s, but where ASIC’s or SoC’s utilise multiple parts (e.g. memory, and CPU) on a single IC, hardware troubleshooting becomes di cult. Furthermore, the disassembly technique will not work if a microprocessor has on-board cache memory. To address these problems, the JTAG (Joint Test Action Group) protocol was developed. This serial protocol is based on the concept of a simple sampling circuit connected to each "virtual pin" within the IC. All the sampling circuits are connected in a loop, which in turn acts as a large shift register. The state of all the virtual pins at any time, may be obtained by shifting out the value. Similarly the value at any virtual pin may be set by shifting in a particular value. In the previous unit, we mentioned that where host and target are separate machines, the debug kernel on the target communicates with the debugger on the host. Alternatively, (or in conjunction w/ the debug kernel) there may be built-in hardware support for debugging. This is referred to as in-circuit debug, or background debug. Two examples are Microchip’s OCD, and Motorola’s BDM. Specialty hardware within the IC can monitor/query the processor state, match a single breakpoint, or stop execution when a signal is detected on a pin. The hardware is programmed/reports serially across dedicated pins. In order to support more sophisticated functions using the basic hardware debug functions, interface circuitry is used between the target microprocessor and host circuitry. The interface circuitry (often containing another microprocessor), generates the appropriate hardware commands, and logs/bu ers information reported by the hardware. Debugging with a debug kernel and debugger, has the disadvantage that the debug kernel code may somehow interact with the application code. This is not a di culty for development. Both JTAG and hardware debugging support methods have the advantage that each nal product (with optimized code) may be tested for hardware and/or software aws before it is shipped. The target system often has a rudimentary command line interface, which necessitates the use of a keyboard and display. The terminal is a device with a serial connection, which is designed to take keyed input, and relay it out as ASCII data, and display ASCII data transmitted back to it. It is extremely rare to nd text terminals e.g. VT100 in use these days, however most operating systems on host computers will allow the PC to emulate a terminal (e.g. hyperterm). The target system may also require a rudimentary le storage system. Random Access ling systems, originated with disk-shaped magnetic media, and the terminology (tracks, sectors, blocks) re ects this. The actual le data is stored in a number of blocks. The FAT (File Allocation Table) (stored at a known location on the medium) is a list of records representing the information stored at each block. Each record speci es the following block. Filing systems for solid media (Flash, RAM, ROM) follow the same format, so that they may be be used interchangeably. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 12 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 13 Review Exercises 1. Write a de nition for all italicised terms in this unit. 2. Label the following statements as True or False. (a) A PC may be used to download software to the target (programming). (b) A logic probe provides facilities to capture and display multiple signals simultaneously. (c) Debug Kernels provide services which can be accessed by the programmer. (d) Firmware is software which is stored in a volatile medium. (e) JTAG allows the injection and extraction of values to/from an integrated circuit. (f) Terminal emulation software allows a PC to be used as a dumb terminal. (g) The le storage system is a device with a serial connection, which is designed to take keyed input, and relay it out as ASCII data. (h) The host computer may be used for the display of information reported by the debug kernel. 3. We would like to examine the supply DC voltage for a microprocessor based system, for suspected noise. We should use: (a) logic analyser (b) logic probe (c) memory chip (d) oscilloscope (e) volt-meter 4. You are developing software for a hardware platform which has been built, but the microcon- troller is presently unavailable. Which ONE of the following items will you use to determine whether your hardware platform functions as expected? (a) debug kernel (b) integrated development environment (IDE) (c) emulator (d) rmware (e) scripts 5. From (Wilmhurst 2001; 12.4) \ You have been asked to set up a .... [microprocessor] development system. List [two] items of hardware .... you would wish to purchase, stating brie y what each would be used for." c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 14 6. Di erentiate between the following pairs of items: (a) an oscilloscope and a logic analyser (b) rmware and software (c) JTAG and hardware debug support (d) a microprocessor development board and a custom microprocessor-based board. 7. You are developing a microprocessor-based system which requires a display and a keypad. You need to choose between: an LCD display and a keypad. a terminal. Identify two issues that you would consider, and explain how you would make your decision based on those issues. 8. A micro-processor based system fails to provide the required output in a limited number of cases. You suspect that there may be a voltage problem which is causing certain bus lines to be incorrectly interpreted as "low". What piece of equipment would you use to track down this problem? Explain your answer. 9. Challenge Question: Investigate the following topics JTAG uses the concept of a large shift register. This can become unwieldy for large numbers of virtual pins. How does the JTAG standard address this problem? How do developers of Flash Filing Systems cope with the fact that Flash memory can be written in small blocks but must be erased in larger blocks? 10. Challenge question: ROM emulators, instead of emulating the entire microprocessor, simply emulate the program/data memory. Outline how this could be used to implement debugging. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 15 Tutorial Exercise 3B O ine Version14 ID# Congratulations! As a new graduate, NOVATE has hired you to complete an embedded system which monitors oil ow in pipelines. The system will provide an estimate of the oil transported via the pipeline, as well as automatically detect changes in ow (e.g. pipeline breaks). The contract also speci es that the system must be demonstrated to operate correctly in a variety of di erent scenarios. The sensor and microprocessor hardware have been specially developed for solar power consumption, and adverse environmental conditions, and are now available for testing. The software was previously written and tested on a simulator. 1. Your boss says: \The software already works, so just download it onto the platform and send it out. Don’t bother to test it again." What will you say to convince him that testing is required? Your answer should identify potential system aws, and the tools/methods you will be using to test the software on the platform. 6 marks 2. The nal system has passed all in-lab tests. The system fails in the eld. The hardware developers have determined that the hardware meets all electrical speci cations. Explain (using diagrams if required) what you will do to nd/ x the fault. 4 marks PLAIGIARISM DECLARATION: For the purposes of this exercise, unauthorised collaboration is any form of collaboration which does NOT fall into one of the following categories: verbal or written discussion/clari cation of question and/or related concepts Department of Electrical and Computer Engineering PLAGIARISM Plagiarism is the presentation by a student of an assignment which has in fact been copied in whole or in part from another student’s work, or from any other source (e.g. published books or periodicals), without due acknowledgement in the text. COLLUSION Collusion is the presentation by a student of an assignment as his or her own which is in fact the result in whole or part of unauthorised collaboration with another person or persons. DECLARATION I declare that this assignment is my own work and does not involve plagiarism or collusion. I have read and understood University Examination Regulations 73,75,76 and 79 regarding cheating. Signed: Date: (Department of Electrical and Computer Engineering) 14Students are advised that O ine versions are to be used either with the explicit permission of the course lecturer OR at times when the electronic course support site is unavailable for more than 48 hours. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 16 T U T 3 BUnit 7 Your lecturer will put up a diagram with several development support items labeled with letters. Answer the following questions for the part whose letter you were assigned. Write the letter you have been assigned here . 1. The part is called the . 2. Circle the correct answer. The primary function of the part is: (a) provide random access storage for the target system . (b) act as an initial hardware prototype for the designed target system . (c) capture and view signals on the pins of target system . (d) program rmware for use in the target system . 3. If you did NOT have access to this part, what e ect would/could it have on your development of a micro-processor based system? Suggest alternatives to this part. Re ection & Feedback Indicate the objectives that you feel you have achieved in this unit. Explain the role of { rmware, operating systems, oscilloscopes,logic probes/analyzers, { terminals, disk drives, external memory, host computers debug protocols e.g. JTAG in the development and support of microprocessor based systems. Which aspect of this unit did you have the most di culty understanding? Which aspect of this unit did you like best? Why did you like it? Identify one thing (if any) that you learned while doing this unit/tutorial. Identify one way in which this unit/tutorial could be improved. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 17 8 Microprocessor families and forms At the end of this unit the student will be able to: recognize and di erentiate between the di erent commercially available families of microprocessor based systems (e.g. Motorola, AVR, PIC ) forms of microprocessor based systems i.e.chip/component packages { SOC, micro- controller, PC, back-plane bus, PC104, standalone, embedded based on their pictures/properties/descriptions and supported development tools. Microprocessor technology is relatively young and constantly changing. Over the last 30{40 years, most changes in CPU architectural design have been driven by the need for speed. Design tradeo s made over time include increasing bit widths, RISC/CISC, use of DMA, peripheral support, cache RAM, and dedicated/hierachical busses. Manufacturing improvements also improved clock speeds by reducing heat/distance considerations. What does all this change mean for the developer of a microprocessor based system? In manufacturing a system, we need to be concerned about two things: the expected lifetime of an individual system, and whether we will be able to repair/support it for it’s lifetime, the expected lifetime of the design, and whether we will be able to produce/sell the required number of units to recoup design costs. Clearly we can do neither if the processor around which we have designed our system becomes obsolete soon after we have gone into production/sale. To reconcile the reality of a rapidly changing marketplace, with the customers need for stability, manufacturers of microprocessor have adopted several strategies including: clones { a classic case is the 8051; originally produced by Intel, many companies now o er a pin compatible, architecturally equivalent processor. It is used as a replacement for the original 8051, as well as in new designs which can take advantage of instruction set exten- sions/enhancements. families { most people are familiar with the Intel x86 processors. These were designed to be backward compatible i.e. code compiled for a 286 processor will run on a 486 processor. Support for the base instruction sets is built into later members, even though the packaging and overall architecture may be di erent. scaled function versions { where di erent variants of the CPU are made available, each with a unique set of features, targeting a speci c market. For example, device A may require only 10 general I/O lines, but device B only 2 general I/O lines. The manufacturer makes two versions of the CPU, one with more lines and one with less lines, and prices them accordingly. The developer can then choose the lowest cost option that matches his needs. The developer cannot decide on the CPU to be used for a particular application, without inves- tigating the form in which the microprocessor is available. Apart from the myriad packages in c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 18 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 19 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 20 which they are singly supplied (DIP, PLCC etc.), they may also be supplied as either a part of an IC containing other functional parts/peripherals (microcontroller, ASIC, SoC), or as part of a bus-ready (PC104, back-plane) board containing other functional parts and peripherals, or as a stand-alone computer system. In addition, any of these variants can come with di erent maximum clock speeds, depending on the manufacturing processes used to produce the CPU. The choice of form and clock speed will depend on the particular application. Some additional items to consider include: Environmental tolerance Will the processor have to work in dusty, chemical, radiation, haz- ardous, vibrating, or zero gravity environments? If so special packaging will be required. Business Is the CPU available? How long will it take to get the product to market? What will the unit cost be? How many units can we sell? What will the net pro t be? History What are we already familiar with? Do we already have the support tools? What legacy code/features do we need to support? Power What is our entire power budget? What power-saving options are available? All other things being equal, we can choose a processor on the basis of code e ciency i.e. the time it takes to execute an algorithm and the space required to store the algorithm in memory (Palmer 1997a). Review exercises 1. In your own words, write out a list of guidelines for choosing a processor for a given application. 2. Using the Intel 8051 as an example, di erentiate between clones, families and scaled-function versions of microcontrollers. 3. Manufacturer X supplies an IDE which is appropriate for all the microprocessors that he supplies. We can presume that microprocessors supplied by Manufacturer X: (choose all the appropriate answers) (a) all have the same instruction format. (b) are all supported by the same assembler/compiler. (c) are all pin-compatible with each other. (d) all operate at the same clock speed. (e) all support on-line debugging. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 21 4. A microcontroller may be supplied in di erent variants. This means that: (choose all the appropriate answers) (a) The number, spacing and type of pins on the chip may be di erent for each package variant. (b) All variants will have the same operating voltages. (c) Di erent variants may have di ering environmental tolerances. (d) Di erent variants may have di ering maximum clock rates. 5. The microprocessor which was used in a particular design is no longer available. You have been asked to locate a suitable replacement. In order to be able to use the existing code, without re-assembly, the replacement MUST: (choose all the appropriate answers) (a) come from the same manufacturer (b) be pin compatible (c) have the same instructions in it’s instruction-set (d) have the same instructions & instruction-format 6. The microprocessor which was used in a particular design is no longer available. You have been asked to locate a suitable replacement. In order to be able to use the existing circuitry, without re-design, the replacement MUST: (choose all the appropriate answers) (a) come from the same manufacturer (b) be supplied in the same package (c) have the same instructions in it’s instruction-set (d) be a unit with the same power/current characteristics 7. AN520 (Palmer 1997a)compares the performance of several microprocessors using typical algorithms. This is an example of benchmarking. Justify your answers to each of the following questions. Is it appropriate to use benchmark data to choose a processor without: (a) an understanding of the benchmark algorithm? (b) an understanding of the application algorithm? 8. Based on (Vahid and Givargis 2002; 3.8): The PIC16F877 is one of a family of microcon- trollers. (a) Using the datasheet, identify i. the basic instruction set features (# of instruction(s) variants, instruction width) ii. the I/O facilities (# of ports, tri-state facilities) (b) Go to the MicroChip web-site (http:\\www.microchip.com) and identify i. a scaled back version of the same microcontroller ii. another microcontroller belonging to the same family iii. another family with a similar (but not the same) instruction set c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 22 9. Role Play/Challenge Question: Imagine you are an engineer in a company which used an Alpha processor in a design for a system. Your company would like to continue selling the system for another 10 years. Investigate the current status of the Alpha family, and then write a letter to your line manager making recommendations as to: how your company can continue to support the systems you have already sold, how your company can continue to produce the system. 10. Role Play: A microcontroller based product, for use in a hostile environment, was designed using a microcontroller IC which has become obsolete. The company must decide between a pin-compatible microcontroller which is not binary-compatible, or a binary-compatible mi- crocontroller which is not pin-compatible. Form teams which will debate this issue from the following viewpoints: The software developers want to redesign/modify the board and keep the software be- cause the code has already been checked, and the modi ed system could be re-tested with existing scripts. The hardware developers want to rewrite/recompile the software and keep the board because it is already designed/checked for operation in a hostile environment. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 23 Tutorial Exercise 4A O ine Version15 ID# Congratulations! Because of your excellent work, NOVATE has promoted you. You head the production team for an embedded system which monitors oil ow in pipelines. The system was successfully developed with a socketed PIC16F877 microcontroller in a 40-pin DIP package, and a 4MHz clock signal. The system utilises the Timer, PWM, and A/D features of the variant. NOVATE is committed to delivering and installing 20,000 modules over 2 years. The procurement department has been ordering parts in batches for 1000 modules on a monthly basis. Ten months into production, procurement advises your team that the PIC16F877 microcontroller is no longer available in the required variant. Furthermore, they cannot locate a pin-compatible variant, with the required features, which will also be binary-compatible. 1. Identify and explain two choices you could have made back in the development stage which would have made this transition easier. 6 marks 2. How will your team modify the system, so that the remaining modules can be delivered? Your answer should identify changes in hardware, software, testing, tools and/or tool-chains. 4 marks PLAIGIARISM DECLARATION: For the purposes of this exercise, unauthorised collaboration is any form of collaboration which does NOT fall into one of the following categories: verbal or written discussion/clari cation of question and/or related concepts Department of Electrical and Computer Engineering PLAGIARISM Plagiarism is the presentation by a student of an assignment which has in fact been copied in whole or in part from another student’s work, or from any other source (e.g. published books or periodicals), without due acknowledgement in the text. COLLUSION Collusion is the presentation by a student of an assignment as his or her own which is in fact the result in whole or part of unauthorised collaboration with another person or persons. DECLARATION I declare that this assignment is my own work and does not involve plagiarism or collusion. I have read and understood University Examination Regulations 73,75,76 and 79 regarding cheating. Signed: Date: (Department of Electrical and Computer Engineering) 15Students are advised that O ine versions are to be used either with the explicit permission of the course lecturer OR at times when the electronic course support site is unavailable for more than 48 hours. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 24 T U T 4 AUnit 8 Write the letter and number you have been assigned here . Answer the following questions for the Microprocessor Alternate whose letter you were assigned. 1. The CPU is made by .. 2. Circle the correct answer. What type of IC package is the CPU inside?: (a) DIP (b) PLCC (c) QFP (d) Unspeci ed or Other 3. In what form is the CPU presented for the micro-processor-based system developer? (a) Microcontroller (b) Microprocessor-only IC (c) Motherboard, PC104 board, or Board for back-plane bus system (d) Unspeci ed or other 4. Compare the PIC16F877 & this processor (assign one group member to each item) (a) look at the block diagram(s) identify the internal features of the CPU core identify additional features of the microcontroller/board identify other family members/clones (b) look at the memory map(s) is this Von Neumann/Harvard architecture? are devices memory-mapped? is there a separate I/O bus? (c) locate the branch/jump instruction what is the mnemonic? what is the op-code? what is the branch address size? (d) locate the clock signal/data speci cations what is the maximum clock frequency? what is the CPI? MIPS ? what is data/instruction width? (e) locate the power/current requirements what is an appropriate operating frequency for both platforms? what is the minimum operating voltage for a given frequency? what is the average current (CPU Only) draw at a given voltage/frequency? c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 25 T U T 4 A Unit 8 Re ection & Feedback Indicate the objectives that you feel you have achieved in this unit. Recognize and di erentiate between the di erent commercially available { families of microprocessor based systems (e.g. Motorola, AVR, PIC ) { forms of microprocessor based systems i.e. chip/component packages; board forms based on their pictures/properties/descriptions and supported development tools. Which aspect of this unit did you have the most di culty understanding? Which aspect of this unit did you like best? Why did you like it? Identify one thing (if any) that you learned while doing this unit/tutorial. Identify one way in which this unit/tutorial could be improved. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 26 Informative Abstract You have been assigned an article on a topic of relevance to microprocessor-based systems. Groups A1, B1, C1, D1 : \Fuzzy Logic Control for an Autonomous Robot" by V.M. Peri and D. Simon, Annual Meeting of the North American Fuzzy Information Processing Society (NAFIPS), 2005, 26-28 June 2005, page(s): 337- 342. Groups A2, B2, C2, D2 : \Sni ng Robot" by Silvio Tresoldi, Circuit Cellular, Issue 108, July 1999, page(s): 12-16. Groups A3, B3, C3, D3 : \Machine Chameleon" by D. Verkest, IEEE Spectrum, Volume 40, Issue 12, Dec. 2003, page(s):41 - 46. Groups A4, B4, C4, D4 : \The transistor laser" by Nick Holonyak Jr. and Milton Feng, IEEE Spectrum, Volume 43, Issue 2, Feb. 2006, page(s):50 - 55. 1. Read your assigned article (or choose another article from an IEEE magazine, and have it approved by your lecturer), and submit (at most) a one (1) page informative abstract of the article. Your abstract should include the following areas: 12 marks (a) The objectives of the article or research undertaken; (b) The scope of the work; (c) The methodology employed; (d) The signi cant ndings or results; (e) The signi cant recommendations and; (f) The conclusions drawn. 2. Identify, and explain in your own words, either (a) a potential application of this research/work to (b) a prediction about how this research/work may a ect the design/production of microprocessor-based systems in the near-future. 2 marks Your submission should be headed with the article reference and your name/ID number. You must upload your submission to Moodle using the relevant assignment link. Your submission should be named Fnnnnnnnn.xxx where nnnnnnnn is your ID number, and xxx is the le extension re ecting the le type. Files may be PDF, Microsoft Word (DOC) or plain ASCII les (TXT). Please remember to electronically submit AHEAD of the deadline in order to avoid possible prob- lems with system overload. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 II 27 Microprocessor-based system development There are many issues to be considered when developing a micro-processor based system. In this section we have examined some of the technology available for software and hardware development support, as well as the di erent ways in which CPU technology is made available to the designer of a microprocessor-based system. As such we have addressed part of the rst learning objective \in general, identify, and de- scribe the role of, the components of a development suite (hardware, software) for a microprocessor-based system" and hinted at the nal learning objective \select (and cri- tique the selection of) a microprocessor-based system for an application, given relevant datasheets and application requirements". In the next section we will be looking in some detail at a particular CPU, it’s instruction set, and memory map, and at the developmental support tools available for it. In doing so, we will complete the rst learning objective. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) Introduction to microprocessors c DECE, UWI, St. Augustine, Trinidad original author: Feisal Mohammed; updated: March 11, 2008{ CLR Part III PIC16 Introduction All microcomputer systems, irrespective of their complexity, are based on similar building blocks. The CPU or microprocessor is the core component of any microcomputer and it requires the external components such as the ROM, RAM, I/O etc. to accomplish its purpose. A microcontroller is a stripped-down version of the very same architecture, with all the important features placed on one chip. The same system using a microprocessor or a microcontroller looks like Figures 2,3. The microcontroller based system requires no additional circuitry except a clock input and it can, in many cases, directly drive peripheral outputs. The di erence between the microprocessor and the microcontroller arises because of their di erent end-usage. The microcontroller that will be investigated is the PIC16F877, which is at the upper end of the mid-range series of the microcontrollers developed by MicroChip Inc. It is characterized by a RISC architecture instead of the CISC architecture used, for example, by the Motorola 6809. Figure 2: Basic building blocks of a computer Figure 3: A microcontroller based system ECNG2006 (EE25M) March 11, 2008 III 2 9 PIC16F877 Overview At the end of this unit the student will be able to: explain the memory layout for the PIC16F877 explain the operation of the instruction cycle for the PIC16F877 explain the operation of the basic instructions (move, add, subtract, shifts) for the PIC16F877 The history of the PIC series of microcontrollers started in in 1965, when General Instruments (GI) formed a Microelectronics Division, and used this division to generate some of the earliest viable EPROM and EEPROM memory architectures. GI also made a 16 bit microprocessor, called the CP1600, in the early 1970s. While this was a reasonable microprocessor, it was not particularly good at handling I/O. Therefore, around 1975, GI designed a Peripheral Interface Controller (or PIC for short) for some very speci c applications where good I/O handling was needed. It was designed to be very fast since it was I/O handling for a 16 bit machine, but it did not need a large amount of functionality, so its microcoded instruction set was small. Its architecture was substantially the PIC16C5x architecture of today. The market for the PIC remained small for the next few years. During the early 1980s, GI restructured their business to concentrate more on their core activity which was power semiconductors. As a result of the restructuring, the GI Microelectronics Division became GI Microelectronics Inc (a wholly owned subsidiary) which, in 1985, was nally sold to venture capital investors. The sale included the fabrication plant in Chandler, Arizona. The new owners decided to concentrate on the PICs, the serial and parallel EEPROMs and the parallel EPROMs. A decision was later taken to start a new company, named Arizona MicroChip Technology, with embedded control as its di erentiator from the rest of the industry. As part of this strategy, the PIC family was redesigned to use one of the other things that the edgling company was good at, i.e. EPROM. With the addition of CMOS technology and erasable EPROM program memory the PIC family, as we know it, was born. Architecture of the PIC microcontroller The PIC series of microcontrollers are RISC-based processors with an accumulator(also called the working register, W), which use the Harvard16 architecture; therefore the microcontroller has a program memory data bus and a data memory data bus. Separate buses mean that simultaneous access of program and data can be done, which gives a greater bandwidth over the traditional von Neumann architecture. Separating the program and data memory, allows instructions to be sized di erently than the 8-bit wide data word. This separation means that the instruction words can be ideally sized for the speci c CPU/application. This is necessary since RISC architectures require that instructions have the source and destination operands be encoded within the instruction. The PIC opcodes for the mid-range processors are 14-bits wide, and the 14-bit wide program bus fetches an instruction in a single cycle. 16This architecture had been a scienti c curiosity since its invention by Harvard University in a Defense Department funded competition that pitted Princeton against Harvard. Princeton won the competition because the MTBF of the simpler single memory architecture was much better, albeit slower, than the Harvard submission. MicroChip has made a number of enhancements to the original architecture, and updated the functional blocks of the original design with modern advancements made possible by the low cost of semiconductors. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 3 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 4 There are 35 single word instructions. A two-stage pipeline overlaps fetch and execution of in- structions. As a result, all instructions execute in a single cycle except for program branches. The pipeline uses static branch prediction and assumes that the branch is never taken, so that condi- tional branch instructions can take either one or two cycles. One cycle if the branch is not taken, since it would be in the pipeline and two cycles if the branch was taken. Non-conditional branch instructions such as call or goto always take two cycles. All program memory is internal i.e. the program bus is not accessible outside of the chip. The data path is 8 bits wide. Data memory may be accessible from outside of the chip using the Parallel Slave Port; when enabled, the port register is asynchronously readable and writable by the external world. The mid-range PIC processors can directly or indirectly address their data memory17. All special function registers18, including the program counter, are mapped in the data memory. The design of the instruction set is such that it is possible to carry out any operation on any register using either addressing mode. This design simpli es the programming of the device. The term le register is, in PIC terminology, used to denote the locations that an instruction can access via an address. The term register le is used to collectively refer to the group of registers. The PIC ALU can perform arithmetic and Boolean functions between data in the working register and any le register. The unit is 8-bits wide and capable of addition, subtraction, shift and logical operations. In two-operand instructions, typically one operand is the Working (W) register and the other operand is a le register or an immediate constant. In single operand instructions, the operand is either the W register or a le register. Depending on the instruction executed, the ALU may a ect the values of the Carry (C), Digit Carry (DC) and Zero (Z) bits in the STATUS register. The C and DC bits operate as Borrow and Digit Borrow bits respectively, in subtraction. Memory Layout The PIC16F877 has 8K 14-bit words of Flash program memory, 368 bytes of data RAM, 256 bytes of data EEPROM and an 8-level x 13 bit wide hardware stack. The Program Counter (PC) is 13 bits wide, thus making it possible to access all 8K x 14 addresses. The low byte is the PCL (Program Counter Low byte) register which is a readable and writable register. The high byte of the PC (PC<12:8>) is not directly readable or writable and comes from the PCLATH (Program Counter LATch High) register. The PCLATH register is a holding register for the PC<12:8>. The contents of the PCLATH are transferred to the upper byte of the program counter when the PC is loaded with a new value. Although the PC is capable of addressing the entire program memory space, conceptually the program memory is represented by four banks of 2K 14-bit words. Banking is necessary since there are only 11 bits for the address in the instruction word for a call or goto. The other two bits are obtained from the top two bits of PCLATH (i.e. PCLATH<4:3>). This means that the user must set those extra bits in PCLATH before branching out of the 2K bank that contains the current instruction. Within the program memory space, the reset vector (location to go to on reset) is at 0000h and the interrupt vector (location to go to on interrupt) is at 0004h. The data memory space e ectively has 9 bit addresses, and is also banked. There are 4 banks; each bank holds 128 bytes of addressable memory. The banked arrangement is necessary because there are only 7 bits are available in the instruction word for the addressing of a register, which gives only 128 addresses. The selection of the banks is determined by control bits RP1, RP0 in 17Data memory may be EPROM based, or RAM based. General purpose registers are contained in the RAM 18Note: The Working register (W) is an 8-bit register used for all ALU operations; it is not addressable. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 5 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 6 the STATUS register (STATUS<6:5>). Together the RP1, RP0 and the speci ed 7 bits e ectively form a 9 bit address. The rst 32 locations of Banks 1 and 2, and the rst 16 locations of Banks 2 and 3 are reserved for the mapping of the Special Function Registers (SFR’s). SFRs (e.g. PC, STATUS) are used to control the \core" operation of the microcontroller as well as peripherals such as the I/O ports. The SFRs are mapped into the data memory space to facilitate addressing. The 368 bytes of static RAM which are used as general purpose registers (GPR), are arranged in the data memory space so that each is accessed by a unique address, with the exception of the last 16 bytes of each bank, which are shared. Each mapped SFR and GPR is 8-bits wide. The entire data memory can be accessed either directly using the absolute address of each register le, or indirectly through the INDirect File (INDF) register and the File Select Register (FSR). The INDF register is not a physical register. Any instruction using the INDF register actually accesses the register pointed to by the FSR. Reading the INDF register itself, indirectly (i.e. FSR = 0) will read 00h. Writing to the INDF register indirectly results in a no operation (although status bits may be a ected). Because the FSR is 8 bits wide, indirect addressing can access two data memory banks simultaneously. The e ective 9-bit address is obtained by concatenating the IRP bit (STATUS<7>) and the 8-bit FSR register. The 256 bytes (8 bit address) of EEPROM memory is indirectly mapped into the data memory using the EEPROM ADRess (EEADR), EEPROM CONtrol (EECON1) and EEPROM DATA (EEDATA) registers19. Reading the data EEPROM memory only requires that the desired address to access be written to the EEADR register and the EEPGD bit of the EECON1 register be cleared (to indicate the data memory is to be read). Then, once the RD bit of the EECON1 register is set20, data will be available in the EEDATA register on the very next instruction cycle. EEDATA will hold this value until another read operation is initiated or until it is explicitly written. The stack is not part of the program or data space and the stack pointer is not readable or writable. There are also no operations to place or remove data to or from the stack. Addresses are placed on the stack by the CPU when a call instruction is executed or when an interrupt occurs. The various return instructions then remove the previously stored address from the stack. The stack operates as a circular bu er, meaning that after the stack is full, subsequent ’pushes’ start overwriting the previously stored data from the top (the very rst push). Similarly when the stack is ’popped’ nine times, the ninth value is the same as the rst pop. The programmer never has to interact directly with the stack, but should always remember the 8-level limit. The stack does not give any indication if over ow or under ow occurs. The 8-bit working register (W) is also not part of the program or data memory space. It can however be read/written using particular instructions. Register-Register operations are not possible. Instruction set for the PIC microcontroller The format of the instruction words are shown in Figure 4(PIC 2001; Figure 13.1) . All instructions can use either direct or indirect addressing to access a register le. Since the addresses range from 00h to 7Fh in each bank, only 7 bits are required to identify the register le address and this is contained within the instruction. The eighth and ninth bits, which identify the bank, then comes from the register bank select bits (RP1,RP0) from the STATUS register. Figure (5) illustrates how the bits are composed to access the appropriate address. In indirect addressing, the 8-bit register 19The program memory could be read indirectly in a similar fashion, however this is a multi-cycle operation, and is not normally required. 20The RD bit of EECON1 will automatically clear once the read is performed c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 7 PICmicro MID-RANGE MCU FAMILY DS31005A-page 5-4 1997 Microchip Technology Inc. 5.2 General Instruction Format The Mid-Range MCU instructions can be broken down into four general formats as shown in Figure 5-1. As can be seen the opcode for the instruction varies from 3-bits to 6-bits. This variable opcode size is what allows 35 instructions to be implemented. Figure 5-1:General Format for Instructions 5.3 Central Processing Unit (CPU) The CPU can be thought of as the “brains” of the device. It is responsible for fetching the correct instruction for execution, decoding that instruction, and then executing that instruction. The CPU sometimes works in conjunction with the ALU to complete the execution of the instruc- tion (in arithmetic and logical operations). The CPU controls the program memory address bus, the data memory address bus, and accesses to the stack. 5.4 Instruction Clock Each instruction cycle (TCY) is comprised of four Q cycles (Q1-Q4). The Q cycle time is the same as the device oscillator cycle time (TOSC). The Q cycles provide the timing/designation for the Decode, Read, Process Data, Write, etc., of each instruction cycle. The following diagram shows the relationship of the Q cycles to the instruction cycle. The four Q cycles that make up an instruction cycle (TCY) can be generalized as: Q1: Instruction Decode Cycle or forced No operation Q2: Instruction Read Data Cycle or No operation Q3: Process the Data Q4: Instruction Write Data Cycle or No operation Each instruction will show a detailed Q cycle operation for the instruction. Figure 5-2:Q Cycle Activity Byte-oriented file register operations 13 8 7 6 0 d = 0 for destination W OPCODE d f (FILE #) d = 1 for destination f f = 7-bit file register address Bit-oriented file register operations 13 10 9 7 6 0 OPCODE b (BIT #) f (FILE #) b = 3-bit bit addressf = 7-bit file register address Literal and control operations 13 8 7 0 OPCODE k (literal) k = 8-bit immediate value 13 11 10 0 OPCODE k (literal) k = 11-bit immediate value General CALL and GOTO instructions only Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 Q1 Q2 Q3 Q4 TCY1TCY2TCY3 Tosc Figure 4: Format of instructions Mnemonic, Description Status Operands A ected Byte-oriented le register operations ADDWF f,d Add W and f C,DC,Z ANDWF f,d AND W with f Z CLRF f Clear f Z CLRW - Clear W Z COMF f,d Complement f Z DECF f,d Decrement f Z DECFSZ f,d Decrement f, Skip if 0 INCF f,d Increment f Z INCFSZ f,d Increment f, Skip if 0 IORWF f,d Inclusive OR W with f Z MOVF f,d Move f Z MOVWF d Move W to f NOP - No operation RLF f,d Rotate Left f through Carry C RRF f,d Rotate Right f through Carry C SUBWF f,d Subtract W from f C,DC,Z SWAPF f,d Swap nibbles in f XORWF f,d Exclusive OR W with f Z Bit-oriented le register operations BCF f,b Bit Clear f BSF f,b Bit Set f BTFSC f,b Bit Test f, Skip if Clear BTFSS f,b Bit Test f, Skip if Set Literal and Control operations ADDLW k Add literal and W C,DC,Z ANDLW k AND literal with W Z CALL k Call subroutine CLRWDT - Clear watchdog timer TO, PD GOTO k Goto address IORLW k Inclusive OR literal with W Z MOVLW k Move literal to W RETFIE - Return from interrupt RETLW k Return with literal in W RETURN - Return from subroutine SLEEP - Clear watchdog timer TO, PD SUBLW k Subtract W from literal C,DC,Z XORLW k Exclusive OR literal with W Z Field Description f Register le address (0x00 to 0x7F) W Working register (accumulator) b Bit address within an 8-bit le register k Literal eld, constant data or label d Destination select: d = 0, Store result in W d = 1, Store result in le register f default is d = 1 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 8 Instruction13 6 0 0 0 1 0 1 0 0 RP1 RP0 Bits 0 0 0 0 0 0 1 0 1 0 0 Address014h Instruction13 6 0 0 0 0 0 0 0 0 IRP Bit 0 0 0 0 0 1 0 1 0 0 AddressofINDFsaystouseFSRasapointer FSR Address014h Figure 5: Direct and indirect addressing modes le address is rst written to the the FSR, which is a special purpose register that is used as an address pointer to any address in the entire register le. A subsequent direct access to the INDF register will actually access the register le whose address is contained in the FSR i.e. the FSR acts as a pointer. Since the FSR is an 8-bit register, both banks can be addressed without needing to switch between them. The INDF register is not a physical register like the other special function registers. The FSR register is one of several Special Function registers that have been assigned multiple addresses so that they can be accessed in all banks. Figure (5) shows how the address is formed. The sparseness of the instruction set means that more programming e ort is required in the pro- gramming of the PIC. A few of the special considerations are listed below. Default destination The instructions from the table of the instruction that have f,d as the operands use the d as an indicator to tell where to place the result. The default is f ( le register), but this can be confusing so it is better to always specify the destination directly as the following code fragment demonstrates. W EQU H’0000’ ; standard definitions F EQU H’0001’ ; ...to avoid having to write numbers incf var,W ; W = var + 1, var is unchanged incf var,F ; var = var + 1, W is unchanged c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 9 STATUS register The STATUS register contains the arithmetic status of the ALU, the RESET status and the bank select bit for the data memory. As with any register, the STATUS register can be the destination for any instruction. If the STATUS is the destination for an instruction that a ects the Z, DC or C bits, then the write to these three bits is disabled. These bits are set or cleared according to the device logic. Furthermore the TO and PD bits are not writable, therefore the result of an instruction with the STATUS register as destination may be di erent than intended. For example: clrf STATUS will not set the STATUS register to all zeros as expected but will clear the upper three bits and set the Z bit. This leaves the STATUS register as 000u u1uu (where u = unchanged). Only the bcf, bsf and movwf instructions should be used to alter the STATUS register because these instructions do not a ect any status bits. Review Exercises 1. Label the following statements about the PIC16F877 as True or False: (a) Both the data and program memory spaces require switching banks to access the full space. (b) Data memory is 8 bits wide with a 9 bit address. (c) It has 8 bit data registers, and 16 bit instructions. (d) PIC16F877 machine cycle consists of 4 clock cycles. (e) Register to register operations are supported. (f) The INDF register is used to specify the address which is indirectly addressed when FSR is read. (g) The PIC16F77 has a RISC-based Von Neumann architecture. (h) The banking bits are located in the STATUS register. (i) The data memory has 9 bit addresses and the program memory has 13 bit addresses. (j) The stack used to store the PC during a subroutine call is only 8 levels deep. 2. Which ONE of the following is NOT a feature of the PIC16F877? (a) 2 stage pipeline (b) 4 bit multiplier (c) Harvard architecture (d) built-in timers (e) indirect addressing 3. Certain general purpose and special function registers are mapped to multiple addresses in the memory space of the PIC 16F877. What possible advantage could such a scheme o er? 4. Determine which of the following statements concerning the following code snippet is/are NOT correct: c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 10 movlw 0x21 movwf 0x04 movlw 0x09 movwf 0x00 incf 0x04,1 sleep (a) After this code has been executed, the CARRY ag will be clear. (b) After this code has been executed, the ZERO ag will be clear. (c) After this code has been executed, the value stored in location 0x00 is 0x09. (d) After this code has been executed, the value stored in location 0x04 is 0x21. (e) The code performs direct addressing of location 0x04, indirect addressing of location 0x21, and immediate addressing of literal 0x09. 5. (a) Explain (and illustrate using pieces of code) the direct and indirect mechanisms of ad- dressing Special Function Registers. (b) What happens when the assembly language statement clrf STATUS is executed? (c) Explain how the INDF register behaves when it is indirectly addressed for read/write. (d) Di erentiate between the indirect addressing mechanisms for the register le and the data EEPROM. 6. Each instruction requires one cycle for its fetch and one cycle for its execution, yet the PIC16F877 executes a new instruction every cycle. (a) Explain how this accomplished. (b) Why does a branch instruction, which also requires the same two cycles for fetching and execution, introduce an extra cycle in the CPU’s execution of instructions? 7. Explain what the following PIC16F877 assembly language instructions for the PIC16F877 will do (source; operation; destination): (a) ADDWF 0x20,0x00 (b) XORLW 0x02 8. In the PIC16F877, how is the instruction cycle related to machine cycles and clock cycles? 9. Role play: For the PIC 16F877, "The programmer never has to interact directly with the stack, but should always remember the 8-level limit". For a similar processor with a 2-level stack, il- lustrate (using diagrams) the problems that may occur if the programmer overruns/underruns the stack. 10. Challenge: Find a single instruction that will toggle bit 0 of a le register in the PIC16F877 if: (a) you do not care what happens to the other bits in the le register, (b) you wish to preserve the values of the other bits in the le register, (c) the le register is the PC register (d) the le register is the STATUS register c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 11 Tutorial Exercise 4B O ine Version21 ID# 1. Di erentiate between the operation of the following instructions: 2 marks addwf Reg,F addwf Reg,W 2. What types of applications are microcontrollers (as opposed to microprocessors) commonly used for? Explain your answer. 3 marks 3. The PIC16F877 has both data EEPROM and static data RAM (general purpose registers) included in the microcontroller. Suggest ONE reason why the data EEPROM is also included in the microcontroller. 2 marks 4. BRIEFLY explain the concept of \banking" and give ONE reason why memory banks might be used in a microcontroller. 3 marks PLAIGIARISM DECLARATION: For the purposes of this exercise, unauthorised collaboration is any form of collaboration which does NOT fall into one of the following categories: verbal or written discussion/clari cation of question and/or related concepts Department of Electrical and Computer Engineering PLAGIARISM Plagiarism is the presentation by a student of an assignment which has in fact been copied in whole or in part from another student’s work, or from any other source (e.g. published books or periodicals), without due acknowledgement in the text. COLLUSION Collusion is the presentation by a student of an assignment as his or her own which is in fact the result in whole or part of unauthorised collaboration with another person or persons. DECLARATION I declare that this assignment is my own work and does not involve plagiarism or collusion. I have read and understood University Examination Regulations 73,75,76 and 79 regarding cheating. Signed: Date: (Department of Electrical and Computer Engineering) 21Students are advised that O ine versions are to be used either with the explicit permission of the course lecturer OR at times when the electronic course support site is unavailable for more than 48 hours. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 12 T U T 4 BUnit 9 Write the letter you have been assigned here . The registers are A: FSR; B: STATUS; C: PCL; D: INDF. Answer the following questions for the PIC16F877 register whose letter you were assigned. 1. Locate all the mapped addresses in the data memory space 2. What happens when the assembly language instruction movwf is executed on this register? Which ags are a ected? Are there any strange/unusual e ects as compared to general le registers? Re ection & Feedback Indicate the objectives that you feel you have achieved in this unit. { explain the memory layout for the PIC16F877 { explain the operation of the instruction cycle for the PIC16F877 { explain the operation of the basic instructions (move, add, subtract, shifts) for the PIC16F877 Which aspect of this unit did you have the most di culty understanding? Which aspect of this unit did you like best? Why did you like it? Identify one thing (if any) that you learned while doing this unit/tutorial. Identify one way in which this unit/tutorial could be improved. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 13 10 MPLAB Overview At the end of this unit the student will be able to: utilize the MPLAB IDE and CCS compiler, to develop software for the MicroChip PIC16Cxxx series of microcontroller, in C, C++ and assembly language. Assemblers and compilers tend to have speci c keywords or pre-processor directives, which are used to: access non-standard hardware features, specify code generation options/placement, sup- ply code \shortcuts" e.g. macros, de nes. In this unit, we will examine some of the relevant keywords/directives of the MicroChip MPASM assembler and the CCS compilers. \ Absolute code is the default output from MPASM. ... When a source le is assembled in this manner, all values used in the source le must be de ned within that source le, or in les that have been explicitly included. If assembly proceeds without errors, a HEX le will be generated, containing the executable machine code for the target device. This le can then be used in conjunction with a device programmer to program the microcontroller. ... [extracts from]Table 2.1: MPASM Default Extensions Extension Purpose .ASM Default source le extension input to MPASM: .ASM .LST Default output extension for listing les generated by MPASM: .LST .HEX Output extension from MPASM for hex les (see Appendix A): .HEX ... The source code le may be created using any ASCII text le editor. It should conform to the following basic guidelines. Each line of the source le may contain up to four types of information: labels, mnemonics, operands, comments. The order and position of these are important. Labels must start in column one. Mnemonics may start in column two or beyond. Operands follow the mnemonic. Comments may follow the operands, mnemonics or labels, and can start in any column. The maximum column width is 255 characters. Whitespace or a colon must separate the label and the mnemonic, and the mnemonic and the operand(s). Multiple operands must be separated by a comma. A label must start in column 1. It may be followed by a colon (:), space, tab or the end of line. Labels must begin with an alpha character or an under bar ( ) and may contain alphanumeric characters, the under bar and the question mark. Labels may be up to 32 characters long. By default they are case sensitive, ... If a colon is used when de ning a label, it is treated as a label operator and not part of the label itself. ... If there is a label on the same line, instructions must be separated from that label by a colon, or by one or more spaces or tabs. ... MPASM treats anything after a semicolon as a comment. All characters following the semicolon are ignored through the end of the line. String constants containing a semicolon are allowed and are not confused with comments. The listing le format produced by MPASM is straight forward: The product name and version, the assembly date and time, and the page number appear at the top of every page. The rst column of numbers contains the base address in memory where the code will be placed. The second column displays the 32-bit value of any symbols created with the ... EQU, ... directives. The third column is reserved for the machine instruction. This is the code that will be executed by the PICmicro MCU. The fourth column lists the associated source le line number for this line. The remainder of the line is reserved for the source code line that generated the machine code. Errors, warnings, and messages are embedded between the source lines, and pertain to the following source line. The symbol table lists all symbols de ned in the program. The memory usage map gives a graphical representation of memory usage. X marks a used location and - marks memory that is not used by this object. The memory map is not printed if an object le is generated. Intel Hex Format: This format produces one 8-bit hex le with a low byte, high byte combination. Since each address can only contain 8 bits in this format, all addresses are doubled. Each data record begins with a 9 character pre x and ends with a 2-character checksum. Each record has the following format: :BBAAAATTHHHH....HHHCC where: BB - is a two digit hexadecimal byte count representing the number of data bytes that will appear on the line. AAAA - is a four digit hexadecimal address representing the starting address of the data record. TT - is a two digit record type record type that will always be 00 except for the end-of- le record, which will be 01. HH - is a two digit hexadecimal data byte, presented in low-byte/high-byte combinations. CC - is a two digit hexadecimal checksum that is the twos complement of the sum of all preceding bytes in the record. c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 14 c DECE, UWI, St. Augustine, Trinidad ECNG2006 (EE25M) March 11, 2008 III 15 ... Directives are assembler commands that appear in the source code but are not translated directly into opcodes. They are used to control the assembler: its input, output, and data allocation. ... ... ORG Set Program Origin. Syntax: [