Current Labman

188
ECE 3724/CS 3124 Microprocessors I Lab Manual © R. B. Reese

description

laB

Transcript of Current Labman

  • ECE 3724/CS 3124

    Microprocessors I

    Lab Manual

    R. B. Reese

  • PrefaceThe goals of these lab experiments are simple; to expose you to a range of topics in microprocessor assembly language programming and hardware interfacing. The PIC18F242 is used as it is supported by freely available development tools from Microchip (MPLAB IDE, assembler and simulator) and high quality C compilers (Hi-Tech Software, the PIC18 C Compiler). The availability of PICs in small pin count DIP packages with on-chip USART, I2C, and A/D modules make it easy to build a small protoboard system that is used to support a wide variety of relevant exercises.

    Experiments 1 and 2 relate basic digital design to the microprocessor world. The next three experiments introduce PIC assembly language programming and the con-nection between assembly language and C programming. Experiments 6 through 13 build a PIC18F242 system from scratch to explore topics such as RS232 interfac-ing, the I2C bus, A/D and D/A conversion, interrupt driven IO, IR pulse width decoding, and audio record/playback. The experience of building a microprocessor system from the ground up provides skills that prove useful in later design experi-ences, such as the capstone senior design course.

    These labs assume a basic digital design course prerequisite (ECE 3714), exposure to C or C++ programming, and familiarity with the Altera Maxplus toolset (used in the first two lab exercises). A physics-level circuits theory exposure is all that is needed to succeed in the hardware labs. An oscilloscope and multimeter are used in the hardware experiments. The parts kit cost is approximately $50 and can be pur-chased through the department; the lab web site has the complete parts list posted. The protoboard purchased previously for ECE 3714 is used throughout the semester to build the PIC-based system. The board must stay wired between lab exercises, so if you have another lab that requires a protoboard then a second protoboard must be purchased. You may also find it necessary to purchase an extra wiring kit. All of the C and assembly language programs referenced in this document are available from the lab web site (http://www.ece.msstate.edu/~reese/ece3724/lab).

    The material in this document is intended to supplement material in the textbook and datasheets. Refer to the lab web site for a detailed lab schedule and lab report guidelines. If errata is found in this lab manual, please send email to [email protected]. Feel free to send comments about clarity, difficulty or any other topic concerning the exercises to the same email address! Send any comments about the Knuts & Boltz strips at the start of each exercise to my evil twin whose email address is [email protected] (FYI: yes, he is my twin but is really not evil;

  • he is an ex-F15 fighter pilot with an MSEE degree who after 20 years in the Air Force currently flies boxes for UPS in-between drawing Knuts & Boltz strips, see http://www.b0ts.com -- that is a zero in b0ts).

    Many thanks goes to J. Harden, J.W. Bruce, and J. Moorhead for discussions and suggestions.

    Good luck, and I hope your lab experience is a good one.

    R. B. Reese 5/2004

  • Summer 2004/V0.2 iContents

    Experiment 1: A Stored Program Machine- - - - - - - - - - - - - - - - - - - - - 1-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-2 Finite State Machine versus Stored Program - - - - - - - - - - - - - - - - 1-2 The Problem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-3 A Stored Program Computer - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-4 What instructions are needed? - - - - - - - - - - - - - - - - - - - - - - - - - - 1-5 Instruction Encoding - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-6 The Hardware - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-8 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-11 Background - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-11 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-11 Maxplus LPMs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-12 Changing a Parameter Value - - - - - - - - - - - - - - - - - - - - - - - - - - 1-12 LPM_DFF - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-12 LPM_COUNTER - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-13 LPM_ROM - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-13 MIF format - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-13 Bus Labeling - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1-14Experiment 2: The PIC 18Fxx2 Architecture - - - - - - - - - - - - - - - - - - - 2-1 PreLab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-2 A quick introduction to MPLAB - - - - - - - - - - - - - - - - - - - - - - - - 2-2 Simulating your program - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-3 Single Stepping - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-4 Reset, Clearing Memory - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-5 QuickBuild Mode instead of Projects - - - - - - - - - - - - - - - - - - - - - 2-5 Watch Window - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-5 Animate Command - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-5 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-6 Exploring PIC18 Data memory organization - - - - - - - - - - - - - - - - 2-6 Data Memory Banks in the PIC18 - - - - - - - - - - - - - - - - - - - - - - - 2-6 Moving data between banks - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-9 showid.asm - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-10 bit test and skip - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-10 Controlling the value of odd - - - - - - - - - - - - - - - - - - - - - - - - - - 2-10 The Stopwatch - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-10 A poor emulation? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-11 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2-12Experiment 3: PIC18Fxx2: Instruction Set- - - - - - - - - - - - - - - - - - - - - 3-1

  • Summer 2004/V0.2 ii Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-2 A Quick C Review - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-3 Loops and Conditions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-4 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-6 STATUS Register: Carry, Zero Flags - - - - - - - - - - - - - - - - - - - - - 3-6 Converting the C operations to PIC Assembly - - - - - - - - - - - - - - - 3-7 arithmetic operations - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-8 logical operations - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-8 Shift operations - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-8 Condition Tests - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-10 Test for bit set or clear - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-10 Zero/Nonzero Test with branch instruction - - - - - - - - - - - - - - - - 3-11 Zero/Nonzero Test with branch instructions - - - - - - - - - - - - - - - - 3-12 tests - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-13 Compare instructions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-15 Equality, Inequality tests - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-16 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 3-17Experiment 4: Data: Wider is Better - - - - - - - - - - - - - - - - - - - - - - - - - 4-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-2 Data Sizes in C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-3 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-5 Storing 16-Bit values in memory - - - - - - - - - - - - - - - - - - - - - - - - 4-5 Addition/Subtraction of 16-bit values - - - - - - - - - - - - - - - - - - - - - 4-7 increment, decrement - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-7 left, right shift - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-8 Unsigned 16-bit comparisons - - - - - - - - - - - - - - - - - - - - - - - - - - 4-10 16-bit Equality tests - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-11 16-bit Zero/Nonzero tests - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-11 Signed Comparisons - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-12 Integer Signed Comparison: N, V flags - - - - - - - - - - - - - - - - - - - 4-13 Equality, zero, nonzero tests for 16-bit signed data - - - - - - - - - - - 4-15 PC Relative Addressing - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-15 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 4-17Experiment 5: Beyond Assembly Language- - - - - - - - - - - - - - - - - - - - 5-1 Prelab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-2 Pointers in C - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-2 Pointers in PIC assembly language - - - - - - - - - - - - - - - - - - - - - - - 5-3 Subroutine Parameters - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-4 main code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-5 strcnt subroutine - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-5 POSTINC0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-6 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-9 Compiling C programs to PIC18 machine code - - - - - - - - - - - - - 5-10 Simulating cstrcnt.c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-12 Compiling, Simulating your C program - - - - - - - - - - - - - - - - - - - 5-13 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-14

  • Summer 2004/V0.2 iii Formal Report Questions - - - - - - - - - - - - - - - - - - - - - - - - - - - - 5-14Experiment 6: Bringing the PIC to Life - - - - - - - - - - - - - - - - - - - - - - - 6-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6-4 Which pins are Tx and Rx? - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6-6 Detailed RS232 Serial Port Debugging - - - - - - - - - - - - - - - - - - - - 6-7 What is next? - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6-9 Optional In-Circuit Programming Connection - - - - - - - - - - - - - - 6-14 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 6-15Experiment 7: Serial versus Parallel - - - - - - - - - - - - - - - - - - - - - - - - - 7-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 7-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 7-3 Formatted IO via printf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 7-5 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 7-7Experiment 8: Interrupt-Driven IO - - - - - - - - - - - - - - - - - - - - - - - - - - 8-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8-3 The Overrun Problem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8-7 Fixing the Problem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8-7 Storing/Retrieving values from a circular buffer - - - - - - - - - - - - - - 8-7 Empty, Not-empty, Full - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8-8 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 8-9Experiment 9: Memory and the I2C Bus - - - - - - - - - - - - - - - - - - - - - - 9-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-3 Streaming writes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-4 Use two buffers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-4 Checking for Overrun - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-6 Program Operation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-7 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 9-8Experiment 10: Talking to the Real World- - - - - - - - - - - - - - - - - - - - -10-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10-3 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10-6 Formal Report Questions - - - - - - - - - - - - - - - - - - - - - - - - - - - - 10-6Experiment 11: Controlling Time- - - - - - - - - - - - - - - - - - - - - - - - - - -11-1 Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11-4 sqwave.c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11-4 ledpwm.c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11-5 sinegen.c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11-7 Comments on sinegen.c measurements - - - - - - - - - - - - - - - - - - - 11-8 Arbitrary Waveform Generation - - - - - - - - - - - - - - - - - - - - - - - - 11-9 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 11-12Experiment 12: Time Measurement - - - - - - - - - - - - - - - - - - - - - - - - -12-1

  • Summer 2004/V0.2 iv Prelab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-2 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-3 swdet.c - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-3 Multiple Timer1 Overflows - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-4 IR Pulse Decoding - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-5 1,0, Start periods - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-6 Hints for IR Decoding - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-7 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 12-10Experiment 13: The PIC Listens and Speaks - - - - - - - - - - - - - - - - - - -13-1 PreLab Requirements - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 13-2 Audio Sampling - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 13-3 Lab Activity - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 13-5 Implementing Playback - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 13-5 Report - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 13-7Appendix A: Prototyping Hints - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-1 Protoboard and Parts - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-2 Protoboard Layout - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-2 Power Connector - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-3 Voltage Regulator (7805) - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-3 PCB Fuse - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-4 Resistor SIP Packages - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-4 Capacitors (1.0 F/0.1 F) - - - - - - - - - - - - - - - - - - - - - - - - - - - A-4 Light Emitting Diodes (LEDs) - - - - - - - - - - - - - - - - - - - - - - - - - A-5 Power LED - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-5 Power Switch - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-6 Momentary Pushbutton Switches - - - - - - - - - - - - - - - - - - - - - - - A-6 7.3828 MHz Crystal - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-6 Potentiometers - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-7 Audio Connector - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-8 Wire Wrapping - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-8 Get a decent protoboard! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-9 Get a multimeter! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-10 Debugging - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A-11 My board used to work and now it doesnt! - - - - - - - - - - - - - - - A-11 My fuse keeps blowing, my board used to work, help! - - - - - - - - A-11 My RS232 interface does not work and/or serial bootloader does not work. A-12 My I2C interface does not work. - - - - - - - - - - - - - - - - - - - - - - A-13 My PIC seems to be spontaneously resetting?! - - - - - - - - - - - - - A-13 My A/D input does not work? - - - - - - - - - - - - - - - - - - - - - - - - A-14Appendix B: Instrumentation- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-1 TDS 210 Oscilloscope - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-1 Displaying a continuous waveform - - - - - - - - - - - - - - - - - - - - - - B-1 Voltage/Time Scaling - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-2 Measure Function - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-2

  • Summer 2004/V0.2 : Cursor Function, measuring voltage difference, pulse width - - - - - B-3 Trigger Function, continuous or single shot capture - - - - - - - - - - - B-3 AC vs. DC Coupling - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-4 Multimeter - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-5 Measuring Voltage - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-5 Measuring Resistance - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-5 Measuring Current - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - B-6 v

  • : Summer 2004/V0.2 vi

  • Summer 2004/V0.2 Experiment 1: A Stored Program MachineE x p e r i m e n t 1

    A Stored Program Machine

    There was this guy named Von Neu-man who hated wiring a new circuit every time he had a new problem to solve (kinda like students in the logic gates class). So, because of this hatred of wires, the stored program machine was born. It lives to fetch and execute all day long, and sometimes, if we are lucky, we can make it do useful work for us. The best thing is that we dont have to change any wiring when we want it to do something different!

    SummaryUse a stored program machine approach to implement a state machine that displays a number sequence.1 1

  • Experiment 1: A Stored Program Machine Summer 2004/V0.2A. Prelab Requirements

    Finite State Machine ver-sus Stored Program

    In the digital devices course, a logic network was designed to implement a student ID sequencer. The logic design used flip-flops and combinational logic to implement a specific number sequence. A different student ID required a different logic design. An alter-nate approach to solve this problem uses a general pur-pose logic network called a stored program machine. The operation of a stored program machine is deter-mined by instructions stored in a memory. Changing the instruction sequence (changing the contents of memory), changes the actions of the machine. A new problem is solved by simply reprogramming memory; no hardware modifications are required. This general purpose logic network might not be as fast as a special

    Table 11: Prelab Checkoff

    Do This Comments

    1. Review the notes below on the Student-ID CPU machine.

    More notes on this subject are linked to the lab web site.

    2. Have Altera Maxplus 10.1+ Baseline edition installed on your PC and review how to compile/simulate designs within Maxplus. Perform the Maxplus tutorial found in the digital devices (ECE 3714) textbook if a review of Maxplus operation is needed.

    3. Download the file archive containing the Student-ID CPU. Compile the design in Altera Maxplus, and verify that you can simulate it. The scpu.gdf Altera Maxplus schematic in the ZIP archive attached to this lab is the student ID CPU implementation

    The rom.mif file specifies the memory contents (i.e, the program); if this file is changed the schematic must be recompiled. The rom.mif file can be edited with a text editor such as notepad or wordpad.

    4. Become familiar with the LPM modules used within the Student-ID CPU design (lpm_counter, lpm_rom, lpm_dff). Read the material at the end of this lab on LPM usage within Maxplus. 1 2

  • Summer 2004/V0.2 Experiment 1: A Stored Program Machinepurpose logic network, but the flexibility of being able to solve multiple problems by changing memory con-tents is often worth this trade-off.

    The ProblemThe Algorithmic State Machine (ASM) chart below illustrates the problem to be solved. The machine dis-plays either the odd or even digits of a student ID. A single input called odd determines if the odd or even sequence is displayed.

    Figure 1.1 ASM Chart for Student ID 458 70 2198

    The finite state machine implementation shown below

    odd?0 1

    Dout = 4 Dout = 5

    Dout = 8

    Dout = 0

    Dout = 2

    Dout = 8

    Dout = 7

    Dout = 1

    Dout = 9

    S1

    S2

    S3

    S4

    S5

    S6

    S7

    S0odd?0 1

    Dout = 4 Dout = 5

    Dout = 8

    Dout = 0

    Dout = 2

    Dout = 8

    Dout = 7

    Dout = 1

    Dout = 9

    S1S1

    S2S2

    S3S3

    S4S4

    S5S5

    S6S6

    S7S7

    S0S0

    CombinationalLogicCircuit

    Memory Element

    n m

    k k

    k-bitPresent State

    Value

    k-bitNext State

    Value

    Inputs OutputsCombinational

    LogicCircuit

    Memory Element

    n m

    k k

    k-bitPresent State

    Value

    k-bitNext State

    Value

    Inputs OutputsFigure 1.2 FSM

    Block Diagram1 3

  • Experiment 1: A Stored Program Machine Summer 2004/V0.2requires three D flip-flops (k=3) to implement the eight states of the ASM, one input signal (n=1) to implement odd, and four output signals (m = 4) to dis-play the current student ID digit (the values 0-9 are encoded in 4 bits). A new digit is displayed every clock cycle. A different student ID requires redesign of the combinational logic network that produces the out-put value and next state value.

    A Stored Program Com-puter

    A more general approach solves the problem via a stored program approach. The block diagram of a stored program machine (a computer) is shown below.

    A stored program machine has three principle blocks:

    Memory: stores data and instructions. The memory contents determines the machines actions. The address bus specifies a particular location in mem-ory, and the data bus contains the data fetched from or stored to that location.

    Control: logic that controls the fetch and execution of instructions stored in memory.

    Input/Output: used for interaction with the external world.

    The input/output signals for our stored program machine are the same as for the finite state machine;

    Control

    Memory

    Address bus

    Databus bus

    Input/Outputdevices

    Control

    Memory

    Address bus

    Databus bus

    Input/Outputdevices

    Figure 1.3 A Stored program

    machine1 4

  • Summer 2004/V0.2 Experiment 1: A Stored Program Machineone input for odd and a four bit output bus for display-ing the current digit of the student ID.

    What instructions are needed?

    A stored program machine executes a program that is stored in memory. A program consists of a sequence of instructions. The key design question is What instruc-tions are needed to solve this problem?. To answer this, transform the ASM chart to a pseudo high-level language description as shown below (translation: something that looks like C or Pascal or any other pro-gramming language you know).

    start: if (odd == 1) then goto odd_starteven_start: output even digit #1 output even digit #2 .... output last even digit goto start odd_start: output odd digit #1 output odd digit #2 .... output last odd digit goto start

    In the above program, there are three different opera-tions:

    out data: output a 4-bit value representing the cur-rent digit (i.e, output odd digit #2)

    jmp location: unconditionally jump to a location (i.e, goto odd_start). To jump to a location means to fetch the next instruction from that loca-1 5

  • Experiment 1: A Stored Program Machine Summer 2004/V0.2tion instead of the location immediately following the current instruction.

    jc location: conditionally jump to location (i.e. if odd == 1 then goto odd_start).

    Instruction Encoding The three instruction types above must be encoded in a binary form for efficient implementation in digital logic. Typically an instruction is divided into at least two parts:

    opcode: specifies the instruction type. In this case, there are three instruction types, so two bits are suf-ficient for opcode specification.

    data: every instruction operates on data. The data for the out instruction is the four bits that specifies the current ID value. The data for the jc and jmp instructions is the address of the memory location being jumped to. The number of bits required depends on the maximum number of locations in memory. If memory is limited to 16 locations, then four bits are sufficient to specify a memory loca-tion.

    The instruction format requires two bits for opcode, and four bits for data as shown below. The term mne-

    monic refers to the human-readable form of the instruction; the encoding is the binary form of the instruction that is stored in memory. Each instruction

    0 0 | 4-bit locationJMP location

    b5 b4 b3 b2 b1 b0

    0 1 | 4-bit locationJC location

    1 0 | 4-bit dataOUT data

    mnemonic encoding

    0 0 | 4-bit locationJMP location

    b5 b4 b3 b2 b1 b0

    0 1 | 4-bit locationJC location

    1 0 | 4-bit dataOUT data

    mnemonic encodingFigure 1.4 Instruction mnemon-

    ics vs. encoding1 6

  • Summer 2004/V0.2 Experiment 1: A Stored Program Machinerequires 6 bits. The encoding choice for the opcode affects the boolean logic required to decode the instruction. This encoding allows bit b5 to differentiate an out instruction from the two jump instructions.

    The pseudo code written previously for the ASM is written using these instructions in Table 12. Note that

    this program almost fills available memory as the four bit data field for the jc and jmp instructions limit mem-ory to 16 locations. The process of converting the instruction mnemonic to its binary form (machine code) is called assembly; typically a computer pro-gram called an assembler is used to perform this pro-cess automatically. A program written using the instruction mnemonics of a stored program machine is called an assembly language program.

    Table 12: Program for Student ID 458 70 2198

    Memory Location

    Memory Contents mnemonic

    00 01 0111 start: jc odd_start (loc 7)

    01 10 0100 out 4

    02 10 1000 out 8

    03 10 0000 out 0

    04 10 0010 out 2

    05 10 1000 out 8

    06 00 0000 jmp start (loc 0)

    07 10 0101 odd_start: out 5

    08 10 0111 out 7

    09 10 0001 out 1

    0A 10 1001 out 9

    0B 00 0000 jmp start (loc 0)1 7

  • Experiment 1: A Stored Program Machine Summer 2004/V0.2The Hardware The stored program machine is implemented using the following components:

    Memory: a 16 x 6 memory. The K x N notation for memory indicates the memory has K locations, with each location containing N bits.

    Registers: recall from your digital devices course that a register is used to store a N-bit binary value, where N is the number of bits in the value. This machine needs two registers: out and program counter (PC). The out register is 4-bits wide and contains the current digit being displayed. The pro-gram counter contains the address of the current location accessed from memory. The PC is imple-mented as a counter that is either incremented to point to the next location, or loaded from the data field of the current instruction to implement the jump instructions.

    Decode logic: this logic controls the loading of the out register, and the loading or incrementing of the program counter. The inputs to the control logic are the odd input, and the opcode of the current instruc-tion.1 8

  • Summer 2004/V0.2 Experiment 1: A Stored Program MachineFigure 1.5 shows a block diagram of the stored pro-gram machine implementation.

    Figure 1.5 Stored program machine implementation

    The r_ld output of the decode logic controls the load-ing of the out register, which needs a new value when an out instruction is executed. The Boolean equation for r_ld is:

    r_ld = op1as the op1 bit is a logical 1 for an out instruction. The PC register (the counter) is loaded when a jmp instruc-tion is executed, or if a jc instruction is executed and the odd input is true. Written as a VHDL statement, this equation is:

    c_ld

  • Experiment 1: A Stored Program Machine Summer 2004/V0.2The PC register is incremented if a parallel load is not done, so:

    c_en

  • Summer 2004/V0.2 Experiment 1: A Stored Program MachineB. Lab ActivityBackground

    DEMONSTRATE THAT THE CHANGES MADE TO THE ROM.MIF FILE DISPLAYS YOUR STUDENT ID. DEMON-STRATE THE MODIFIED VERSION OF THE STUDENT ID MACHINE THAT SUPPORTS 32 INSTRUCTIONS.

    C. Report1. Include the assembly code and machine code of the

    programs for checkpoints 1 & 2 of Table 13.

    Table 13: Student ID machine Checkoff

    Checkpoint Comments/Debugging

    1. Write a program for the student ID CPU that outputs the digits of your student ID. You must have the pro-gram represented both as instruc-tion mnemonics and machine code. Modify the rom.mif file to contain your assembled program.

    Step through the operation of the student ID CPU with the original rom.mif file and verify that you understand what is happening on each clock cycle.

    Include the instruction mnemonic as a comment on each line of machine code in the rom.mif file.

    2. Create a new schematic called my_scpu.gdf and make the neces-sary modifications to it so that it can support a program that contains up to 32 lines of code. Test the changes by placing your original program starting at location 16 in memory. At location 0, place a 'goto 16' instruction.

    Review the material at the end of this lab on LPM modules. You will need to change the width parameters to one or more LPM modules and also change the size of the data busses that con-nect to them.

    Discuss your proposed changes with the TA before proceeding too far into the implementation.1 11

  • Experiment 1: A Stored Program Machine Summer 2004/V0.22. Include a screenshot of your schematic for check-point 2 of Table 13.

    3. Briefly discuss the changes made for the student ID CPU design for checkpoint 2 of Table 13 and the reasoning behind the changes.

    4. Assume a new instruction is needed called 'NOT' that performs a one's complement (invert the bits) on the current value in the OUTPUT register. What changes are required to the decode logic and over-all design to implement this? Show a sketch or rough schematic of the necessary modifications (there is more than correct solution).

    D. Maxplus LPMs The student ID CPU uses three elements from the Maxplus Library of Parameterized Modules (LPM). Each LPM implements a common digital system building block such as a counter, register, memory, etc. with parameters used to control key attributes. For example, each LPM has a parameter called LPM_WIDTH that determines the components data width (i.e, for a counter, if LPM_WIDTH = 4, then it is a 4 bit counter). Converting a 4-bit counter to a 16-bit counter is as easy as changing the value of the LPM_WIDTH parameter and the labels on the data busses that connect to the counter.

    Changing a Parameter Value

    To change an LPM parameter value, double-click on the LPM within the schematic to open the Edit Ports/Parameters window. The lower half of the window has a scroll list containing all of the parameters. Select a parameter and edit its value in the Parameter Value type-in field. Click OK to close the window.

    LPM_DFF The LPM_DFF module is used to implement the out register. The enable input functions as the load line for 1 12

  • Summer 2004/V0.2 Experiment 1: A Stored Program Machinethe register. The LPM_WIDTH parameter is currently set equal to 4.

    LPM_COUNTERThe LPM_COUNTER module is used to implement the PC register. The sload input is the load signal for the counter; when asserted the counter is loaded from the data inputs on the next rising clock edge. The counter increments its current value on the next rising clock edge when the cnt_en signal is asserted. The LPM_WIDTH parameter is currently set to 4.

    LPM_ROMThe LPM_ROM module is used to implement the pro-gram memory (ROM = Read Only Memory). At com-pilation time, the memory contents are initialized from the file specified by the LPM_FILE parameter, cur-rently set equal to rom.mif. The LPM_WIDTHAD parameter specifies the width of the address bus; the number of locations in the ROM is equal to 2**LPM_WIDTHAD. The current value of LPM_WIDTHAD is 4, so the number of locations is 2**4 = 16. The LPM_WIDTH parameter controls the number of bits per location and sets the width of the output data bus (q[]); its value is currently equal to 5.

    MIF formatThe MIF file, which can be edited with a text editor, specifies the contents of the ROM. The format is fairly self-explanatory, but a few words of caution are needed. The number of locations in the LPM_ROM is controlled by the LPM_WIDTHAD parameter. A change to this parameter requires a corresponding change to the MIF file Depth value that specifies the number of locations in the ROM. Similarly, a change to the LPM_WIDTH parameter of the LPM_ROM requires a corresponding change to the MIF file Width value. The MIF file does not need a value specified for every location in the ROM.

    A comment is bracketed by two % symbols; there MUST BE two % symbols! Formatting errors are 1 13

  • Experiment 1: A Stored Program Machine Summer 2004/V0.2generated during compilation if an ending % symbol is missing.

    Bus Labeling After changing the LPM_WIDTH parameter on an LPM, the size of the data busses connected to the LPM must also be changed by editing the bus label. For example, assume the LPM_WIDTH parameter of the LPM_COUNTER is changed from 4 to 5. This requires modifying the sizes of the busses connecting to the data[] and q[] pins by changing the bus names from instr[3..0] to instr[4..0], and pc[3..0] to pc[4..0]. Note these changes affect other busses/components in the schematic requiring modifications to related LPM_WIDTH values and bus names as well. Double click on a bus label to edit it. During compilation, a width mismatch error indicates that the width of the data bus connecting to an LPM does not match the internal width of the LPM.1 14

  • Summer 2004/V0.2 Experiment 2: The PIC 18Fxx2 ArchitectureE x p e r i m e n t 2

    The PIC 18Fxx2 Architecture

    It is suspected that the favorite bible story of microprocessor (P) architects is The Tower of Babel given the gazillion varieties of microcontrollers available, each with its unique set of instructions, registers, and features. But dont worry, we will only concentrate on one in this lab. Unfortunately, it is generally agreed the first P instruction set you learn is the toughest....

    SummaryUse MPLAB to assemble and execute a small assem-bly language program. Execute the same program on a PIC18Fxx2 model in Maxplus-II, and trace data move-ment on internal data busses.2 1

  • Experiment 2: The PIC 18Fxx2 Architecture Summer 2004/V0.2A. PreLab Requirements

    A quick introduction to MPLAB

    If you have not already done so, install the latest ver-sion of MPLAB on your PC by visiting to http://www.microchip.com, selecting Engineers Toolbox Development Tools Software MPLAB IDE, and downloading the MPLAB IDE executable.

    Copy the file mptst.asm to a local directory. Caution: MPLAB 6.0+ does not allow pathnames to exceed 62 characters so be careful where you place this file. Exe-cute MPLAB and create a new project for it. Call the new project mptst and browse to the directory that con-tains mptst.asm. Use View Project to view the project file hierarchy. Right click on Source Files

    Table 21: Prelab Checkoff

    Do This Comments

    1. Attached to this lab is a program called mptst.asm. Assemble and execute this pro-gram in MPLAB using the 18F242 as the tar-get device. Follow the instructions below on how to do this.

    Trace the program until address 0x0212 in program memory is reached.

    Verify that the value of the k variable stored at location 0x02 has the value 0xC9 at this point.

    2. Change the value of the myid symbol to be the decimal equivalent of the last two digits of your student id. If the last two digits of your student ID are 00, then use the first two digits.

    Trace the program until address 0x0212 in program memory is reached. Capture a screen shot that shows the Program mem-ory and File Register contents at this point.

    Verify that the value of the k vari-able stored at location 0x02 has the expected value in it given the new value of myid. 2 2

  • Summer 2004/V0.2 Experiment 2: The PIC 18Fxx2 Architectureand use the Add Files... command to add mptst.asm to the project.

    At this point the project window should appear as shown on the right.

    Use Project Set Language Toolsuite and choose Microchip MPASM Toolsuite. This selects the tools used to assemble or compile files in the project.

    Next, use Configure Select Device and select the PIC18F242 as the target device. Before doing any editing of the program, use Project Build All to assemble the program, which should produce a Build Succeeded message in the output window.

    Simulating your programUse Debugger Select Tool MPLAB Sim to set the MPLAB simulator as the debugging tool. Use View Program Memory to view the machine code of your program (use the Symbolic button the program memory window to see the most readable representa-tion of the code). Use View File Registers to view the internal memory of the PIC. Use View Special Registers to view the special registers (W, TRISA, 2 3

  • Experiment 2: The PIC 18Fxx2 Architecture Summer 2004/V0.2PORTA, etc.) of the PIC. Double click on the mptst.asm file in the project window to open a source file window. Use either F6 or Debugger Reset Processor Reset to reset the processors program counter to point at the instruction in location 0. The figure below is approximately what should be dis-played:

    Single Stepping Use F7 or Debugger Step Into to single step through the program. The Special Function Registers window is useful for observing changes to often-used registers such as W and STATUS. The File Registers window is useful for observing changes to all of the other internal memory locations of the PIC. 2 4

  • Summer 2004/V0.2 Experiment 2: The PIC 18Fxx2 ArchitectureIn this program, using the original value of 100 for the myid definition causes the k variable to finish with the value 201 (0xC9). Single step the program until loca-tion 9 is reached and verify that location 0x02 (corre-sponds to variable k) has the value 0xC9.

    Reset, Clearing MemoryTo start the program back at location 0x0, use Debugger Reset Processor Reset (bound to the F6 key). To clear data memory contents back to their original values, select Debugger Clear Memory GPRs. The command Debugger Clear Memory All Memory clears all memory including program memory requiring the file to be re-assembled before execution.

    QuickBuild Mode instead of Projects

    A project does not have to be created each time you want to assembly and simulate a file. Close MPLAB, then re-open it, and open the mptst.asm file. Next, use Configure Select Device and select the PIC18F242 as the target device. Now use Pro-jectQuickbuild mptest.asm to assemble the pro-gram without creating a project. If you only have one file to assemble, use QuickBuild instead of building a project.

    Watch WindowThe command View Watch opens a watch win-dow which is useful for monitoring select memory locations. After the watch window is opened, use the pull down list next to the Add Symbol button to list all variables in the program. Find the i symbol, then click Add Symbol to add it to the watch window. Do the same for the j, k variables. You are now able to moni-tor these values during program execution.

    Animate CommandUse the command Debugger Animate to watch the program execute in slow speed. Use the F5 key (halt) to stop execution.2 5

  • Experiment 2: The PIC 18Fxx2 Architecture Summer 2004/V0.2B. Lab ActivityExploring PIC18 Data memory organization

    This part of the lab explores how the data memory of the PIC18 is organized.

    Data Memory Banks in the PIC18

    The data memory banks in the PIC18 is split into mul-tiple banks. The PIC18F242 has three banks - bank0 (0x00-0xFF), bank1 (0x100-0x1FF), and bank2 (0x200-0x2FF). A 8-bit memory address within a PIC18 instruction word specifies the location within a bank; the value in the Bank Select Register (BSR) selects the bank that is accessed. The default value for the BSR is 0, which means that Bank 0 is selected by

    Table 22: Data Memory variations checkoff

    Activity Questions to be answered

    1. Modify the mptst.asm file so that the CBLOCK starting location is now 0x80. Re-assemble and re-execute the pro-gram. Verify that the i, j, k variables are updated at locations 0x80-0x82.

    When the program memory is viewed, the instruction at program location 0x202 is now different from the original mptst.asm file. Record this difference, and determine the reason for this behavior.

    2. Modify the mptst.asm file so that the CBLOCK starting location is now 0x100. Re-assemble and re-execute the pro-gram.

    Use the File Registers window to deter-mine what locations are changed when the i, j, k variables are modified. Record these locations and determine the reason for this behavior. Hint: look at the defini-tion of the BSR (Bank Select Register).

    3. To the program in step 2, add the state-ment MOVLB 0x1 just after the main label and before the statement movlw myid. Re-assemble and re-execute the program. The MOVLB instruction is Move Literal to Bank Select Register; MOVLB 0x1 moves the value 0x1 to the BSR (BSR= Bank Select Register).

    Use the File Registers window to deter-mine what locations are changed when the i, j, k variables are modified. Record these locations and determine the reason for this behavior.

    4. Based on the knowledge gained from steps 2 and 3, modify the mptst.asm pro-gram so that the i,,j,k variables are located at locations 0x200-0x202. Re-assemble, re-execute, and verify that these locations are modified.

    2 6

  • Summer 2004/V0.2 Experiment 2: The PIC 18Fxx2 Architecturedefault. To select Bank 1, the value 0x1 must be placed in the BSR. This can be done by executing the instruc-tion:

    MOVLB 0x1which moves the value 0x1 into the BSR, selecting bank 1. To select Bank 2, one can do:

    MOVLB 0x2which moves the value 0x2 into BSR, selecting Bank 2. To reselect Bank 0, do:

    MOVLB 0x0When specifying an address in a PIC18 instruction, if the access bit is set, then the BSR register is ignored, and addresses 0x00-0x7F are mapped to locations 0x00-0x7F in bank 0 (access bank low), and addresses 0x80-FF are mapped to locations 0xF80-0xFFF (access bank high) which are the special function reg-isters (WREG, STATUS, etc.). The movf instruction below forces the address for j to be in the access bank.

    movf j,w,A ;ignore BSR registerThe movf instruction below uses the BSR with the address of j:

    movf j,w,BANKED ; use BSR registerWith MPLAB, you should not have to use either the A (use access bank) or BANKED (use BSR) quali-fiers on instructions as long as the CBLOCK state-ments have the full bank address for a variable (i.e, address 0x100 for j places j in bank 1) as the default rules for variable access in the absence of A or BANKED make sense. If you do not explicitly spec-ify the A or BANKED qualifier on an instruction, the following rules are used by MPLAB assembler:2 7

  • Experiment 2: The PIC 18Fxx2 Architecture Summer 2004/V0.2a. If the address for the variable is between 0x0 - 0x7F, or between 0xF80-0xFF (special function registers), then qualifier A is assumed, which causes the BSR to be ignored, forcing it into bank 0.

    b. If the address is between 0x80 and 0xF7F, then qualifier BANKED is assumed, which causes the BSR to be used for data access.

    SHOW THE TA THE RESULTS FOR STEPS 1-4 AND EXPLAIN THE REASONS BEHIND THE OBSERVED RESULTS. BE SURE TO INCLUDE THIS REASONING IN THE LAB REPORT. 2 8

  • Summer 2004/V0.2 Experiment 2: The PIC 18Fxx2 ArchitectureMoving data between banks

    This portion of the lab explores moving data between memory banks.

    .

    DEMO THE PROGRAMS YOU WROTE IN STEPS 2 AND 3 TO THE TA.

    Table 23: Data Movement Checkoff

    Activity Questions to be answered

    1. In MPLAB, open a File Registers win-dow that shows locations 0x0000 through 0x0120. Click on the first line of ... under the ASCII column and type the first 5 let-ters of your first name, and seven digits of your phone number. Then type enough spaces so that the entire type in column has been filled.

    Record what appears in the hex locations 0x0 through 0x0F. Justify to yourself the reason for these values (and explain in the lab report).

    2. Using the mptst.asm file as a starting point, create a new program with a series of data movement instructions that will move the contents of locations 0x0-0x7 to locations 0x100 -0x107. Verify the opera-tion of this program by typing data of your choice into locations 0x0-0x7, executing your program, and verifying that the data is moved to locations 0x100-0x107. You may NOT use the movff instruction in this program.

    You do not need a CBLOCK statement for this program, you can specify addresses for memory locations within instructions as:

    movf 0x0, w

    You may find the instructions BSF BSR, 0 (bit set) and BCF BSR, 0 (bit clear) useful.

    Starting at location 0x200 in Program Memory, determine the number of BYTES needed for this program (most PIC18 instructions need 2 bytes, some need 4 bytes). Report this number IN DECIMAL.

    3. Create a new version of the program done in step 2 (keep the old version!) that uses the movff instruction to accomplish the data movement (i.e., movff 0x0, 0x100 moves the contents of location 0x0 to 0x100). Re-assemble, and verify that your program exhibits the same behavior as the program in step 2.

    Starting at location 0x200 in Program Memory, determine the number of BYTES needed for this program (most PIC18 instructions need 2 bytes, some need 4 bytes). Report this number IN DECIMAL.

    Which program took fewer program bytes?2 9

  • Experiment 2: The PIC 18Fxx2 Architecture Summer 2004/V0.2showid.asm The showid.asm program attached to this lab dupli-cates the action of the Student ID CPU of the previous lab by copying the even or odd digit sequence of a stu-dent ID to the out variable. The odd input is simulated through a variable called odd; if the least significant bit (LSB) of variable odd is 0 then the even sequence is chosen, else the odd sequence is chosen. Variable odd is located at location 0x0 in data memory; this value can be changed by opening a File Registers win-dow and directly typing a new value in location 0x0.

    bit test and skip The LSB of variable odd is tested via the instruction sequence:

    btfsc odd, 0goto odd_seq

    The btfsc instruction tests if a particular bit of the spec-ified file register is clear (a logic 0 value). If the speci-fied bit is clear, then the next instruction is skipped. In this case, the next instruction is a jump to the sequence of instructions the copies the odd sequence to the out variable.

    Controlling the value of odd

    Note that the variable odd is cleared to 0x00 by the instruction clrf odd. This causes the even sequence to always be chosen. To cause the odd sequence to be chosen after reset, replace the instruc-tion clrf odd with bsf odd, 0. This sets the LSB of file register odd to a logic 1. During program execution, you can type a new value for odd into the location 0x0 in the file registers window to change the number sequence that is displayed.

    The Stopwatch The command Debugger Stopwatch can be used to display how many instruction cycles and how much time an instruction requires when executed. This is useful in determining the amount of execution time required for a particular section of code. The com-2 10

  • Summer 2004/V0.2 Experiment 2: The PIC 18Fxx2 Architecturemand Debugger Settings can be used to changed the simulated clock frequency of the processor.

    DEMO THE SHOWID PROGRAM THAT DISPLAYS THE DIGITS OF YOUR STUDENT ID TO THE TA.

    A poor emulation?The showid.asm program does a poor job of emulating the student ID CPU as the variables odd and out are internal memory locations and do not correspond to external pins on the PIC18Fxx2. However, you will soon discover that setting and testing external pin val-ues is done in the same way as internal memory loca-tions.

    Table 24: showid Checkoff

    Checkpoint Comments

    1. Single step through showid.asm in MPLAB for both odd and even sequences. Note that location 0x0 corre-sponds to out, and 0x01 to odd.

    To force the odd sequence, either do as above and modify the instruction that ini-tializes odd, or directly change variable odd (location 0x20) by typing into the file register window.

    2. Modify showid.asm to display the digits of your student id. Assemble and verify the operation.

    3. Use the Stopwatch command in the simulator and record the instruction cycles and time for displaying all of the odd digits of your student ID.

    This instruction count and time is for one complete pass through the loop. Use a time of 20 MHz and record this time. Then change the clock speed to 8 MHz and record this time.

    4. Use the Stopwatch command in the simulator and record the instruction cycles and time for displaying all of the even digits of your student ID.

    This instruction count and time is for one complete pass through the loop. Use a time of 20 MHz and record this time. Then change the clock speed to 8 MHz and record this time. 2 11

  • Experiment 2: The PIC 18Fxx2 Architecture Summer 2004/V0.2C. Report1. Include the .lst files of any assembly language

    programs written for this lab.2. Include the MPLAB screenshot required in the

    prelab checkoff.3. Include the results from Table 22 and your rea-

    sons for the observed behavior.4. Include the results from Table 23 and your rea-

    sons for the observed behavior. 5. Include the results from Table 24 and verify via

    manual calculations that the recorded time for both even and odd sequences is correct, for both clock frequencies. Explain the execution time required for the btfsc odd,0 under both conditions (odd = 0 and odd = 1).

    6. For the following instruction, assume j is location 0x64 and has an initial value of 0x40. Give the val-ues of w and j after the instruction is executed as well as the machine code for the instruction:

    decf j, w

    7. For the following instruction, assume j is location 0x7C and has an initial value of 0xDA. Give the values of w and j after the instruction is executed as well as the machine code for the instruction:

    incf j, f2 12

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction SetE x p e r i m e n t 3

    PIC18Fxx2: Instruction Set

    Surely youve seen the TV commer-cial of the two female engineers mud-wrestling while arguing about the PIC instruction set1. Less Fill-ing! Tastes Great!. Well, Im not sure about tastes great, but less filling is right on. So much so, you often find yourself saying Why in the #$!*& doesnt it have instruc-tion X?!? But, fewer instructions means less to know! Woot!

    SummaryExperiment with different PIC instruction sequences in the context of C code examples.

    1. At least, I think thats what the argument is about. They never really say.....3 1

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2A. Prelab Requirements

    Table 31: Prelab Checkoff

    Do This Comments

    1. The C programs ops_var{1-5}.c and loops_var{1-5}.c attached to this lab per-form operations on three unsigned byte variables: i, j, k. Verify that you can com-pile and execute these programs on any machine/operating system of your choice.

    The programs variants 1 through 5 re-arrange C statements in different orders. For the ops programs, the files ops_{a-l}.c define 12 different C operations that are included in different orders within ops_var{1-5}.c. For the loops programs, the files loops_{a-e}.c define 5 different C code segments that are included in differ-ent orders within loops_var{1-5}.c.

    Print statements are included after each block of code to track variable modifica-tions.

    These programs are used to illustrate how common C operations are implemented in PIC18F242 assembly language.

    These programs can be compiled and executed on the ECE Unix machine (leto.ece) once the ZIP archives have been unpacked into a common directory.

    An example compilation/execution is shown below:

    To compile: gcc -o ops_var1 ops_var1.c

    This produces the executable ops_var1

    To execute: ./ops_var1

    2. Compile and execute your assigned op and loop program variation as given by the tables below. Have a printout the val-ues of i, j, k ready for checkoff.

    Understand the functionality of your assigned op/loop program as you are required to implement these in PIC 18F242 assembly language.

    Table 32: Program Variations for ops

    If the last digit of your student ID is...

    Use the program...

    0 or 2 ops_var1.c

    1 or 3 ops_var2.c

    4 or 6 ops_var3.c

    5 or 7 ops_var4.c

    8 or 9 ops_var5.c3 2

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction SetA Quick C ReviewIn case you are a bit rusty on C (or have never had it!), here is a quick review. The use of C in this course is very simplistic; please refer to any C reference manual for deeper coverage of the topics presented here.

    Variables declared as:

    unsigned char i, j, k;are 8-bit (byte) variables. The unsigned modifier is important as this affects how comparisons such as > or > 1); the MSB stays the same for a right shift of a signed data type.

    The table below explains the operators used in ops_var{1-5}.c.

    Table 33: Program Variations for loops

    If the last digit of your student ID is...

    Use the program...

    0 or 9 loops_var1.c

    1 or 8 loops_var2.c

    2 or 7 loops_var3.c

    3 or 6 loops_var4.c

    4 or 5 loops_var5.c

    Table 34: Some C operators

    Operator Comment

    ++, -- increment (i++) or decrement (i--) the variable by one.

    +, - addition, subtraction3 3

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2The bitset and bitclr macros in ops_var{1-5}.c use log-ical and shift operations to do a set or clear on the specified bit of the operation. The bittst macro returns the value of the specified bit in the operand; either 0 or 1.

    Loops and Conditions A condition test in C is considered false if the condi-tion test returns a 0 value; true if it returns a non-zero value. Thus an if statement written as:

    if (bittst(i,0)){ /* true block */} else { /* false block */}

    will execute the true block if the LSB of variable i is a 1, else it will execute the false block.

    The for loop has three parts; initialization, condition test, and end-of-loop statements:

    >>, > 1) or left shift (i , =, =), less than or equal (

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction Setfor (init; ctest; end-of-loop) { /* loop body */}

    A for statement is equivalent to a while statement writ-ten as:

    init;while (ctest) { /* loop body */ end-of-loop statements}

    The most common use of a for loop is to execute some block of code a fixed number of times:

    for (i=0; i < 10; i++) { /* loop body */}

    The above code executes the loop body 10 times. The equivalent while statement is:

    i = 0;while (i < 10) { /* loop body */ i++;}

    The difference between a while loop and a do-while loop is that the loop body in a do-while loop is guaran-teed to execute at least once because the condition test is done after the loop body. The above for loop can also be written as:

    for (i=0; i!= 10; i++) { /* loop body */}

    Note that the bodies of both for loops execute 10 times.3 5

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2B. Lab Activity

    STATUS Register: Carry, Zero Flags

    That STATUS register is a special function register whose individual bit values are called referred to as

    Table 35: ops in PIC18F242 Assembly

    Checkpoint Comments/Debugging

    1. Convert your assigned ops_var{1-5}.c program to PIC18F242 assembly and ver-ify that the i, j, k variables have the same values at each step as with the original C program.

    Use the table below to determine what file register locations to use for i, j, k.

    The print statements in the original C file cannot be converted; you must track the progress of the i, j, k variables by observ-ing memory contents.

    Test your code for different i, ,j, k initial values. Use the STOPWATCH and record the amount of time it takes for this pro-gram to execute with a processor fre-quency of 20 MHz.

    Look at the hints below on implementing these C operations.

    Develop your program one operation at a time. There is no need to advance to the next operation until the current one pro-duces the correct value. Do not worry about any code optimization; do it in the easiest, most straight forward manner. Modify the C code to have print state-ments after each operation if you do not trust your hand computation of the vari-able values.

    Table 36: Register file assignment for ops

    If the last digit of your student ID is...

    Use the following locations...

    0 or 1 i: 0x48 (bank 0), j: 0x49 (bank 1), k: 0xC8 (bank 2)

    2 or 3 i: 0x51 (bank 2), j: 0x31 (bank 0), k: 0x52 (bank 1)

    4 or 5 i: 0xE1 (bank 1), j: 0x60 (bank 2), k: 0x61 (bank 0)

    6 or 7 i: 0x70 (bank 0), j:0xB1 (bank 2), k: 0x30 (bank 1)

    8 or 9 i: 0xC4 (bank 1), j:0x44 (bank 0), k: 0xC5 (bank 2)3 6

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction Setflags, and which are set or cleared as a side-effect of instruction execution. There are two other bits in the STATUS register that are useful in this exercise. They are the carry flag (bit 0), and zero flag (bit 2). The carry (C) flag is affected in multiple ways, but the most common methods are through addition and sub-traction. In an addition, the carry bit is set when there is a carry out of the MSB. In a subtraction, the carry bit is cleared if there is a borrow into the MSB during the subtraction. The carry flag will prove useful in unsigned comparisons operations. The zero (Z) flag is set whenever the result of an operation is zero. The zero flag is useful in equality tests. The C and Z flags are set as side-effects of PIC operations. Look at the instruction descriptions to determine when these flags are affected; not all instructions affect these flags.

    Converting the C opera-tions to PIC Assembly

    Convert each C operation separately from the other, and use the simulator to check the result as you go. Remember that the w register is involved in every two-operand PIC instruction. If it is a two-operand calcula-tion such as k = i op j, use the approach:

    1. load the w register with i2. perform op j; store the result in w3. store the w register to k.

    For example, if the calculation is k = i + j, then:

    movf i,w ; w iaddwf j,w ; w w + jmovwf k,w ; k w

    This code assumes that i, j, k are all in bank0. If k is in bank1, the code is written as:

    movf i,w ; w iaddwf j,w ; w w + j3 7

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2movlb 0x1 ; select bank1movwf k,w ; k wmovlb 0x0 ; re-select bank 0

    If the operation k=k+i, then the code is written as:

    movf i,w ; w imovlb 0x1 ; select bank1addwf k,f ; k w + kmovlb 0x0 ; re-select bank 0

    Note that in this case the addwf command is written to modify the k file register location. This is because k is both a source operand of the operation, and the desti-nation.

    arithmetic operations The arithmetic operations (addition, subtraction, incre-ment, decrement), are straightforward as there are PIC instructions that do all of these. Remember that with the subtraction operation, it is f - w, where f is the file register value, and not vice-versa. The increment and decrement operations are convenient in that a separate instruction does not have to be used to load the w reg-ister with the operand value; the instruction does this automatically.

    logical operations The PIC has instructions for AND, OR, XOR, and complement (negation) that do the equivalent of the bitwise operations in C, so conversion is again straight forward.

    Shift operations The PIC has two rotate instructions (left and right) that are used to implement shift operations. A rotate right performs a shift right, with the MSB filled by the value of the carry bit, and the LSB becoming the new carry bit. A single shift right (i >> 1, i is an unsigned char) using a rotate instruction is written as:

    bcf STATUS,C ; clear carryrrcf i,f3 8

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction SetRepeat this sequence as many times as needed to accomplish the specified C shift operation. Do not put the code in a loop; simply duplicate the two-instruc-tion sequence. In the above code, STATUS and C are symbols that are defined in the pic18f242.inc file as:

    STATUS EQU H'0FD8'C EQU H'0000

    The previous BCF instruction could have been written as:

    bcf 0xFD8,0 ; clear carrybut this is much less readable. Symbols for special function registers and bits/bit fields within special function registers are declared in pic18f242.inc. Use these symbols to improve code readability. These sym-bols are all declared as uppercase, and MPLAB is case sensitive, so you will get an undeclared symbol error for the following code:

    bcf status,c ; clear carrybecause status and c are lowercase.

    A shift left (i

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2Condition Tests A condition test is part of all loops and if statements. The four types of condition tests used in this lab are:

    1. test for a particular bit being zero or non-zero2. test if an entire byte is zero or non-zero3. test if a byte is less than or greater than a value4. test if a byte is equal to another value

    Test for bit set or clear An condition check for a particular bit set or clear is easy because the PIC has direct instructions for this. The C code:

    if (bittst(i,5)) { /* true block */} else { /* false block */}

    can be directly translated as:

    btfss i, 5 goto false_blocktrue_block

    Table 37: loops in PIC18F242 Assembly

    Checkpoint Comments/Debugging

    1. Convert your assigned loops_var{1-5} program to PIC18F242 assembly and verify that the i, j, k variables end up with the same values as your original C program.

    Use the same variable location assignments as used for the ops program.

    Test your code for different i, ,j, k ini-tial values.

    Look at the hints below on imple-menting loops and condition checks in PIC assembly language.

    Again, convert one block at a time and verify the result before proceed-ing to the next block.3 10

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction Set ...true blk goto false_block_endfalse_block ...false blkfalse_block_end

    ... remaining statementsNote that the bit test and skip if set (btfss) instruction is used because the condition is checking for the bit being equal to a 1.

    The condition below:

    if (i) {/* if_body */}

    executes the if body if i is nonzero. This can be imple-mented as:

    movf i,f ;move i onto itself! btsfc STATUS, Z goto skip ; Z=1, so i == 0 ...if body...skip ... rest of code

    Note that the movf i,f instruction moves i onto itself; the only useful thing this accomplishes is setting the Z flag if i is zero. The if body true is executed if i is non-zero.

    Zero/Nonzero Test with branch instruction

    The condition below:

    if (!i) {/* if_body */}

    executes the if body if i zero. This could be imple-mented using the movf/btsfsc approach above, or can be done by PIC18 code:3 11

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2 tstfsz i ; is i == 0? goto skip ; i != 0, skip ...if body... i is zeroskip

    ... rest of codeThe tstfsz instruction is test F, skip if zero; it skips the next instruction if the file register contents is zero. There is usually more than one way to accomplish a task, use the approach that you understand the best.

    Zero/Nonzero Test with branch instructions

    The condition below:

    if (i) {/* if_body */}

    can be implemented using the branch instructions, which are conditional goto instructions based upon the setting of a single flag bit in the status register:

    movf i,f ;move i onto itself! bz skip ; skip if Z=1 ...if body...skip ... rest of code

    The bz skip (branch on zero) instruction jumps to skip (branches to skip) if Z = 1.

    The condition below:

    if (!i) {/* if_body */}

    can be written as:

    movf i,f ;move i onto itself! bnz skip ; skip if Z=03 12

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction Set ...if body...skip ... rest of code

    Using branches typically improves code clarity and reduces instruction count. The remaining code exam-ples use branches to implement condition tests.

    testsTo perform a test such as A > B, note that this is the same as A - B > 0. This test is true if the result is non-zero (Z = 0) and if no borrow occurred during the sub-traction (C = 1). Written in a boolean fashion:

    (A-B > 0) is true if (!Z) & C(A-B > 0) is false if Z |!C

    The false test is derived by using DeMorgans law on the true test. The statement below:

    if (i > j) {/* if body */}

    can be to translated to PIC assembly as: movf j,w ;w j subwf i,w ; w i - w bz skip ; skip if Z=1 bnc skip ; skip if C=0 ; Z=0 & C=1, do if body ..if body....skip ... rest of code...

    The subtraction operation is written to leave the oper-ands unchanged; its only purpose is to affect the flags. Note that the if body is executed if the two successive bit operations are both true (the AND condition, as in !Z & C). The if body is not executed if either bit test fails (the OR condition, as in Z | !C). 3 13

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2The test for i > j is accomplished in fewer statements if the subtraction j - i is performed instead of i - j. If i is greater than j, then j - i will produce a borrow (C = 0). Thus, the PIC assembly is written as:

    movf i,w ;w i subwf j,w ; w j - i bc skip ;skip if C=1 ; C=0, do if body ...if body....skip ... rest of code...

    To implement

    if (i >= j) {/* if body */}

    the subtraction i-j will not produce a borrow (C=1) if the comparison i >= j is true. This is implemented as:

    movf j,w ;w j subwf i,w ; w i - j bnc skip ;skip if C=0 ; C=1, do if body ...if body....skip ... rest of code..

    The table below shows the subtraction operation and C flag test required for the comparison i > j and i >= j which is sufficient for all comparisons (i < j can be written as j > i, and i = i).3 14

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction Set Compare instructionsAn alternate method of accomplishing:

    if (i > j) {/* if body */}

    is to use the cpfsgt instruction (Compare F with W, skip if >). This instruction combines the subwf and btfsc of the previous example into one instruction. Thus, the PIC18 assembly is written as:

    movf j,w ;w j cpfsgt i ; i > j? goto skip ;skip if i =< j ; i > j, do if body

    ...true block.... skip ..rest of code...

    The instruction cpfslt instruction (Compare F with W, skip if = (greater than or equal) test:

    if (i >= j) {/* if body */}

    can be written as:

    Unsigned Comparison Operation Flag setting if true Flag setting if false

    i > j j - i C = 0 (borrow occurred) C=1 (no borrow)

    i >= j i - j C = 1 (no borrow) C=0 (borrow occurred)3 15

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.2if (! (j > i)) {/* if body */

    }

    which reads if NOT ( j > i) . One way to implement the above test in PIC18 assembly is:

    movf i,w ;w i cpfsgt j ; j > i? goto if_body ;i >= j goto skip ;j > i

    if_body .... if body code.... skip ..rest of code...WARNING: While the compare instructions can result in fewer instructions, they cannot be used for 16-bit inequality comparisons. The subtraction/flag test approach is the more general approach and you need to understand it as we will be using that approach for other types of comparisons in future labs.

    Equality, Inequality tests Equality (i == j) and inequality (i != j) are done in a similar manner using the subtraction operation. Equal-ity is true if Z=1 after the i-j operation; inequality is true if Z=0 after the i-j operation. The cpfseq instruc-tion (compare F, skip if equal) can also be used if desired.

    DEMONSTRATE YOUR LOOPS.ASM PROGRAM AND SHOW THAT THE I, J, K RESULT VALUES ARE THE SAME AS PRODUCED BY THE C CODE. BE PREPARED TO CHANGE THE INITIAL VALUES OF I, J, K.3 16

  • Summer 2004/V0.2 Experiment 3: PIC18Fxx2: Instruction SetC. Report1. Include the lst files for all assembly language pro-

    grams and any C source code. Comment your assembly language program very well; at least one comment every other line (points will be deducted if your assembly program is not well commented).

    2. For the ops program, calculate the total number of 8-bit operations performed (each 8-bit assignment counts as 1, each logical/add/sub/inc/dec counts as 1, each shift operation counts as 1). For shift opera-tions, count each required shift as 1 (a >> 3 counts as 3 shift operations). Make this calculation based on the C code, not the assembly code. Take the exe-cution time value recorded for the ops program, and divide by the total number of 8-bit operations to get an average execution time per 8-bit opera-tion. Take the inverse of this value to get the num-ber 8-bit operations per second that can be expected from the PIC18 running at 20 MHz. Com-pare this to what is obtained by taking the ADDWF instruction and computing the same values based on its execution time. Why are the values different? Discuss this in your report. What could be done dif-ferently in the ops program to give it higher perfor-mance?3 17

  • Experiment 3: PIC18Fxx2: Instruction Set Summer 2004/V0.23 18

  • Summer 2004/V0.2 Experiment 4: Data: Wider is BetterE x p e r i m e n t 4

    Data: Wider is Better

    P life crawled out upon the silicon beach in 1972 as a 4-bit critter, then began expanding faster than a Japanese rubber-suit monster eat-ing nuclear waste -- first 8 bits, then 16, 32...64...128....Mommie!!! Will the madness ever stop?! ...Hopefully not, because then us hardware types would be out of a job. Can the lil ol PIC handle wide data? Sure! ... Fast?.... Nope! But many times, getting the job done slowly is perfectly alright. But dont try that with your lab report!

    SummaryExperiment with manipulating 16-bit arithmetic opera-tions, and comparisons on 16-bit unsigned and signed data. 4 1

  • Experiment 4: Data: Wider is Better Summer 2004/V0.2A. Prelab RequirementsTable 41: Prelab Checkoff

    Do This Comments

    1. The C programs intops_var{1-5}.c attached to this lab performs operations on two unsigned 16-bit integer variables: i, j. The C programs unsigned_var{1-5}.c performs operations on two unsigned 16-bit variables. The C programs signed_var{1-5}.c performs operations on two signed 16-bit variables. Verify that you can compile and execute your assigned program versions on any machine/operat-ing system of your choice.

    Have a printout of the i, j values for both programs ready for checkoff.

    When viewing the printed i, j values from within signed_var{1-5}.c, ignore the most significant four F digits if 8 hex charac-ters (32-bits) are displayed for a value. This is the extension of the sign bit to 32-bits.

    2. The following HEX values are 2s complement, 8-bit integers. Convert to decimal.

    a) 0xFD, b)0x70 c) 0x82

    3. Convert the following signed decimal values to 8-bit twos complement values. Write the values in Hex.

    a) -20 b) -78 c) + 39

    4. Perform the following operations, give the result in hex. Also give the values for the N, V, C flags based on the 16-bit computation.

    a) 0xA8AF + 0x9C23

    b) 0x49B0 - 0x82F3

    5. The machine code for a branch instruction is 0xE4E6 and is located at address 0x0232. What branch instruction is this and what is the target address?

    6. What is the machine code for instruction sequence below. Does this machine depend on where it is located in memory?

    here bra here4 2

  • Summer 2004/V0.2 Experiment 4: Data: Wider is BetterData Sizes in CThe char data type is always 8 bits regardless of the processor type. The size of the int data type is depen-dent upon the processor and is typically 32 bits. A short int is 16 bits. A long data type on high perfor-mance CPUs is 64 bits; on most other CPUs it is 32 bits. The following program can be used to determine the data sizes of a particular C implementation:

    main()

    {

    printf (" A char is %d bits.\n", sizeof(char)*8);

    printf (" A short int is %d bits.\n", sizeof(short int)*8);

    printf (" A int is %d bits.\n", sizeof(int)*8);

    printf (" A long is %d bits.\n", sizeof(long)*8);

    Table 42: Program variations for intop

    If the last digit of your student ID is...

    Use the program...

    0 or 3 intop_var1.c

    1 or 4 intop_var2.c

    2 or 5 intop_var3.c

    6 or 9 intop_var4.c

    7 or 8 intop_var5.c

    Table 43: Program variations for unsigned, signed

    If the last digit of your student ID is...

    Use the programs...

    0 or 1 unsigned_var1.c, signed_var1.c

    2 or 3 unsigned_var2.c, signed_var2.c

    4 or 5 unsigned_var3.c, signed_var3.c

    6 or 7 unsigned_var4.c, signed_var4.c

    8 or 9 unsigned_var5.c, signed_var5.c4 3

  • Experiment 4: Data: Wider is Better Summer 2004/V0.2}

    By default, a char, int, or long type is assumed signed unless specified otherwise via the unsigned modifier. 4 4

  • Summer 2004/V0.2 Experiment 4: Data: Wider is BetterB. Lab Activity

    Storing 16-Bit values in memory

    When storing an integer that is more than one byte in memory, the bytes can arranged either least significant to most significant (little endian) or most significant to least significant (big endian). On an 8-bit processor like the PIC, the choice is up to the programmer. There is no inherent advantage to either ordering. As an example, the code below uses little endian format for

    Table 44: intops.c in PIC16F873 Assembly

    Checkpoint Comments/Debugging

    1. Convert your assigned intops_var{1-5}.c program to PIC18F242 assembly and ver-ify that the i, j variables finish with the same values as your original C program.

    Use the table below to determine what file register locations to use for i, j.

    Test your code for different i and j initial values.

    Use the STOPWATCH and record the amount of time it takes for this program to execute with a processor frequency of 20 MHz.

    Look at the hints below on implementing these C operations.

    Develop your program one operation at a time. There is no need to proceed to the next operation until the current one pro-duces the correct value. Do not worry about any code optimization; do it in the easiest, most straight forward manner. Modify the C code to have print state-ments after each operation if you do not trust your hand computation of the vari-able results.

    Table 45: Register file assignment for intops.c

    If the last digit of your student ID is...

    Use these locations...

    0 or 9 i: 0x53 (bank 0), j: 0x55 (bank 0)

    1 or 8 i: 0x5A (bank 0), j: 0x5E (bank 0)

    2 or 7 i: 0x63 (bank 0), j: 0x68 (bank 0)

    3 or 6 i: 0x71 (bank 0), j: 0x77 (bank 0)

    4 or 5 i: 0x4A (bank 0), j: 0x4C (bank 0)4 5

  • Experiment 4: Data: Wider is Better Summer 2004/V0.2the 16-bit variable i that is initialized to the value 0xC428:

    CBLOCK 0x040i_low, i_highENDCorg 0movlw 0x28movwf i_low ; LSB = 0x28movlw 0xc4movwf i_high ;MSB = 0xC4

    The low and high bytes are explicitly named i_low and i_high for clarity, with i_low at location 0x40 and i_high at location 0x41. Another way to accomplish the same thing is shown below:

    CBLOCK 0x040i:2ENDCorg 0movlw 0x28movwf i ; LSB = 0x28movlw 0xc4movwf i+1 ;MSB = 0xC4

    In this example, the statement i:2 reserves two bytes of storage for i. The Least Significant Byte (LSB) is ref-erenced as i, while the Most Significant Byte (MSB) is referenced as i+1 as it resides in the byte location fol-lowing the LSB. In these examples, little endian byte ordering will always be used.4 6

  • Summer 2004/V0.2 Experiment 4: Data: Wider is BetterAddition/Subtraction of 16-bit values

    Assume that the 16-bit variables i, j are declared as shown below:

    CBLOCK 0x040 i:2, j:2 ENDC

    The operation i= i+j can be accomplished via:

    movf j,w ; w j (LSB) addwf i,f ;i LSB i LSB + w movf j+1,w ; w j (MSB) addwfc i+1,f ;i MSB i MSB + w +C

    The addwfc instruction adds the C (Carry) flag to the sum of the two MSBs; if a carry is produced by the addition of the two LSBs then C=1 and this adds a +1 to the MSB sum.

    Similarly, in an i=i-j operation, the MSB subtraction is performed by the subwfb instruction the subtracts from W with a borrow. This subtracts a 1 from the MSB subtraction if the subtraction of the two LSBs pro-duces a borrow.

    movf j,w ; w j (LSB)subwf i,f ;i LSB i LSB - wmovf j+1,w ; w j (MSB)

    subwfb i+1,f ;i MSB i MSB - w -(~C)

    increment, decrementIncrement and decrement also can also use the addwfc/subwfb instructions. One way to do an integer incre-ment (i++) is:

    movlw 0x00 ; w 0 incf i,f ;i LSB i LSB + 1 addwfc i+1,f ;i MSB i MSB + 0 +C4 7

  • Experiment 4: Data: Wider is Better Summer 2004/V0.2The movlw 0x00 instruction is needed to ensure that W is zero for the addwfc instruction used on the MSB.

    The following is a more efficient 16-bit increment:

    infsnz i,f ;i LSB i LSB + 1 incf i+1,f ;i MSB i MSB + 1The infsnz instruction is increment, skip if nonzero. If the result of incrementing the LSB is a zero, then this means a carry is produced, and the MSB must be incremented. However, it cannot be generally applied to values greater than 16-bits.

    A 16-bit decrement (i--) can be performed as:

    movlw 0x00 ; w 0 decf i,f ;i LSB i LSB - 1

    subwfb i+1,f ;i MSB i MSB -0 - (~C)or as:

    tstfsz i ; is LSB 0? decf i+1,f ;i MSB i MSB - 1

    decf i,f ;i LSB i LSB -1The second version tests to see if the LSB is zero; if yes, then MSB is also.

    left, right shift For an unsigned right shift operation, the MSB is shifted first followed by the LSB, with the carry flag propagating the carry bit from the MSB to the LSB. The operation i = i>>1 is written as:

    bcf STATUS,C ; clear carry rrcf i+1, f ; i MSB >> 1 rrcf i, f ; i LSB >> 1

    For a left shift operation, the reverse is done; the LSB is shifted first followed by the MSB.4 8

  • Summer 2004/V0.2 Experiment 4: Data: Wider is BetterDEMONSTRATE YOUR INTOPS.ASM PROGRAM AND SHOW THAT THE I, J RESULTS ARE THE SAME AS PRO-DUCED BY THE C CODE. BE PREPARED TO CHANGE THE INITIAL VALUES OF I, J.4 9

  • Experiment 4: Data: Wider is Better Summer 2004/V0.2Unsigned 16-bit compari-sons

    Unsigned 16-bit comparisons are performed using the subtraction/C flag test as was done for 8-bit numbers. The comparison:

    unsigned int i, j;if (i > j) { /* if body */}

    is accomplished by performing j-i and checking if C=0. In PIC18 assembly this is:

    movf i,w ; w i (LSB) subwf j,w ; w j LSB - i movf i+1,w ; w i (MSB) subwfb j+1,w ; w j MSB -i MSB-(~C) bc skip ; C = 1, j >= i, so skip ... if _body....skip .... rest of code

    The cpfsgt or cpfslt instructions cannot be used for 16-bit unsigned compares.

    Table 46: unsigned 16-bit comparisons in PIC18F242 Assembly

    Checkpoint Comments/Debugging

    1. Convert your assigned unsigned_ver{1-5}.c program to PIC18F242 assembly and verify that the i, j variables finish with the same values as the C program.

    Use the same file register locations for i, j as used for the previous section. Use any address you want for variable k.

    Test your code for different i and j initial values.

    Look at the hints below on implementing signed comparisons in PIC assembly lan-guage.

    Again, convert one block at a time and verify the result before proceeding to the next block.4 10

  • Summer 2004/V0.2 Experiment 4: Data: Wider is Better16-bit Equality testsThe equality test below:

    unsigned int i, j;if (i == j) { /* if body */

    }is done by performing i-j (or j-i) and checking if both byte results are zero:

    movf j,w ; w j (LSB) subwf i,w ; w i LSB - j bnz skip ;skip if LSB != 0 movf j+1,w