New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Louisa O'Kon I


Louisa O'Kon I
OK State
GPA 3.58


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course


This 0 page Class Notes was uploaded by Louisa O'Kon I on Sunday November 1, 2015. The Class Notes belongs to ECEN 4213 at Oklahoma State University taught by Staff in Fall. Since its upload, it has received 14 views. For similar materials see /class/232915/ecen-4213-oklahoma-state-university in ELECTRICAL AND COMPUTER ENGINEERING at Oklahoma State University.

Similar to ECEN 4213 at OK State





Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 11/01/15
ECEN 4213 Computer Based System Design Microcontroller Architecture Dhinesh Sasidaran PIC16C57 GENERAL DESCRIPTION The PC16C57 is an EEPROMROM based 8 bit CMOS Microcontroller It contains a Reduced Instruction Set Computer RISC based Central Processing Unit CPU with only 33 single word instructions All instructions are fetched and executed within a single cycle except for program branches which take up 2 cycles The maximum operating frequency is 4OMHz ARCHITECTURAL OVERVIEW The PC15C57 microcontroller uses a 2 stage pipelined Harvard architecture in which program and data are accessed using independent buses This architecture enables instructions to be fetched in one cycle While program memory is being accessed data memory is on an independent bus and can be read and written This improves bandwidth over the traditional von Neumann architecture where program and data are fetched on the same bus The von Nuemann architecture requires more accesses across the bus to fetch the instruction and the data will then need to be operated on and possibly written back This makes the bus extremely conjested With the Harvard architecture instruction opcodes are 12 bits wide while data word is 8 bits wide With the addition of the pipeline stages the fetch and execution cycle are allowed to overlap The microcontroller contains an 8 bit Arithmetic Logic Unit ALU and working register This device is an accumulatorbased architecture whereby one of the operands is implicitly in the accumulator also called the working register W The ALU performs arithmetic and boolean functions between the data in the working W register and any register file The W register is an 8 bit working register used for ALU operations and is not an addressable register Figure 1 shows the block diagram of the PlC16C57 The clock forthe system is obtained from an external memory component called an oscillator The clock enters the microcontroller and will be then divided into four non overlapping clocks which make up one instruction cycle during which one instruction is executed With the pipeline stages the execution of instructions start by calling an instruction that is next in line Fetching decoding and execution of this instruction will then be done during the next instruction cycle Figure 2 shows the ClockInstruction cycle for the microcontroller Microcontroller Architecture August 29 2002 1 ECEN ma Cumpmev Based System Desng m M W FIGllRE 1 PIC16C57 zmhile ure hlnck diagram um m1 m1 we Que Qx qz Qz QMQHQZ Qz Q 050 Q Q2 Lxmm 4 39 m Q3 1 EM Q 7 Dc K Exezuu stTDc FIGURE 2 clackInstructinn cycle wammm mm Anamzmnnz ECEN 4213 Cembutet based System Destdn Frum thure 2 the tnstructtctn cycte cctnststs ctr cycte 01 02 as and 04 Thrctugh ptpEr ttntnn a auut cyctes are needed rctr executtctn at an tnstructtctn Thts ts because the tnstructtctn must be brbcessed agam and truth the nghtaddress The tnstructtctn Regtster H tswrttten durtng the at Etuckwhtte the decctdtng and executtctn starts wtth 02m and 04 ctucks ttwb Flpellne Flow a tttt ut t t euttu t ANHAA FUJEV ttntng ts tntrctduced cxccuttbn btbettne stages and extts but at the ctther end Ptpehmng ts trnbternented by addth a reg tster between each stage at the tnstructtctn cycte Furthe women there are 2 btbettne s shctws the tnstructtctn cycte databath as tt prugresses thrctugh the btbettne chz ch3 row ch5 63 r vuktAtana onedNuP FlGlJRE 3 Instructinn pipeline nw tn thure 3 abctve chu reads tn tnstructtctn MOVLW 55h cht ts when tnstructtctn MOVLW 55h ts beth executed whtte the nexttnstructtctn MOVWF PORT 3 ts beth read SUEJ subpmgram CALL su EJ and reads tn the tnstructtctn ESF PORT At Etta Stnce the PC the R r EN 3 tnstructtctn whtch has atready been retched must be rtushed truth the ptpEr ttne whtte the new tnstructtctn must be retched and then executed Wmmdlzukmhnncm Angm 2 mm 3 ECEN 4213 Computer Based System Design th h t instructions roug pu ti me The following diagram Figure 4 shows the comparison between an unpipelined proces sor and a pipelined one instruction clock period number number 1 I 2 I 3 i Fetch i DecodeEgtltecuteigt i1 i Fetchi1 unpipelined I I instruction number i Fetch i W Execute igt i1 WW1 gtlt3ecode Executei1gt pipelined Fetch i1 FIGURE 4 Unpipelined vs Pipelined processor 1 instruction in 2 clock periods have been reduced to 1 instruction in 1 clock period Therefore throughput have been increased from CPI Clocks cycles per instruction 2 throughput unpipelined CPI Clocks cycles per instruction 1 throughput pipelined Computer Operation Codes Opcode The first step of a design of a microcontroller is to determine the type of operations it has to perform The operation code is part of the instruction set and essentially encodes all the functions ofthe microcontroller thus providing a unique code for each necessary operation Figure 5 shows the instruction set opcodes operands and the operations that the PC16C57 can perform Microcontroller Architecture August 29 2002 4 ECEN 4213 Cnmputer Based System Deswgn Mnemomc 0mm nescmnmn Add w mm AND W wth bar by w mmemem memem Ecremenl a 5m n a ncremenl r kw n o x we on w mth Va 0 Yuve w w a Onem on m 3E 21 v lhquh cw Dlake nghl r lhmuqh cm uhtmcl w mm my Em Se Em Tea 5m C ear Em TesH 5km w Set ste on Lxlem n W FIGURE 5 Instruction set opcoueoperanus for the Pc1scs7 central Processing Unit CPU tne current mstructmn decnmng wt and Executmg n Tms umt cunnects aH pans nfme mm W H mm ugH an Erbwtd 39 n N HaH x m aH m tame nntrnHEr e x m tne Regwster FHE and me Antnrneu Lngu umt ALU Mmcmmutmecm August 2 mm s ECEN 4213 Computer Based System Design Program Counter PC The program counter is a register that holds the address of the next instruction to fetch from the program memory and is updated by one at every instruction cycle unless an instruction changes the PC The processorthen fetches the instruction from the memory location pointed to by the PC places it in the Instruction Register IR and then incre ments itself The PIC16C57 has an 11bit PC used to access the 2048 x 12 program memory Figure 6 shows a simple PC implementation To memory clock FIGURE 6 Program counter example Instruction Register IR The currently 39 339 is stored I quot in the39 quot register The processor interprets the contents ofthe IR via the instruction decoder and determines the type of operation to be executed depending on the instruction set Figure 7 shows the contents of the IR if a byteoriented instruction is loaded register clockA OPCODE d from ALU sourcedestination binary decoder binary decoder to 8 Register to to W Register FIGURE 7 Instruction Register Microcontroller Architecture August 29 2002 ECEN 4213 Computer Based System Design ALU The Arithmetic Logic Unit ALU is the core of any processor which performs the calcula tions arithmetic boolean and shifts on the operands The ALU is bascially a number crunching mechanicsm which computes the results based on the control signals provided to it by the opcode part of the instruction set The opcode is used to select between the the arithmetic boolean or shift operations Figure 8 shows the block diagram of the ALU Depending on the type of operation performed by the ALU the status register will be affected to and from W register from register ALU to status register FIGURE 8 Block diagram of ALU Register File Highest level ofthe memory hierarchy which is determined by the data memory The data memory is actually divided into 2 Special Function Registers SPRs and General Pur pose Registers GPRs In the case of the PlC16C57 there are 8 SPRs and 24 GPRs which are 8 bits wide SPRs are registers used by the CPU and peripheral functions to control the operation of the device The Register File for the PC16C57 is a single port memory device which is implemented using Static Random Access Memory SRAM technology Figure 9 shows the registerfile block diagram for the PlC16C57 STATUS 8 spRs FSR 24 GPRs FIGURE 9 Register file block diagram Microcontroller Architecture August 29 2002 7 ECEN 4213 Computer Based System Design IIO Ports Ports refer to a group of pins on a microcontroller which can be accessed simultaneously or on which we set the desired combination of zeros and ones or read from them an existing status They represent the connection of the CPU and the outside world The ports are basically lO registers which can be read and written under program control There are 16 fully programmable lO s on the PC16C57 which can be used interchange bly for both input and output Figure 10 shows the equivalent circuit for a single lO pin The Output Driver Control Registers are loaded with the contents of the W register by executing the TRIS f instruction A 1 from a TRIS register bit puts the corresponding out put driver in a hiimpedance state input mode A 0 puts the contents of the output data latch on the selected pins enabling the output buffer Nil l39v39fl FIGURE 10 IIO pin Memory organization The micrcontroller is divided into program memory and data memory The PC16C57 has 2Kx 12 program memory space and is accessed using a paging scheme The program memory pages are accessed using one or two STATUS register bits Figure 5 shows the program memory map for the microcontroller The data memory consists of 32 registers 8 SPRs and 24 GPRs Microcontroller Architecture August 29 2002 8 ECEN 4m Cempmer Based system Desrgn Stack Leve 2 Oncmv qumm Mammy mags m Dn END qumm Mamaw wigs Oncmv qumm Mammy may On mm qumm Memary rpm 3 RESU Vedar FIGU RE 11 Program memory map Instruction set summary Each rnstmetrun rs Wirbrts Whmh specr esthe rnstmetrun type and tune Dr mere uperands Whmh further spem esthe uperatmn uf the rnstmetrun The rnstmetruns are gruuped mm byterurrented bmurrented and rrterar and untrm uperatmns Furthe women a 2 uperr resu t mm d F m regrster H m r at r r u ngL uperatmn rstu be praeee rt e rs uxtheresurtrspraeeernthevvregrster f d rs the turmat ter a byte errented ms tructmn 4 r LUBE tr quot39hrMnsHH um I tr 1w rrrsmmnmr t lm star FIGU RE 12 aytenrrenten me regrster nperatmns mmumummn August 3 mm ECEN 4213 0277712727 32522 Sys em D2573quot 7 77772 7 wt 75 ucated F7gu72 6 snuws m2 g27727a7 funnatfur a bwtru ented mstructmn M a 7 5 4 OPCODE 77mm u bu 27177255 m 7772 72g7s27 3227255 FIGLIRE13BiL ienled m2 7292127 nperminns 77 x7 27 777 a 7 7W 77 mm 7777 m7 am g ure 7 snuws m2 g27727a7 727m atfur 77t27a7 and 22771727 77517772172775 Lneral aml comm 27272772775 exnem 00707 M a 7 77 OPCODE x 77772727 k 277 77777271777277 Mara and cnmrnl Buzmlmnsr com 7775772277277 M 9 a 7 OPCODE Muemu 7 Brmhmmedmlevmue FlGlJRE 1a Literal and cnnlrnl npemlinns Insxrucuon Examples 77 727 m 7 H717 7 72975127 77 2 uxm277 m2 725mm 22 512722 777 m2 W 72975127 77 2 m277m2 725mm W777 22 512722 back 777 m2 72975127 22s7gnat2u by 7 1y ADDWF nu Operatmn W r 77gt nest Encudmg mum Mdf m Examp72 ADDWF TEMPiREG D Eefure mstructmn W EIgtlt17 n Wmmxumm Angm 2 mm m ECEN 4213 Computer Based System Design TEMPREG OxC2 h After instruction W 0xD9 h TEMPREG OxC2 h In example 2 below the contents of the W register are AND ed with the eightbit literal k The result is then placed in the W register 2 ANDLW k Operation WANDk gt W Encoding 1110 kkkk kkkk Example ANDLW H 5F Before instruction W 0xA3 h After instruction W 0x03 h In example 3 below the contents ofthe W register are AND ed with register f If d 0 the result is stored in the W register lf d 1 the result is stored back in register f 3 ANDWF fd Operation W AND f gt dest Encoding 0001 01df ffff Example ANDWF TEMPREG1 Before instruction W 0x17 h TEMPREG OxC2 h After instruction W 0x17 h TEMPREG 0x02 h Microcontroller Architecture August 29 2002 11 ECEN 4213 Computer Based System Design In example 4 below bit location designated by b is set in register f 4 BSF fb Operation 1 gt fltbgt Encoding 0101 bbbf ffff Example BSF FLAGREG 7 Before instruction FLAGREG OxOA h After instruction FLAGREG Ox8A h In example 5 below TRIS register f f56 or 7 is loaded with the contents ofthe W reg ister 5 TRIS f Operation W gt TRIS registerf Encoding 0000 0000 Offf Example TRIS PORTB Before instruction W OxA5 h After instruction TRISB OxA5 h Microcontroller Architecture August 29 2002 12 ECEN 4213 Computer Based System Design BASIC StampBoard of Education Introduction Dhinesh Sasidaran Microcontrollers A microcontroller is an inexpensive computer on a single chip It is capable of storing and running programs similar to a standard personal computer Microcontrollers are used in many modernday electronics ranging from microwave ovens to televisions and not to mention cars They are used to perform a specific function or a range of functions for a particular system and is typically not designed to be programmed by the end user The microcontroller is typically used to replace mass logic circuits in a system but intro duces a hardwaresoftware codesign requirement However with the introduction of a software component ease of programmability and flexibility is also introduced which allows the designer to create variations on the design by changing or updating the soft ware Interfacing with the outside world is done through the microcontroller s InputOutput lO pins A microcontroller performs its functions by taking the inputs from the embedded sys tem it is controlling and controls the system by sending signals to its different compo nents The output pin reflects the value of some bit in the microcontroller s memory which is determined by the software program stored in memory Components of a Microcontroller A microcontroller s brain is the Central Processing Unit CPU The CPU basically fetches decodes and executes the instruction set Memory is an integral part of the microcontroller It essentially functions to store data The peripherals of the microcontroller allows communication with the outside world Input peripherals take in external signals and produces an external signal on the output periph erals based on the software routine The software adds value to the entire embedded system by determining how the system works and how well it functions The BASIC Stamp The BASIC Stamp is a small 8bit microcontroller produced by Parallax Inc It is a Pro grammable Interface Controller PlCbased device the size of a postage stamp and runs on a simplified form of the BASIC language called PBASIC Parallax BASIC program BASIC StampBoard of Education Introduction October 14 2002 1 ECEN 4213 CempdteT Based System DesTdh ThTs mTerueuhtruuer has Te To pThs that can be used tn dheetTy Thterraee tn the udtsTde WEIHd These To pThs are at Thput pThs by deramt but are My pmgrammame Ware mutThe and RAM fur sturage urvahames used Th yuur prugram EEPROM may aTsu hd mes Thtepretereth The Thtepretereth retehes the ThstmetTuhs uhe at a tune and permhhs the PEASIC macs1 2a m MM Tad dmrmt a vveymalnv FlGlJRE 1 BASIC Stamp cnmpnnenls Hoard of Education EOE ddTTdTTTd a TT dTT mTerueuhtruher The buard pruwdes the meahstu prugram the stamp and uhtaThs sTmpTe Thputuutput dEVTEES The buard euhtaThs the ruhuwmg T h T TTTWT T T T hTeatTuh duhhg ru rUmE 2 WaHrpaEK ur Brvmt battery puwersuppTy euhheetmhs a A Reset buttun tn restan the 352 prugram A FEW 15 To pms Vdd ahd V55 euhheet ans 5 Fem aTe WEIme duaT ruw uhheeturrur uptTuhaT AppM eds fur To uhehted garments and adthTuhaT breadbuard mudmes e 2 gtlt T 38 Ereadbuard area BASIC mudam uvahnmchmm ucm Omaha 1 mm 2 ECEN 4213 Cumpmev Based Sys em Desng Usmg the breadboard x1 m m mm a mac r5 1 F Wmng 1 Pms ave shunned JD Duu FIGURE 337 IC plugged inln hrezdhnzrd w W w Fur Examp e fyuu use 3 av battery men m av mxc Sump502d uvahmcmxmmm Oahu 1 mm ECEN 4m CempmeT Based SysTem DESTgn PAslc Stamp lO Access vaa and Vss breadbuard The To pThs are accessed by pTuggThg WTres mm the header theh Thm the x3 sucketfurvdd and V55 Programming the Plum Stamp m Wm TTT Tu T TuTT TT ha remmeh utes TTT TTTTT TTTT TTT e a a heynum a d muhTmr a d Send the nude thruugh the prugrammThg came m the mTErDr untruHEr ThTs prugram then runs ThsTue the aAsTc Stamp me Even T m UT TTT TTTT mu THTT TTTTT Ware E d Pruperdebuggmg ufme suftware WTTT Ehmmate these prunTems The Temp UHUY grams m the mTcrucuntruHEr PROGRAMMING EXAMPLE Th thTs sTmpTe Examp e We WTTT be aAsTc Slam LED s are a spEETa netted m mTErDEDnthErdEVTEES uhheeuhg we LTght EmTuThg DTEIdE LED s m the T mm at Tamp that furvarmus reasuns are EasHy EDHV The Wu maTh thmgs m euhsTuerwheh EDWTEEUHQ LED s m the aAsTc Stamp The mat Ts Ham 4 SEEDHdTy make sure matthe puTahty ufme LED Ts current Tnhe puTahty Ts reversed the LED WTTT nutwurk m 2 s4 4ch 4 Q70 s FIGURE 5 LED canne inn In BASIC sump pin mxc Sump502d armumxmmm Oahu 1 mm ECEN 4213 Computer Based System Design Each of the BASIC Stamp pins has a signal namequot associated with it For example pin 24 is VIN pin 5 is PO pin 6 is P1 and pin 21 is Vdd 5 volts Therefore when pro gramming the BASIC Stamp we refer to the Signal Name rather than the actual pin num ber associated with it PBASIC has many commands to choose from 36 to be exact However for the purpose of this example we will look at only 4 commands OUTPUT PAUSE GOTO and OUT The program will be executed in a sequence determined by the structure of the program itself It is important to keep in mind the sequence of instructions that we desire The Stamp Editor can be used to write and download programs to the BASIC Stamp microcontroller Once the program has been written it will be downloaded into the micro controller The following is an example of a program to be typed into the Stamp editor output 0 make P0 an output reblink loop begins here out0 0 turn on the LED pause 1000 wait for 1 sec with LED on out0 1 turn off the LED pause 1000 wait for 1 sec with LED off goto reblink go back to beginning of loop After running the program and downloading it into the microcontroller If everything went well the LED connected to PO pin 5 should be blinking on and off The second LED won t blink yet because we haven t written any code to control it The first command used is output Each signal PO amp P15 can be setup as input or out put Since we want the microcontroller to manipulate the LED real world then we want PO to be an output The first command output 0 makes PO an output output 1 makes P1 an output The next command reblink is a label To turn the LED on we need to cause PO to go low Here PO is acting as a switch that can be flipped on or off using the program control Current flow is from voltage through the resistor LED and into PO where PO is connected to ground Figure 5 shows the cir cuit condition when PO is high and Figure 6 shows the condition when PO is low BASIC StampBoard of Education Introduction October 14 2002 5 ECEN 4213 Campum Based Sys em Desng FlGlJRE 5 LED is an FlGlJRE 6 LED is an The secunu Dmmand Out m cause PEI m gm uw wmch m turn causes the LED m turn an Hu swpxy turmng an we LED and turmng L err wnn me next cummanu wm nut shuw any vwswb e resuus Therefure me prugram needst be s uwed uuwn usmg me Pause cummanu The Pause mun cummanu causes me pmgram m wanrur mun mmsecunds um 527 and The next Dmmand s numw ans Dmmand causes me PEI m gm mgn ans turns the LED err because mere 5 nu urrenmuw Nextwe pause mnn u urwanrur anumem sec emc sumam uvahmchxmvhccm 0mm 1 mm ECEN 4213 Computer Based System Design The Goto command causes the program to jump to another part ofthe program In the programing example goto reblinkquot causes the program to jump to reblink and executes the commands again This causes the LED s to continuously flash on and off Comments remarks are distinguished from program code with the apostrophe sym bol Readability is enhanced with the use of comments in your program In orderto reduce the number of lines and to simplify the program we can change the program example to the following reblink beginning of loop low 0 make P0 an output and low pause 1000 wait for 1 sec with LED on high 0 make P0 an output and high pause 1000 wait for 1 sec with LED off goto reblink jump to beginning of loop BASIC StampBoard of Education Introduction October 14 2002 7 ECEN 4213 Computersased systern Design IO Interfacing Issues Dhinesh Sasidaran the outside the the microcontroller The user can enter program and data execute the program and obtain the results on the HO plnS There are two main factors to considerwhen interfacing to the outside worl 1 The physical and electrical characteristics between the microcontroller chip and the external deVICeS being interfaced VoltageCurrent limitations physical connections common ground 2 Com munications aspect lOs data transfers Electrical Characteristics M leum output current sunk by any O pin 25mA 2 Maxlmum output current sourced by any O pin 20mA Vdd5f Vdc n v Vdd til39 l Britle stamp Output touiuut m FIGURE 1 Currant source and sink oezsmA is enough to light up and LED but it is not enough for relays lamps motors and other load chip in Figure 1the load is ered from the output pin to ground When you set an out r the rom put pin high 5v appears ac oss load resistor RL Load current Will ow f gro nd to the resistor and into the output pin This is the current sourc IO Intufamnglxue SEPumbex 22 2002 ECEN 4213 Computer Based System Design Also in Figure 1 the load is between the output pin and the 5V VDD supply Electrons will flow through the load now when the BASIC Stamp output is set Lowground Cur rent will flow from the BASIC Stamp output pin and up through the load resistor to VDD This is the current sinking mode Maximum output current sunk by a single IO port PORTA B and C 50mA Maximum output current sourced by a single IO port PORTA B and C 40mA The total current sunk by any port should not exceed 50mA while the total current sourced by a single port should not exceed 40mA A00 01 Power Supply VDD 5V through the voltage regulator If your power supply is between 615V you should connect it to pin VIN and GND pins or to the battery clips 0 Input impedance of IO pins 1 Meg Ohm DRIVING LARGER LOADS Many real world devices are not suitable for driving directly from a STAMP pin A relay is a common example A relay coil may require 50100mA to turn on A lamp is another example of a device that requires more current than the STAMP can source Sometimes the load does not require more current but need more voltage instead In either case there needs to be a way to switch the load indirectly The BASIC Stamp s current andor voltage capability can be increased with the addition of an output transistor Circuit component values stem from load current and voltage 39 lquot quot a on the 39 of the device to be controlled the appropri ate current andor voltage boosting device can be selected For example a bipolartran sistor or a power MOSFET can be used when the load needs more power than the BASIC Stamp can deliver The maximum current andor voltage capability ofthese devices must be higher than that required by the component The circuit values should be designed such that a high 5V output from the BASIC Stamp drives the transistor into saturation without drawing more current than that BASIC Stamp can source Bipolar Junction Transistor The circuit symbol for a Bipolar Junction Transistor BJT is shown in Figure 2 In general use a NPN transistorto switch between the device and ground while a PNP transistor can be used to switch between a positive supply and the load Without going into transistor theory the transistor basically needs to be saturated A tran sistor operating in the saturation region acts like a closed switch To turn things off you want to cut off the the transistor which turns it into an open switch A 2N222A s collector current is rated at 800mA and it can handle about 40V on its collec tor The manufacturer s datasheet will show the relationship between the base current and the collector current From the family of curves select the curve that is nearest to IO Interfacing Issues September 22 2002 2 ECEN 4213 Cumputev Easeu Sysmn Desrgn HEIEUNE c r c 1 r r a e gt e B V92 B WI s e s We vb s e T c e e as upmranssm 2n pnruanmr FlGlJRE 2 an Irznsislnrs nsnunr rims cnange m base current causes a rnucn arger cnange m the cuHecmr current rn surtame mmmts rau ranu s Whmh a an rs used m draw a current at AAnrnA tnruugn tne man Na 42ch Lead 7 were nun sv FIGURE 3 Wnen transrsmr 01 rs drwen mm saturatmn tne man currenter be Equa m vspprmm w hamburg Ms SemawbuZZ 2cm ECEN 4213 Computer Based System Design load current by the beta 3 of Q1 IBIc3Q1 Given a 20mA maximum BASIC Stamp output current a minimum transitor beta may be calculated by rearranging this formula to betaQ1minlcIB Where IB is the 20mA maximum BASIC Stamp drive current A transistor must be chosen that meets and preferably exceeds these minimum require ments Once a transistor is chosen an appropriate base limiting resistor value can then be determined which is defined by IcBQ1 and must be less than the 20mA BASIC Stamp limit The voltage drop across Rlimit is equal to the 5V BASIC Stamp output minus the PN junction drop of Q1 5O644V In Figure 3 Rlimit1k IB44mA forthe required application Darlington transistor To switch currents larger than 50mA on and off with a port line a single transistor may not have enough current gain to do this dependably One solution to this problem is to con nect 2 transistors in a Darlington configuration Figure 4 shows how a small solenoid can be driven with such a configuration In Figure 4 the output port supplies base current to the transistor Q1 This base current produces a collector current IcBb The collector cur rent of Q1 becomes the base current of Q2 and is amplified by the current gain of Q2 The result of all of this is that the device acts like a single transistor with a current gain of I3Q1BQ2 Assuming we need 440mA to drive the solenoid then the worst case current that must be supplied by the output port pin is about 440Beta 044mA 31000 With a Darlington transistor configuration a smaller base current can be used to produce a much larger col lector current output pin FIGURE 4 Darlington transistor Power MOSFET The power MOSFET can be driven into saturation by applying a gate voltage A positive 5 volts from the BASIC Stamp s output is sufficient to place the MOSFET in an on state IO Interfacing Issues September 22 2002 4 ECEN 4213 Computer Based System Design Extremely high input impedance for the device means that no gate current is required to drive the gate therefore a single output from the BASIC Stamp can control multiple MOS FETs Figure 5 shows how a power MOSFET transistor can be used to drive a solenoid relay or motor winding FIGURE 5 Power MOSFET circuit INTERFACING WITH THE ANALOG WORLD In order to control the outside world the microcontroller needs to determine the values of variables such as pressure and temperature The interface circuitry therefore needs to convert these variables into into the appropriate digital form Also devices such as sen sors output signals that are quite small and therefore needs to be amplified and perhaps filtered Operational Amplifiers An operational amplifier op amp amplifies the difference in input between its two input pins determined by the gain of the op amp Figure 6 shows a block diagram of an ideal opamp Vcc Vcc gt v v39 Vout Vcc FIGURE 6 0p Amp block diagram IO Interfacing Issues September 22 2002 5 ECEN 4213 Computer Based System Design Depending on the given application 1 of 4 possible modes can be considered for amplifi cation 1 Voltage to voltage 2 Voltage to current 3 Current to voltage 4 Current to current Analog to Digital AID and Digital to Analog AID Converter Analog signals will need to be converted into digital signals before the microcontroller can perform the necessary function The purpose is to convert a binary word into proportional current or voltage There are a number of characteristics to consider when interfacing a DA or AD converter to your microcontroller 1 Resolution Depending on the number of bits required for a given application the res olution can be determined An 8bit binary input has 256 possible output levels so its res olution is 1256 2 Fullscale output voltage The maximum output voltage of a converter will always have a value 1 least significant value less than the named value For example If you have an 8 bit requirement with a 5V reference voltage Voltage range 10 1LSB 2N 256 3 Settling time When changing the binary word applied to the input of a converter the output wil change to the appropriate new value The output however may overshoot and ring for a while before finally settling down to the correct value The time it takes the out put to get within a specified error band of the final value is called settling time This speci fication is important because this must be faster than the frequency of the signal in order to be able to reconstruct the waveform SIMPLE IIO DEVICES The switch is the most basic of all binary input devices The output of the switch will be high or low depending on the position of the switch A pullup or pulldown resistor is nec essary when dealing with switches to provide a default logic level when the switch is open Absence of a default logic level can produce random noise components on the lO pin IO Interfacing Issues September 22 2002 6 ECEN 4213 Computer Based System Design A problem with all switches is switch bounce When a switch makes contact its mechani cal springiness will cause the contact to bounce or make and break for a few milisec onds If a program is counting switch closures and the software is fairly fast it may count several bounces and return an incorrect count Therefore depending on the type of appli cation switch debouncing may be necessary There are 2 known ways to debounce a switch 1 Software debouncing 2 Hardware debouncing Software debouncing There are 2 methods of software debouncing The first method may be called wait and seequot Since the switch bounces the software can be made to wait a few milliseconds longerfrom the time the switch is closed before testing the input again to determine the appropriate logic level The second method is an integrating debouncer The idea is to initialize a counter with a value of 10 and after the first logic level is detected to poll the switch every millisecond While polling If the output logic is the same as the initial logic level then decrement the counter otherwise increment the counter When the counter reaches zero we know that the switch output has stayed the same for at least 10 milliseconds If on the other hand the counter reaches 20 we know that the switch has been open for at least 10 millisec onds In the BASIC Stamp you can also use the BUTTON command to eliminate switch bounces BUTTON Pin DownState Delay Rate Workspace TargetState Label Pin gt specifies the lO pin to use 015 DownState gt specifies which logical state occurs when the button is pressed 01 Delay gt specifies how long the button must be pressed before autorepeat starts 0255 Rate gt specifies number of cycles between autorepeat Workspace gt byte variable used by the BUTTON command for workspace It must be cleared to 0 before being used by BUTTON TargetState gt specifies which state the button should be in for a branch to occur Label gt specifies where to branch if the button is in the target state BUTTON is designed for use inside a program loop Each time through the loop BUT TON checks the state of the specified pin When it first matches DownState BUTTON debounces the switch Then in accordance with TargetState it either branches to address TargetState 1 or doesn t TargetState 0 IO Interfacing Issues September 22 2002 7 ECEN 4213 Computer Based System Design The BUTTON command does not stop program execution In order for its delay and auto repeat functions to work properly BUTTON must be executed from within a loop program Hardware Debouncing There are several hardware debouncing schemes to debounce your switches three of them are shown in Figure 7 In a and b single pole doublethrow switches are debounced with NAND and NOR latches An intergrating debouncer is shown in c with a Shmitt trigger gate This gate does not switch until the input voltage exceeds a threshold 1 when switch u 0 when switch up 0 when switch down 1 when switch down R 0 when switch open 1 when switch closed FIGURE 7 Hardware debouncing methods IIO SYNCRONIZATION There are some situations where the external lO device and the processor must be syn chronized before data transfer can take place 1 Processor may be faster than the lO device Software and hardware must be syn chronized the fast processor and the slow lO device 2 When lO needs to transfer data at unpredictable intervals Interrupts 3 When the lO device is faster than the processor Direct Memory Access DMA IO Interfacing Issues September 22 2002 ECEN 4213 Computer Based System Design Software IIO synchronization This method of synchronization uses a software delay to match the processorto the tim ing requirements ofthe IO device Consider outputting data to a serial port that transmits at 9600 baud 1200 characterssec The time between characters is 08 milliseconds but the program is likely to be able to read characters from memory and output to the serial device at a much higher rate lfthe program does not have to do anything during the transmittal of data then a simple delay loop can be used to synchronize the processor with the serial port Another method is called polled Ho The status register with a DATAREADYquot bit is added to the input device The software reads the status register and checks the DATAREADYquot bit lfthe device is not ready the program loops until it is ready and then reads the information The input contains additional logic to set this bit and reset it when the information register has is read by the processor Software synchronization for an output operation is accomplished with a READYTORECEIVEDATAquot bit in the status register and logic in the output device to set and reset this bit The software polls the bit waiting until it is asserted before output ting the data to the output register Handshaking IIO This is a hardware synchronization method available for processors equipped with a con trol signal READYquot or WAIT for data transfers When the WAIT signal is asserted the sequence controller spins its wheels in a wait state until the control signal is deasserted allowing the processor to continue its operation Software vs Handshaking IIO Methods used to synchronize depends on what hardware andor control signals are avail able in the processor If it does not have a WAIT or READY input the hardware hand shaking method cannot be used unless other provisions have been made by the manufacturer In the processors with the READY or WAIT input either methods can be used Handshaking IO is potentially faster than software polling and does not require additional program instructions to poll the status register A disadvantage is that while the processor is in the WAIT state it cannot do anything else When polling is used the CPU can be doing otherthings while it is waiting for IO device to be ready IO Interfacing Issues September 22 2002 9 ECEN 4213 Computer Based System Design Direct Memory Access DMA This is a type of lO tecnique in which data can be transferred between the microcontroller memory and external devices without any processor involvement DMA is typically used to transfer blocks of data between memory and the external device An interface chip called the DMA controller chip is used for transferring data The CPU is considered the bus master and all memory lO interfaces and other devices on the buses are slaves With DMA the CPU is no longerthe only bus master A DMA controller can transfer a block of data directly to memory bypassing the CPU altogether Request signals allow the second bus master DMA controller to suspend the operation of the CPU and generates the addresses and the control signals to transfer the data between the lO device and the memory Interrupt IIO Conditional programmed lO which requires a device intiated transfer This type of lO transfer is dependent on the speed ofthe external device This is a way for asynchronous events to be recognized and taken care of by the processor The external device is con nected to an interrupt pin When the device needs an lO transfer with the microcontrol ler it activates the interrupt requestquot IRQ The microcontroller saves the current instruction or at least the current contents ofthe current program counter PC in the stack The IRQ requests the program to take immediate action called when an interrupt is pro duced The microcontroller automatically loads an address into the PC to branch to a sub routinelike program called the interrupt service routinequot ISR which is a program written by the user and executed whenever an interrupt occurs Once the ISR has finished its service the contents of the stack are then loaded back into the PC and the microcontrol ler continues executing the main program IO Interfacing Issues September 22 2002 10 ECEN 4213 Computer Based System Design PBASIC Language Basics Dhinesh Sasidaran PBASIC INTRODUCTION PBASIC stands for Parallax BASIC which is a variant of BASIC This special language has familiar BASIC instructions such as FORNEXT lFTHEN and GOTO along with some useful extra instructions that are specially for input and output lO Programs can be written using the STAMP programming software and downloaded on a serial port to the BASIC Stamp YOUR FIRST STAMP PROGRAM You can use the DEBUG command to print values to the debugging terminal managed by the STAMP programming software The command allows you to view variables or track the flow of execution through your program Run the parallax software and write the fol lowing program in the STAMP editor window STAMP BS2 DEBUG My first STAMP Programquot END Run your program A window should pop up and you should see the debugging message on the screen What appears is what was sent from the BASIC Stamp through the programming cable to the PC The first line of the program is a special comment or directive which indicates which version of the Stamp is in use PBASIC Language Basics August 26 2003 ECEN 4213 Computer Based System Design Writing your program Write your program using the BASIC Stamp Windows Editor as shown in Figure 1 o Z7 the57 YaluEs FIGURE 1 BASIC Stamp Windows Editor A er entering your program using the Stamp editor select Run gt Run or by pressing Ctrl R This tokenizes your code and downloads it into the Stamp MEMORY MAP AND IIO 139quot m quot rquot bytesof 39L39 m r a J L 39 quotiguleZ INS iNH I iNL Eh I BIO OUTS iNH I iNL ma I 512 DIRS W7 DIRHI DIRL ms I am W9 BI I BO 517 I BIB Wt W9 as I 52 my I BIB W2 W10 55 I Ed at I 520 W3 WM BI I BE as I 522 W4 W12 w I BE m I 525 FIGURE 2 Stamp memory map PEASIC Languga Basins Augistz 2003 ECEN 4213 Computer Based System Design IDENTIFIERS Identifiers are names that a programmer makes up when writing a program In PBASIC an identifier must begin with a letter and can be composed of a combination of letters digits and the underscore character but cannot be the same as PBASIC keywords reserved words or labels PBASIC is not case sensitive and therefore both upper case and lower case letters can be used in an identifier KEYWORDS Reserved Words Appendix B of the STAMP manual provides a list of PBASIC keywords You can down load the manual from the class website click on handouts then click on the link to the BASIC Stamp Manual GENERAL PROGRAM FORMAT 1 Labels You can place labels in your program to identify a particular spot that your program has to jump to Labels are identified by colons proceeding the label name 2 Variables The VAR keyword is used to specify a variable along with the size of the variable The VAR keyword causes the Stamp II programming software to reserve a register based on the size specified Before you use a variable in your program you will need to declare it PBASIC however does have predefined variables that you can use without first declaring them in your program These are generalpurpose variables with defined names W0 through W12 BO through B25 where B0 is the lower byte of W0 and B1 is the high byte of WO However it is recommended that you avoid using fixed variables in most situations and let the PBASIC arrange the variables into the registers as it sees fit to make optimal use of memory For example counter VAR byte This command selects one of the bytesized registers to be assigned to the variable named counter The sizes ofthe variable can vary from WORD BYTE NIB nibble or BIT Dog VAR BIT Value can be 0 or 1 Cat VAR NIB Value can be 0 to 15 Dolphin VAR BYTE Value can be 0 to 255 Whale VAR WORD Value can be 0 to 65535 PBASIC Language Basics August 26 2003 3 ECEN 4213 Computer Based System Design Variables should be assigned by determining the largest value that will ever be stored in it The smallest size with respect to that should be chosen for the variable Aliases for variables can also be created using the VAR command For example counter VAR BYTE countodd VAR counter In the lines above countodd is an alias to the variable counter Anything stored in counter shows up in countodd and vice versa Both names will refer to the same phys ical address You can also use the alias as a window into a portion of another variable This is done using modifiers For example Whale VAR WORD A 16bit variable Dolphin VAR WhaleHlGHBYTE Highest 8 bits of Whale Shark VAR WhaleLOWBYTE Lowest 8 bits of Whale The following table lists the modifiers and the definition of their use with variables Modifiers Definition LOWBYTE Low byte of a word HIGHBYTE high byte of a word BYTEO byte 0 low byte of a word LOWNIB low nibble of word or byte HIGHNIB high nibble of word or byte NIBO nib O of a word or byte NB1 nib 1 of a word or byte NB2 nib 2 of a word NB3 nib 3 of a word LOWBIT low bit of a word byte or nibble HIGHBIT high bit of a word byte or nibble BITO bit 0 of a word byte or nibble BT1 bit 1 of a word byte or nibble BIT2 bit 2 of a word byte or nibble BIT3 bit 3 of a word byte or nibble BT4 BT7 bits 4 through 7 of a word or byte BT8 BIT15 bits 8 through 15 of a word a Array variables You can also declare arrays using the VAR command An array has multiple items of the same type The following command is used to declare an array with a list of 3 bytes PBASIC Language Basics August 26 2003 4 ECEN 4213 Computer Based System Design myarray VAR byte3 This command creates a 3 bytesized element array With the abovementioned decla ration the following assignments could be made myarrayO myarray1 10 myarray2 100 Using an array without the specified index will cause the software to respond withto the 1st element in the array A P InputOutput direction The direction of input and output pins on the Stamp can be controlled by setting the appropriate bits in the DIRS register a 1 indicates an output pin and a 0 indicates an input pin For example dirs FOOO this is equivalent to setting IO pins 1512 as output pins while pins 11 0 are designated as input pins Separate registers are provided for input INS and output OUTS and can be assigned separately INO or OUT1 The OUTS register remembers what is written into it even if some of the bits are not outputs to begin with at that time When the DIRS register changes the directions of those bits to outputs the output pin will use the value that exists in the OUTS register 01 Math expressions Math operations are performed from left to right There are no operator precedence rules except when it comes to UNARY and BINARY operators Unary operators are given precedence in math calculations For example 10 SQR 16 The BASIC Stamp first takes the square root of 16 and then subtracts it from 10 In the case of binary operators the expression 5 3 2 will yeild the result 16 and not 11 Therefore for proper calculation the parentheses character can be placed in the expression 5 3 2 11 Note Only 8 levels of parentheses are allowed in your math expressions Math expressions can also be used when dealing with input and output pins For example B1 10 INPUT B11 Make pin 11 an input pin 0 Constants Constants can be specified using the CON keyword For example delay CON 1000 Constants can also be defined in terms of another constant but must be kept fairly sim ple For example PBASIC Language Basics August 26 2003 5 ECEN 4213 Computer Based System Design Whale CON 20 Dolphin CON Whale2 1 NUMBERS PBASIC allows you to use several numbering systems By default it assumes that num bers are in decimal but you can identify binary and hexadecimal numbers with a prefix 99 decimal 1010 binary FE hex BASIC Stamp performs integer match whole numbers only and drops any fractional por tion from the results ofthe computation The size ofthe variables can be a bit 01 nibble 015 byte 0255 or word 065535 respectively For negative numbers two s complement math can be used for representation Negative Numbers When the Stamp performs calculations ifthe value is greater than the size of the variable then itjust chops offthe extra bits from left to right to form the appropriate size For exam ple When adding 64 to FFDF DEC 100 and 33 the result would be 10043 but the Stamp chops the extra bits off leaving the result to be 0043 67 Adding 2 large numbers Sometimes there may be a need to add or subtract large numbers depending on the application In orderto do this we can concatenate not physically several registers together For example suppose we wish to add 2 32 bit numbers together Add x x x xhwxlw thylw xhw 2 xlw FFFF XhWXIW 0002 FFFF overflow results in this word xlw being less than the original xlw thylw 0000 0001 xhwxlw 0003 000 Add 1 to xhw or th and add words xhw and th together PBASIC Language Basics August 26 2003 6 ECEN 4213 Computer Based System Design Program Example 1 xhw VAR WORD xlw VAR WORD th VAR WORD ylw VAR WORD temp VAR WORD xhw 2 xlw FFFF th O ylw 1 temp xlw temporary storage for xlw xlw xlw ylw IF xlw gt temp THEN nocy xhw xhw 1 if xlw lt old xlw nocy xhw xhw th Subtracting 2 large numbers Subtract x x x xhwxw thyw th 2 underflow results in this word xlw being ylw FFFF more than the original xlw xhwxw 0000 0001 thyw 0002 FFFF xhwxw FFFD 000 Subtract 1 from xlw and subtract word th from xhw PBASIC Language Basics August 26 2003 ECEN 4213 Computer Based System Design Program Example 2 xhw VAR WORD xlw VAR WORD th VAR WORD ylw VAR WORD temp VAR WORD xhw O xlw 1 th 2 ylw FFFF temp xlw temporary storage for xlw xlw xlw ylw IF xlw lt temp THEN nobor xhw xhw 1 if xlw gt old xlw nobor xhw xhw th Multiplying 2 large numbers Multiplying 2 16 bit numbers requires a 32 bit result The and operators can be used for this purpose gt returns value of bottom 16 bits gt returns value of top 16 bits For example Multiplication of FFFF and FFFF produces the result FFFEOOO1 W1 FFFF W2 FFFF W3 W1 W2 W4 W1 W2 Noninteger numbers The BASIC Stamp can only handle Whole integer numbers Therefore methods of con version to integer numbers is necessary depending on your exact needs For the expres sion F 18 C 32 can be reWritten as F 18 C 320 This conversion however means that the actual result 110th of the result obtained from the calculation PBASIC Language Basics August 26 2003 ECEN 4213 Computer Based System Design One way to deal with fractional numbers is to use the operator It has the effect of multiplying a value by a whole number and a fraction This operator places the whole number portion in the upper byte multiplies the fractional part by 256 and places the result in the lower byte For example if multiplying value with 18 using the would mean 08 256 2048 205 and therefore Upper byte 01 Lower byte CD so 18 can be represented as 01CD Therefore some care will need to be taken when dealing with noninteger numbers Now F 18 C 32 can be rewritten as F C 01CD 32 PBASIC Language Basics August 26 2003 9


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.