78
MICROBOARD MANUAL Revised and edited by David Zeibin, Summer 2001 Based on documents by Ben Bathgate, Mike Cumming, Patrick Pilarski, and Paul Bartosek Special thanks to Dr Chris Backhouse

MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

MICROBOARD MANUAL

Revised and edited by David Zeibin, Summer 2001

Based on documents by

Ben Bathgate, Mike Cumming, Patrick Pilarski, and Paul Bartosek

Special thanks to Dr Chris Backhouse

Page 2: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

HOW TO USE THIS MANUALIn an effort to enable students with the appropriate skill set needed to make this course as rewarding as possible, I havedivided this manual into five parts. There is a lot of material here but you may not to need use all of it for your project.

PARTS

I The MicroBoard: Design, Assembly and Maintenance This section breaks down the parts of the MicroBoardand explains what each does. An assembly guide and testing procedures follow this. Finally, the section finishesoff with a short tutorial to complete the initial programming of the MicroBoard’s onboard micro-controller.Everyone will need this information, if only as a reference.

II Getting Started: Hosted Mode The second part introduces operation of the MicroBoard in the Hosted mode andwill outline some of the methods you can use to “test drive” your board and also demonstrate some very simpleexamples. This section will also introduce you to some very basic programming of the PIC, which will consist of(typically) nothing more than cutting, pasting, and thus, utilizing code that has already been written for you. Toattain any sort of marks in the course, you will need to use this section. To attain great marks, it is possible to stopwith the documentation at this point; however, you will need to design some pretty fancy electronics tocomplement the simple code.

III Beyond Getting Started: Autonomous Mode & Advanced Programming Techniques This section opens anew chapter that will allow you to unleash the full capabilities of the MicroBoard. Along with in-depthprogramming documentation (allowing you to tailor the PIC’s program to suit your exact needs), this sectioncontains detailed examples and is complemented by bits of usable sample code, schematic diagrams, and boardlayouts. The hand-holding ends with this section and those who venture beyond here will seldom find step-by-step procedures but will be applauded for their ambition and persistence!

IV Examples: Both Simple and Complex Sample projects possessing some commonly used input/output traitshave been designed and documented for you. The documentation is available for your perusal, complete withcode, diagrams, and explanations.

V Appendices These are referenced by the four previous parts. Feel free to detach the appendices from the bulk ofthis manual; you will likely refer to them often.

Using this manual not only as a reference but also as a guide should make the journey much more interesting if not trulyenjoyable. I would sincerely recommend taking the time to read the entire manual from beginning to end; the things youwill learn along the way will be integral when it comes to designing your own project. Be aware, however, thatcompletion of this manual will merely lay the groundwork for more interesting, albeit more useful, applications of theMicroBoard.

Keep in mind that the MicroBoard is just the central nervous system of your project. You are responsible for the design ofthe extraneous circuits that your project will utilize (sensors, motors, etc…). It would be prudent to make your initial circuitdesigns on an SK10 board, then later transfer your design to a computer using EAGLE to have it milled into a clean PCB.In general, rat’s nests of wires don’t hold up very well and, in accordance with Murphy’s Law, will inevitably let youdown when you need them the most (during demonstrations of course!).

Good luck.

David ZeibinAugust 2001

Page 3: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

TABLE OF CONTENTS

Part I The MicroBoard: Design, Assembly, and Maintenance1 INTRODUCTION ................................................................................................................................21.1 Specifications ...............................................................................................................................21.2 Functional Description .................................................................................................................31.3 DC Power Supplies .......................................................................................................................31.4 RS-232 Serial Peripheral Interface (SPI).....................................................................................41.5 The Micro-Controller ....................................................................................................................51.6 PIC Micro-Controller Chip Diagrams (PIC16F873) ......................................................................6

2 MICROBOARD KIT ASSEMBLY GUIDE....................................................................................................7

3 WRITING YOUR PROGRAMS TO THE PIC ...............................................................................................9

Part II Getting Started: Hosted Mode4 HOSTED MODE ...............................................................................................................................124.1 Communicating with the MicroBoard (Windows system) .........................................................124.2 Communicating with the MicroBoard (HP-UX system)..............................................................134.3 Communicating with the MicroBoard (Unix flavours) ...............................................................13

5 HOSTED MODE COMMANDS...............................................................................................................145.1 General Commands ....................................................................................................................145.2 Pulse Width Modulator (PWM) Commands................................................................................145.3 Analog-to-Digital Converter (ADC) Commands .........................................................................155.3.1 Maximum ADC Values.................................................................................................................. 155.4 Serial Peripheral Interface (SPI) Commands ............................................................................155.5 Infra Red (IR) Command ...........................................................................................................165.6 LCD Screen Interface Commands ..............................................................................................165.7 Delay Command .........................................................................................................................175.8 A Few Comments about Syntax .................................................................................................175.9 Utilizing Hardware Flow Control ................................................................................................175.10 Programming in C ......................................................................................................................17

6 HOSTED MODE EXAMPLES ................................................................................................................186.1 Flashing LEDs .............................................................................................................................186.2 Digital-to-Analog Converter using PWM....................................................................................196.3 Using SPI Devices ......................................................................................................................206.4 Adding Additional Outputs Using Shift Registers and SPI.........................................................216.5 A Rudimentary Hosted Mode Project: The GrabberBot..............................................................226.5.1 Using the GrabberBot in Hosted Mode ........................................................................................... 226.5.2 Using the GrabberBot with Scripted Files ....................................................................................... 236.5.3 Using the GrabberBot with a C Program......................................................................................... 24

Part III Beyond Getting Started: Autonomous Mode& Advanced Programming Techniques

7 AUTONOMOUS MODE .......................................................................................................................277.1 PIC Programming.......................................................................................................................277.1.1 Register Operations..................................................................................................................... 277.1.2 Mathematical Operations ............................................................................................................. 287.1.3 Flow Control ............................................................................................................................... 287.2 Digital I/O Ports.........................................................................................................................297.3 Limitations .................................................................................................................................30

Page 4: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

8 DEBUG.HEX ................................................................................................................................318.1 Code Map....................................................................................................................................318.2 Upper-Page Subroutines ............................................................................................................328.2.1 Global Subroutines ...................................................................................................................... 328.2.2 UART Module Subroutines............................................................................................................ 328.2.3 ADC Module Subroutines.............................................................................................................. 328.2.4 PWM Module Subroutines ............................................................................................................ 328.2.5 SPI Module Subroutines (Master Mode Only).................................................................................. 338.2.6 LCD Module Subroutines .............................................................................................................. 338.2.7 Programming Module Subroutines (only available on the PIC16F877)................................................ 338.2.8 Programming Utility Subroutines................................................................................................... 348.2.9 Help Function ............................................................................................................................. 358.2.10 IR Module Subroutines ................................................................................................................ 35

9 YOUR FIRST PIC ASSEMBLY CODE PROJECT........................................................................................369.1 Getting Started with MPLAB ......................................................................................................369.2 The PIC16F87x Assembly Template...........................................................................................38

10 MPLAB SIMULATOR .......................................................................................................................4110.1 Using the Simulator to Test Code...............................................................................................41

11 USING THE DEBUG.HEX CODE ........................................................................................................4411.1 The ADC Lines.............................................................................................................................44

Part IV Examples: Both Simple and Complex12 WORKING EXAMPLES.......................................................................................................................4912.1 Servo Motors ..............................................................................................................................4912.1.1 Testing a Servo in Hosted Mode ................................................................................................... 4912.1.2 Testing a Servo in Autonomous Mode............................................................................................ 5012.2 SPI Bar Graph.............................................................................................................................5112.2.1 SPI Bar Graph in Hosted Mode ..................................................................................................... 5112.2.2 SPI Bar Graph in Autonomous Mode.............................................................................................. 5212.3 Motor Speed Controller ..............................................................................................................5412.4 Shaft Encoder .............................................................................................................................57

13 MEDULLA: THE SOUND-SENSING ROBOT...................................................................................................61

14 SNAKE TURRET (MKII – AUTONOMOUS VERSION).................................................................................... 633

15 LINE FOLLOWER................................................................................................................................. 635

16 RF CONTROL (RC LINK) ..................................................................................................................... 637

Part V AppendicesAPPENDIX A. MICROBOARD SCHEMATIC DIAGRAM.........................................................................................69APPENDIX B. COMPONENT AND SOLDER SIDE OF BOARD..................................................................................70APPENDIX C. ASSEMBLING A MILLED BOARD (PLUS HOW TO SOLDER)...............................................................71APPENDIX D. CHECKLISTS: COMPONENTS, POWER, AND INTEGRATED CIRCUITS..................................................73

Page 5: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 1

Part IThe MicroBoard: Design, Assembly, and Maintenance

Page 6: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 2

1 INTRODUCTIONThe first-generation MicroBoard is a compact low-power controller board based on the Microchip TechnologiesPIC16F873 micro-controller. The PIC is the heart and soul of the MicroBoard, acting as the central processing unit for theboard. The MicroBoard is used in the EE401 project course and will be common to most projects, while the addition ofstudent-designed-and-built circuits combined with customized software will complete individual projects.

Realized by way of an in-house design, the MicroBoard is an inexpensive alternative to the previously used Handy Board.However, this does not mean the MicroBoard is inferior to its predecessor. In fact, the onboard PIC can perform up to 1MIPS (million instructions per second) making the MicroBoard nearly 1000 times faster than the Handyboard, whichoperated on a millisecond time scale (due to the fact that the Handyboard executed commands through interpreted C).

Every MicroBoard comes loaded with the following features:

Support for Three Built-in Motor Drivers: Each capable of driving a stepper motor, two bi-directional DCmotors, or four unidirectional DC motors.

Communication Interfaces: RS-232 communication with a PC; SPI and I2C buses for communicating with otherchips; and standard 5V CMOS digital I/O for anything else.

Extra Features: Five-channel analog-to-digital converter and two pulse-width-modulated outputs for servomotors or other uses.

Two modes of operation are available for the MicroBoard:

Hosted mode: The MicroBoard runs a program allowing control of most of its functions through a serial link to adesktop PC (see Part II). HyperTerminal is used to communicate with the MicroBoard in a command-promptfashion. It is also possible to write and compile a C program that will communicate with the MicroBoard for youusing commands you have defined (see Section 5.10).

Autonomous mode: More powerful than hosted mode, autonomous mode uses assembly code you havecompiled and then “burned” onto the PIC (see Part III). The code need not be hand-written from scratch; thereare many available subroutines you can call directly from the main portion of DEBUG.HEX, the Hosted modecontrol program.

Complete with a relatively powerful processor and large I/O capability, the MicroBoard is an impressive control system.The range of projects is virtually limitless: you can control robotics, perform wireless communication, carry out digitalsignal processing, or even connect your MicroBoard to the Internet. The only real limit is your own imagination.

1.1 SPECIFICATIONS

This table lists the electrical characteristics of the MicroBoard; exceeding maximum or minimum values may damageyour board very quickly:

Maximum Input Voltage 18 Vdc

Minimum Input Voltage 6 Vdc

PIC Clock Speed 4 MHz (Upgradeable to 20 MHz)

PIC Digital I/O Pins 22

PIC Analog-to-Digital Channels 5 (multiplexed)

PIC Pulse-Width-Modulated Pins 2

Power Consumption with all ICs 140 mA @ 7.2 Vdc

Page 7: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 3

Power Consumption with no L293s 20 mA @ 7.2 Vdc

Max current drawn from +12Vdc connector 500 mA

Max current drawn from +5Vdc connector 500 mA

Max current drawn from -12Vdc connector 50 mA

Max current per pin on PIC 20mA

Max current per L293 chip 1A

1.2 FUNCTIONAL DESCRIPTION

The MicroBoard is designed in a modular manner. Please refer to Appendix A – MicroBoard Schematic Diagram andAppendix B – Component and Solder Side of Board as necessary to improve your understanding.

Figure 1-1: PIC MicroBoard Block Diagram

1.3 DC POWER SUPPLIES

Figure 1-2: Power Supply Circuitry

DC power is supplied to the board through a 2.1mm coaxial barrel connector with center-positive polarity. Normally, thispower comes from a 9Vdc 500mA wall adapter plugged into the barrel connector. However, a 12Vdc 1A wall adapter orsuitably sized battery array can also be used.

PIC16F873Micro-Controller

Digital Interface Support &H-bridge Drivers

RS-232 Serial Interface

Analog/Digital Interface Support

DC Power Supplies Analog Supply Inverter

InterfaceConnectorsto the Restof Project

Page 8: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 4

Diodes D1 and D2 provide some reverse polarity protection and power supply transient isolation. Capacitors C1 and C2provide power supply bulk charge storage while C3 - C6 provide additional power supply transient isolation for theirrespective supplies.

IC1 regulates the bulk supply to the +5Vdc needed for the PIC micro-controller and logic devices (logic side of the L293 andMAX232). IC2 and its associated components regulate the bulk supply for the voltage inverter, IC3, and are only installedif IC3 is to be used. IC3, an ICL7662P, and capacitors C9-C14 provide a negative voltage for analog circuits (dual supplyop-amps).

You will notice that the polarized capacitors have a non-polarized capacitor in parallel with them. This is not alwaysnecessary in designs but is here. The reasoning is that real capacitors are not ideal capacitors: larger capacitors tend to havegreater amounts of intrinsic inductance associated with them due to their construction. This greater inductance gives thempoorer high frequency performance. Smaller capacitors tend to have better high frequency performance. Therefore,multiple real capacitors are used to approximate the required ideal capacitor performance.

1.4 RS-232 SERIAL PERIPHERAL INTERFACE (SPI)

Figure 1-3: RS-232 Serial Circuitry

The RS-232 circuitry consists of a DB09 female connector, the MAX232 chip, and related circuitry. The DB09 connector isconfigured for an IBM PC-style 9-pin RS-232 connection. The MAX232 (sometimes called a HIN232) converts the RS-232+/-12V signals to logic levels for the micro-controller. Resistors R31 and R32 (330Ω each) limit line slew rates and providesome short-circuit protection. Resistors R23, R24 (not shown here; see Appendix A – MicroBoard Schematic Diagram),R33 and R34 provide output contention protection (a possible short circuit is created if the digital I/O pin of PIC isincorrectly configured as an output and connected to the output of the MAX232).

Page 9: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 5

1.5 THE MICRO-CONTROLLER

Figure 1-4: Micro-Controller

IC4 is the PIC16F873 micro-controller. Most of the pins, when configured as outputs, can source and sink 20mA of currentdirectly. The maximum voltage on any pin should not exceed the bounds of VDD and VSS.

The combination of SW1, R1 and R2 provides a reset switch. Note that R1 must be on the order of ten times greater thanR2 for pin 1 on the PIC to reach a reset level when SW1 is closed.

The arrangement of Y1, C15 and C16 provides the oscillator circuitry for the micro-controller. Y1 may be a quartz crystal, atwo-pin ceramic resonator, or a three-pin ceramic resonator with internal capacitors. Capacitors C15 and C16 are sizedaccording to the manufacturer’s data sheets (typically 10 to 15pF). NOTE: If a three-pin ceramic resonator with internalcapacitors is used, C15 and C16 should not be used (this is the case for the supplied MicroBoard kits).

Resistors R3 through R24 (all 470Ω) are used to limit input and output currents to the micro-controller, thus affordingsome limited protection. If a pin is used for either digital or analog input, no resistor is required but a 1.0kΩ resistor willprovide some static protection. If the H-bridges are connected directly to the micro-controller, no resistors are requiredbetween the L293 and the PIC16F873. Otherwise, the resistors may be used to limit output current from the PIC to driveLEDs and other output devices.

CAUTION! This device is static sensitive.

Page 10: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 6

1.6 PIC MICRO-CONTROLLER CHIP DIAGRAMS (PIC16F873)

The PIC16F873 is shown at right. The diagramis a modified version of that found in theMicroChip PIC16F87x data sheet(http://www.ee.ualberta.ca/~ee401/datasheets/PIC16F87x.pdf). Modifications have beenmade to reflect the preprogrammedcapabilities.

The A bank (pins 2 through 7) is ADC capablewith the exception of pin 6. If not used as ADCinputs, the entire A bank can be used for digitalI/O. With a bit of programming, variouscombinations of digital I/O pins and ADC pinscan be attained.

The B bank (pins 21 through 28) is comprised of ready-to-use digital I/O pins. If you choose to enable your board withhardware flow control, RB1 and RB2 (pins 22 and 23) cannot be used a regular digital inputs or outputs (see Section 5.9 formore details on hardware flow control).

The C bank (pins 11 through 18) has various capabilities. RC1 and RC2 (pins 12 and 13) can be set as PWM outputs whileRC3, RC4 and RC5 (pins 14 through 16) are used in SPI communications. RC6 and RC7 are reserved for the DB09 serialconnection.

Page 11: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 7

2 MICROBOARD KIT ASSEMBLY GUIDEYou will receive a small kit containing all the parts you’ll need to assemble the basic MicroBoard. The kit includescomponents to fill the 5V regulator circuit, one H-Bridge interface circuit, the RS-232 connection, and the required PICcircuitry (refer to Appendix A – MicroBoard Schematic for complete details).

For designing circuits or modifying your MicroBoard, certain parts are kept on hand at all times, while others will besupplied especially for EE401 projects. Check out the EE401 web site for complete part listings(http://www.ee.ualberta.ca/~ee401/).

To begin assembly of the board, you’re going to need a few things:

⇒ soldering iron⇒ 63/37 electronic-grade rosin-core solder NOTE: Do NOT use the cheap solder that comes with the

tool kits; get good solder from a TA.⇒ needle nose pliers for forming leads⇒ small wire cutters for trimming leads

If you’re not familiar with soldering and circuit board assembly, you may want to digest Appendix C – Assembling aMilled Board (plus How To Solder) before continuing. If you have any questions about the MicroBoard assembly don’thesitate to ask a TA; that’s what they’re there for. You can waste a lot of time and effort simply finding and repairing a badsolder joint; do it right the first time and life will be much more pleasant.

As mentioned previously, the component and solder side diagrams of the board are contained in Appendix B.

2.1 MICROBOARD ASSEMBLY (A FEW SIMPLE GUIDELINES)

Remember these axioms whenever working with electronics:

Keep it clean.It is easier to keep electronics clean than to clean electronics. Contamination can cause many problems: a simplefingerprint will etch a copper trace and foul a solder connection; a fingerprint or leftover flux residue can act as anundesirable resistor.

Keep it cool.Use the correct soldering techniques and soldering temperatures; high temperatures will destroy components orshorten life times.

Minimize stresses.Miniaturization means less mechanically robust component packaging. Allow for thermal expansion, mechanicalflexing, and component movement. Do not pull leaded components too tight against the board.

To begin, refer to Appendix D – Checklists: Components, Power, and Integrated Circuits; make certain you have all theparts in your kit. If you’re missing anything, hassle a TA.

Using the same checklist, assemble the board, checking off components as you go. Solder the components that sit closest tothe board first, then those that stand higher after.

WARNING! Do NOT solder ICs directly into the board!Solder the IC sockets into the board; plug the ICs into their sockets.

Page 12: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 8

Before installing any ICs, test the board for proper power connections. Continue with the Power Checklist in AppendixD. Once all the power checks have been tested and are correct, continue with the IC Checklist.

After your board is completely assembled, the next section will aid you in actually installing some “software” on to thePIC.

Page 13: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 9

3 WRITING YOUR PROGRAMS TO THE PICTo actually make your MicroBoard “do” anything, it needs to be running a program. Since you’ve probably not writtenanything yet, a basic but multi-talented program has been supplied for you (called DEBUG.HEX). In this section, you willinstall DEBUG.HEX onto the PIC. In the next section, you’ll be able to take the PIC for a test drive.

The PIC has flash-type program memory, which can be written, erased, and rewritten; this is very useful for debugging(you can test out the capabilities and connections of your circuitry before letting your project run amuck). Typically theflash memory can go through several thousand of these cycles so you don’t need to worry about it breaking down on you.You will need to use a computer in the EE401 lab with a PICSTART Plus Development Programmer connected to it (seeFigure 3-1).

In the future, you will likely want to use the subroutines in DEBUG.HEX as part of your own program. If you modifyDEBUG.HEX or write your own program from scratch, you’ll need to follow these procedures to “burn” the new,modified program onto the PIC.

But, first things first:

Start MPLAB (Start>Programs>Microchip MPLAB>MPLAB).

1 Ensure that the PICSTART Plus is connected to thecomputer and that the power cord is plugged in (seeFigure 3-1).

2 Put your PIC chip into the uppermost position in thesocket on the PICSTART Plus with the notch on the PICpointing to the top (refer to Figure 3-1).

Figure 3-1: PICSTART Plus programmer

WARNING! Do NOT put your chip inthe PICSTART upside-down or you willpermanently damage the programmer

or destroy your chip!

Page 14: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part I – The MicroBoard: Design, Assembly, and Maintenance Page 10

3 Click on PICSTART Plus>Enable Programmer. A window willpop up if the programmer is attached correctly (Figure 3-2). If thebox does not appear, check the connections and try again.

4 Select PIC16F873 from the Device drop box in the PICSTARTPlus Device Programmer window (Figure 3-2).

5 Choose File>Import>Import To Memory and select yourprogramming file (DEBUG.HEX). You may need to downloadthe file from the EE401 web site:http://www.ee.ualberta.ca/~ee401/debug/debug.hex.

Figure 3-2

6 Click on the Configuration Bits button. A new window should open; select the following options from each of thedrop boxes:

Figure 3-3 Configuration Bits window

7 Finally, click Program in the PICSTART Plus Device Programmer window to burn your program onto the PIC.

8 The program will tell you if the program was transferred onto the chip successfully.

9 Take the chip out of the programmer, plug it into your MicroBoard, and you’re ready for business.

Page 15: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 11

Part IIGetting Started: Hosted Mode

Page 16: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 12

4 HOSTED MODEDEBUG.HEX allows you to control most of the functions of the MicroBoard without writing a single line of code. You caneven automate operations using Hosted mode by writing C programs for the PC that will control the MicroBoard (seeSection 5.10). DEBUG.HEX provides only the bare essentials available on the MicroBoard. To really make use of theMicroBoard, you’ll need to write your own code (using DEBUG.HEX’s pre-written subroutines or from scratch if you’re upto the challenge) and burn it onto the chip.

You will use a terminal program (HyperTerminal on the Windows systems and Seyon on the HP-UX systems) tocommunicate with the MicroBoard through the serial port. DEBUG.HEX uses a command prompt interface; all thecommands available to you are outlined in Section 5.

4.1 COMMUNICATING WITH THE MICROBOARD (WINDOWS SYSTEM)Before beginning, make sure that you have exited MPLAB; HyperTerminal and MPLAB cannot be running at the same time.

1 Connect a straight-through serial cable to the MicroBoard.

2 Open a HyperTerminal session with the desktop icon EE401.ht. If the icon isn’t there, you can start HyperTerminal usingthe Start Menu (Start>Programs>Accessories>Communications>HyperTerminal).

3 Connect power to theMicroBoard. You should begreeted with the “HelpScreen” (Figure 4-1). Thisscreen will also be shownevery time you type helpat the command prompt.

4 Should you need toconfigure HyperTerminal(if you need flow controlenabled, for example), selectFile>Properties and click onthe Configure… button inthe window that opens.

5 Select the COM2 port andconfigure it to use 9600bps,8 data bits, no parity, and 1stop bit (8-N-1). Chooseflow control depending onhow you’ve configuredyour board (see Section 5.9).

Figure 4-1: The Help Screen

Page 17: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 13

4.2 COMMUNICATING WITH THE MICROBOARD (HP-UX SYSTEM)

There are HP systems running HP-UX also available in the lab space; most students will be familiar with operating theseterminals. Use your EE-department student-user logon and password to gain access. Open a terminal session (select“Terminal” from the arrow menu) and enter the following to start up Seyon, the HP system equivalent of HyperTerminal:

seyon –nodial –modem /dev/tty0p0

When Seyon starts up, the “Seyon Command Center” will pop up. To configure Seyon, click on “SET” and select“CTS/RTS”. Seyon should already be configured properly, but to make sure, choose the appropriate settings under eachbutton: 9600bps, 8 data bits, no parity, 1 stop bit (8-N-1), hardware flow control disabled (unless your MicroBoard hashardware flow control enabled; refer to Section 5.9), etc….

NOTE: To change the flow control, go to the “SET” menu and choose “RTS/CTS” (hardware flow control) or “None” (noflow control).

Connect the power and the serial cable to the MicroBoard; you should be greeted with the Help Screen. Like inHyperTerminal, this screen will be shown if you type help at the command prompt.

NOTE: Only one Seyon terminal session can be launched on a machine at a time.

4.3 COMMUNICATING WITH THE MICROBOARD (UNIX FLAVOURS)

The terminal program should (no guarantees though!) work with various Unix-based operating systems. Using a similarvariant of HyperTerminal, connect using ttycua0 or ttys0.

Unless you need to, however, it’s probably best to stick to the tried and true methods in Sections 4.1 and 4.2.

Page 18: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 14

5 HOSTED MODE COMMANDSThe Help Screen (refer to Figure 4-1 above) lists the preprogrammed commands available to you. Using these commandsyou are able to control the MicroBoard, from the lowest level digital I/O to high level LCD screen control.

There are 22 general purpose I/O pins on the MicroBoard, many capable of multiple functions (refer to Section 1.6 for moredetails). However, two of them are used by the serial interface leaving 20 available pins for your use. Five of these pins can beused as inputs to the built-in ADC (note that all five of them must be configured the same, either digital or analog I/O). Twoof the pins can be independently configured as outputs for the built-in PWM.

5.1 GENERAL COMMANDS

General-purpose I/O pins can be set as either inputs or outputs. To specify which state you want the pin to be in, use thecommands input or output followed by a pin identifier (A0 to A5, B0 to B7, or C0 to C5 for example). Realize that if any ofthe ADC, PWM, LCD, or SPI is using the pin, it won’t be accessible as an I/O pin.

When a pin is configured as an input, the read command will return “0” or “1” depending on the input voltage at the pin(thus determining whether the pin is “on” or “off”). If a pin is configured as an output, the commands set and clear willchange the output to a “0” or “1”, 0V or +5V respectively.

>> input c3 - turns pin c3 of the PIC into an input>> read c3 - reads the value of pin c3 of the PICPin=1 - which happens to be “1” in this case>> output c2 - turns pin c2 of the PIC into an output>> set c2 - outputs a logical 1 (+5V) on pin c2>> clear c2 - outputs a logical 0 (0V) on pin c2

5.2 PULSE WIDTH MODULATOR (PWM) COMMANDS

PWMs can be extremely useful if you would like to use servomotors in your project. Refer to Section 11.1 for a briefintroduction to servos and a tutorial on connecting and testing your servo using a three-wire connection. The PWM outputscan also be used to drive stepper motors. Be sure to do some research on stepper motors before trying to hook anything up;there are many resources scattered throughout the Internet.

The two built-in PWM modules are started using the commands pwmstart1 and pwmstart2. Different duty cycles (the ratioof high-output time to low-output time) can be set but both PWMs must have the same period. The commands pwmperiod,pwmduty1 and pwmduty2 control the period and respective duty cycles. All three commands take an 8-bit number as aparameter (hexadecimal 00 to ff).

How the PWM works: A counter begins at zero and counts up to the value specified by pwmperiod. The counter then resetsto zero and begins counting again. At the beginning of each period, the output is set high and only goes low when the counterreaches the value specified by pwmduty1 or pwmduty2. If the pwmduty1 or pwmduty2 value is greater than the pwmperiodvalue, the output will remain high always and never go low. (Note that one of the PICs built-in timers, Timer 2, controls thePWM period for both PWMs. See the Advanced MicroBoard Manual for details.)

The actual period can be calculated using the pwmperiod value and this formula:

Actual period = (pmwperiod value + 1) x 16µs

Page 19: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 15

Use pwmstop1 or pwmstop2 to stop the PWM.

>> pwmstart1 - starts the PWM module connected to pin c2>> pwmperiod ff - sets the PWM period to approximately 4ms>> pwmduty1 40 - sets the duty cycle to about ¼ = 1ms (40/ff)>> pwmstop1 - stops the PWM output on pin c2

NOTE: On the PIC, pin c2 corresponds to PWM1 while pin c1 corresponds to PWM2.

If you hook up an LED to the PWM, you can change the brightness by varying the duty cycle and period.

5.3 ANALOG-TO-DIGITAL CONVERTER (ADC) COMMANDS

There is a five-channel ADC built into the PIC; all of these channels are available for you to use with DEBUG.HEX. The ADCpins are in the A bank on the PIC and are referenced by a0 through a3 and a5 (a4 is used as a digital I/O1).

To use the ADC you must initialize it with the adcinit command. After initializing, you can read a value from the ADCusing the command adcread followed by a channel number (0 to4; one of the five ADC channels). The program will return a10-bit number (0000 to 03ff) corresponding to the voltage level on the input pin:

>> adcinit - starts the analog-to-digital converter>> adcread1 - reads an analog voltage on pin a1 (pin 3)Val=0155 - in this case (155/3ff) x 5V = approximately 1.67V

NOTE: After running adcinit, all five channels are enabled. You may have problems if you want to turn only one of the fiveoff. By running an input or output command on any of the five pins (thus turning a pin into a digital line), all five ADCchannels will turn off automatically.

5.3.1 MAXIMUM ADC VALUES

All five ADC ports have a limited amount of diode protection toprevent input voltages outside of the Vdd to Vss range. A better way tomake sure your PIC doesn’t get fried by stray analog voltages though,is to set up a small circuit before the signal reaches the ADC pin similarto the one to the right. This circuit will not let any voltage hit the ADCpin unless it is between 0 and 5V and doesn’t depend on the PIC’slimited protection.

The PIC16F87x data sheet also recommends that the maximum inputimpedance of an analog source be less than 10kΩ and that any currenton any pin should not exceed ±20mA.

5.4 SERIAL PERIPHERAL INTERFACE (SPI) COMMANDS

Many electronic components are capable of communication via SPI; the MicroBoard can communicate with these devicesusing the built-in SPI module. Use the spiinit command to enable SPI communications. Transfers in SPI mode are donesynchronously: when the MicroBoard sends a byte using SPI, it then receives a byte from the device it is communicating with.Begin a transfer using the spitrans command. The MicroBoard will send a byte and then print out the byte that it received.

1 On older MicroBoards, a pull-up resistor is required between the a4 pin and the power.

ADC line

PIC16F873

MicroBoard

1kΩ 4.7kΩ

+5V

Page 20: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 16

>> spiinit - starts the SPI module>> spitrans 28 - sends the value 28 out the SPI portval=92 - and returns the value 92 from the selected SPI device

- NOTE: if the SPI device is one-way (such as a 595 shift- register or an LCD screen) spitrans will return val=00

To use the SPI, you must use pins c0, c3, and c5 on the PIC. Pin c5 sends data out while pin c3 takes care of the SPI clock.Pin c0 is used to send a clock pulse out to the SPI devices, usually used to update the data sent through pin c5. Pin c4 is usedas an SPI input if your SPI device returns pertinent data. For a more detailed explanation of the SPI refer to Sections 6.3 and6.4. For an example using the SPI input, see Section ELSEWHERE.

5.5 INFRA RED (IR) COMMAND

DEBUG.HEX contains a usable IR command that will return three 8-bit values from a universal TV remote (note that theirread function may not give consistent values or work at all with any remote control). When the external IR circuit (seeFigure 5-1 below) is connected up to pin b0 (through Vout), run the irread b0 command. The pin will wait for some sort ofresponse (meaning the command will stay active until it receives a signal). Once the signal is received, irread returns threelines, each containing an 8-bit hexadecimal value.

>> irread b0 - begins waiting for IR dataVal3=AF spits out three sets of data once a signal isVal2=FF receivedVal1=FF

47Ω ± 5%

IR Receiver(IS1U60

Vout

GND

5V

47µF

GND

Vout

Vcc

Figure 5-1: Infra Red Receiver Schematic Diagram

5.6 LCD SCREEN INTERFACE COMMANDS

DEBUG.HEX can make controlling an LCD screen extremely easy. The screen typically used in projects is a 2x20-character (2rows of 20 characters each for a total of 40 characters) DMC-50218 Optrex display. DEBUG.HEX uses the MicroBoard’s SPIinterface (see Sections 6.3 and 6.4) to communicate with an external helper board containing a 595 shift register and the LCDscreen. This circuit board, however, will need to be built by the student, making LCD screens an advanced topic. For moreinformation on LCD screens, refer to Section 2 in the MicroBoard Advanced Manual.

To start the LCD interface use the commands lcdinit and lcdclear. The command lcdput followed by a string of textwrites to the LCD. To switch between lines on the display, use the lcdline1 or lcdline2 commands.

>> lcdinit - initializes the LCD screen>> lcdput hello - writes “hello” to the LCD>> lcdline2 - move cursor to the first character on second line>> lcdput world!! - writes “world!!” on the second line>> lcdclear - clears the contents of the LCD screen

Page 21: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 17

5.7 DELAY COMMAND

This command is not terribly useful when you are connected to the MicroBoard through HyperTerminal since you, as theoperator, can wait as long as you like between sending commands. The delay command will, however, be of use if you areplanning to send a script of commands to a hardware-flow-control-enabled MicroBoard (see Section 5.9). The commandexpects an 8-bit hexadecimal number and will wait (hh x 10)ms before returning to the prompt.

>> delay 10 - waits 10 x 10ms = 160ms>> delay 8f - waits 8F x 10ms = 1430ms>> delay ff - waits FF x 10ms = 2550ms

5.8 A FEW COMMENTS ABOUT SYNTAX

DEBUG.HEX will only accept commands up to 20 characters long. The only time this limitation may arise is when writingtext to the LCD. Also, keep in mind that the program expects numbers to be in hexadecimal (base 16) format and will returnnumbers in hexadecimal as well. DEBUG.HEX ignores upper-case commands, letters, and hexadecimal numbers.

5.9 UTILIZING HARDWARE FLOW CONTROL

The MicroBoard has been designed such that it is possible to enable hardware flow control (the board’s default state isdisabled). This means that a string of commands can be sent to the PIC all at once (like a script) and the PIC will execute thecommands in the order they were received. In the past, this was not possible and the PIC, when sent a script, would onlyperform a command if it could be taken care of before the next command arrived.

Enabling hardware flow control is a simple matter:

1 Add two 470Ω resistors at positions R33 and R34 beside theMAX232 chip.

2 Solder a wire between the end of the resistor closest to the DB9connector in R34 and pin b1 on the PIC

3 Solder a wire between the end of the resistor closest to the DB9connector in R33 and pin b2 on the PIC.

To create a script, simply save to a text file the set of commands in theorder you would like them carried out. Start a HyperTerminal sessionand select Transfer>Send Text File…. Choose your saved script. Thecommands will be sent to the PIC and performed one by one (seeSection 6.1 for a scripted example).

5.10 PROGRAMMING IN C

An interface program has been written that, when executed, is able to communicate with the MicroBoard using nearly all ofthe commands available in Hosted mode. Since logic structures can be developed in C much more easily than in assemblylanguage, projects that don’t require extreme mobility and thus, don’t require Autonomous mode programming, can simplyuse DEBUG.HEX pre-programmed on the PIC and a C program running on an HP-UX terminal (refer to Patrick Pilarski’sGuide to the HP-UX Systems for a quick tour of the system).

The skeleton interface program was originally written by Dr Chris Backhouse but has gone through various stages ofdebugging and development. If you run into any problems with the original code, please report the problem immediately sothat it can be remedied as soon as possible.

Get the code here: http://www.ee.ualberta.ca/~ee401/debug/both.c

Please note that this diagram is incorrect. The wires are crossed.

Page 22: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 18

6 HOSTED MODE EXAMPLESAs mentioned previously, Hosted mode is a good way to run your MicroBoard through the motions of normal operation. It’sa good idea to make sure that, for example, a certain input will result in the desired output. Or, even simpler, just make surethat your MicroBoard is working. This section has four examples including schematics and the Hosted mode commands tomake it all happen. At the end of this section, there is a short write-up on the GrabberBot, an extremely simple project that canbe run in the Hosted mode.

6.1 FLASHING LEDS

By hooking up some LEDs and attempting to turn them on and off, you can check to make sure your MicroBoard is workingcorrectly. To connect an LED to your board, you’ll need to remove the L293 H-bridge chip closest to the serial port. Insert thepositive lead (it is typically longer than the negative lead) of the LED into pin 10 of the now vacant IC socket; the negative lead(the side with a small flat portion on it) goes to ground (pin 5 of the same socket is fine). This procedure can be used for all ofthe I/O pins on the MicroBoard to test it to ensure the wiring and soldering has been done correctly.

Connect your MicroBoard to a PC, start up HyperTerminal, and power up your MicroBoard in Hosted mode. To flash theLED you need to turn pin c0 into an output using the output command, then you can switch the LED on and off using theset and clear commands:

>> output C0 - sets pin c0 as an output>> set C0 - turns the LED on>> clear C0 - turns the LED off

Still using Hosted mode (and ensuring that your board has hardware flow control enabled; see Section 5.9), you can use ascript to perform the same task. Make a *.txt file containing the following commands and send it to the MicroBoard usingthe Transfer>Send Text File… command. Add as many repetitions as you see fit (don’t include the comments on the right;those are there for your understanding only):

output c0 - sets pin c0 as an outputset c0 - turn LED ondelay 96 - wait for 1.5 secondsclear c0 - turn LED offdelay 96 - wait

set c0 - turn LED on againdelay 96 - waitclear c0 - turn LED offdelay 96 - wait

set c0 - repeat ad nauseumdelay 96clear c0delay 96

When you send the file, you’ll see each command pop up in the terminal window as they are processed (if you leave a line inthe script blank, the MicroBoard will simply skip to the next command).

WARNING! Always make sure that you connect a 470Ω current-limiting resistor in series with an LED! Simply solder an LED onto a

resistor so that you have two free leads. Not using a resistor in serieswill surely destroy the LED and will likely damage the MicroBoard!

Page 23: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 19

To finally beat this example to death, the LED can be controlled using a C program as an interface between you, the user, andthe MicroBoard. Using the general C interface program, both.c (http://www.ee..ualberta.ca/~ee401/debug/both.c), writtenby Dr Backhouse, plop in this main function to automate the process completely:

main ()

// begin initialization routinelong t; int j;struct termios oldtio;Initialize(&comm_port,&oldtio);

// end initialization routine

// begin main codeoutput("c0"); // set pin c0 to output

// this small loop will flash the LED 10 timesfor (j=0;j<10;j++)

set_pin("c0"); // turn on LEDmy_delay(1); // wait one secondclear_pin("c0"); // turn off LEDmy_delay(1); // wait again

6.2 DIGITAL-TO-ANALOG CONVERTER USING PWM

When you have verified that all of the I/O pins on the MicroBoard function properly, you can check to see if the PWMmodule is working by making a simple digital-to-analog converter. Connect the simple RC circuit below with a 10µFcapacitor and a 1.0kΩ resistor:

1.0kΩ

PIC16F87x

AnalogOutput

10µF

RC1orRC2

Figure 6-1: Circuit schematic for DAC using PWM

Choosing two components with the appropriate values forms a low-pass filter with the necessary time constant for creatingan analog signal from the PWM output. The values shown are merely a suggestion; you’ll need to make sure that the PWMperiod is sufficiently short compared to the RC time constant or ripple will be evident. The output of this signal is controlledby the duty cycle of the PWM signal: to increase the voltage, increase the duty cycle and vice versa. Shown below is a set ofcommands that will control the output of the PWM DAC:

>> startpwm1>> pwmperiod ff>> pwmduty1 00 - output will be 0 volts>> pwmduty1 80 - output will be 2.5 volts>> pwmduty1 ff - output will be 5 volts

Page 24: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 20

6.3 USING SPI DEVICES

SPI is a very versatile interface. It is possible to connect multiple SPI devices (DIO, ADC, DAC, DSP, shift registers, etc, etc…)to your MicroBoard and individually communicate with each of them.

Simply connect all the clock lines together, all the input lines to the output of the MicroBoard (pin c5) and all the output linesto the input of the MicroBoard (pin c4) to complete the SPI bus. To choose which device you want to communicate with, youwill need to use the chip select line of the device (connected to a free output pin on the PIC).

To better explain how to do this, we will go through an example using an SPI digital-to-analog converter, specifically theLTC1448, which should be available for you to use. The chip should be connected to the MicroBoard using the following

schematic:

Figure 6-2: LTC1448 circuit schematic

The LTC1448 is a 12-bit, 2-channel DAC utilizing an SPI interface. When you write to the DAC you have to update bothchannels at the same time, which means you have to write 2 x 12 (or 24) bits, with the upper 12 bits corresponding to VoutA andthe low 12 bits corresponding to VoutB. The PIC transfers 8 bits at a time in SPI mode so you will need three write cycles to setthe DAC.

Below is a sequence of Hosted mode commands that will select the DAC, write 24 bits to it, and then deselect it:

>> spiinit - initialize the SPI>> output c2 - sets pin c2 as an output for chip select>> clear c2 - select the LTC1448 (chip select is active low)>> spitrans 12 - send first 8 bits>> spitrans 34 - send next 8 bits>> spitrans 56 - send last 8 bits (for a total 24 bits)>> set c2 - deselect the LTC1448

Notice that the chip select line on the DAC is active low so you need to clear it when you want to select the DAC. Once youhave typed in these commands, the outputs VoutA and VoutB should be 0x123 (1.35V) and 0x456 (0.35V) respectively.

There are many SPI devices available from digital signal processors (ADCs and DACs for example) to memory (RAM andEEPROM’s) to other micro-controllers. There is even an MP3 decoder chip available that uses an SPI interface. Since SPI is aneasily implemented interface, many companies find it advantageous to use it.

PIC16F873LTC1448

1234

CLKDin

CSVREF

5

8

+5V

67

VoutA

VoutB

Vcc

GND

141613C2

C3C5

Chip Select

SCKSDO

Page 25: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 21

6.4 ADDING ADDITIONAL OUTPUTS USING SHIFT REGISTERS AND SPI

By way of the PIC’s SPI interface, you can add additional outputs using 595 shift register chips (eight outputs per chip). Thereare two clever ways to connect and utilize the 595s: one a “series” setup and the other a “parallel” setup (and of course thecombination of the two). The “parallel” method allows you to perform a “chip select” command to choose which chip (or“series” array of chips) you want to control.

The diagram below shows two chips in parallel and a third “series” array also in parallel with the other two chips.

Figure 6-3: 595 Shift Register Schematic

We want to select a chip (or array of chips), send the desired output values (in the form of an 8-bit number, each bitcorresponding to an output pin), then finally activate those values by sending a clock pulse to the chip (or array). Output RC3(pin 14) is the SPI clock and connects to every chip in parallel. Using any available output on the PIC (here we use pins b3, b4,and b5), we can select a chip by making that output low (the 595’s “enable” pin is active low). Output RC5 is where we’llsend a byte of data to the chip we chose. That byte is merely stored in the shift register and does not activate the eight outputsimmediately. To update the outputs, we send a clock pulse to the shift registers by turning output RC0 on and then off.

If there is only one shift register per parallel connection, the byte that is sent moves directly to that chip. If more than one areconnected in series though, the first byte you send moves into the first shift register and the old contents is carried over to thenext shift register. The next byte you send moves into the first register and its old contents (the stuff you just sent in theprevious command) moves to the next one, pushing the really old stuff onto the next chip, or into oblivion if that chip is thelast in the array (as would be the case in the above diagram).

Here are some sample commands to demonstrate how you would control each shift register:

>> spiinit - initializes the SPI>> output c0 - set pin c0 to an output>> clear c0 - make sure c0 is off

>> output b3 - set pin b3 to an output (chip select line)>> output b4 - set pin b4 to an output (chip select line)>> output b5 - set pin b5 to an output (chip select line)

>> set b3 - deselect the first register>> set b5 - deselect the last two registers>> clear b4 - select the second register

>> spitrans 9f - send a byte (10011111) to second register>> set b4 - deselect the second register>> set c0 - send clock pulse to update all registers>> clear c0 - stop clock pulse

74HC595 74HC595

RC5/SDO

RC3/SCK

PIC16F873

RC0

14

16

14

11

14911 1112 1213 13

+5V+5V

10 10

15 1 2 3 4 5 6 7 15 1 2 3 4 5 6 7

8 816 16

74HC5951411 12 13

+5V

10

15 1 2 3 4 5 6 7

816

74HC5951411 12 13

+5V

10

15 1 2 3 4 5 6 7

816

RB3

RB4

RB5

24

25

26

Page 26: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 22

>> clear b5 - select the two-chip array>> spitrans b2 - send a byte to the third register (10110010)>> spitrans 0d - send a byte to the third register (00001101)

- the previous byte gets bumped to the fourth>> set b5 - deselect the two-chip array

>> set c0 - update the registers>> clear c0 - make sure c0 is off for subsequent spitrans

Using pin c4, the SPI input line, one could hook up SPI input devices and use a similar process to select an input device onthe SPI bus and clock data in on the SDI line (pin c4).

6.5 A RUDIMENTARY HOSTED MODE PROJECT: THE GRABBERBOT

Using only DEBUG.HEX without any additionalprogramming, you can design a simple robot that can movearound, grab an object, and move the object to another location.All of this is performed using a few simple commands in theHosted mode. Rig up a robot using the diagram on the right asa reference.

The following sets of commands control the robot; simply typethem in during a HyperTerminal session and, provided you’vehooked everything up properly, the robot should respondaccordingly. Check out the EE401 web site for photos andmovies of the GrabberBot.

NOTE: In all these examples, hh is a hexadecimal number from00 to ff.

6.5.1 USING THE GRABBERBOT IN HOSTED MODE

Initialization

>> pwmstart1>> pwmstart2>> pwmduty1 00>> pwmduty2 00>> output b0>> output b3>> output c0>> output c3

Move Forward

>> pwmduty2 00>> set c0>> set c3>> pwmduty2 hh

Move Left

>> pwmduty2 00>> clear c0>> set c3>> pwmduty2 hh

Move Right

Stop Motion

>> pwmduty2 00

Open Grabber

>> pwmduty1 00>> set b0>> clear b3>> pwmduty1 hh

Close Grabber

>> pwmduty1 00>> clear b0>> set b3>> pwmduty1 hh

Stop Arm

>> pwmduty1 00

NOTE: Reverse motion is not possible with this setup.However, by setting up motor circuits similar to that of the

RC1RC2

RC0RC3

RB0

RB3

PIC16F873

11

1213

14

2124

MicroBoard

- +

63

11

14

1015

72

L293D

- +

- +

GND

RightMotor

LeftMotor

GrabberMotor

Page 27: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 23

>> pwmduty2 00>> set c0>> clear c3>> pwmduty2 hh

grabber arm, you can switch the direction of rotation byreversing the polarity of the leads to the motor.

6.5.2 USING THE GRABBERBOT WITH SCRIPTED FILES

The setup of GrabberBot for scripted file control is simple. Most importantly, make sure your MicroBoard is equipped withhardware flow control; if it’s not, refer to Section 5.9 for instructions.

Create *.txt files containing the commands outlined above and name the file appropriately. You will want to replace the "hh"in the code with a reasonable value. You can change the speed of your motors by sending individual text files configured fordifferent PWM settings.

To send a script to the MicroBoard, connect to the board as you normally would using HyperTerminal. Once the Help Screenappears, select Transfer>Send Text File… Choose the script you want to send and click OK. Once that script finishesexecuting, you can follow the same procedure to execute the next script.

A possible call sequence could look like this: FORWARDfull.txt; LEFTmed.txt; FORWARDmed.txt; STOP.txt;GRABBERopen.txt; FORWARDslow.txt; STOP.txt; GRABBERclose.txt. The robot would move forward, turn a bitleft, slowly crawl toward its target, stop, open its claw, inch forward until the object is in its reach, and then close the claw.Using delay calls and good timing, this could be done with a single large script.

Each script outlined below performs one task, moving the GrabberBot left or right or forward, or controlling the Grabber arm:

INITIALIZATION.txt

pwmstart1pwmstart2pwmduty1 00pwmduty2 00output b0output b3output c0output c3

MOVEFORWARD.txt

pwmduty2 00set c0set c3pwmduty2 hh

MOVELEFT.txt

pwmduty2 00clear c0set c3pwmduty2 hh

MOVERIGHT.txt

Pwmduty2 00Set c0Clear c3Pwmduty2 hh

STOP.txt

pwmduty2 00

OPENGRABBER.txt

pwmduty1 00set b0clear b3pwmduty1 hh

CLOSEGRABBER.txt

pwmduty1 00clear b0set b3pwmduty1 hh

STOPGRABBER.txt

pwmduty1 00

Page 28: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 24

6.5.3 USING THE GRABBERBOT WITH A C PROGRAM

Implementing a C program to control the GrabberBot is likely the easiest and most efficient method. In conjunction with thecode below (get the source file here), you’ll need to be familiar with the HP-UX to MicroBoard interface code, both.c (refer toSection 5.10 for more details).

This is the main code you’ll want to use. It’s effectively a simple user interface similar to that of the HyperTerminalenvironment, although now tailored to the GrabberBot specifically.

main

// begin spi initializationlong t; int j;struct termios oldtio;Initialize(&comm_port,&oldtio);

// end spi initialization

// GrabberBot code begins hereoutput("c0"); // set pins for outputoutput("c3");output("b0");output("b3");

startpwm1(); //start PWM modulesstartpwm2();

pwmduty1(0);pwmduty2(0);

int choice=0;int motorspeed=0;int clawspeed=0;

while(1)

printf("Select an option:\n");printf("-----------------\n");printf("1: Forward\n");printf("2: Stop\n");printf("3: Left\n");printf("4: Right\n");printf("5: Open Claw\n");printf("6: Close Claw\n");printf("7: Stop Claw\n");printf("8: Change Wheel Speed\n");printf("9: Change Claw speed\n");printf("0: Exit\n\n")

printf("What is your choice?");cin >> choice;

if ( choice == 0 ) break; // exit on 0

switch (choice)

case 1:pwmduty2(0); //set duty cycle to 0set_pin("c0"); //set pinsset_pin("c3");pwmduty2(motorspeed); //set motor speed pwmbreak;

case 2: // stop motorspwmduty2(0);break;

case 3: // move leftpwmduty2(0);clear_pin("c0");set_pin("c3");pwmduty2(motorspeed);

Page 29: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part II – Getting Started: Hosted Mode Page 25

break;case 4: // move right

pwmduty2(0);set_pin("c0");clear_pin("c3");pwmduty2(motorspeed); break;

case 5: // open grabberpwmduty1(0);set_pin("b0");clear_pin("b3");pwmduty1(clawspeed);

break;case 6: // close grabber

pwmduty1(0);clear_pin("b0");set_pin("b3");pwmduty1(clawspeed);break;

case 7: // stop grabberpwmduty1(0);break;

case 8: // change motor speedprintf("\nWhat speed (0-100)?");cin >> choice;motorspeed=choice;break;

case 9: // change grabber speedprintf("\nWhat speed (0-100)?");cin >> choice;clawspeed=choice;break;

default:printf("unknown command");break;

Hook up the HP-UX's serial cable, compile the interface program (with your new main function shown here) with g++ oranother compiler, and run the new executable. Enter the commands to operate the GrabberBot.

Page 30: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 26

Part IIIBeyond Getting Started: Autonomous Mode

and Advanced Programming Techniques

Page 31: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 27

7 AUTONOMOUS MODEUsing the MicroBoard in Autonomous mode is a much more powerful manner of doing things and will let you unleashits full potential, but you’ll likely need to get your fingers a little bit dirty and play around with some real, live assemblycode. Before reading any further, you are advised to browse through the PIC16F87x data sheet(http://www.ee.ualberta.ca/~ee401/datasheets/PIC16F87x.pdf); what follows is intended to supplement that data sheet.

Use MPLAB (Start>Programs>Microchip MPLAB>MPLAB) to write and compile your code. If you’d like to downloadMPLAB, it is available on the EE401 web site at http://www.ee.ualberta.ca/~ee401/software/microchip/MPL51100.exe.

The following will introduce several concepts involved in developing systems using the PIC, specifically assemblylanguage code structure and intricacies using MPLAB, digital I/O, and downloading your code to the PIC itself.

Before parsing through this section, make sure you are familiar with assembly language basics and the PIC instruction set,available in the aforementioned data sheet.

Notes: bold words denote registers, bits, and op-codes

foo and bar can be any built-in or user-defined register

Fosc is the global clock frequency

7.1 PIC PROGRAMMING

The PIC micro-controller uses a RISC-based architecture with only 35 commands (described in detail in the PIC datasheet). There are three distinct memory regions onboard the PIC: register memory, program memory, and EEPROMmemory. Register memory is used in virtually every operation; program and EEPROM memory are generally notaccessed by user programs.

There are six important sections of memory in the PIC16F873:

Memory Section Address Range Notes

Bank0 Registers 000h-07Fh RMem Use RP1=0 and RP0=0 in STATUS register to select.

Bank1 Registers 080h-0FFh RMem Use RP1=0 and RP0=1 in STATUS register to select.

Bank2 Registers 100h-17Fh RMem Use RP1=1 and RP0=0 in STATUS register to select.

Bank3 Registers 180h-1FFh RMem Use RP1=1 and RP0=1 in STATUS register to select.

Page0 Program Memory 0000h-07FFh PMem 0000h is RESET vector; 0004h is INTERUPT vector

Page1 Program Memory 0800h-0FFFh PMem Use PCLATH to switch between program memory pages.

Table 7-1: Memory Sections and Address Ranges

7.1.1 REGISTER OPERATIONS

All but eight of the available assembler op-codes utilize register memory. There are 512 addressable registers (memorylocations) available on the PIC. These registers are divided into four 128-byte-sized pages. The pages are selectable usingthe RP0 and RP1 bits in the STATUS register (as shown above).

Although there are 512 addressable registers, several special registers are available on all four pages to simplifyprogramming: W, INDF, PCL, STATUS, FSR, PCLATH, and INTCON.

There is also a section of general purpose RAM available on all four pages in the range 70h to 7Fh as well as F0h to FFh,170h to 17Fh, and 1F0h to 1FFh.

Page 32: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 28

NOTE: Many of the register locations are reserved and should not be used by the users program and general-purposestorage. See the memory map in Figure 2-3 of the PIC data sheet for more details.

There are two methods of addressing memory: direct and indirect mode. Direct mode is bound by the values of the RP0and RP1 bits and can only address the currently selected register page. This is the normal mode where individualoperations can access separate registers using commands such as

clrf foo ; set all bits of variable foo to ‘0’

The other method of accessing registers does not depend on the value of RP0 or RP1, instead IRP is used to select either therange 00h to FFh or 100h to 1FFh. Using the indirect addressing method, the lower byte of the address of the register to beaccessed is written into the FSR register. On the next instruction cycle the contents of the selected register are available inthe INDF register, ready for reading or writing.

To access a variable using this method you could use the following code:

movlw bar ; put address of bar into Wmovwf FSR ; copy address of bar to FSRclrf INDF ; clear contents of bar

Obviously, the direct addressing method is faster. When it is necessary to move data from one page to another, however,the indirect method is much faster than the direct method.

7.1.2 MATHEMATICAL OPERATIONS

Since the PIC is RISC-based, there are very few mathematical operations available. For example, there are no hardwarefloating-point operations, or even multiplication or division for that matter. Two add and two subtract instructions areavailable though. If you require this functionality in your code, Microchip does offer some software emulation libraries forthese operations (check out the subset of pertinent project ideas on the Project Suggestions page of the EE401 web site).

One tricky part when using the built-in math operations lies in the subtraction op-codes sublw and subwf. Care must betaken when using these operations to ensure that the operation performed is indeed the operation desired.

Example:

subwf foo,W ; W = foo - Wsublw d’30’ ; W = 30 – W

The first command is fairly straightforward; the second, on the other hand, can be counterintuitive.

An alternative to actually performing the calculations is a look-up table. For example, instead of performing the samecalculation over and over, a Celsius to Fahrenheit conversion table could be made listing all the corresponding Fahrenheittemperatures for 0 to 100ºC. Choose a method that will work best for your particular application.

7.1.3 FLOW CONTROL

There are four op-codes that provide conditional branches: btfss, btfsc, incfsz, and decfsz. The first two test a singlebit in a register and skip the next instruction depending on the instruction used and the value of the bit. The last twoincrement and decrement the operand, respectively, and skip the next instruction if the value of the register after theoperation is zero.

Three examples of code are shown below to demonstrate commonly used comparison operations:

Page 33: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 29

To test foo == bar:movf foo,W ; load foo into Wsubwf bar,W ; subtract foo from barbtfss STATUS,Z ; check if result is zerogoto FALSE ; condition is falsegoto TRUE ; condition is true

To test if foo > bar:movf foo,W ; load foo into Wsubwf bar,W ; subtract foo from barbtfsc STATUS,C ; C is clear if borrow occurredgoto FALSE ; condition is falsegoto TRUE ; condition is true

To test if foo <= bar:movf foo,W ; load foo into Wsubwf bar,W ; subtract foo from barbtfss STATUS,C ; C is set if borrow didn’t occurgoto FALSE ; condition is falsegoto TRUE ; condition is true

The values of foo and bar are being compared: if the condition being tested is true, the program will jump to the labelTRUE; otherwise, it will jump to the label FALSE.

7.2 DIGITAL I/O PORTS

Eventually, when you want the PIC to communicate with other hardware, the I/O ports will come in handy.

The PIC you are using has one 6-bit data port (PORTA) and two 8-bit data ports (PORTB and PORTC) for a total of 22 general-purpose I/O lines. Each port is controlled using two registers: TRISx determines the data direction and PORTx is the datatransfer buffer (where x is one of A, B, or C). By setting a bit in a TRISx register the associated pin becomes a high-impedance input; the input can be read using the corresponding bit in the PORTx register.

Clearing a bit in the TRISx register turns the pin into an output; the output level can be changed by writing to the relatedbit in the PORTx register. These registers can be written to/read from using both single bit and word length operations.Shown below is a table describing the data registers used for I/O operations:

Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Function

05h PORTA RA5 RA4 RA3 RA2 RA1 RA0 Data Transfer

85h TRISA PORTA Data Direction Register Transmit/Receive Selection

06h, 106h PORTB RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0 Data Transfer

86h, 186h TRISB PORTB Data Direction Register Transmit/Receive Selection

07h PORTC RC7 RC6 RC5 RC4 RC3 RC2 RC1 RC0 Data Transfer

87h TRISC PORTC Data Direction Register Transmit/Receive Selection

Table 7-2: I/O Port Registers

Page 34: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 30

The following code demonstrates I/O operation using the same example as in the hosted mode: turning an LED on andoff. Unfortunately, the human eye will not be able to see the LED flashing since the frequency is about 250 kHz. You canuse an oscilloscope to view the output though:

startbsf STATUS,RP0 ; switch to register page 1bcf TRISC,0 ; make RC0 an outputbcf STATUS,RP0 ; switch back to page 0

loopbsf PORTC,0 ; turn LED onbcf PORTC,0 ; turn LED off

goto loop

end

7.3 LIMITATIONS

As mentioned previously, the PIC has a limited set of functions. There are no multiply or divide instructions available andthere is no floating-point math either.

The PICs you were given are rated to run at 4MHz; this may prove to be too slow if you are making any processorintensive applications. A 20MHz version is available, however.

There are 192 bytes of RAM and 128 bytes of EEPROM available on the PIC. For most applications that should be plenty,but it may not be enough for storing large amounts of data. Additional memory chips can be connected to the PIC shouldthe need arise.

Page 35: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 31

8 DEBUG.HEXIf you require Autonomous mode (many will), you’ll need to either write your program from scratch, or modify anexisting program. DEBUG.HEX contains many subroutines that you can reuse in your own project. As long as you’refamiliar with the PIC instruction set and the basics of assembler language, programming the PIC to suit your needs shouldbe a relatively painless procedure: just simply call the subroutines that have already been written for you. The majority ofthe grunt work has been done; it’s up to you, however, to design the logic structure of your program.

DEBUG.HEX is described below. You can get the full source code on the EE401 web site(http://www.ee.ualberta.ca/~ee401/debug/debug.asm).

8.1 CODE MAP

DEBUG.HEX is divided up into four main parts:

1 Variable and constant declarations: It will be important to look at this section in conjunction with any codesamples from DEBUG.HEX you choose to copy to make sure you also copy any required variables and constantsinto your code.

2 Command input subroutines (user interface display and parsing): This code displays a prompt on the terminalscreen, allows a user to type in a command and input data, then calls for its execution. If the command isrecognized then the appropriate calls are made to command subroutines in the next section of code to execute thecommand. The interface section contains general interface code and a set of subroutines starting with the word“parse_”. If a command is not recognized then “Unknown Command” is displayed on the terminal screen andthe prompt is redisplayed. This code is useful to examine, but unless you are planning an interactive user interfacefor your project, it is unlikely you will need to understand the details of this section. Given that a valid commandis entered, the command is stored in ASCII format in a set of variable locations starting at the “input” variablelocation in the first bank of register memory.

3 Command execution subroutines: The names of these subroutines each begin with the letters “cmd_”. Thesesubroutines serve two purposes: The first is to parse the input data included with many of the commands toidentify incorrect input data and to use that data to make the appropriate call to the implementation subroutinesin the next section. The second is to display the results of the call to the implementation subroutines. Though youwill probably want to write your own code to call the implementation subroutines, the code here will give you agood example of what you’ll need to do to call commands in an appropriate order and set variables to requiredvalues.

4 Low-level device implementation subroutines: These routines initialize and manipulate the registers and datanecessary to perform a desired process in the PIC processor. All these subroutines are located in the upper page ofprogram memory. Though most of the code in this section does not need to be changed to include it into a usersprogram, several of the routines contain display components that the user may want to change or delete. Notethat the routines putUART and putHexByteToTerm sends data contained in W to the terminal and can bereplaced by user code that performs operations on this data or transfers it to other variables for later use.

Parts 1 through 3 are located in the lower memory page (page 0 for both devices), and part 4 is located in the uppermemory page (page 1 for the PIC16F873 and page 3 for the PIC16F877).

Keep in mind that DEBUG.HEX contains much programming dedicated to receiving and parsing input in Hosted mode.Thus, there is a lot in DEBUG.HEX that you simply will not need since a project running in Autonomous mode doesn’treceive any user input. Make sure you understand what something does before you cut it out of the program though;everything can be pieced back together if you lose something, but this is time consuming and, of course, causes unwantedfrustration. You can safely cut Parts 2 and 3 without any lost functionality (save for communication via Hosted mode). If

Page 36: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 32

you are planning to do a lot of low-level programming, you may consider starting with the Autonomous flashing LEDcode outlined in Section 9.2.

8.2 UPPER-PAGE SUBROUTINES

These are the subroutines you will be calling. Each is listed with its description, what it receives, what it uses, and what itreturns.

8.2.1 GLOBAL SUBROUTINES

initializeChip

Sets specific registers on startup. Sets port A to all digitalI/O. Clears and sets all ports to digital output.

Receives: nothingUses: WReturns: nothing

8.2.2 UART MODULE SUBROUTINES

initializeUART

Initializes the UART. Receives: nothingUses: WReturns: nothing

getUART

Gets a byte from the Rx line and stores it in W. Receives: nothingUses: WReturns: W (ASCII value read from terminal)

putUART

Puts the byte in W on the Tx line. Receives: W (ASCII value read from terminal)Uses: WReturns: nothing

8.2.3 ADC MODULE SUBROUTINES

initADC

Initializes RA0 as an ADC input. Sets the (right justified)data flag.

Receives: nothingUses: WReturns: nothing

readADCX

Initiates a read of AN<X> as an ADC which stores its valuein ADRESH, and ADRESL (right justified). The X value is anumber from 0 to 4 and is located in W prior to call.

Receives: W (port pin to read)Uses: WReturns: nothing

8.2.4 PWM MODULE SUBROUTINES

The “X” in these commands can be either 1 or 2, referring to one of the two PWM outputs (PWM1 is on RC2 while PWM2is on RC1).

startPWMX

Starts output on PWM1 (pin RC2) or PWM2 (pin RC1).Defaults the period and duty cycle to ff/50% respectively.

Receives: nothingUses: WReturns: nothing

stopPWMX

Stops output on the PWM1 (pin RC2) or PWM2 (pin RC1). Receives: nothing

Page 37: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 33

Uses: WReturns: nothing

setPWMDutyX

Sets the value of the duty cycle on the PWM1 (pin RC2) orPWM2 (pin RC1). The value must be less than the value ofthe period or the duty cycle will be 100%. The duty cycle isdetermined by the ratio: duty/period = % duty cycle

Receives: WUses: WReturns: nothing

setPWMperiod

Sets the value of the period on both PWM pins. The valuecan be 0 to 0xFF and is the value of the period of bothPWM pins. This is because the PIC circuit uses Timer 2 toset the period for both pins.

Receives: WUses: WReturns: nothing

8.2.5 SPI MODULE SUBROUTINES (MASTER MODE ONLY)

initializeSPI

Initializes the SPI pins. The communication protocol is set toperform data transfer on a rising edge clock. See thePIC16F87x data sheet and the Mid-Range PIC Manual tosee how to modify code to other protocols.

Receives: nothingUses: WReturns: nothing

transferSPI

Performs concurrent send and receive data transfer overthe SPI pins.

Receives: W (data to be sent)Uses: WReturns: W (data received)

8.2.6 LCD MODULE SUBROUTINES

initializeLCD

Initializes the LCD to run an Optrex 2x20 LCD display overthe SPI. Refer to Section 4.1 of the MicroBoard AdvancedManual for hookup diagrams and other important details.

Receives: nothingUses: W, tempReturns: nothing

sendLCDChar

Sends an ASCII character contained in W to the SPI. Receives: WUses: W, char, tempReturns: nothing

sendLCDCmd

Sends a command byte contained in W to the LCD on theSPI.

Receives: WUses: W, char, tempReturns: nothing

LCDDelay

Performs delays during LCD initialization. Receives: W (multiplier of the 1ms delay)Uses: W, DCOUNT1, DCOUNT2, DCOUNT3Returns: nothing

8.2.7 PROGRAMMING MODULE SUBROUTINES (ONLY AVAILABLE ON THE PIC16F877)

initializeProgrammer

Initializes the chip to program an external application PIC(refer to the MicroBoard Advanced Manual for moreinformation on programming).

Receives: nothingUses: nothingReturns: nothing

Page 38: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 34

setHighVoltageProgrammingMode

Places an external application PIC connected to theMicroBoard into programming mode using the standardICSP (In-Circuit Serial Programming) method. See theMicrochip application notes on ICSP for more information.

Receives: nothingUses: W, tempReturns: nothing

setLowVoltageProgrammingMode

Places an external application PIC connected to theMicroBoard into programming mode using the low-voltage ICSP (In-Circuit Serial Programming) method. Seethe Microchip application notes on ICSP for moreinformation.

Receives: nothingUses: W, tempReturns: nothing

programmingPrompt

Displays a “Send File…” prompt on the terminal whenwaiting for a *.HEX file during programming.

Receives: nothingUses: nothingReturns: nothing

clearProgrammingMode

Sets the external application PIC (the one that was justprogrammed) into a standard running mode afterprogramming.

Receives: nothingUses: W, tempReturns: nothing

beginProgramming

Decodes a *.HEX file and transfers it to the programmemory of an external application PIC.

Receives: nothingUses: W, temp, appPCLow, appPCHigh, byteCount,lineCheckSum, addressHigh, addressLow, recordType,DCOUNT1, DCOUNT2, addrIncrementLow,addrIncrementHigh, hexOutDataHigh, hexOutDataLow,hexDataHigh, hexDataLowReturns: W (1 on error)

sendProgrammerDataSends a 14-bit word (plus start and stop bits) to the memoryof an external application PIC.

Receives: hexOutDataHigh, hexOutDataLowUses: W, temp, hexOutDataHigh, hexOutDataLowReturns: nothing

receiveProgrammerData

Receives a 14-bit word (plus start and stop bits) to thememory of an external application PIC. NOTE: Thisfunction is not yet implemented in the user interface.

Receives: nothingUses: W, temp, hexOutDataHigh, hexOutDataLowReturns: hexInDataHigh, hexInDataLow

sendProgrammerCommand

Sends a 6-bit word to an external application PIC. Receives: hexOutDataLowUses: W, temp, hexOutDataLowReturns: nothing

8.2.8 PROGRAMMING UTILITY SUBROUTINES

getHexByteFromTerm

Reads two ASCII bytes from the terminal and creates a hexbyte, which is stored in W.

Receives: nothingUses: W, tempReturns: nothing

setProgHex

Converts an ASCII hex value in W to a binary value andreturn it in W.

Receives: WUses: WReturns: W

Page 39: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 35

putHexByteToTerm

Converts a two-digit hex value in W into 2 ASCII valuesand send them to the terminal.

Receives: WUses: W, tempReturns: W

programmerDelay

The programmer delay is a fixed delay used only by theprogramming subroutines.

Receives: nothingUses: W, DCOUNT1, DCOUNT2Returns: W

8.2.9 HELP FUNCTION

help

Displays the Help Screen to the terminal. Reads “=” as rowof “-” and “0” as END.

Receives: nothingUses: W, DCOUNT1Returns: nothing

8.2.10 IR MODULE SUBROUTINES

getIR

Function subroutine to do an example of reading the inputfrom a universal TV remote on RB0 and displaying it to theterminal. NOTE: The program will wait indefinitely untilsome signal is received.

Receives: nothingUses: W, IRCOUNTER, BYTE1, BYTE2, BYTE3Returns: BYTE1, BYTE2, BYTE3

Page 40: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 36

9 YOUR FIRST PIC ASSEMBLY CODE PROJECTTo get you started writing code as quickly as possible, step-by-step instructions are given describing how to create a newproject. You will also find a skeleton code template for your use.

9.1 GETTING STARTED WITH MPLAB1 Start MPLAB (Start>Programs>Microchip MPLAB>MPLAB).2 Select File>Open and select c:\progra~1\mplab\template\code\f873temp.asm.

Figure 9-1: The MPLAB IDE environment.

3 Select File>Save As… and save the template as your own file. You will be editing the code in this file and comingback to it often so choose an appropriate file name and directory.

4 Select Project>New Project. Choose a file name and save it to the same directory as in Step 3. The project and theproject’s files must be in the same directory.

Page 41: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 37

5 In the Edit Project window, click the Change… buttonnext to Development Mode. Under the Tools tab, chooseMPLAB-SIM Simulator. For Processor choosePIC16F873. Click OK.

6 Click on your file in the Project Files window (it will be“yourfilename [.hex]”) and click Node Properties.

Figure 9-2: The Edit Project window

7 Set all the options in the Node Properties window as shown in Figure 9-3. Click OK when you’re finished.

Figure 9-3: The Node Properties window

8 Select the file you created and click Add Node to add your file to your project.9 Click OK to leave the Edit Project window.

Page 42: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 38

You now have a working piece of code that you can build onto. When you are ready to assemble your program click onProject>Build All.

9.2 THE PIC16F87X ASSEMBLY TEMPLATE

We will write a program in assembler that will flash an LED on and off whenever a push button is pressed. The LED willbe connected to RC0 (PORTC, bit 0) in series with a resistor (refer to Section 6.1), and the push button will be connected toRC1, (PORTC, bit 1). Let us start by examining the code template you saved earlier. The first block contains notes on usingthis template, identifies the code and other files used with this file, and includes a section for notes (the complete sourcecode, without interjections, can be found at http://www.ee.ualberta.ca/~ee401/examples/ee401a.asm).

***********************************************************************; This file is a basic code template for assembly code generation *; on the PICmicro PIC16F873. This file contains the basic code *; building blocks to build upon. *; *; If interrupts are not used all code presented between the ORG *; 0x004 directive and the label main can be removed. In addition *; the variable assignments for 'w_temp' and 'status_temp' can *; be removed. *; *; Refer to the MPASM User's Guide for additional information on *; features of the assembler (Document DS33014). *; *; Refer to the respective PICmicro data sheet for additional *; information on the instruction set. *; *; Template file assembled with MPLAB V4.00 and MPASM V2.20.00 *; *;**********************************************************************; *; Filename: EE401a.asm *; Date: June 6, 2001 *; File Version: 1.0 *; *; Author: Ben Bathgate *; Company: UofA EE401 project course *; *;**********************************************************************; *; Files required: p16f873.inc *; *;**********************************************************************; *; Notes: This program will turn on and off a LED connected to RC0 *; if RC1 is at a logic high *; *;**********************************************************************

Take a look at p16f873.inc to see how the assembler converts labels to register addresses and arguments.

list p=16f873 ; list directive to define processor#include <p16f873.inc> ; processor specific variable definitions

When you programmed your PIC with the Host program in Part II, you were shown how to manually set theconfiguration bits. This is how to set them in your code. Change your code as below (note the changes made):

__CONFIG _CP_OFF & _WDT_OFF & _BODEN_ON & _PWRTE_ON & _XT_OSC & _WRT_ENABLE_ON &_LVP_OFF & _CPD_OFF

Page 43: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 39

; '__CONFIG' directive is used to embed configuration data within *.asm file.; The labels following the directive are located in the respective *.inc file.; See respective data sheet for additional information on configuration word.

These are variables and their register address assignment. w_temp resides in register memory location 0x20. This is the firstlocation of the General Purpose Registers (data RAM). Add three more variables as shown (temp0, temp1, andtemp2):

;***** VARIABLE DEFINITIONSw_temp EQU 0x20 ; variable used for context savingstatus_temp EQU 0x21 ; variable used for context savingtemp0 EQU 0x22temp1 EQU 0x23temp2 EQU 0x24

;**********************************************************************ORG 0x000 ; processor reset vectorclrf PCLATH ; ensure page bits are clearedgoto main ; go to beginning of program

Comment out this section or delete it (it has been deleted in the source code file):

; ORG 0x004 ; interrupt vector location; movwf w_temp ; save off current W register contents; movf STATUS,w ; move status register into W register; bcf STATUS,RP0 ; ensure file register bank set to 0; movwf status_temp ; save off contents of STATUS register

; isr code can go here or be located as a call subroutine elsewhere

; bcf STATUS,RP0 ; ensure file register bank set to 0; movf status_temp,w ; retrieve copy of STATUS register; movwf STATUS ; restore pre-isr STATUS register contents; swapf w_temp,f; swapf w_temp,w ; restore pre-isr W register contents; retfie ; return from interrupt

main

This is where our code goes. Fill-in the following:

bsf STATUS,RP0 ; change to register bank 1bcf STATUS,RP1movlw b’11111110’ ; binary value, 1 bit per port bitmovwf TRISC ; RC0 set to digital output,

; all other PORTC as inputsbcf STATUS,RP0 ; change to register bank 0

LOOPbtfsz PORTC,1 ; test status of bit1 of PORTCbsf PORTC,0 ; if high, set PORTC bit 0, turn on LEDcall onesec ; call one second delay routinebcf PORTC,0 ; clear PORTC bit 0, turn off LEDcall onesec ; call one second delay routinegoto LOOP ; loop infinitely turning LED on and off

End of main program code, one second delay subroutine follows:

onesec ; one second delay subroutinemovlw d’100’ ; decimal value one hundredmovwf temp0 ; load value d’100 into variable temp0movlw d’13’movwf temp1 ; load value d’13 into variable temp1

Page 44: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 40

movlw d’250’movwf temp2 ; load value d’250 into variable temp2

onesec_adecfsz temp2,F ; decrement temp2 by 1, result in temp2goto onesec_a ; innermost loopdecfsz temp1,F ; decrement temp1 by 1, result in temp1goto onesec_a ; middle loopdecfsz temp0,F ; decrement temp0 by 1, result in temp0goto onesec_a ; outer loopreturn ; return from subroutine

END ; assembler directive 'end of program'

After the END directive, the assembler stops looking at the file. Any code after this point is ignored. Save and compile thisprogram.

Page 45: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 41

10 MPLAB SIMULATORMPLAB has a built-in microprocessor simulator. If you compile assembly code you can test its operation by simulatingwhat it does. The simulator is designed to step through your code to view registers, stimulate pins, etc… to debug yourcode. Remember, however, the simulator does have limitations.

10.1 USING THE SIMULATOR TO TEST CODE

1 After starting up MPLAB, select menuOptions then Development Mode.

2 Set the development mode to MPLAB-SIMSimulator.

3 Select menu Window then ProgramMemory. This shows the current programmemory.

Figure 10-1: Development Mode Dialog Window

A quick breakdown of Figure 10-2:

The first column (1-27 shown here) is the linenumber.

The second column, 0000 through 001A, is theprogram memory address.

The third column is the machine code, thebinary microprocessor control code and passedparameter.

The fourth column is for labels (currentlytruncated to six characters).

The fifth column shows the assemblerinstruction.

The last column shows the parameters passedto the machine instruction in hexadecimal.

Note that the first memory location, 0000, holdsan instruction to clear location hex’A’. Thesecond memory location holds a goto main

(“main” is at memory location 0002). Memorylocation 0014 holds a goto onesec_a. See thatthe first part of the instruction 28 of 2813 is thegoto and the second half is the memory location0013.

Figure 10-2: Program Memory Window

Page 46: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 42

4 From the pull-down menu, select Window>SpecialFunction Registers to open the Special FunctionRegister Window (Figure 10-3). This window allowsus to see the PORTC port.

Figure 10-3: Special Function Register Window

Figure 10-4: Asynchronous Stimulus Dialog

5 Select Debug>Simulator Stimulus>AsynchronousStimulus to open the Asynchronous StimulusDialog window. This window enables you to assigna pin to a button.

6 Right-click on the Stim 1 (P) button and select AssignPin. The Pin Section window will appear. Double-click on RC1. You have just assigned a pin to thebutton.

7 Now we want to assign an action to the button. Right-click on the RC1 (P) button in the AsynchronousStimulus Dialog window and select Toggle.

8 Move both the Special Function Registers andAsynchronous Stimulus Dialog windows to allowyou to view these along with your source file.

Page 47: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 43

Figure 10-5: MPLAB Simulator environment

9 Next, we’ll start stepping through your code. Press F6 (Reset) or select Debug>Run>Reset. If you feel you need tostart over at any time, just press F6.

10 In your “source file” a line is highlighted indicating the next instruction to be executed. The highlighted text should beclrf PCLATH.

11 In the Debug>Run>Step window you will notice F7 single steps through your program. Slowly step through yourprogram by repetitively pressing F7. Note that the PCL register is highlighted in red as the simulator steps through theprogram memory and changes to the program memory location (the value is the location highlighted in the ProgramMemory Window).

See menu Debug>Run for running, stopping, single stepping, and reset commands.

Set breakpoints by right clicking on a line of code, and selecting Breakpoint.

The stopwatch under Window>Stopwatch is useful for timing how long code takes to run. Set breakpoints before andafter, then run it.

Other important areas not covered here include Trace, Arm Counter, Stimulus from a File, and Environment Setup.These items are explained in the MPLAB Users Guide, the MPLAB Help Files, and on the Microchip web site(http://www.microchip.com). The simulator is also discussed in Microchip’s PICSTART PLUS Mechatronics GettingStarted Guide (http://www.ee.ualberta.ca/~ee401/reference/PICmech.pdf).

Page 48: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 44

11 USING THE DEBUG.HEX CODEThe best way to think about designing your project should include a very minimal amount of programming. Thefollowing are two examples using the ADC input and the SPI respectively. Only a few changes have been made toDEBUG.HEX providing you with full functionality.

11.1 THE ADC LINES

Writing a program to access the analog-to-digital converter will require you to read the section in the PIC16F87x datasheet. There is a simple method that must be followed to set registers so the required pin is set as an analog input. Unlikesetting a single pin as a digital input or output, the entire port A must be configured all at once which allows some but notall pin combinations. The ADCread command takes the value in W as the AN port number where the input is read. Thechanges to the original routines are have been colour coded: the original code is shown in pink and the replacement codeis shown in green. Other notable changes that may not be obvious are highlighted in red. The following is a code exampleusing the provided ADC subroutines in the debug code.

;************************************************************************; Program Header; - Documentation about your program is very important for not ; only your information but also to guide the person marking your project; through your thought process.;; The following program is a simple version of a volt meter. The ; program takes analog input from RA1 and displays a binary readout on ; the 8 Port B pins. The input is a voltage from any supply between GND; and VCC. It is wise to use a current limiting 470 Ohm resistor on the input.; The output from each pin can be run through a 470 Ohm resistor- LED pair; or collectively as the input to an LED digit display.;;************************************************************************; Filename: ADCsample.asm; Start Date: July 10, 2001; Last Revision Date: July 11, 2001; File Version: 1.0;; Author: Michael Cumming; Company: University of Alberta;************************************************************************; Files required: P16F873.inc; 16F873.lkr;************************************************************************; Notes:;************************************************************************

list p=16f873 ; list directive to define processor#include <p16f873.inc> ; processor specific variable definitions

; '__CONFIG' directive is used to embed configuration data within .asm file.; The labels following the directive are located in the respective .inc file.; See respective data sheet for additional information on configuration word.

__CONFIG _CP_OFF & _WDT_OFF & _BODEN_OFF & _PWRTE_OFF & _XT_OSC &_WRT_ENABLE_ON & _LVP_OFF & _DEBUG_OFF & _CPD_OFF

errorlevel -302 ; These remove unwanted warningserrorlevel -305 ; from the compile information listingerrorlevel -306

;***** VARIABLE DEFINITIONS;**** General Variableschar EQU 0x20newData EQU 0x21

Page 49: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 45

;********* CONSTANTS *************

;** Directive Data ConstantsBANK0 EQU 0x0000BANK1 EQU 0x0080BANK2 EQU 0x0100BANK3 EQU 0x0180

PAGE0 EQU 0x0000PAGE1 EQU 0x0800PAGE2 EQU 0x1000PAGE3 EQU 0x1800

TRUE EQU 1FALSE EQU 0

;**********************************************************************ORG 0x000 ; processor reset vectorclrf PCLATH ; ensure page bits are cleared

goto main ; go to beginning of program

main

startbanksel BANK1clrf TRISB ; Port B is used as an output displaybanksel BANK0clrf PORTB

pagesel PAGE1call initADC ; Call to ADC init. routine in Page1 of Program memorypagesel PAGE0

mainLooppagesel PAGE1movlw 0x01call readADC ; An AD conversion is done on AN1 and the resultpagesel PAGE0 ; is returned in the newData variable.

movf newData,W ; The newData value is displayed on Port Bmovwf PORTB

goto mainLoop ; Repeat main loop

;****************************************************************;*** PAGE 1 Subroutines;****************************************************************

org PAGE1;****************************************************************

;*******************************************************************; ADC Module Subroutines;*******************************************************************

;*******************************************************************; Function subroutine to initialize RA0 as an ADC input.; Sets the (right justified) data flag.; receives: nothing; uses: W; returns: nothing;*******************************************************************initADC

banksel BANK1 ; Move to Bank 1

; movlw 0x82 ; Set all AN pins on Port A as analog; and right justify data in ADRESH and ADRESL

movlw 0x02 ; Set all AN pins on Port A as analog

Page 50: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 46

; and left justify data in ADRESH and ADRESL; See page 111 and 112 of the PIC16F87x data sheet for; details on ADCON0 and ADCON1

movwf ADCON1

banksel BANK0 ; Move to Bank 0

movlw 0x01 ; Shutoff all ADC function and set defaultmovwf ADCON0 ; selected channel to A0

; Also selects: A/D clock = Fosc/2

movf PORTA,W ; Initialize Port A values to 0andlw 0x10movwf PORTA

banksel BANK1 ; Set to bank1bcf PIE1,ADIE ; Disable A/D interrupt

movf TRISA,W ; Initialize Port A Analog ANs to inputsiorlw 0x2fmovwf TRISA

banksel BANK0 ; Move to Bank 0

bcf PIR1,ADIF ; Clear A/D interrupt flag

return

;*******************************************************************; Function subroutine to initiate a read of ADC port pins; which stores its value in ADRESH, and ADRESL (right justified); receives: W - <0 to 4> pin to read; uses: W, char; returns: nothing;*******************************************************************readADC

movwf char

swapf char ; Move input value into the ADCbcf STATUS,C ; pin selection bitsrrf charbsf char,0 ; Set the enable bit 0movf char,W

movwf ADCON0

bsf ADCON0,GO ; Start A/D conversion (sets bit 2)

btfsc ADCON0,GO ; Repeat until the GO bit is automaticallygoto $ - 1 ; set low by hardware

bcf PIR1,ADIF ; Clear A/D interrupt flag; Values are now stored in ADRESH and ADRESL

; movlw d'13' ; Print Carriage return; call putUART; movlw d'10' ; Print Line Feed; call putUART; movlw 'V'; call putUART; movlw 'a'; call putUART; movlw 'l'; call putUART; movlw '='; call putUART

Page 51: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part III – Beyond Getting Started: Autonomous Mode and Advanced Programming Techniques Page 47

movf ADRESH,W ; ADC value is10 bits and is; stored in the ADRESH and ADRESL; The top 8 bits of the value are moved to W

; call putHexByteToTerm ; registers when a read is; conducted.

; banksel BANK1; movf ADRESL,W; banksel BANK0

; call putHexByteToTerm

return

END ; Directive 'end of program'; Code reaching this point may perform erratically.

Page 52: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 48

Part IVExamples: Both Simple and Complex

Page 53: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 49

12 WORKING EXAMPLESThis is the beginning of the last section. Contained are a number of examples with code available for your use as either acomplete operational module or a starting point for your own ideas.

With the exception of the Motor Speed Controller and the Shaft Encoder, all of these examples should be functional inboth Hosted mode and Autonomous mode.

12.1 SERVO MOTORS

Using the PWM output of the MicroBoard, it ispossible to control a servo. Most servos operatesafely when the period of the input signal isbetween 10 to 30ms; unfortunately, the built-inPWMs on the MicroBoard can only output amaximum 4ms period. Normally, one would usean actual servo controller to attain the desiredperiod. This setup should work with some servosbut may produce undesirable effects with others. Ifyou’d like to use servos in your project and have aguarantee that they’ll work properly, design yourown functions and timers such that the servo will function within its safe operating range.

The servo receives a 0.5 to 2.5ms pulse every 10 to 30ms (or 4ms in this case). The values between 0.5 and 2.5 correspond toa different angle of the servo arm. The 0º point is at approximately 1.5ms and a change of 0.5ms will cause the servo arm tomove by about 45º. A normal servo will have a 200º range of motion and will start to “scream” if you attempt to exceedthis (by setting a duty cycle outside the 0.5 to 2.5ms range). If your servo starts to grind, remove the power immediately or,at very least, quickly return the servo to a normal duty cycle.

12.1.1 TESTING A SERVO IN HOSTED MODE

NOTE: This example is fairly straightforward, but keep in mind that servos are delicate; any deviation from theprocedure can damage your servo beyond repair very quickly!

1 Connect the servo’s red wire to the 5V source on the auxiliary power connector on the MicroBoard (these are the sixpins near the top of the board. Pin 6 is the 5V source). Connect the servo’s black wire to ground (pin 2 or 3 on theauxiliary power connector). If you’re worried about causing a brownout, use an external 5V source to supply theservo with power.

2 Connect the PWM1 output (PWM1 is RC2 on the PIC which corresponds to pin 13) to one end of an orange wire.

3 Start a HyperTerminal session and execute the following commands:

>> pwmstart1>> pwmperiod ff - sets the PWM to a 4ms period>> pwmduty1 75 - sets the duty cycle to about 1.5ms

4 Tap the free end of the orange wire against the yellow servo control wire. If the servo jumps to it's maximum rangeand starts “screaming,” remove the wire immediately! Check your duty cycle to make sure that it’s within theallowed range.

Page 54: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 50

5 If the servo moves to the 0º point (the desired response), plug the orange wire in all the way.

6 You can change the servos position by changing the duty cycle using the pwmduty1 command:

>> pwmduty1 hh - where hh is a value from 30 to a0

Any value outside this range could damage the servo.

12.1.2 TESTING A SERVO IN AUTONOMOUS MODE

Steps 1 to 3 are the same as above, except now the MicroBoard will take input from the B port to position the servo.

1 Burn the supplied servocontroller.hex file (http://www.ee.ualberta.ca/~ee401/examples/servo/servocontroller.hex) tothe PIC’s memory. The important bits of the source code (http://www.ee.ualberta.ca/~ee401/examples/servo/servocontroller.asm) are shown below:

main

startpagesel PAGE1call initializeChip ; initialize the entire Chip to known statepagesel PAGE0

pagesel PAGE1 ; Start the PWM on line RC2call startPWM1pagesel PAGE0

pagesel PAGE1 ; set duty cycle to servo’s ‘0’ positionmovlw h'75' ; h'7f' is about 0º

; h'30' is the servo min, h'a0' is it's maxcall setPWMDuty1 ; set PWM1 Dutypagesel PAGE0

banksel BANK1bsf PORTB,4 ; set last 4 ports of B to inputsbsf PORTB,5bsf PORTB,6bsf PORTB,7banksel BANK0

mainLoop

; NOTE: These values may be nowhere NEAR the actual angles!; They are, however, within the safe movement range of h'30' - h'a0'; Exceeding these values will blow up your servo!

movlw h'75' ; set servo position to roughly 0º via tempbtfsc PORTB,4movlw h'35' ; set servo position to about –180º via tempbtfsc PORTB,5movlw h'5C' ; set servo position to about –90º via tempbtfsc PORTB,6movlw h'84' ; set servo position to about +90º via tempbtfsc PORTB,7movlw h'9f' ; set servo position to about +180º via tempmovwf temp

pagesel PAGE1 ; select upper memory to call duty functionmovf temp,W ; moves temp to W to be passed to duty-change

; function (pagesel clears the W register,; so don't try and tranfer to W too soon)

call setPWMDuty1 ; set PWM1 period based on the W register value

pagesel PAGE0 ; back to lower memory

Page 55: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 51

goto mainLoop ; repeat main loop

2 Connect power to the MicroBoard. Connect the orange wire to the yellow input as before (again, if the servo begins to“scream”, remove the wire). The servo should move to the 0º position. If not, unplug everything and examine yoursetup thoroughly.

3 The servo position can be changed by setting pins b4 to b7 high using the set and clear commands or by takinginputs from an external circuit. The servo will remain in position as long as the line is held high, returning to 0º whenthe input stops.

12.2 SPI BAR GRAPH

Use of a shift register in conjunction with the PIC creates the opportunity for more digital outputs. This setup uses a shiftregister to create eight extra digital outputs each accessed using the SPI unit. The schematic below outlines the necessaryconnections (note that you will need eight LEDs and eight 470Ω resistors in addition to the 74HC595 shift register chip):

NOTE: Remember to connect a resistor in series with all outputs of the PIC to limit current and protect the PIC.

12.2.1 SPI BAR GRAPH IN HOSTED MODE

1 Connect the shift register and LED array using the above diagram.

2 Connect the serial cable and power and begin a HyperTerminal session.

3 Type the following (this will initialize the SPI unit and make sure all the LEDs are off):

>> spiinit - initializes the SPI unit>> output c0 - selects the clock pulse pin>> clear c0 - make sure it’s off>> spitrans 00 - set all eight 595 outputs to zero>> set c0 - sends the clock pulse>> clear c0 - resets the clock pulse pin

4 Cycle through the light levels as you wish. Try out different hexadecimal values:

>> clear c0>> spitrans hh ; Where hh is a hexidecimal value>> set c0 ; send clock pulse

RC0RC3

PIC16F873

1

1114

MicroBoard595Shift

Register

2

3

4

5

6

7

8

16

15

1413112

11

10

RC5RB0

1621

ALLRED ON

RED +YELLOW

ALLON

RED +YELLOW

h’07’

h’3F’

h’FF’

h’3F’

Circuit Diagram Logic Diagram

+5V470Ω

Page 56: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 52

>> clear c0

5 For a bar-graph-esque illumination, use the values 00, 01, 03, 07, 0f, 1f, 3f, 7f, and ff. This will light all the LEDsin order from red to green (calculate it out if you can't figure out why these values work: 1 hex digit = 4 binary digits.Example: h‘03’ = b‘00000011’, h‘1f’ = b‘00011111’, etc).

12.2.2 SPI BAR GRAPH IN AUTONOMOUS MODE

The Autonomous code is a basic program that cycles through three preset light levels. The code is fairly bulky and not thatfunctional, yet it proves to be a nice example. The MicroBoard will light all the red LEDs, then it will add the yellow LEDs,and finally will light the green LEDs. This is accomplished by calling the cmdSPIInit command and the transferSPIfunction in the original DEBUG.HEX source code. Watch the use of the PAGESEL command: using it clears the W register,so don't pass your values too soon!

******** NEW VARIABLE DECLARATIONS ********COUNTH EQU 0x56 ; variables for delayA and delayLong functionsCOUNTL EQU 0x57COUNTH2 EQU 0x58

******** MAIN CODE *************main

startpagesel PAGE1call initializeChip ; Initialize the entire Chip to known statepagesel PAGE0

call cmdSPIInit ; initialize the SPI device on lines b0,c0,c3,c5clrf temp ; clear the temporary register

mainLoop

movlw h'07' ; move light value to the W registermovwf temp ; set the temp register to W

pagesel PAGE1 ; select upper memorymovf temp,W ; moves temp to W to be passed to the SPIcall transferSPI ; Set SPI period based on the W register vlauepagesel PAGE0 ; back to lower memory

bsf PORTC,0 ; latch the data to the shift registersbcf PORTC,0

call DelayLong

movlw h'1f' ; move value to the W registermovwf temp ; set the temp register to W

pagesel PAGE1 ; select upper memorymovf temp,W ; moves temp to W to be passed to the SPIcall transferSPI ; Set SPI period based on the W register vlauepagesel PAGE0 ; back to lower

bsf PORTC,0 ; latch the data to the shift registersbcf PORTC,0

call DelayLong

movlw h'ff' ; move value to the W registermovwf temp ; set the temp register to W

pagesel PAGE1 ; select upper memorymovf temp,W ; moves temp to W to be passed to the SPIcall transferSPI ; Set SPI period based on the W register vlaue

Page 57: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 53

pagesel PAGE0 ; back to lower

bsf PORTC,0 ; latch the data to the shift registersbcf PORTC,0

call DelayLong

movlw h'1f' ; move value to the W registermovwf temp ; set the temp register to W

pagesel PAGE1 ; select upper memorymovf temp,W ; moves temp to W to be passed to the SPIcall transferSPI ; Set SPI period based on the W register vlauepagesel PAGE0 ; back to lower

bsf PORTC,0 ; latch the data to the shift registersbcf PORTC,0

call DelayLong

goto mainLoop ; Repeat main loop

;**********************************************************************DelayA

TenMsmovlw d'13movwf COUNTHmovlw d'250'movwf COUNTL

Ten_1decfsz COUNTL,F ; Inner Loopgoto Ten_1decfsz COUNTH,F ; Outer Loopgoto Ten_1

return

;**********************************************************************DelayLong

LongMs;movlw d'3' ; 10ms * value in quotes is duration of Long;movwf COUNTH2

Ten_2decfsz COUNTH2,F ; Loopgoto Ten_3

return

Ten_3call DelayAgoto Ten_2

A much better algorithm can be made by applying a logical shift operation (LSL to fans of the 68000-series processors),using the PIC's rotate function and a bsf command like so:

clrf temp ; temp set to 0000 0000 STATUS,C = 0call LightItUp ; turn on lights based on tempbsf temp,0 ; temp is now 0000 0001 STATUS,C = 0call LightItUp ; turn on lights based on temp againrlf temp,F ; temp is rotated left, and stored back in itself

; (hence the ,F)

Page 58: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 54

; temp = 0000 0010 STATUS,C = 0bsf temp,0 ; temp = 0000 0011 STATUS,C = 0call LightItUp ; turn on lights based on temprlf temp,F ; temp is rotated left, and stored back in itself

; temp = 0000 0110 STATUS,C = 0bsf temp,0 ; temp = 0000 0111 STATUS,C = 0call LightItUp ; turn on lights based on temp

Get the idea? This would sequentially light the first two LEDs in your array. Use rrf to reverse the process.

If a 1 is shifted out of the register (either left or right) it will be moved to the carry register. This allows you to test if theregister is “full” and execute operations accordingly (if your bar graph is maxed out, then start decrementing values). Thevalue of the carry register is rotated to the front of the register, so keep this in mind if you have other operations that mightaffect the STATUS register. You can implement a technique similar to this to light only one LED and have it move back andforth along the row (PIC-LED Pong perhaps?).

12.3 MOTOR SPEED CONTROLLER

Using a looping routine, one can monitor a value and adjust another based on that input. The motor speed controllerrepeatedly checks the ADC value and adjusts the PWM duty cycle accordingly.

Figure 12-1: Motor Speed Controller Flow Charts

Attach PWM2 output (RC1, pin 12) to the motor's positive terminal through the H-bridge on the MicroBoard (into the H-bridge through pin 7 and out to pin 6. Refer to Appendix A – MicroBoard Schematic and the L293 Motor-driver chipdata sheet).

The positive terminal of the motor’s analog output is connected to the PIC’s RA0 input (ADC line). Connect two LEDs topins RC2 and RC3 (don’t forget to add a couple pull-up resistors to limit current. 470Ω ones will work just fine).

Start Up

Init PWMInit ADC

Main Loop

ReadADC

OutputSpeed

CheckADC

DecreaseDuty Cycle

IncreaseDuty Cycle

>2.5V<2.5V

=2.5V

ADRESH - 02

Done

ADRESL - 00

Z=1

DutyDown

DutyUp

-

Z=1

+C=1

C=1 C=0

C=0

Check ADCFlow Chart

Page 59: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 55

Figure 12-2: Motor Box (with inputs and outputs) and Motor Speed Controller Schematic

The program below checks the voltage on the ADC port, samples it against a hexadecimal value that should be equivalentto 2.5V, and then adjusts the duty cycle such that it brings the ADC value closer to the 2.5V mark. The code assumes thatthe motor will output 0V (hexadecimal 0000) at its stopped speed, and 5V (hexadecimal 03ff) at its maximum speed. If themotor only outputs to a certain ADC range (say 0100 to 02ff), the code would need to be modified to check for that.The code also assumes that the delay is long enough to allow the ADC to catch up with the changes in the motor speed;this may not be the case. In terms of writing the output to the screen, the adcread command automatically prints to theUART when it is called.

**** ADDED VARIABLE DECLARATIONS ****

COUNTH EQU 0x56COUNTL EQU 0x57

**** MAIN CODE ********

main

startpagesel initializeChipcall initializeChip ; Initialize the entire Chip to known statepagesel PAGE0

pagesel initializeUARTcall initializeUART ; Initialize the serial portpagesel PAGE0

pagesel PAGE1 ; do PWM with CCP2(RC1)call startPWM2 ; (intitialize the PWM on RC1)pagesel PAGE0

pagesel PAGE1movlw 0xff ; set long PWM period into W, pass it to settercall setPWMperiod ; set PWM periodpagesel PAGE0

pagesel PAGE1 ; initialize the ADCcall initADC

RC1/PWM2

RC2RC3

GND

RA0

PIC16F873

12

1314

21

2

MicroBoard

7

L293D

_MotorIn

MotorOut

_+

+

6

Page 60: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 56

pagesel PAGE0

banksel BANK1bcf TRISC,2 ; set RC2,3 to output (monitor motor correction)bcf TRISC,3 ; green LED to RC2 / red LED to RC3banksel BANK0 ; green is duty up / red is duty down

mainLoop

bcf PORTC,2 ; clear status lightsbcf PORTC,3call Delaycall cmdADCRead ; read data on ADC line, output it to the UART

; and store data in ADRESL and ADRESH registers

testhi

movlw h'02' ; move h'02' to W (upper byte of h'0200')subwf ADRESH,W

btfsc STATUS,Z ; check to see if high byte is equal to h'02'goto testlo ; if equal, check lower bytebtfss STATUS,C ; check if high byte is greater/less than h'02'goto DUTYup ; if less (c=0) increase duty cycle of PWMgoto DUTYdown ; if greater than (c=1) decrease PWM duty cycle

testlo

banksel BANK1movlw h'00' ; move h'00' to W [lower byte of h'0200'

; approx 0.5 * h'03ff' (2.5 volts)]subwf ADRESL,Wbanksel BANK0

btfsc STATUS,Z ; check to see if high byte is equal to h'00'goto mainLoop ; if equal, return to topgoto DUTYdown ; if not, low byte MUST be greater than h'00'

; must decrease PWM duty

DUTYup

bsf PORTC,2 ; set green light onpagesel PAGE1movlw d'1' ; put '1' in the W registeraddwf CPR2L,F ; increment 8 MSBs of PWM2 duty cyclepagesel PAGE0

goto mainLoop ; Repeat main loop

DUTYdown

bsf PORTC,3 ; set red light onpagesel PAGE1movlw d'1' ; put '1' in the W registersubwf CCPR2L,F ; decrement 8 MSBs of PWM2 duty cyclepagesel PAGE0

goto mainLoop ; Repeat main loop

This entire routine can be performed step-by-step in Host mode. Read the ADC line using the adcreadx command(where x is and ADC line 0 to 4), and then modify the PWM duty cycle accordingly using pwmduty2 hh:

>> pwmstart2 - starts the PWM connected to RC1>> pwmperiod ff - sets full period with 50% duty cycle

>> adcinit - initialize the ADC>> adcread0 - read the ADC line on RA0

Page 61: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 57

1f0 - which is less than 50% (1f0/3ff = 48%)>> pwmduty2 82 - so increase PWM duty slightly>> adcread0 - check again and adjust accordingly, etc...

12.4 SHAFT ENCODER

The shaft encoder’s mechanical workings consist of a rotating diskwith a half circle open space and two IR LED/detector sensors, oneat the disk’s side and the other at the bottom. Upon some carefulinvestigation, you will notice four pins coming out of each sensor.Two will be connected together on each and a brown wire ties thetwo connections together and also to ground.

By testing the impedance of each of the other two pins with respectto ground, you will notice that one will give an infinite resistancewhile the other gives a reasonable reading. By process ofelimination, you can conclude that the infinite side is the transistorside (orange lead) while the reasonable side must be the IR LED(yellow lead). Apply a 5V load to the LED side (don’t forget aresistor in series with it; 330Ω will do) and test various values of resistance on the transistor side until you can achieve an“on/off” value that switches from 0V to 5V. You should find that a 10KΩ resistor will work just dandy.

As per Figure 12-3, solder the wires and resistors in place. Hook the transistor-side outputs to pins b0 and b1 (on a boardwithout hardware flow control enabled; see Section 5.9). It may be a good idea to add a couple current-limiting resistors tothese lines to protect the PIC. Connect the appropriate pins to 5V or ground. You can hook up two LEDs to pins b2 andb3 to monitor the status of the wheel.

Figure 12-3: Shaft Encoder Schematic

RB0

RB2

RB1

RB3

PIC16F873

21

23

22

24

MicroBoard

10kΩ330Ω

10kΩ

330Ω

+5V

Top

Bottom

Close-up of Sensor Wiring

10kΩ330Ω

+5V

Vout

LED phototransistor

Page 62: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 58

Figure 12-4: Shaft Encoder Flow Chart

The code below checks the status of the top and bottom switches and stores them in the two least significant bits of theW_STAT_NEW register. It checks these against the same bits of the W_STAT register. They are compared following the flowchart in Figure 12-4. The W_STAT register is then set with the values in the W_STAT_NEW register, and the directioncalculated is stored in the third bit (bit 2) of W_STAT.

******* NEW VARIABLE DECLARATIONS *******

COUNTH EQU 0x56 ; delay function variablesCOUNTL EQU 0x57W_STAT EQU 0x58 ; status register of wheel:

; 0 is top switch; 1 is bottom; 2 is wheel direction

W_TURNS EQU 0x59 ; # of turns made by wheel (not implemented)W_POWER EQU 0x5A ; absolute value of turns (not implemented)W_STAT_NEW EQU 0x5B ; new status temp register

; (same bit config as W_STAT)

******* MAIN CODE **********

main

startpagesel initializeChip ;call initializeChip ; Initialize the entire Chip to known statepagesel PAGE0

banksel BANK1bsf TRISB,0 ; set RC1,0 to input (1 btm, 0 is top switch)bsf TRISB,1 ; monitors the LED/transistor switchesbcf TRISB,2 ; set light outputs green if W_STAT,2 = 1bcf TRISB,3

; bcf TRISC,1 ; intialize ground pins when PWM's not active; (not implemented)

Page 63: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 59

; bcf TRISC,2 ; set motor direction output grounds on; (not implemented)

banksel BANK0

; bcf PORTC,1 ; motor ports (not implemented); bcf PORTC,2

clrf W_TURNS ; turns the motor has madeclrf W_POWER ; absolute power of motor (duty cycle)clrf W_STAT ; stat bits 3=Motor Direction, 2=Wheel

; Direction, 1=Btm Sw 0=Top Sw

bcf PORTB,2bcf PORTB,3

mainLoop

call CheckSensors ; call sensor check routine; set W_STAT registercall DirectionDisp ; turn on LEDs to indicate directioncall Delay

goto mainLoop

CheckSensors

clrf W_STAT_NEW ; clear temp register

btfsc PORTB,1 ; test status of btm SWbsf W_STAT,1 ; set registers btm switch flag s1bcf W_STAT,1 ; else clear it

btfsc PORTB,0 ; test status of top SWbsf W_STAT_NEW,0 ; set temp registers top switch flag s0bcf W_STAT_NEW,0 ; else clear it

btfsc W_STAT_NEW,0 ; check condition of top switch vs last valuegoto NewTopOngoto NewTopOff

NewTopOff

btfss W_STAT,0 ; if old off and new off, returnreturn

bcf W_STAT,0 ; set old top equal to new top

btfsc W_STAT,1 ; check new s1 to set directionbsf W_STAT,2 ; set D = 1 if s1 onbcf W_STAT,2 ; clear D if s1 is off

goto checkend ; goto end of checking routine

NewTopOn

btfsc W_STAT,0 ; if old on and new on, returnreturn

bsf W_STAT,0 ; set old top equal to new top

btfsc W_STAT,1 ; check new s1 to set directionbcf W_STAT,2 ; clear if s1 onbsf W_STAT,2 ; set D if s1 is off

goto checkend ; goto end of checking routine

Page 64: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 60

checkend

return

DirectionDisp

bcf PORTB,2bcf PORTB,3

btfsc W_STAT,2 ; check the wheel direction status bitbsf PORTB,2 ; set green light if d=1bsf PORTB,3 ; set red light if d=0

return

DUTYchange

pagesel PAGE1

movf W_POWER,W ; put '1' in the W registerbtfsc W_STAT,3 ; test wheel direction (which Duty to change?)movwf CCPR2L ; increment 8 MSBs of PWM 2 duty cyclemovwf CCPR1L

pagesel PAGE0

return

;**********************************************************************Delay

TenMs

movlw d'13'movwf COUNTHmovlw d'250'movwf COUNTL

Ten_1

decfsz COUNTL,F ; inner Loopgoto Ten_1decfsz COUNTH,F ; outer Loopgoto Ten_1

return

This example leaves a turn counter to be implemented (fairly trivial, just increment/decrement the W_TURNS registerevery time the W_STAT,2 bit is calculated). One could also use this program to control the speed and direction of a motorusing the PWM, the full code to do this is not included but some functions and registers have been set up and commentedout. Also, it is assumed no debouncing is needed; this may be something to investigate.

Page 65: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 61

13 MEDULLA: THE SOUND-SENSING ROBOTThis is the final milled version of the Medusasound-sensing robot. It is designed to detect 38kHzIR beacons, loud sounds, and bumps to the front ofits chassis. It has three onboard op-amps, six sensorinputs with pull-up resistors, and an external 7.2Vdc

battery unit for the PIC and the motors (whichdraw 3V).

13.1 SENSORS AND PSP BOARD

The bot has three types of sensors: bump sensors, IR sensors, and sound sensors. All three run off the PSP board (PortableSensor Platform).

The microphones are each activated individually by the code, and a reading is sampled from them. This signal is filteredto remove any DC signal, amplified by an op-amp, filtered again, and then passed over a reverse-biased diode to rectifythe signal and limit the voltage to about 5.1V maximum.

The bump sensors feed directly into PORTB, and the IR sensors are connected to the PSP.

The IR sensors detect a 38kHz pulse from an infrared beacon (actually works best at 41kHz, but factory specs say 38kHz),and will track this beacon quite well at close range. For long-distance tracking, a better beacon must be used,implementing at least three emitting diodes to increase the photon count. Additionally, the sensors should be wipeddown with alcohol swabs to remove grease from human hands. The PSP board connects both power and signals to theMicroBoard and, as such, is a great method to test multiple platforms without resoldering or reconfiguring the sensorarrays each time.

Medula has three sensor priority levels, sound being the lowest. If the robot is chasing a noise, it will leave its target topursue a recognized IR signal. If it hits an obstacle at any time, it will avoid the obstruction before resuming its normalprogram.

An addition to the PSP is the microphone assembly board. This board contains the basic circuit to multiplex themicrophones and rectify the output. The input from the MicroBoard selects the active microphone; the signal of this unit isthen sent to the op-amp for magnification. Next, the signal is passed back to the microphone board where it is stripped ofits DC component, rectified, and clipped to ensure a nice 0 to 5V signal for the ADC input on the MicroBoard. If youwould like to improve performance, use a diode bridge to perform full-wave rectifying on the output signal.

13.2 BATTERY POWER

Medulla runs off a single 7.2V NiCd battery pack located between the MicroBoard and the two motors for the treads. Thisbattery supplies the regulators with voltage to power the board and the motors. Thus, both 5V and ±7.2V are available foruse.

Page 66: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 62

A modified H-bridge mounting assembly allows the 7.2V input voltage to be converted to a 3V steady power source forthe motors. It is possible that 5V motors could be inserted in place of the 3V, in which case you would need to modify theresistor ratio on the 3V-regulator board. This board employs an LM317 chip (variable voltage regulator) which takes aninput voltage and converts it to a Vout between 1.25V and 30V. The ratio of the two resistors on the board determines whatthis value will be. Check the LM317 or LM117 data sheet for more information.

The capacitors between the input and output voltages and the ground help keep a nice accurate output voltage. The H-bridge plugs into a socket on this board, which in turn plugs into the MicroBoard’s H-bridge socket (“piggyback” style).Pin 8 (the supply voltage pin) connects to the 3V regulator output, thus bypassing the MicroBoard’s H-bridge supplyvoltage trace.

13.3 THE PROGRAM

The Autonomous code for Medulla is based on DEBUG.HEX’s monolithic code modules (the Hosted mode program).The main function has been deleted and replaced with a new set of routines. The main routine checks the status of thesensors’ inputs and sets a corresponding bit in the neurons register. The program then checks the neurons and calculateswhich motor neurons need to be activated. Finally, the program checks which motors are pending activation and switchesthem on. A delay is then called and the process is repeated indefinitely. This code could be greatly improved with multipleADC lines and an interrupt- or multi-tasking-based system.

The main program is quite large so it is not included here. It is, however, available on the EE401 web site:http://www.ee.ualberta.ca/~ee401/examples/medulla/phoenix.asm

13.4 QUIRKS

There is a threshold value in the sound recognition function, which allows you to cut out all lower power noise and notuse it in the evaluation process. Currently, the entire sound system runs by comparing only the eight most significant bitsof the input; this will be improved in the next version by checking all 16 input bits. The sound equipment also produces afair amount of noise, which could possibly be removed with more advanced filtering hardware.

3V motors are a little too weak for the current application. A 5V motor of the same size could easily replace the currentmotors and provide a much stronger and more versatile locomotion system.

You may notice that three of the PSP pull-up resistors have been attached at only one end. This mainly serves to bridge thegaps in the very small IR sensor output traces. Connecting these resistors puts far too great a load on the IR sensors,causing erratic behaviour.

13.5 REFERENCE FILES

All relevant files for this project are available on the EE401 web site:

3v_regulator.brd Eagle board and schematic files for the 5V to 3V H-bridge supply board3v_regulator.sch

microphone_setup.brd Eagle board and schematic files for the microphone multiplexing/rectifyingmicrophone_setup.sch

pspboard.brd Eagle board and schematic files for the sensor expansion boardpspboard.sch

phoenix.brd assembler/hex files for primitive version of final PIC code (pin-outs for sensors in this file underphoenix.sch their declarations)

Page 67: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 63

14 SNAKE TURRET (MKII – AUTONOMOUS VERSION)NOTE: An artificial neural network (ANN) version of this robot isavailable also. Please see the MicroBoard Advanced Manual forvarious ANN examples.

Snake turret is a stationary robot that moves its “head” to track thesignal from a 38kHz infrared beacon. Its “head” is made up of fiveIR sensors and a mercury switch. The PWM lines of the MicroBoardare each connected to a motor. When the middle IR sensor “sees”light, the PWMs are set to half speed. This allows slow correctionwhen the beacon is near the center of the bot. In all other cases, thePWM lines are set to a 100% duty cycle resulting in much quickermotion.

The red light on the head of the robot will be active when it senses noIR signal. When it is tracking, the yellow light will be illuminated,and when it finally centers on the beacon, the green light and buzzerwill activate. This device will sense “good” beacons at distances upto or exceeding 1.5m.

The mercury switch (not implemented on the MkII version yet) is abasic example of a position sensor or shaft encoder. If the turret tiltsto a dangerous level, the switch will shut off its motors and restrict its vertical motion preventing the wrapping of cablesand pulling of wires. A real shaft encoder setup would allow the bot to sense the position of its body and correct for anyexternal forces applied to it, thus improving the accuracy of the device. Two or more snake turrets with shaft encoderscould be used to accurately calculate the position and velocity of any beacon between them.

14.1 EXTERNAL CIRCUITRY

Snake Turret uses two additional milled boards. The board located at the top of its chassis provides a mounting point forthe ribbon cable, some additional power connections, and a mounting plate for the three lights. The head of Snake Turretis a simple milled board that holds the five IR sensors. For more accuracy, a 47µF capacitor should be added between the5V and ground pins. Additionally, small capacitors may be needed between the power and ground pins of each IRdetector.

Power is supplied to the Snake Turret via a NiCd 7.2V battery pack. The sensors will behave erratically if the batterypower wanes so keep it well charged.

14.2 QUIRKS

One major problem with Snake Turret is the power consumption of the large base motor. This motor cannot takeadvantage of the turret’s PWM correction for small beacon angles. A 50% duty cycle does not provide enough juice tokeep the big motor going.

14.3 POSSIBLE IMPROVEMENTS

A nice future addition might be the implementation of a “search” mode. Like a radar dish, the robot could pivot until itdetects an IR signal. When it loses the signal, it will resume its scanning. The code for this is included in the main programbut is currently commented out until it has been tested properly.

Page 68: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 64

The skeleton robot is not limited to IR beacons; it could be made to track magnetic field strength, sound, light, TAs,whatever your imagination can devise. All it requires is a little sensor building on your part, and a few small changes inthe assembler code. Experiment!

14.4 SENSOR-TO-PIC CONNECTIONS

Infrared Sensors Pin #Top RB0 21Left RB1 22Middle RB2 23Right RB3 24Bottom RB4 25

Motors Pin #Up RC3 14Down RC2 13Left RC0 11Right RC1 12

Lights Pin #Red RB5 26Yellow RB6 27Green RB7 28

Buzzer RA1 3

14.5 REFERENCE FILES

All relevant files for this project are available on the EE401 web site:

snake.asm program files for autonomous turret operation (assembler and hex)snake.hex

snakehead.brd turret head mounting board layout

snakerouter.brd router board layout

Page 69: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 65

15 LINE FOLLOWERThe Line Follower is capable of following a set path given that the line it is to follow is somewhat reflective compared to itsbackground (for example, white tape on black or dark grey floor). And since this robot has been programmed with shortterm “memory,” it will interpolate between breaks in the line and follow turns that are too sharp for its turning radius.

15.1 MODIFYING THE CHASSIS

The main vehicular portion of Line Follower is a modified radio-controlled Dodge Viper. The MicroBoard replaces the RCcar’s original control mechanism by connecting the h-bridge (pins RC0 through RC3) to the car's motor and steering line.

The steering is digital, and by reversing the polarity on the steering lines, the MicroBoard can cause the car to turn left orright. The rear motors that drive the vehicle are pulsed-width modulated to control the speed of the robot. In futuremodels, the PWM could also be used to control the angle of the steering mechanism allowing for much more accuratenavigation.

15.2 THE SENSOR UNIT

The sensor unit is composed of 5 IR transmitter/receiver pairs. The first half of each pair is an IR diode placed in serieswith a 220Ω resistor, allowing about 20mA to flow through diode. This light reflects off the surface below Line Follower,and is received by the unit's phototransistors (bluish black diode-shaped components). The phototransistors are placed inseries with a 2.2kΩ pull-down resistor. The MicroBoard receives voltages from this array and coordinates output based onthe input. A white patch on the ground will yield approximately 5V, while a black surface returns 0V.

The only concern with this setup is the parallel connectivity. To reduce the current draw of the sensor board, one mayconsider connecting several of the emitter diodes in series.

15.3 LINE FOLLOWER’S CODE

The sensors read five values from the IR phototransistors into the register inLR: bit 4 is the left sensor, bit 3 is the middleleft, bit 2 is the middle, bit 1 is the middle right, and bit 0 is the right sensor. The program compares this register topreviously stored outcomes, and decides where to move based on the comparison. It sets the bits of an output register (theoutALL register): bit 3 turns right, bit 2 turns left, bit 1 is half speed, and bit 0 is full speed. The output register is thentested, and depending on the bits that are set, different subroutines are called to control the four output lines (c0 and c3 forsteering and PWM1 and 2 for speed).

15.4 SENSOR-TO-PIC CONNECTIONS

Infrared Sensors Pin #Left (blue wire) RB0 21Middle Left RB3 24Middle RB4 25Middle Right RB5 26Right RB6 27

Motors Pin #Brown to blue RC0 11White to green RC1 12

Steering Pin #Blue to blue RC3 14White to green RC4 15

Power Pin #Sensor 5V 6 aux power connSensor GND 2 aux power conn

Power SwitchesSide 1 TYCO 6V to NiCd 7.2VSide 2 barrel connector (+)Batt GND TYCO GND to barrel (-)

Other connections made: vias to H-bridge from lines c0, c1, c2, c3

Page 70: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 66

15.5 REFERENCE FILES

All relevant files for this project are available on the EE401 web site:

linefollower.asm program files for autonomous line follower operation (assembler and hex)linefollower.hex

lineboard.brd EAGLE board layout of sensor boardlineboard.sch EAGLE schematic of sensor board

Page 71: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 67

16 RF CONTROL (RC LINK)If someone has only utilized the chassis and motors of an RC car (oryou’d like to control the car from a computer), you can use the RCtransmitter/receiver pair.

16.1 PREPARING THE TRANSMITTER

The first step is to get the transmitter case open. Take out the onescrew in the back and remove the battery. Next, begin to pry openthe back plate. This may take a little work and ingenuity. The clipsthat hold the two pieces together must be dislodged from theirmoorings (try a flat-blade screwdriver). Lastly, dislodge thepyramid-shaped piece at the base of the antenna. Once this is free,the case should come apart rather easily.

Remove the blue buttons from the circuit board. You’ll notice a small donut of metal beneath each end of the two V-shaped pieces of metal. In normal operation, the ends of the “V” must contact the donut to send the signal for the car tomove. Using a multimeter, you’ll find that the donuts are at 8.6V while the “V”s are grounded.

1 1 Cut four pieces of blue (or any other colour except red or black) wire. These will be your control lines.

2 Solder one end of each wire to each of the four donuts. Make sure your solder joints do NOT contact the rockers .

3 Cut a piece of black wire and solder one end to the ball of solder directly above the ground plate of the batteryconnector.

16.2 PREPARING THE MICROBOARD

1 Solder vias between your PIC and the PORTC H-bridge (resistor locations R17, R18, R19, R20)

2 Solder the other end of one of the blue wires to the RC0 output of the H-bridge. Do the same for RC1, RC2, and RC3.

3 Solder the black wire to the ground of the MicroBoard. This creates a common ground

16.3 PREPARING THE RECEIVER

If you’re simply going to drive the car around, you can bypass this section, otherwise cut the control lines going from thereceiver to the RC car.

1 Connect a 6V battery or power supply (your choice) to the red and black wires protruding from the receiver board.

2 Make sure the antenna is securely fastened to the board with a screw.

3 Solder your output circuitry to the steering and motor power wires. The motor power lines are the thick brown andwhite wires, while the thin blue and white wires control the steering.

When there is no signal there will be no voltage drop across these wires. When a signal is received from the transmitter,there will be a 6V drop across the affected pair, the polarity determined by the nature of the signal. The demo example hasLEDs connected across the wire pairs to indicate polarity.

Page 72: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Part IV – Examples: Both Simple and Complex Page 68

16.4 USING THE TRANSMITTER/RECEIVER IN HOSTED MODE

1 Burn the DEBUG.HEX file onto the PIC16F873. Connect the serial cable and power to the MicroBoard.

2 Type the following in HyperTerminal:

>> output c0>> output c1>> output c2>> output c3>> set c0>> set c1>> set c2>> set c3

3 This will set up the board for use by setting PORTC to output. Since the donuts are active low (the rockers aregrounded) we set all the output lines to 9V (the power supply voltage going through the H-bridge. 12V might ruinthe transmitter, so stick to 9V or less). This step ensures that the transmitter is in the “off” state.

4 Put the 9V battery into the transmitter unit. If you do this step before initializing the board, the H-bridge output will below and the transmitter will begin sending signals with unpredictable results.

5 To activate individual outputs on the receiver, simply clear the desired PORTC output line. On the demo example youcan control the steering by clearing lines RC0 and RC1, and the motor power with lines RC2 and RC3. You candeactivate the receiver outputs by setting the desired PORTC line in HyperTerminal.

>> clear c0 - activates the steering lines of the receiver>> set c0 - deactivates the steering lines

If your MicroBoard is set up with hardware flow control, you can run script files. Try the blinking light example over theRC link.

Page 73: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Section V – Appendices Page 69

Appendix A. MICROBOARD SCHEMATIC DIAGRAM

Page 74: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Section V – Appendices Page 70

Appendix B. COMPONENT AND SOLDER SIDE OF BOARD

Page 75: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Section V – Appendices Page 71

Appendix C. ASSEMBLING A MILLED BOARD (PLUS HOW TO SOLDER)

If you have to drill holes in the PCB…

You should only have to drill holes if you are using an in-house milled board; the manufactured boards should already bedrilled. Start off by locating the component side of the printed circuit board. Note that all components will be installed onthis side and most of the soldering will be done on the other side (solder side).

Suggested hole sizes: DB9 connector mounting holes and 2.1mm power connector – #32 (0.116 inch)

Diodes, voltage regulators and SIP connectors – #60 (0.040 inch)

All other component holes – #67 (0.032inch)

After using the drill, clean up the mess you have created.

Installing and soldering components

Before soldering, trial fit all components to ensure all hole sizes are correct and components will fit properly.

You will likely need to clean the copper on a milled board of tarnish and oils. Cleaning can be accomplished by lightlyabrading the surface with a kitchen, non-detergent pad (Scotch/Brillo pad), fine steel wool, or fine sandpaper. Care mustbe taken not to damage the board. Be careful not to touch the copper surfaces with you hands; fingerprints willcontaminate the clean copper surface. Some boards may be tin-plated for greater durability.

Install components from the shortest first to the highest last. With this in mind, solder the vias first, then install the resistorsand diodes, followed by the IC sockets and monolithic capacitors and then lastly the electrolytic capacitors and connectors.

Install vias using short pieces of solid wire such as the leads from the resistors. On the milled board, the resistors, diodesand mono-caps are used as electrical feed-throughs from circuit board top to bottom. Solder both sides where appropriate.

Ensure that the diodes and electrolytic capacitors are installed correctly. If they are not installed properly, this will causeyou unnecessary grief and time spent unnecessarily troubleshooting the board.

When installing the IC sockets, ensure that the notched section matches with the orientation of the ICs. The notchdesignates the end of the IC that pin 1 is at. For the 28-pin PIC, you will be given two 14-pin IC sockets. Once again, ensurethat both notched sections are facing the same direction prior to soldering them to the circuit board.

Soldering

Turn soldering iron on and allow time for the iron to heat up. While the iron is heating up, ensure that the sponge is dampas you’ll need to clean the tip of the iron prior to soldering. To clean the soldering iron tip, simply wipe the heated tip of thesoldering iron against the damp sponge. The tip should have a bright silvery appearance after you have cleaned it.

1 Insert the component lead into the proper position on the printed circuit board. Don’t pull the component too tightagainst the board; the component must be able to expand as the temperature changes.

Page 76: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Section V – Appendices Page 72

2 Use the hot soldering iron held at a 45º angle. The iron’s tip should come in contact with both the component lead andthe circuit board. Let the iron heat up the component lead and component pad.

3 Try not to touch the solder to the soldering iron. Touch the solder to the component lead and let the heated lead meltthe solder. Allow the solder to melt and spread around the entire connection. After the solder flows around andadheres to the part being connected, remove the soldering iron.

4 Examine the solder connection. If the connection appears to be cone shaped, the proper temperature was reached; badsolder appears grayish and round.

5 Cut the component’s wire lead, leaving a bit of wire protruding from the solder.

6 Examine the area around the connection and remove any excess solder.

Testing the assembled board – Power Check

Please refer to Appendix D – Checklists: Components, Power, and Integrated Circuits. Before installing any ICs, test theboard for proper power connections. Use a DMM set to measure resistance to check for short circuits across power supplyconnections. Connect the power supplies and use a DMM on DC volts to check the supply voltages at the IC sockets.

Page 77: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Section V – Appendices Page 73

Appendix D. CHECKLISTS: COMPONENTS, POWER, AND INTEGRATED CIRCUITS

Your MicroBoard kit should include the following (do a quick check to make sure):

Qty Description Part Number1 100µF 25V electrolytic radial lead (100-220µF 25V or greater) C16 0µ01F 50V mono-cap C2, C5, C7, C17, C22, C232 10µF 25V electrolytic radial lead (10-22µF 25V or greater) C3 plus one for testing5 0µ1F 50V mono-cap C24-C281 2.1mm barrel power connector CN11 9-pin female right angle DB connector CN61 1N4000 1A 50V rectifier (1N4000-1N4007) D11 LM7805 5V 1A TO-220 voltage regulator IC11 PIC16F873-04 IC41 L293 dual H-bridge driver IC51 MAX232A RS-232 interface chip IC84 4.7kΩ ¼-watt resistor R1, R29, R30 plus one for testing3 470Ω ¼-watt resistor R23, R24 plus one for testing2 330Ω ¼-watt resistor R31, R321 4.00MHz 3-pin ceramic resonator with integral capacitors Y12 14-pin IC sockets sockets for IC42 16-pin IC sockets sockets for IC5 and IC81 red LED plus one for testing1 9Vdc 500mA wall adapter1 MicroBoard printed circuit board

The assembly checklist begins here (soldering the components in this order would be a good idea):

Description Part Number(s) Notes

IN400x diode D1 White band toward Y1

4.7kΩ ¼-watt resistors R1

R29

R30

Yellow violet red gold

You will have one extra for testing purposes

470Ω ¼-watt resistors R23

R24

Yellow violet brown gold

You will have one extra for testing purposes

330Ω ¼-watt resistors R31

R32

Orange orange brown gold

0µ1F 50V mono-caps C24

C25

C26

C27

C28

Marked 104 for 10x104pF

0µ01F 50V mono-caps C2

C5

C7

C17

C22

C23

Marked 103 for 10x103pF

Two 14-pin IC sockets for IC4 Sockets for IC4 Notches away from DB9/CN6 connector

Page 78: MicroBoard - University of Albertaee401/resource/manuals/Microboard... · 2001-08-24 · 9.2 The PIC16F87x Assembly Template ... The MicroBoard is used in the EE401 project course

Section V – Appendices Page 74

16-pin IC socket for IC7, IC8 Sockets for IC7 & IC8 Do NOT solder DIP ICs directly into the PCB

4.00MHz 3-pin ceramic resonator Y1

2.1mm barrel power connector CN1 Tabs may need to be bent to fit holes in PCB

9-pin DB female connector CN6

100µF 25V C1 Negative to edge of PCB

10µF 25V C3 Positive to edge of PCB

You will have one extra for testing purposes

LM7805 IC1

Before installing any ICs, test the board for proper power connections:

Test Probe connectionsDesiredValue

Use a DMM to measure resistance. Check for a short circuit from Vcc toground (auxiliary power connection pin 1 to pin 3; the auxillary powerconnector is the collection of six pads on the top side of the board).

Aux power: pin 1 to pin 3 > 500kΩ

Plug the wall adapter in and connect it to the 2.1mm barrel connector.

Use a DMM to measure the voltage Vcc with reference to ground. Aux power: pin 1 to pin 3 Vcc

Measure the +5Vdc supply with reference to ground. Aux power: pin 6 to pin 3 +5Vdc

Measure voltage on MCLR on the PIC socket with respect to ground. IC4: pin 1 to pin 19 +5Vdc

Measure the supply voltage on the PIC socket. IC4: pin 20 to pin 19 +5Vdc

Measure the supply voltage on the RS-232 interface socket. IC8: pin 16 to pin 15 +5Vdc

Measure the drive supply voltage on the L293D driver socket. IC7: pin 8 to pin 4 Vcc

Measure the logic supply voltage on the L293D driver socket. IC7: pin 16 to pin 13 +5Vdc

Measure the ENA voltage on the L293D driver socket. IC7: pin 1 to pin 4 +5Vdc

Measure the ENB voltage on the L293D driver socket. IC7: pin 9 to pin 12 +5Vdc

If, and only if, all the power checks are correct, continue on:

Disconnect the power and allow the supply voltages to drain to 0Vbefore inserting any ICs.

Insert the MAX232 in the IC8 socket. Pin 1 is furthest away from theDB9 serial connector.

Connect power through 2.1mm barrel connector.

Use a DMM on DC volts to check Vcc on the MAX232 with reference toground.

IC8: pin 16 to pin 15 +5Vdc

Measure V+ on the MAX232 with reference to ground. IC8: pin 2 to pin 15 +10Vdc

Measure V- on the MAX232 with reference to ground. IC8: pin 6 to pin 15 -10Vdc

You are now ready to program a PIC16F873.