Getting Started With The PICBASIC Pro Compiler And MPLAB … Archive...where the PICBASIC PRO...

6
THE LATEST IN PROGRAMMING MICROCONTROLLERS . .. - ." \ . . BY CHUCK HELLEBUYCK GETTING STARTED WITH THE PICBASIC™ PRO CO MPILER AND MPLAB® IDE [] It rEEl. Uc J( HAf h11} DE n .. ,.; 'r L I n t-tii jWh i' \1Vt)uf lil( tYi e 'If) go back onlid Cti! .r '0 H;d; n ...· tb ... ",hlf ., or' t he c ol w itb ' Thou!Jh rv c ivered hh; iii (1ft: !'ou s cohln'Ii ,·. II ud . i •• u: c han qed ,a nd there "t ill . fH e. topi cs .. I H ot cov . ne area missed is how to set up and use Microchip's MPLAB IDE for developing your programs. If you writ e in assembly, C, or even microEngineering Labs' PICBASIC or PICBASIC PRO compilers, you can use the sam e MP LAB IDE. This is important to learn, especially for those who may graduate from a hobbyist programmer to a pro fession al pro gr amm er. All Mi crochip tools work directly with the MPLAB IDE. This includes the PICkit™ 2 Starter Kit (Part #DV'164 120), which I've covered in many articles before and I plan to use again as the hardware. For the software, I decided to keep it simple and inexpensive by using the sample version of the PICBASIC PRO compiler. This is the Basic language compiler I've written about many times before. Af ter all, the BASIC acronym stands for "Beginner's All-purpose Symbo lic Instruction Code." The keyword , here, is beginner. The sample version of the PICBASIC PRO compiler is available as a free downl oad from htlp:/ /melabs.com/pbpde mo.htrn, and the MP LAB ID E is available as a free download from www.microchip.com/mplab, The PICkit 2 Starter Package will cost you $49.99 plus shipping if you purchase it from www.rnicrochipd irect.com, but you can get it for the same price from M ouser or any other catalog source. The starter package includes a PIC16F690 microcont roller (MCU), so the free compiler and IDE do wnlo ads (plus the starter package) will give you everything you need to start programmin g. If you want to follow along with this article, you'll need these items. INSTALLATION The M PLAB IDE is a very powe rful tool, with a lot of features. I will go over the essentials you'll need to know in order to get started quickly. First, down load the latest release of the MPLAB IDE. 96 N UTSI V OLTS May 2008 As I write this article, version 8.02 is the latest. The M PLA B ID E downl oad is a zip file that needs to be extracted into the directory of your choice. Once you have un-zipped the files, you will see a file named "lnstall_M PLAB_vBJl2 .exe." This is the installation setup file that you need to run. Follow the installation procedure and let it install at the default directory. This will put the MPL AG IDE and all of its components in the C \ Program Files\ M icrochip directory of your hard drive. Next, do wnl oad the PICBASIC PRO compiler demo version into J directory on your hard drive. This includes an installation file called "PBPDEM 03 .EX E." Run this file and let it install at the default director y, which will be located at C \ PBPDEMO . Next, download the file called "PBPlugins.bat." This file is strictly for the M PLAB-PBPRO connection. You can get this program from the http:/ /melabs.com/sup p or t/ mplab.htm page, along with details on how to Li se the PICBASIC PRO compiler with the M PLAB IDE. I'm tellin g you my way of doing this because I found one little glitch that I could not get around, and I suspect you'll run into the same thin g. Run the PBPlugins.bJt program. The instructions at microEngineering Labs' rnplab.htm Web page explain how to update the search path for the version of Mi cros oft Windows® you are running. Follow those instructions and upd ate the search paths. Next is the Irick I recommend for getting around the glitch I ran into. Go to the C \ PBPDEMO directory and you will see three folders - INC, M CS, and SAM PLES. Add

Transcript of Getting Started With The PICBASIC Pro Compiler And MPLAB … Archive...where the PICBASIC PRO...

  • THE LATEST IN PROGRAMMING MICROCONTROLLERS ~r .

    ..

    - ."\ .

    ~ .

    • BY CHUCK HELLEBUYCK

    GETTING STARTED WITH THEPICBASIC™ PRO CO MPILERANDMPLAB® IDE[] I· It rEEl. Uc J( HAf h11} DE n ..,.;r. ~i 'r L ~hHflo ;jn~ I n t-tii jWhi ' \1Vt)uf ~lil( ~ tYie 'If) go back onlid Cti! .r h~Jin, '0 H"; '~ :S~,"'~ H;d; n...· tb ... ",hlf., or' t he c olw itb ':iUj~l(~

  • SETUPNow that everyt hing is installed, we need to set up

    the M PLAB IDE to recognize the PICBASIC PRO compiler.

    This list includes all the MCUs supported by the PICBASICPRO samp le version, w hich wi ll make it easier to find thesefiles later w hen we create a project in the MP LAB IDE.

    ·1

    ",,",",,~~~u1ml!--- - Iii,

    4 ) Add existing files to your project. This is w here you mayselect one of the PICBASIC PRO samp le fi les tha t youw ish to use or modify, or maybe an older fi le that youwrote. For this example, select the BLlNK.BAS file in thePBPDEMO/SAMPLES directory. Highlight it, and then clickon the Add» button.

    WA IT!!!! ! Don't press the " Next" butto n, yet. Instead,use a trick that I found - change to the PFILES directoryyou created and select the P16F690. INC fi le. Then, cl ickthe Add» button to add it to the project, as we ll. This w illsave you an error later. Finally, next to each file, you w illsee a big "A." Click on that A unt il it changes to a C. Thisw ill automatically copy these files to your project directory.Figure 3 shows what your screen should look like.

    3) Create a new project. Use the browse button, andselect the directo ry where you want to store the projectand all of the fi les. I suggest you create it as close to C aspossible, to keep the path name short. Figure 2 shows myproject, entit led " 16F690_Blink" in the PBPCode di rectorythat I created at the root.

    2 ) Selec t a language tool suite. Choose the PICBASIC PROtool suite.

    1) Selec t a device. Choose the PIC16F690, as that is thepart included in the PICkit 2 St?rter Kit.

    in the M PLAB IDE. Click on the M PLAB Project menu andselect the Project Wizard. You will be wa lked thro ugh sev-eral w indows, which take you thro ugh the fo llowing steps:

    P16F871.INCP16F872.INCP16F873.INCP16F873A. INCP16F874.INCP16F874A. INCP1 6F876.INCP16F876A.INCP16F877.INCP1 6F877A.INC

    a new directory called PFILES. Now, go to the directoryw here the M PLAB IDE is stored (C \ Program Files\M icrochip\MPASM Suite) and you w ill see a bunch of filesthat start w ith a "P" and end w ith an ". inc." These includethe Ii les the compiler w ill look for and, for some reason, Icould not get the M PLAB/ PICBASIC PRO combination tofil":;:! them. I even changed all the recom mend ed pathstatements show n on micro Engineering Labs' MP LABinstruction page and it still co uld not find them. You cancop y all those Pxxx.inc files into the PFILES directory thatyou made, bu t I suggest you just copy the list below:

    P12F683.INCP16F84.INCP16F84A. INCP16F627.INCP16F627A. INCP16F628.INCP16F628A.l NCP16F688.INCP16F690.INCP16F870.INC

    1) Start M PLAB and select "Set Language Tool Locations"under the Project menu.

    2) Select the " PICBASIC PRO Tool suite" name.3) Use the brow se button to select PBPDEMOW .EXE in the

    PBPDEM O directory wh ere the PICBASIC PRO Demoversion w as installed.

    5) At this po int, you're done so click the FINISH button .

    FIRST PROGRAMOdds are that your MPLAB screen is now blank. If so,

    II: FIGURE 1. PICBAS IC PRO Langu age Sel ection.

    r Location- - ------------- -·

    I l c: \PBPDEMO\PBPWD EM~ . ExE _

    - Registered Tools·----- --·--- -----·----··-- - ·---··- --- - ·-····---··- --1! . I

    I

    ftc IAR Systems Mldranoe • I~; M ~croch~p .0.5: 130 T~o lsuite I

    ! Lt' Ivhcrochlp Cl l Toolsuite II 8') Microchip C18 Toolsuite II t±) .Microchip C30 Toolsuite !! it" MiclOchip MP.6.5MTcolsuite 'JIi f? MicrochipPIC32Assembler Toolsuite i, Et.~ MicrochipPIC32 C·Compiler Toolsuite I

    :::: microEngineering PicBasic Pro Toolsuite I[=; Executables I

    microE ngineering PicBasic Pro Compiler [pbpw.exe] ~ I

    May 2008 NUTSIVOLTS 97

    Cancel ApplyHclp OK

    Figure 1 show s the w indow you should seew hen you co mp lete these steps. By choosingthis path , you are indicating to the M PLAB IDEw here the PICBASIC PRO compiler is locatedon your hard dri ve. Click on the OK button toaccept this, and you are now ready to use theMPLAB IDE w ith the PICBASIC PRO demoversio n. If you have the full version of PICBASICPRO, all the steps are the same except thePICBASIC PRO w ill be installed in the C \PBPdirectory, and the file you select in the browsew indow is PBPW.EXE.

    Now, you are ready to build your first project.In the MPLAB IDE, all the software files you createw ill be connected by a project structure. The easiestway to do this is to use the Project W izard utilit y

    FIRST PROJECT

  • Intial i ze AID port s o ff, Ini t i aL ze COJllpar ator 1 of f, Ini t i a l ize Copara t or 2 off

    working. At the top of the program, thou gh,are a few statements that might confuse thebeginner. These are show n below :

    ANSEL ~ 0CHICONO ~ ()CM2CONO ~ a

    These s tatements are requi red for usingthe PIC16F690 MCU's I/O as digital pin s. ThePICl 6F690, like many ot her PIC M CU s, multi-plexes the pin connections w ith o ther features.The PIC16F690 M CU has bo th Analog- to-DigitalConverter (ADC) po rts and co mpara to rs tha tshare the actual pin connections w ith the digitalI/O circuitry. To use the digital I/O pin s, youmust make sure the ADC and comparators aredisconne cted. For this pro ject, we ' ll disconnectthem by clearing the bits in these registers -Analog Select Register (ANSEL), Comparator 1Contro l Register (CM 1CO NO), and Comparator2 Control Register (CM 2CO NO).

    The rest of the program is just a Hi gh, Low, andPause loop that acts on the PORTC pin, RCO. This pin isconnected to the OS1 LED on the PICkit 2 starter board.By flipping the level on the RCO pin from high to low w itha pause in between and looping through that sequencemult ip le times, we make the LED flash.

    O nce the program is w ritten, simply press the FlObutton to co mpile the PICBASIC PRO file in to a binary.hex file. If everything compiles w ithout errors, you w illsee a "Build Succeeded" message in the outpu t window.If you receive an error message, it w ill tell you in w hichline of code it is so that you can see what typo you mayhave accide ntally made.

    PROGRAMMINGTHE PIC16F690 MCU

    Help

    Browse...

    Cancel!iext>

    ;.1,::, ---- ------- ------.--.--.-.-~-- -0----

  • May 2008 NUTSIVOLTS 99

    Loop back and blink LED f or ever

    Tun) off LED connected to PORTC .ODelay for 5 seconds

    Turn on LED connec ted t o PORTC .ODelay for 5 seconds

    , Initialize AID ports offInitialize Comparatorl off

    , Initial ize Comparator2 off

    End

    Low PORTe . 0Pause 500

    Goto l oop

    To get throu gh all of this without erro rs is a very goodstart. However, chances are you might see a few errors, orget all the way to the end and find that the LED does notflash. I' ll try to cover a few of the more common errorsthat the beginner might run into. The fir st involves thePICBASIC PRO comp iler and the MPLA B IDE/Window sstructure. For some reason, no matter how I changed thepath structure in Windows or reset things in the M PLABsetup screens, I wo uld encounter the error shown inFigure 8 w hen I fir st tr ied to run the PICBASIC PROcompiler in the MPLAB IDE.

    In fact, I received a whole list of errors that startedw ith the line "Cannot op en file ... P16F690 .INC." This is

    M CU, and then program and verify it. Afte r this, theprogrammer is ready to run. Click on the rising-edge buttonto bring MCLR to VDD. The LED should start to flash.

    ERRORS

    , Example program from manual to blink and LED connected, t o PORTC .O about once a second .

    loop : High PORTC .OPause 500

    ANSEL = 0CMlCONO 0CM2CONO 0

    LISTING 1: BLlNK.BAS Sample Program

    - '-.J soe ce fi!t~~C: 'PBPC(od~\r.l!NU1A5

    - :-l Header F~~~ C :\,P6F'(W\P I 6F690 , l N':

    :....JOther F~e5

    ··--·-- -'-i--- ···- -·'·'--- PICt6f 691:l- --. ·- --- r- --- - - ~~o · - - - · .zdc-c ·-- ~·· I"--r---"·bri.~o·· r-' "'----. "-"r-~J '- ~i » :~ Caielmf · I

  • FiGURE 7. PICkit ::' Control Su ttons.

    _ confi g I NTRC_ OSC NOCLKOUT & WDT ON& MCLRE ON & CP OFF

    . r-i(3U:~E ;~ . :~:Ckit .~ Fr(l,~' r;_dT:r: ·i(; (Sf:;iei-;tI Oil.

    M CU you are using. In this case, thefile is named 16F690 .inc. You w ill findit in the PBP or PBPDEMO directory,w here you installed the PICBASIC

    ·~ PRO compiler. The file w ill contain a_config line, like the example below :

    This line in the 16F690.inc file iswhere the PICBASIC PRO co mpilergets the information on how to set theconfiguration bit s inside the .hex fil e.In this example, the internal RCoscillator is used as the system clock.This is wh at I reco mmend for thePIC16F690 MCU, but you can changeit to an external oscillator if you needmore accuracy. For the beginn er, Iwould not wo rry about all of this - justknow that it exists. However, if you findthat you r LED does not flash, then youmight want to make sure the settingsare adequate for what you need. Forexample, if you are developin g on a

    board that has an external 20 M Hz crysta l and you keepfinding that the program is running slow, you might havethe internal oscillator set up in the configuration.

    O ne of the biggest errors I've seen with beginners is theexact opposite-they think they are using the internal oscillator,but the configuration is set to run from an external oscillator(i.e., _XT_OSC). The MCU won't run withou t a clock.

    CONCLUSION

    Checksum: lJxd2dl

    J

    w hy I suggest you use the proj ect wizard the first time youcreate a project, and include the P file for the part you areusing to prevent this error from occurring. If you forget,you can add a copy of the P file later, but it has to be putinto the same directory as the .bas file you created,

    Anoth er beginner error that crops up often invo lvesthe co nfiguration sett ings. Outside the structure of yourprogram, the PIC1 6F690 MCU has certain bits that areset at program tim e to control the watchdog tim er, thepower-up tim er, the oscillator selection, and more. Allof the options for the part can be seen by clicking on theConfigure>Configuration bits menu selection in the MPLABIDE (see Figure 9). You can manually select the options, orclick on the littl e box in the upp er-left corner to allow thecompiler to set these in code.

    I recommend that you set the options in code, becausethey w ill then be embedded in the .hex file used to programthe M CU. The PICBASIC PRO co mpiler puts that configu-ration setup in a separate file that it calls at compile time.The setup will be in an .inc fil e that has the name of the

    Execunnq MC.\PBF\PBPWEXE· -empesmwin-cq-t -p16F690 "stcpwetch.bes"E1'1'o1' (1 05 ] C ', PBP, 16F690 me ~ 1 Ca nno t open fil e ( I nc l ude Fr Ie ~ P 16F~~ 9 0 rue not f ou nd )Error ( 11 3 ] C . ', PBP'· 16F b ·~ O rue 22 . Sy ebol not pr ev i c us I v de I i ne d LINTRC_OSC_lI 'XI.Y.('UT )Er r o r( 11 3 ] ( ' PBP' 16Ft.90 . UK ~ 2 Symbol no t prev acue I v de f i ne d L IJDT_Otl )En o I'( I ! 3 1 C. ·...PBp · .lt. f 6 ~ O we ::2 . S:,nl\bo l no t, previousl y de t m ed C-UC1RE_OFF)E:::.:-c,l' { 11::1 I: . ', PBP ' 1 t.F '; 90 . IH~ 2 ':: S ymbo .l no t pre~'l olE:ly def aned (_ ( P_') FF )Error[llS} C ' '; +COVE'.PBPDEllth STOPlJiiTCH ASH 5 9 Du p l i c a t e Le be l ( "_ PORTL " '::>1' redefl ning ::; y ,~ bol tha t cannot be r edet~rror [ 11 3] C . , ,1,, +( ODE' -PBPDEIIO'STOPlJATCH , ASH 1)1 S vnbc I no t p r e v acus I v de f i ned ( PORTe)c.rro r [ l 13 ) C : ' .A+CODE·"PBP[IEUO' .STOPtJATCH ASU 6 3 S Vll\ bo l not crevrous I v de f i ne d ( TRISh )Error (i 1 3 ) I: .~ ;"+C(lDE ·' P 8PDEHO'STOFI'I ATCH . ;.sH SS Syabc I not pre':'l ou !:lly def i ned (TRI SC )~r r"' '''' f l ' ::: l I ,

  • : ~: ; .,. : '-;~- ' _~ ,i£lC: ~:" ._,,_..: .'" .s .d.§Jed Debugger Programmer Tools i Configure Window Help

    -"~--~~"-;" ~iOP.i Address I Value I cacecory I SettingII I II I ,.

    RiAWat ch dog Timer OtfPo wer Up Timer On

    Has t.e I:" c Ieer Enable InternalCode Protect On

    RiA T Data EE Re a d Protec t OnBrown Out Detect BOD and SBOREN d isabledInternal External Switch OVer Ho d e Disab led

    RTA llo n ito r Clock Fai I-s a f e Disabledl JlORT

    I.T. -I I •

    S, Confiq urat ion M enu,

    people who are just gett ingstatl ::d w ith MCUs. O nce youget an I_ED to flash, the fearsubside' Sand you begin tounck_'rst;:1I1d things much easier.YO l' can go back and re-readmy prev ious co lumns, andsudden ly all of the co mplica tedstuf f becomes easier.

    Another probl em is thatsome readers are famili al- w ithusing littl e Basic modul es thathave all the inner details hidd enfrom the user, in order to makethin gs easier. You pay for that, thou gh, by not having theability to use all the features an M CU can offer. Ma ny times,you sacrifice speed and memory space for simplicity, not tomenti on payin g a lot more for the MC U. This w ill seem likea leap at first but, trust me, it 's not that tou gh.

    O n th e other side of the fence, I receive other-co mme nts stating that I ofte n use too simple of anexample - such as flashing an LED - to show how to getstarted (as I've do ne in this co lumn). I w ill cove r moreco mplicated projects using th is same M PLAB IDE,PICBASIC PRO compi ler (sample version), and PICkit 2Starte r Kit setup in futu re co lumns. The idea I have w iththis new app roac h to the beg inner path is to use a co m-mon , but pow erful and profession al set of developm enttoo ls and softwa re to create a step-by-step guide to getti ngstarted in programming. I plan to use th is same setup inmany future co lumns to rem ain co nsistent. I hop e you' llco ntinue to tun e in , Aft er readers get more co mfo rtablew ith the PICBASIC PRO co mp iler, they can then advanceto the full version or possibly co nvert to th e C language.By then, my Beginner's Guide to Embedded C Programming

    book should be in print, and I can help you down that path.Please send your feedback on this particular article to me,

    so that I can determine how successful you we re in gett ingall of this to work. M y email address [email protected] try to answe r all emai ls, bu t I sometimes find messagesfrom readers caught in my spa rn filt er. Please write "N uts& Vo lts" or "N&V" in the subjec t line to help me fin d youremail. Your feedback w ill enable me to explain the subjectmatte r of my co lumns in more co mplete ways (there iso nly so mu ch I can fit in to a few Nuts t'V Volts pages).

    Additi onally, if you get a chance, check out my new web-site dedicated to my books-www.elproducts.com. If you area fan of my modules and other hardware, you can now buythem from my friends at www.beginnerelectron ics.com.

    I hop e yo u tun e in to my next co lumn (Ju ly '08 issue),w here I'll show you how to use an ADC to read th epotentiom eter on the PICkit 2 deve lop me nt boa rd. 5-;;:1\\£

    WithAccessoriesfor $119,95InciudesProgrammer, Sottwere. USB Cable,and Programming Adapterfor 8 to 40-pinDIP.

    See our full range of products, includingbooks, accessories, and components at:

    www.melabs.com

    PICBASIC PRO" Compi ler $249 .95Supports most P ICmicro® MCU FamiliesDirect Access to Internal RegistersSupports In-Line Assembly LanguageInterrupts in PICBASIC and AssemblyBuilt- In USB, 12C, RS-232 and MoreSource Level Debugging

    BASIC Compilers for PICmicro®

    I' Easy-To-Use BASIC Commands

    f'~" Windows 98/Me/2KJXP/Vista

    ~ ~~ , .~. PICBASIC '· Compiler $99.95;: ' i " .' BASIC Stamp 1 Compatible~ , : "':::::- , Support» most 14-bit Core PICs$ , Bunt-In Serial Comm Commands-_._-,._'._--

    Pricing from $8.95 to $19.95

    LAB-X Experimenter Boards- - Pre-Assembled Boardr---l Available for 8, 14, 18,28,

    and 40-pin PI(Ji!!MCUs2-line, 20-char LCD Module9-pin Serial PortSample ProgramsFull Schematic Diagram

    Pric ing from $79.95 to $349.95

    PICPROTO'M Prototyping BoardsDouble -Sided with Plate- Thru Holes

    Circuitry for Power Supply and ClockLarge Prototype AreaBoards Available for Most PI(Ji!!MCUsDocumentation and Schematic

    EPIC'· ParallelPort Programmerstarting at $59 .95

    Programs PICMCUs includinglow-voltage (3,3V)devices

    tnc'uaesSoftware forWindows98, Me, NT.XP,and Vista,

    May 2008 NUTSIVOLTS 10 1

    EPSON001EPSON002EPSON003EPSON004EPSON005EPSON006