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: Fredy Okuneva

Microcontrollers ECE 340

Fredy Okuneva
GPA 3.81


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 90 page Class Notes was uploaded by Fredy Okuneva on Thursday October 22, 2015. The Class Notes belongs to ECE 340 at University of Idaho taught by Staff in Fall. Since its upload, it has received 6 views. For similar materials see /class/227733/ece-340-university-of-idaho in ELECTRICAL AND COMPUTER ENGINEERING at University of Idaho.

Similar to ECE 340 at UI



Reviews for Microcontrollers


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: 10/22/15
Chapter 1 Th 2 Basics Rev January 5 m7 Introduction m a m mmquot r system 15 as fulluws An embeddzdxyxlzm 139 some mmbina an afcanqmlzr hardware and sumpm I39 I39 p m 4 h hII d Fume shuws InZEIEIKLhe mun Wasalmustl 5m 1 D l mm plncmwn m vrucx wwb was w W man mm mm 2qu ma F39gum 1 Usage nfnlicrupmcrs Tudzy vr rFPGAsThe m r m m meml w mm m r mm W m m wVw electxumechamcal and electxumc sysLems Processor History 101 The term microprocessor came about when Intel produced its rst single chip computer in the early 1970 s as a result of a failed attempt to produce a limited IC set to replace existing computer designs1 The development of the original processor continued to the line of Pentium processors that we use today in PC s In 1985 Intel introduced the 8048 microcontroller for use on the F15 jet ghter Two years later Intel introduced the 8051 microprocessor Today the 8051 is one of the most popular microcontroller designs and forms the basis on many variants processors produced by a variety of companies such as Phillips Cypress Atmel and many more Processor Architecture As shown in the simpli ed drawing of Figure 2 computer systems are comprised of a central processing unit CPU memory and input output IO The CPU interfaces with memory and IO using three groups of signal lines or busses The data and IO devices are selected or enabled using the binary codes on the address and control buses The information is transferred to or from the memory and IO devices using the data bus Finally the information transfer process uses the control bus to coordinate or synchronize the read andor write operations The processor performs all of the calculations and manages data transfers with memory or IO Control Bus to 3 m u u 9 0 0 lt Data Bus Figure 2 Block diagram of a basic computer system CPU2 A39 39 39 39 of central it an 39 as separate letters The CPU is the brains of the computer Sometimes referred to simply as the processor or central processor the CPU is where most calculations take place In terms of computing power the CPU is the most important element 1 See httn39 mir nnn 2r 39 39 39 39 39 39 39 39 l micmmhiqt html 2 Excerpts taken from httpwww F 39 102 UK pm in A hm mnm mm 1 1 1 of a computer system A typical central processor unit CPU consists of the following interconnected functional units Registers ArithmeticLogic Unit ALU and Control Circuitry Registers Registers are temporary storage units within the CPU Some registers such as the program counter and instruction register have dedicated uses Other registers such as the accumulator are for more general purpose use Accumulator The accumulator usually stores one of the operands to be manipulated by the ALU A typical instruction might direct the ALU to add the contents of some other register to the contents of the accumulator an store the result in the accumulator itself In general the accumulator is both a source operand and a destination result register Often a CPU will include a number of additional general purpose registers that can be used to store operands or intermediate data The availability of general purpose registers eliminates the need to quotshuf equot intermediate results back and forth between memory and the accumulator thus improving processing speed and efficiency Program Counter Jumps Subroutines and the Stack The instructions that make up a program are stored in the system s memory The central processor references the contents of memory in order to determine what action is appropriate This means that the processor must know which location contains the next instruction Each of the locations in memory is numbered to distinguish it from all other locations in memory The number which identi es a memory location is called its Address The processor maintains a counter which contains the address of the next program instruction This register is called the Program Counter The processor updates the program counter by adding quot1quot to the counter each time it fetches an instruction so that the program counter is always current pointing to the next instruction The programmer therefore stores his instructions in numerically adjacent addresses so that the lower addresses contain the rst instructions to be executed and the higher addresses contain later instructions The only time the programmer may violate this sequential rule is when an instruction in one section of memory is a Jump instruction to another section of memory A jump instruction contains the address of the instruction which is to follow it The next instruction may be stored in any memory location as long as the programmed jump speci es the correct address During the execution of a jump instruction the processor replaces the contents of its program counter with the address embodied in the Jump Thus the logical continuity of the program is maintained A special kind of program jump occurs when the stored program quotCallsquot a subroutine In this kind of jump the processor is required to quotrememberquot the contents of the program counter at the time that the jump occurs This enables the processor to resume execution of the main program when it is nished with the last instruction of the subroutine A Subroutine is a program within a program Usually it is a generalpurpose set of instructions that must be executed repeatedly in the course of a main program Routines which calculate the square the sine or the logarithm of a program variable are good examples of functions often written as subroutines Other examples might be programs designed for inputting or outputting data to a particular peripheral device The processor has a special way of handling subroutines in order to insure an orderly return to the main program When the processor receives a Call instruction it increments the Program Counter and stores the counter s contents in a reserved memory area known as the Stack The Stack thus saves the address of the instruction to be executed after the subroutine is completed Then the processor loads the address speci ed in the Call into its Program Counter The next instruction fetched will therefore be the rst step of the subroutine The last instruction in any subroutine is a Return Such an instruction need specify no address When the processor fetches a Return instruction it simply replaces the current contents of the Program Counter with the address on the top of the stack This causes the processor to resume execution of the calling program at the point immediately following the original Call Instruction Subroutines are often Nested that is one subroutine will sometimes call a second subroutine The second may call a third and so on This is perfectly acceptable as long as the processor has enough capacity to store the necessary return addresses and the logical provision for doing so In other words the maximum depth of nesting is determined by the depth of the stack itself If the stack has space for storing three return addresses then three levels of subroutines may be accommodated Processors have different ways of maintaining stacks Some have facilities for the storage of return addresses built into the processor itself Other processors use a reserved area of external memory as the stack and simply maintain a Pointer register which contains the address of the most recent stack entry The external stack allows virtually unlimited subroutine nesting In addition if the processor provides instructions that cause the contents of the accumulator and other general purpose registers to be quotpushedquot onto the stack or quotpoppedquot off the stack via the address stored in the stack pointer multilevel interrupt processing described later in this chapter is possible The status of the processor ie the contents of all the registers can be saved in the stack when an interrupt is accepted and then restored after the interrupt has been serviced This ability to save the processor s status at any given time is possible even if an interrupt service routine itself is interrupted Instruction Register and Decoder Every computer has a Word Length that is characteristic of that machine A computer s word length is usually determined by the size of its internal storage elements and interconnecting paths referred to as Busses for example a computer whose registers and busses can store and transfer 8 bits of information has a characteristic word length of 8 bits and is referred to as an 8bit parallel processor An eightbit parallel processor generally nds it most efficient to deal with eightbit binary elds and the memory associated with such a processor is therefore organized to store eight bits in each addressable memory location Data and instructions are stored in memory as eightbit binary numbers or as numbers that are integral multiples of eight bits 16 bits 24 bits and so on This characteristic eightbit eld is often referred to as a Byte Each operation that the processor can perform is identi ed by a unique byte of data known as an Instruction Code or Operation Code An eightbit word used as an instruction code can distinguish between 256 alternative actions more than adequate for most processors The processor fetches an instruction in two distinct operations First the processor transmits the address in its Program Counter to the memory Then the memory returns the addressed byte to the processor The CPU stores this instruction byte in a register known as the Instruction Register and uses it to direct activities during the remainder of the instruction execution The mechanism by which the processor translates an instruction code into speci c processing actions requires more elaboration than we can here afford The concept however should be intuitively clear to any logic designer The eight bits stored in the instruction register can be decoded and used to selectively activate one of a number of output lines in this case up to 256 lines Each line represents a set of activities associated with execution of a particular instruction code The enabled line can be combined with selected timing pulses to develop electrical signals that can then be used to initiate speci c actions This translation of code into action is performed by the Instruction Decoder and by the associated control circuitry An eightbit instruction code is often suf cient to specify a particular processing action There are times however when execution of the instruction requires more information than eight bits can convey One example of this is when the instruction references a memory location The basic instruction code identi es the operation to be performed but cannot specify the object address as well In a case like this a two or threebyte instruction must be used Successive instruction bytes are stored in sequentially adjacent memory locations and the processor performs two or three fetches in succession to obtain the full instruction The rst byte retrieved from memory is placed in the processor s instruction register and subsequent bytes are placed in temporary storage the processor then proceeds with the execution phase Such an instruction is referred to as Variable Length Address Registers CPU may use a register or register pair to hold the address of a memory location that is to be accessed for data If the address register is Programmable i e if there are instructions that allow the programmer to alter the contents of the register the program can quotbuildquot an address in the address register prior to executing a Memory Reference instruction ie an instruction that reads data from memory writes data to memory or operates on data stored in memory ArithmeticLogic Unit AL U processors contain an arithmeticlogic unit which is often referred to simply as the ALU The ALU as its name implies is that portion of the CPU hardware which performs the arithmetic and logical operations on the binary data The ALU must contain an Adder which is capable of combining the contents of two registers in accordance with the logic of binary arithmetic This provision permits the processor to perform arithmetic manipulations on the data it obtains from memory and from its other inputs Using only the basic adder a capable programmer can write routines which will subtract multiply and divide giving the machine complete arithmetic capabilities In practice however most ALUs provide other builtin functions including hardware subtraction Boolean logic operations and shift capabilities The ALU contains Flag Bits which specify certain conditions that arise in the course of arithmetic and logical manipulations Flags typically include Carry Zero Sign and Parity It is possible to program jumps which are conditionally dependent on the status of one or more ags Thus for example the program may be designed to jump to a special routine if the carry bit is set following an addition instruction Control Circuitry The control circuitry is the primary functional unit within a CPU Using clock inputs the control circuitry maintains the proper sequence of events required for any processing task After an instruction is fetched and decoded the control circuitry issues the appropriate signals to units both internal and external to the CPU for initiating the proper processing action Often the control circuitry will be capable of responding to external signals such as an interrupt or wait request An Interrupt request will cause the control circuitry to temporarily interrupt main program execution jump to a special routine to service the interrupting device then automatically return to the main program A Wait request is often issued by a memory or 10 element that operates slower than the CPU The control circuitry will idle the CPU until the memory or 10 port is ready with the data 3 Memor Memory has two roles in the Von Neumann type of computer system4 The memory stores the program instructions and the data variables needed for computations as well as share a common data path The rage of memory types are shown in Figure 3 The technology used for different types of memory can depend upon its use in the computer system For example program code initial values for variables and constants are typically stored in some type of nonvolatile memory commonly called ROM Memories in the ROM family are distinguished by the methods used to write new data to them usually called programming and the number of times they can be rewritten Many types of memory devices are available for use in modern computer systems As an embedded software engineer you must be 11 n1 3 Excerpts taken from httpwww netrino CO quotC T lemOr Tvpes html h See httn39 Pic vteduNhistor quot tml In our ducussxon R n w F Hr 1 elassr es the memory devrees we ll ducuss as RAM ROM or ahybnd othe two cam saw mm Hm emu mam mu Mldmll Figure 3 Cummun memury Iypesused in emhadded symms Nanvala leManmy equot mm puwerfadure mstxucnuns m u m arenew calls ROM UwF mum ROM are requrred One step up nm the masked ROM rs the PROM mgammable ROM whmh rs purchased m an unpmgzmmed gate Ifyuu were ten luuk atthe mutants ufan unpmgammed FROM yuu vmuld see Lhatthe dataxs madeup enurely uf 1 s Thepmcess ufwmmg yuur dame the FROvaulves aspeeral be h w 1 aresLLlL pmgzmmable ow aevrees FROM Hewever EFROMs can be erased and repmgmmmed repeatedly Tu erase m EFROM yuu e A EFROMs an essential pm ufthe su tvmre develupmem andtesnng prueess called pmgmmmmg and are number ufumes they can be rewrmer Ths elassreeaum re ects the Pn luvw n Pr failure The very rst ROMS were hardwired devices that contained a preprogrammed set of data or instructions The contents of the ROM had to be speci ed before chip production so the actual data could be used to arrange the transistors inside the chip Hardwired memories are still used though they are now called masked ROMS to distinguish them from other types of ROM The primary advantage of a masked ROM is its low production cost Unfortunately the cost is low only when large quantities of the same ROM are required One step up from the masked ROM is the PROM programmable ROM which is purchased in an unprogrammed state If you were to look at the contents of an unprogrammed PROM you would see that the data is made up entirely of 1 s The process of writing your data to the PROM involves a special piece of equipment called a device programmer The device programmer writes data to the device one word at a time by applying an electrical charge to the input pins of the chip Once a PROM has been programmed in this way its contents can never be changed If the code or data stored in the PROM must be changed the current device must be discarded As a result PROMs are also known as onetime programmable OTP devices An EPROM erasableandprogrammable ROM is programmed in exactly the same manner as a PROM However EPROMs can be erased and reprogrammed repeatedly To erase an EPROM you simply eXpose the device to a strong source of ultraviolet light A window in the top of the device allows the light to reach the silicon By doing this you essentially reset the entire chip to its initial unprogrammed state Though more eXpensive than PROMs their ability to be reprogrammed makes EPROMs an essential part of the software development and testing process Volatile Memory Memory used to store variables for the results of processes and calculations are stored in memory that is designed to be changes quickly and frequently This kind of memory is usually called RAM or random access memory IC Registers and latches are a form of RAM The RAM family includes two important memory devices static RAM SRAM and dynamic RAM DRAM The primary difference between them is the lifetime of the data they store SRAM retains its contents as long as electrical power is applied to the chip If the power is turned off or lost temporarily its contents will be lost forever DRAM on the other hand has an eXtremely short data lifetimetypically about four milliseconds This is true even when power is applied constantly In short SRAM has all the properties of the memory you think of when you hear the word RAM Compared to that DRAM seems kind of useless By itself it is However a simple piece of hardware called a DRAM controller can be used to make DRAM behave more like SRAM The job of the DRAM controller is to periodically refresh the data stored in the DRAM By refreshing the data before it eXpires the contents of memory can be kept alive for as long as they are needed So DRAM is as useful as SRAM after all When deciding which type of RAM to use a system designer must consider access time and cost SRAM devices offer eXtremely fast access times approximately four times faster than DRAM but are much more eXpensive to produce Generally SRAM is used only where access speed is eXtremely important A lower costperbyte makes DRAM attractive whenever large amounts of RAM are required Many embedded systems include both types a small block of SRAM a few kilobytes along a critical data path and a much larger block of DRAM perhaps even Megabytes for everything else Hybrids As memory technology has matured in recent years the line between RAM and ROM has blurred Now several types of memory combine features of both These devices do not belong to either group and can be collectively referred to as hybrid memory devices Hybrid memories can be read and written as desired like RAM but maintain their contents without electrical power just like ROM Two of the hybrid devices EEPROM and ash are descendants of ROM devices These are typically used to store code The third hybrid N VRAM is a modi ed version of SRAM NVRAM usually holds persistent ata EEPROMs are electricallyerasableandprogrammable Internally they are similar to EPROMs but the erase operation is accomplished electrically rather than by exposure to ultraviolet light Any byte within an EEPROM may be erased and rewritten Once written the new data will remain in the device foreveror at least until it is electrically erased The primary tradeoff for this improved functionality is higher cost though write cycles are also signi cantly longer than writes to a RAM So you wouldn t want to use an EEPROM for your main system memory Flash memory combines the best features of the memory devices described thus far Flash memory devices are high density low cost nonvolatile fast to read but not to write and electrically reprogrammable These advantages are overwhelming and as a direct result the use of ash memory has increased dramatically in embedded systems From a software viewpoint ash and EEPROM technologies are very similar The major difference is that ash devices can only be erased one sector at a time not bytebybyte Typical sector sizes are in the range 256 bytes to 16KB Despite this disadvantage ash is much more popular than EEPROM and is rapidly displacing many of the ROM devices as well The third member of the hybrid memory class is NVRAM nonvolatile RAM Nonvolatility is also a characteristic of the ROM and hybrid memories discussed previously However an NVRAM is physically very different from those devices An NVRAM is usually just an SRAM with a battery backup When the power is turned on the NVRAM operates just like any other SRAM When the power is turned off the NVRAM draws just enough power from the battery to retain its data NVRAM is fairly common in embedded systems However it is eXpensiveeven more eXpensive than SRAM because of the batteryso its applications are typically limited to the storage of a few hundred bytes of systemcritical information that can t be stored in any better way Memory Summary Table 1 summarizes the features of each type of memory discussed here but keep in mind that different memory types serve different purposes Each memory type has its strengths and weaknesses Sidebyside comparisons are not always effective Table 1 Characteristics of the various memory types per Byte battery This article was published in the May 2001 issue of Embedded Systems Programming If you wish to cite the article in your own work you may find the following MIAstyle information helpfu We will discuss each of these components during the course and their relationship to special function resources microprocessors may possess Viva la Difference One of the rst questions frequently asked is What is the difference between a microprocessor and a microcontroller There is much disagreement on this issue largely because the distinctions are fuzzy Most microprocessors have limited memory and 10 on the processor IC thus requiring external devices to provide for suf cient memory and IO Microcontrollers usually have both suf cient memory and 10 for smalldedicated jobs Microcontrollers frequently have special functions speci cally designed for control applications Usually however the distinction is usually based upon the application and the software that the processor is running Choosing the righ microprocessor or microcontroller depends on the functional requirements for speci c problem being solved Throughout this book we will use the expression microprocessors to refer to both generalpurpose microprocessors and microcontrollers where applicable and delineate between the two only when the difference has signi cant implications Microcontroller Pedagogy For this course you will learn how to manage resources that are hosted in the microprocessor You will learn just in time how to use the fundamental microprocessors functional capabilities in an evolutionary process that that uses building blocks built of functions written in C that are arranged together to complete a speci c job solve a unique problem or answer a de nite question You will learn just the right thing at just the right time to solve the problem presented to you You will learn how to use microprocessors to solve engineering problems ef ciently effectively and quickly You will also learn a process for translating a set of functional requirements in to tasks that the microprocessor can execute You should have a basic understanding of digital systems This includes combinational and sequential logic Boolean math truth tables and number systems both binary and hexadecimal You should also have a fundamental knowledge of C or C or closely related programming language such as Pascal or Java During this course you will be expected to write programs using Dynamic C written especially for the Rabbit Semiconductor microprocessor The companion text for this course is Embedded System Design using the Rabbit 3000 Microprocessor by Kamel Hyder and Bob Perrin5 You will be directed to chapters and sections of this text as the need arises These referrals will not be necessarily in the order of presentation in the text because the text is designed to teach you about microcontrollers as a solution looking for a problem where as you will learn microcontrollers as a problem looking for a solution in embedded systems You will not cover all of the material in the companion text as later chapters cover topics of networking and the intemet that are beyond the scope of this course This course is lab centric Most concepts discussed in class will be investigated in detail in the lab Labs progressively build in complexity and dependence upon previous labs Poor performing code written for the rst lab will hound you the rest of the semester Unstable or fragile code will crash unexpectedly and require debugging code that should have been otherwise reusable even to the point of plug and play The amount of time that you will spend in the lab will vary depending upon your level of preparation and programming skills Assignment Chapter 1 of F 39 39 39 39 System Design using the Rabbit 3000 quot 5 httpwww el evier m 39 inLiun cw home706357 dc m39 intion Chapter 8 Analog 0 Analog to Di tal Conversion Basic Building Blocks RZR Ladder Network1 output Although srrnple m desrgn and funetaon applyrng an 12212resrstor network to a real L L 7 7 dd rl F 12212 ladder networks 12esrstorladdernetworks provlde a srrnple lnexpenslve way to per rrn dlglt eonversron DAG ladder 2 L f0 alto analog The rnost popular networks are the blnary werghtedladder and the 12212 e manufacture Figure lls a ddagram of the paste 12212 ladder network wrth Nbrts The ladder portray p only two resrstor values 12 and 212 twree the value ofR no rnatter howmany brts rnake up the ladder The pamcularvalue ofR ls not entaeal to the funetaon othe 12212 er Term lt2R R R R R V tnul l J i T T i gt E 2R ZR ZR 2R 2R g 3 5th ammo Bus 0 EH2 ElH g LSB MSB Figure 1 N hit Reresisler ladder netwnrk The blnary werghted ladder shown m Figure 2 requlres double rnultaples of 12 as the number ofblts rnerease As the rataos othe resrstors beeorne more and more obtuse m ablnary l M iv rw rk dtmtnt h d tmtl r Excerptsrrorn http www an camgdf fliesLADDERNETWORKS pd The R 712 to analog conversion i inu quot42 i a 3m 0 4 gt gt J in Bill 0 Figure 2 Binary weighted resistor ladder network o v 35 Let s take a look at how an RZR ladder works The expression Term In Figure 3 is the I I I I 1 I I I a me umt Lu 39 39 39 with all bits grounded is R as shown in Figure 3 The Thevenin resistance ofan RZR ladder is always R 7 regardless of the number ofbits in the ladder Emma l a e 3 Thevenin Resistance Digital information is presented to the ladder as individual bits ofa digital word switched een 39 39 betw nuuiuuuiuu Vrorground nt in a w n n miuVLLfall inputs are a a a Vnme r r A Vrthen an H miuVr occurs quot quot 39 quot39 39 the M R when activated 39 r voltage and the LSB when activated will cause the smallest change in the output voltage wae 39 39 391tobitNL 39 39 UiLLU Vr with all other bits grounded is Vout VrZN where N is the hit number For bit 1 Vout VrZ for bit 2 Vout Vr4 etc The table shows the effect of individual bit locations to the Nth b 1 r signi cant Bit Since an R 712 39 39 eiieuii an app r 39 39r calculate Vout A 39 39 bits connected to Vr For example ifbits 1 and 3 are connected to Vr with all other inputs grounded L p 39 39 Vout 5 Vr8 E i j w 7 1 2 vuut v in R in 2 3 1 f 511 N 39 L55 E Figure 4 Switched RZR resistnr ladder netwnrk A MFRW h e i Th 1 R LSB15 12 othe previous btt Ifth1s sequence ts extendedto aladder ofth htte btts the effect o the LSB W ersely h 0 eohheetedto Vh approaches 1 as shown m equation 1 1 l t M or tt H Rladders devtees the e a1 outputvoltage can be stghtfteautty below the value ofvh Equauoh 2 can e used to esteutate the fuueseate output of an 12212 ladder ofN btts K Fuusme v L I Omput Voltage V 1 Z 1 Ah R2Rladder of4 btts would have afuthseate output voltage of 12 1418 116 15Vh1o oh 0 9375 volts1fVF1voltwh1le a 10 b1tR2Rladder would ha e afuthseate outputvoltage ofU 99902 taF1 vot Resolution andAccurmy 1 RV dd r w or two posstbte states at each thput ground ohvh also destghated as hesotuuoh oth g the number ofbtts T111515 the o er eombmauohs at the mputs The resoluttoh ofthe networkts 11024 or 0 0009766 A ehang state at the LSB input should change the output of the ladder by 09766 of the full scale output voltage The output accuracy of the IUZR ladder is typically speci ed in terms of fullscale output i some number of least signi cant bits IUZR ladders are usually speci ed with output accuracies ofil LSB or ilZ LSB For example a ilZ LSB speci cation on a 10 bit ladder is exactly the same as i004883 fullscale accuracy The ladder function is not affected by the value of R within normal resistance ranges This would indicate that the absolute tolerances of the resistors making up the ladder are of minimal importance Then what controls the accuracy of the ladder output The ladder operates as an array of voltage dividers whose output accuracies are solely dependent on how well each resistor is matched to the others Ideally resistors within the ladder are matched so that the voltage ratio for a given bit is exactly half of that for the preceding bit The ladder operates as an array of voltage dividers whose output accuracies are solely dependent on how well each resistor is matched to the others Ideally resistors within the ladder are matched so that the voltage ratio for a given bit is exactly half of that for the preceding bit Operational Ampli ers2 OperationalAmpli ers OAs are highly stable high gain dc difference ampli ers Since there is no capacitive coupling between their various amplifying stages they can handle signals from zero frequency dc signals up to a few hundred kHz Their name is derived by the fact that they are used for performing mathematical operations on their input signals Figure 5 shows the symbol for an OA There are two inputs the inverting input and the noninverting input These symbols have nothing to do with the polarity of the applied input signals V0 Figure 5 Symbol of the operational ampli er Connections to power supplies are also shown The output signal voltage V0 is given by V0 AV V Excerpts from ht wwwchemuoa ra letsA letO Am sText 0 Am 52 htm V and V are the signals applied to the noninverting and to the inverting input respectively A represents the open loop gain of the 0A A is in nite for the ideal ampli er whereas for the various types of real OAs it is usually within the range of 104 to 106 OAs require two power supplies to operate supplying a positive voltage V and a negative voltage V with respect to circuit common This bipolar power supply allows OAs to generate output signals results of either polarity The output signal v0 range is not unlimited The voltages of the power supplies determine its actual range Thus a typical OA fed with 15 and 15 V may yield a V0 within the approximately 13 to 13 V range called operational range Any result expected to be outside this range is clipped to the respective limit and 0A is in a saturation stage The connections to the power supplies and to the circuit common symbols shown in Figure l hereafter will be implied and they will be not shown in the rest of the circuits for simplicity Because of their very high open loop gain OAs are almost exclusively used with some additional circuitry mostly with resistors and capacitors required to ensure a negative feedback loop Through this loop a tiny fraction of the output signal is fed back to the inverting input The negative feedback stabilizes the output within the operational range and provides a much smaller but precisely controlled gain the socalled closed loop gain Circuits of OAs have been used in the past as analog computers and they are still in use for mathematical operations and modi cation of the input signals in real time A large variety of OAs is commercially available in the form of low cost integrated circuits There is a plethora of circuits with OAs performing various mathematical operations Each circuit is characterized by its own transfer function ie the mathematical equation describing the output signal V0 as a function of the input signal Vi or signals V1 V2 V Generally transfer functions can be derived by applying Kirchhoff s rules and the following two simplifying assumptions 1 The output signal V 0 acquires a value that through the feedback circuits practically equates the voltages applied to both inputs ie V Z V 2 The input resistance of both 0A inputs is extremely highusualy within the range 106 1012 M9 for the ideal OA this is infinite thus no current ows into them In verting Ampli er The basic circuit of the inverting ampli er is shown in Figure 6 The transfer function is derived as follows Considering the arbitrary current directions we have i1 Vi VsRi and i2 VS V0Rf The noninverting input is connected directly to the circuit common ie v 0 V therefore considering simplifying assumption 1 VS V 0 V therefore l1 ViRi and l2 VoRf Since there is no current ow to any input simplifying assumption 2 it is l1 l2 Therefore the transfer function of the inverting ampli er is Vo 39RfRiVi Thus the closed loop gain of the inverting ampli er is equal to the ratio of Rf feedback resistor over Ri input resistor This transfer function describes accurately the output signal as long as the closed loop gain is much smaller than the open loop gainA ofthe OA used eg it must not exceed 1000 and the expected values of V0 are within the operational range of the OA Ri Vs Vin 4 Figure 6 Inve rting operational ampli er circuit Summing Ampli er The summing ampli er is a logical extension of the previously described circuit with two or more inputs Its circuit is shown in Figure 7 The transfer function of the summing ampli er similarly derived is v0 v1R1 vzRz VnRnRf Thus if all input resistors are equal the output is a scaled sum of all inputs whereas if they are different the output is a weighted linear sum of all inputs The summing amplifier is used for combining several signals The most common use of a summing amplifier with two inputs is the amplification of a signal combined with a subtraction of a constant amount from it dc offset Rf R1 AVIW v1 R2 v2 Vs R3 v3 R4 7 V0 v4 Figure 7 Sun 1mng inverting ampli er Comparators3 An integrated circuit quotVoltage Comparatorquot is equivalent to an Operational Ampli er Such as the LM358 or LM324 with two NPN transistors added to the output of each amplifier Refer to the above schematic This arrangement produces an quotOpen Collectorquot output for each of the four comparators in an LM339 chip Each output can sink 15 Milliamps and can withstand voltages of up to 50 Volts The output is switched ON or OFF depending on the relative voltages at the PLUS and MINUS inputs of the comparator see the rules below The inputs are quite sensitive and a difference of only a few millivolts between the two will cause the output to turn on or off The LM339 LM393 and LM3ll comparator chips can operate from a single or dual power supply of up to 32 volts maximum When operated from Dual or Split power supplies the basic operation of comparator chips is unchanged except that for most devices the emitter of the output transistor is connected to the negative supply rail and not the circuit common An exception to this is the LM3 11 which has a separate emitter terminal that can be connected to either When operated from Dual or Split power supplies the input voltages can be above or below the common or zero voltage of the supply If needed one of the inputs can be connected to the common so that a 39Zero Crossing39 detector is created The following drawing show the two simplest configurations for voltage comparators The diagrams below the circuits give the output results in a graphical form For these circuits the REFERENCE voltage is fixed at onehalf of the supply voltage while the INPUT voltage is variable from zero to the supply voltage In theory the REFERENCE and INPUT voltages can be anywhere between zero and the supply voltage but there are practical limitations on the actual range depending on the particular device used Excerpts from httn39 hnme maem N 39 1 A f nmmmmr html BASH OPERAHON OF VOLTAGE COMAPARATORS qu MsLEVzuuz ratur Dperztmn chcweA chcweB v v R R w v 7 um i v 7 mm v r REFERENCE D v 7 MW at 22 22 3 m m m m e W vermm Hum MW vermm Hum MIDUhumecugecucaNrpzwsmyAEwrcmtndexmm Figure 8 Basic comparator operations Input Offset Voltage and Hysteresis wt This The 4 quotsnapquot m quot more information offandtums u A quot L L eh uit u um it A r changing state m m u t quotL as to reinforce the output change A way over ensuring that the switch ends up in a de nite ON or on state Hysleresis 4 OUTPUT STATE n InplllVol39nge Dlaetence vl Figure 9 Cnmparztnr input hysteresis loop The hohzohtal axls ls the lhput ahdhephesehts the allrehehee of the tvvo lnputvoltages The vema1 Y axls represents the comparator s output state Kthe comparatons lhlhallv OFF the tONt loop N OFF L l The TL tt t 4t Thehysteresls lhput voltage hses or falls very slowly or has voltage splkes known as holsel help The FLIPV ADDWG HVSTERVS S TO COMPARATORS eaeamsaavzeez EnmpzrzmrHvstereswsh mam A A WWW HVSTER VS S EQLHVALENT mam v A mama gt gt v A mama v A Wm V R2 chmRAmR euraur rRANswsnR vA wears RH mnK vAmama m EIN 57w m A m KL a vAmama m eaaA 528v 2A m 2v v A Wm v A mama v A euraur Fwnwn chEwED aasarmaas cALcuLmM mama anrAnEs euraur ramsam A UN euraur ramsam A UN v 4 4 x 2 A vAmama A R camhmed R camhmed 2 m mae euraur ramsam A ea euraur ramsam A ea v 4 x mmm A vAmama A mama m mmm A m anrAnE nae AEREISS m aemammas euraur ramsam HAS am auem w m AEEIVE aaaaumeus mp Whame aegeae azm paws eywmrcumndex mm Figure 10 Incr easing The Input nytarexix Range LM3 ll comparator can have other output arrangements as it has both an open collector and open emitter on the output transistor Converter Architectures4 An overwhelming variety of ADCs exist on the market today with differing resolutions bandwidths accuracies architectures packaging power requirements and temperature ranges as well as hosts of specifications covering a broad range of performance needs And indeed there exists a variety of applications in dataacquisition communications instrumentation and interfacing for signal processing all having a host of differing requirements Considering architectures for some applications just about any architecture could work well for others there is a quotbest choicequot In some cases the choice is simple because there is a clearcut advantage to using one architecture over another For example pipelined converters are most popular for applications requiring a throughput rate of more than 5 MSPS with good resolution Sigmadelta converters are usually the best choice when very high resolution 20 bits or more is needed But in some cases the choice is more subtle For example the sigmadelta AD7722 and the successiveapproximations AD974 have similar resolution 16 bits and throughput performance 200 ksps Yet the differences in their underlying architectures make one or the other a better choice depending on the application The most popular ADC architectures available today are successive approximations sometimes called SAR because a successiveapproximations shift register is the key defining element ash all decisions made simultaneously pipelined with multiple flash stages and sigmadelta SD a chargebalancing type All N D converters require one or more steps involving comparison of an input signal with a reference Figure 1 shows qualitatively how ash pipelined and SAR architectures differ with respect to the number of comparators used vs the number of comparison cycles needed to perform a conversion Flash Converters Conceptually the ash architecture illustrated in Figure 2 is quite straightforward a set of 2n l comparators are used to directly measure an analog signal to a resolution of n bits For a 4bit ash ADC the analog input is fed into 15 comparators each of which is biased to compare the input to a discrete transition value These values are spaced one leastsignificant bit LSBFS2n apart The comparator outputs simultaneously present 2n l discrete digital output states If for example the input is just above 1A of full scale all comparators biased to less than 1A full scale will output a digital l and the others will output a digital 0 Together these outputs can be read much like a thermometer The final step is to leveldecode the result into binary form Excerptsfromhttpwwwanalnu quot W quot f 39 html uruu SCALE 1 I 1mm SCALE 1 Figure 2 Basic ash architecture 0000 SUCCESSWE I arr nvpuoxmmou uumasn m commamas c Figure 1 Traden 39hetween deci nn cycles and cnmparztnrs bemgveryfast n r r an quot7be resolution ADst equal to 2M lxmxts of physical mtegrauon andmputloadmg keep the maxlmum resoluuon falrly low For example a4ebltADC requlres 15 eomparators an glut wd k t Pipelined Architecture l A t eonseeutlve n wrblt stages E h h h mtna ur ADC n h n rm ud wwrbltDAconvenerm n u a t slgnal to dlgltal data The converslon result forms the most srgnl eantblts othe dlgltal output 39r L a t u A M1 l ndtt outputls Thls Tu tt k ln W nun ml A d p mg 1quot l p For example a ertage plpelmed eonverter wth Brbltresolutlon requlres 30 eomparators and a4e st e 60 Tu nr h h r generated to provlde for error eorreetlon For more about plpellned AD c5 cllckm Figure 3 A single plpellned ennverter Stage holds lts lnputp converslons ean be underway srmultaneously The total throughput ean t The 1 Successive Approximations rt y 1 u rtrhwuiu iirzi p cornparator overrnany cycies to make its conversion The SAR converter works 1ike an oldr on the other side M513 1 L i i is m H r in r m d smaller weights in binary progression 3 g1418116132 12quot offull scaie unhi the desired resoiution n is attained Each weight represents a binary bit with the 1argest representing the most significant bit and the srnaiiest represenhng the 1east significant bit Figure 4 Successive zpprnxim z nns architecture 1 DC lcyclefor H h n rtr in wnrtr udi Frihi r w R w Hr H wi11 i i 4 L L R wdmnhwd doubiing ofsample rate the effective resoiution improves by 3 dB or 2blt one consideration when using a SAR or pipe1ined converter is aiiasing The process of anticallas fiiter ahead ofthe ADC to rernove highrfrequency noise cornponents which wouid be H r uwd r m V o enm t h Under h mniiu Md F V R w rt r capabie ofunder sarnpiing the faster pipe1ined converters tendto be more effective at it SigmaDelta mm d h M a comparator and a smglerbxt DAC as shown rh Frgure 5 The output of the DAC rs subtracted or o mput to the DAC and the DAC s outputxs subtractedfrom the ADC mput srghal etc Ihrs closedrloop proeess rs named out at avery hrgh over sampled rate The dAgnal data eorurhg from the ADst a stream of ones and zeros and the value othe srghsu rs proporuohsu to the densxty of dAgnal W L A L A 4 Mk m COMPARAYDR magnum Figure 5 Siynzrdaltz ADC architecture As e uh h resoluuoh ADCs for preersroh measurement Also smce the mputls sampled at ahxgh over sampled ram whrehrs types r m s desrghs by usmg muluple integrator stages andor ruuhrbu DACs References hug WW hers deElekuanIkDelt xm aDelusxma 111ml PWM Digital to Analog Conversions Pulse width modulation has been described as a poor mans digital to analog converter but in reality it is one of the most power efficient ways to amplify a signal PWM is also sometime referred to as class D amplification The modulation signal is used to turn on and off the output signal The carrier signal as shown in Figure llis a saw tooth wave The output is created by setting the output high when the modulation signal is greater than the carrier signal The resulting PWM signal is shown in Figure 12 The PWM signal has a 50 duty cycle when the mm m nm in R will Amplitude O l l WWWMWWW Will w ill l 2 ll 11mm 391 0 0001 0002 0003 0004 0005 0006 0007 0008 w W m l h lllmlmlmllllllll mm Time seconds Figure 11 Pulse width modulated signal Modulation Output TWWWWquotquot 0WJ 0 0001 0002 0003 0004 0005 0006 0007 0008 Amplitude Time seconds Figure 12 Graphical plot of a PWM modulated signal PWM is truly a form of modulation used in communications theory because the modulating signal is translated as shown in Figure 13 One knowledgeable in communications theory recognizes that the sidebands on each side of the carrier frequency are in the same form as 5 Class D amplifier Design httpsoundwesthostcomarticlespwm htm an amplitude modulated AM signal The carrier frequency is the inverse of the period of the PWM period The more narrow the on or off periods the higher the modulation frequency becomes Figure 13 also shows a sideband just above zero Hz This is the spectrum of the original modulation signal Filtering this side band from all of the higher sidebands will result in reconstructing the original modulating signal except that the power can be greatly increased Frequency Spectrum of Modulated Signal Amplitude sb 0 3000 6000 90001210 l510 l810 1405410371043404334036103910 h210l5104 Frequency Hz Figure 13 Frequency spectrum for PWM signal Ampli cation takes place by using power transistors to switch the high voltages to the load Since transistors dissipate little power when they completely turned on or off the ampli ers has low losses hence very good efficiency The issue is how to create effective power filters to remove the higher sidebands and carrier signals For our application and audio signals in general the unwanted signals are simply rejected by the system receiving the signal because the device being driven cannot respond the higher frequency signals Other applications require some kind of analog filtering as shown in Figure 14 Comparing Figure 13 and Figure 14 one will see that the signal around zero Hz is not attenuated whereas the higher sidebands and carrier signals are greatly reduced Frequency Spectrum of Filtered PWM Signal Amplitude db II 1 Illa J IL ul U 0 3000 6000 90001210 l510 l810 1405410571043404334036403940121615404 Frequency Hz Figure 14 Spectrum after filtering with a 4th Order Butterworth Filter The effects of ltering are shown in Figure 15 through Error Reference source not found Again it can be seen that the amplitude of the original signal remains approximately unchanged while the distortion and apparent noise generated by the PWM are greatly reduced Un ltered Modulation Reconstruction Amplitude Time seconds Figure 15 Unfiltered reconstructed signal lAmplitudel Amplitude Frequency Sprectrum of Filtered Reconstructed Signal U 0 30 60 90 120 150 180 210 240 270 300 330 360 390 420 450 480 510 540 570 600 Frrequency Hz Figure 16 Spectrum of un ltered reconstructed signal Modulation Signal Reconstruction after Flltering Time seconds Figure 17 Filtered reconstructed signal Appendix 3 UML and Software Documentation Software Documentation or Source Code Documentation is written text that accompanies computer software It either explains how it operates or how to use it In fact the term software documentation means different things to different people This article describes the term as used by the largest groups of users Relationship to hardware Computer software is so called in contrast to computer hardware which encompasses the physical interconnections and devices required to store and execute or run the software In computers software is loaded into RAM and executed in the central processing unit At the lowest level software consists of a machine language speci c to an individual processor A machine language consists of groups of binary values signifying processor instructions object code which change the state of the computer from its preceding state Software is an ordered sequence of instructions for changing the state of the computer hardware in a particular sequence It is usually written in highlevel programming languages that are easier and more ef cient for humans to use closer to natural language than machine language Highlevel languages are compiled or interpreted into machine language object code Software may also be written in an assembly language essentially a mnemonic representation of a machine language using a natural language alphabet Assembly language must be assembled into object code via an assembler ArchitectureDesign Documentation Design documents tend to take a broad view Rather than describe how things are used this type of documentation focuses more on the why For example in a design document a programmer would explain the rationale behind organizing a data structure in a particular way or would list the member functions of a particular object and how to add new ones to the code It explains the reasons why a given class is constructed in a particular way points out patterns and even goes so far as to outline ideas for ways it could be done better or plans for how to improve it later on None of this is appropriate for code documents or user documents but it is important for design Architecture documentation is a special breed of design documents In a way architecture documents are third derivative from the code design documents being second derivative and code documents being rst Very little in the architecture documents is speci c to the code itself These documents do not describe how to program a particular routine or even why that particular routine exists in the form that it does but instead merely lays out the general requirements that would motivate the existence of such a routine A good architecture document is short on details but thick on explanation It may suggest approaches for lower level design but leave the actual exploration trade studies to other documents Another breed of design docs is the comparison document or trade study This would often take the form of a whitepaper It focuses on one speci c aspect of the system and suggests alternate approaches It could be at the user interface code design or even architectural level It will outline what the IS situation is describe one or more alternatives and enumerate the pros and cons of each A goo trade study document is heavy on research expresses its idea clearly without relying heavily on obtuse jargon to dazzle the reader and most importantly is impartial It should honestly and clearly explain the costs of whatever solution it offers as best The objective of a trade study is to divine the best solution rather than to push a particular point of view It is perfectly acceptable to make no conclusion or to conclude that none of the alternatives are suf ciently better than the baseline to warrant a change It should be approached as a scienti c endeavor not as a marketing technique Technical Documentation This is what most programmers mean when using the term software documentation When creating software code alone is insuf cient There must be some text along with it to describe various aspects of its intended operation This documentation is usually embedded within the source code itself so it is readily accessible to anyone who may be traversing it This writing can be highly technical and is mainly used to de ne and explain the APIs data structures and algorithms For example one might use this documentation to explain that the variable mname refers to the rst and last name of a person It is important for the code documents to be thorough but not so verbose that it becomes dif cult to maintain them Often tools such as Doxygen javadoc ROBODoc POD or TwinText can be used to auto generate the code documentsithat is they extract the comments from the source code and create reference manuals in such forms as text or HTML les Code documents are often organized into a reference guide style allowing a programmer to quickly look up an arbitrary function or class Many programmers really like the idea of autogenerating documentation for various reasons For example because it is extracted from the source code itself for example through comments the programmer can write it while referring to his code and can use the same tools he used to create the source code to make the documentation This makes it much easier to keep the documentation uptodate Of course a downside is that only programmers can edit this kind of documentation and it depends on them to refresh the output for example by running a cron job to update the documents nightly Some would characterize this as a pro rather than a con User Documentation Typically the user documentation describes each feature of the program and the various steps required to invoke it A good user document can also go so far as to provide thorough troubleshooting assistance It is very important for user documents to not be confusing and for them to be up to date User documents need not be organized in any particular way but it is very important for them to have a thorough index Consistency and simplicity are also very valuable User documentation is considered to constitute a contract specifying what the software will do and should be free from undocumented features There are three broad ways in which user documentation can be organized A tutorial approach is considered the most useful for a new user in which they are guided through each step of accomplishing particular tasks A thematic approach where chapters or sections concentrate on one particular area of interest is of more general use to an intermediate user The nal type of organizing principle is one in which commands or tasks are simply listed alphabetically often via crossreferenced indices This latter approach is of the greatest use to advanced users who know exactly what sort of information they are looking for A common complaint among users regarding software documentation is that only one of these three approaches was taken to the nearexclusion of the other two It is common to limit provided software documentation for personal computers to online help that give only reference information on commands or menu items The job of tutoring new users or helping more experienced users get the most out of a program is left to private publishers who are often given signi cant assistance by the software developer Tools for architectural design and technical documentation um UMLis the UML z n majurrevlsun m um n uh quotmi sysmsv um um sysLErns engneenng mudelmg and representing urgamzanunal structures Communica ons Collaboration Diagrams 1 Ca abauhanDugamsDaNatMadelecessFlaw 2 mnswsmxsimpmmu Aswan D 3 4 dung are applicable in ca abauhan asgms f 1 carArrival gt nsSignzls M Walksmnzls Sensnr AZ cycleoi ns ghts awSignzls Traf cL ghts WalkSignzls Figure I A mini mummy magma dzpic ng cunnurnnl massage invucz nns 1 indicateaRetumValueOnJyWhenitisn39tCieu 2 1mm pmsms Oniy m They Aren39tcieu 3 DepcthnawFarEachMessage 4 letters A B c and D Msmng um Lhasa m cssagcs are being praccssed cmcurcn y describes information that is passed between modules The arrow direction indicates which module is the source on the information This diagram has inputs and outputs at the bottom interfacing with the hardware using software drivers Each process block uses the input information to compute or schedule outputs System Management Update Compute Set Steppor Controls Motor Outputs T39me Delay P0 Switch Command state 390 to Stepper senlie 3quot CPU Crystal M t r p Oscllator IO from Switches Figure 2 Data flow diagram for stepper motor control Control FLow Diagram The data ow diagram does not describe what the process does or how the input data is operated on See Chapter 2 Step 2 A control ow diagram is used to describe the sequence of operations that implements a process The control ow diagrams shown in Figure 3 through Figure 5 illustrate how they can be constructed with hierarchical levels of detail Figure 3 is the toplevel ow diagram that represents the entire process Figure 4 and Figure 5 provide greater details of the processes that step the motor and update the operating parameters Additional details can be modeled for the update table pointer process shown in Figure 4 Using the hierarchical ow diagrams reduces complexity and eliminates potential confusion from intricate gures The features of the process are explained in a topdown fashion Both the data ow diagram and the control ow diagram are needed to completely capture the organization of the entire process Figure 4 Software flow diagram for stepper motor function parameters Initialize system Update parameters Figure 5 Software flow diagram for update parameters function Figure 3 Software flow diagram for stepper motor control Sequence Diagram A Sequence diagram depicts the sequence of actions that occur in a system The invocation of methods in each object and the order in which the invocation occurs is captured in a Sequence diagram This makes the Sequence diagram a very useful tool to easily represent the dynamic behavior of a system A Sequence diagram is twodimensional in nature On the horizontal aXis it shows the life of the object that it represents while on the vertical aXis it shows the sequence of the creation or invocation of these objects Because it uses class name and object name references the Sequence diagram is very useful in elaborating and detailing the dynamic design and the sequence and origin of invocation of objects Hence the Sequence diagram is one of the most widely used dynamic diagrams in UML Defining 3 Sequence diagram A sequence diagram is made up of objects and messages Objects are represented exactly how they have been represented in all UML diagramsias rectangles with the underlined class name Within the rectangle A skeleton sequence diagram is shown in Figure 6 D L Ammmus call Figure 6 Snmplz sequent d39ngnm shuwing the guard ehmenls uf sequence d39ngm Elements uf 3 Sequence diagram See 215 Chapter 7 Serial IO ReVlsed April 14 2008 Protocols c I 1 between two rearn through one linennedia is in devices A serial protocol is aprotocol that sends data in one st channel There can be inner 39 eonno data Th quot 39 A L A 39 quotr39 Thernain 4 39ha overa r n ri i TV on which allows longer cables and ahigherpossible data rate for one stream 05 Communications Model TL i 1 e L Aquot i c 39 39 39 W 39 A 39L largely been replaced by the TCPIP stack The model 39 t layers 439 quot 39 39 onelae quot 39 r 39 the39 4 below Thernodeli o nan 39 39 mliratinnla eral hin it a duwntothePhysicalLayer 39 39 39 39 quot 39 quot 39 39 39 quot in a n i do it a opthe39 39 W 39 39 39quot A Figure 1 zpullcallnnnmmcnl rresemzmon nrnlncnl session protocol 5 innsnnnninn 3 roioers mners l l E 13 DE DE HnsI A sonnet Inquot Figure 1 0517150 seven layer netvtmrk mudel 27 HnsI a OSI divides telecommunication into seven layers The layers are in two groups The upper four layers are used whenever a message passes from or to a user The lower three layers are used when any message passes through the host computer Messages intended for this computer pass to the upper layers Messages destined for some other host are not passed up to the upper layers but are forwarded to another host The seven layers are Layer 7 The application layerThis is the layer at which communication partners are identi ed quality of service is identi ed user authentication and privacy are considered and any constraints on data syntax are identi ed This layer is not the application itself although some applications may perform application layer functions Layer 6 The presentation layerThis is a layer usually part of an operating system that converts incoming and outgoing data from one presentation format to another for example from a text stream into a popup window with the newly arrived text Sometimes called the syntax layer Layer 5 The session layerThis layer sets up coordinates and terminates conversations exchanges and dialogs between the applications at each end It deals with session and connection coordination Layer 4 The transport layerThis layer manages the endtoend control for example determining whether all packets have arrived and errorchecking It ensures complete data transfer Layer 3 The network layerThis layer handles the routing of the data sending it in the right direction to the right destination on outgoing transmissions and receiving incoming transmissions at the packet level The network layer does routing and forwarding Layer 2 The data link layerThis layer provides synchronization for the physical level and does bitstuf ng for strings of 1 s in excess of 5 It furnishes transmission protocol knowledge and management Layer 1 The physical layerThis layer conveys the bit stream through the network at the electrical and mechanical level It provides the hardware means of sending and receiving data on a carrier Flavors of Serial Communications There are two basic types of serial communications synchronous and asynchronous Part 1 Asynchronous Communications The a 39 39 im 39 L1 is a physical layer transmission technique that is most widely used for personal computers providing connectivity to printers modems fax machines etc As illustrated in Figure 2 the most signi cant aspect of asynchronous communications is that the transmitter and receiver clock are independent and are not m ram 1 Tn Fa V bytes otdata Indmdual characters may be separated by any arbrtrary 1dlepenod see btts ot data Any tote penod Figure 2 Asynchmnnus transmissiun or a series or characters torrnat Frgure 3 shows that each character rspreceded by a startbrt and followed by 172 stop brts 10 The asynchronous Luau utter 1 The startbrto data nommal data rate Tx Clock Stan btt Stop btts Paatet In Sena 011 Snm Fvegtswev se a bit stream Sena tn Paatet an Shm Regtster 39 RX Clock Valid Figure 3 39 39 1 men n mure smp bis At the recewer a clock ofthe sarne nornrnat equency rs constructed and used to clock btts are accepted p UART 7 Wm vs t tn Hrrw n eceryerTransrnrtter Detectrng the edge ofthe fust start brt as shown In Frgure 4 starts the recewer DownWald unnsmon nuggets receives Figure4 reception L 1 r 4 mm original data Speed iha fbltperlod Ehtssamp ex Reconstructed dock Clodlt 2116 X Data Rate blue to the local stable high rate clock black quot4min 39 quot quot4min 39 4 39 39 39 Mo lWide Area Networks use synchronous links and more sophisticated link protocols h quotam mul L 39 39 39 39 r matPointB wil 39 39 cummh n m u I I I 39 39 L happens when transmission clocks differ signi cantly mam nn 39 Dav SamP e a sum W s mm L Deva R D 7 55mm I I MW Iol l1lnlll l lol 5 mm mom Laumvgnul memes aM39 mammm Ideal sna corrupted asynchronous am sampllng Fxgure 6 Asynchronous senal ummg A transmitted L L r A uthestartb1t 4 lookmg for the Vda hw b1 To msure dam m m The pamy whxch they were sent Parity r exght bxts an an y number om evm number ofset Assume for example Lhattwo demes are commumcaungwm evm panty the most L L L e L W 1f llntmsway L L number of set bxts even num e error dunng mnsmsm y commumcahon wm be 1mpossxble Parity checking is the most basic form of error detection in communications Although it detects many errors it is not foolproof because it cannot detect situations in which an even number ofbits in the same data unit are changed due to electrical noise There are many other more sophisticated protocols for ensuring transmission accuracy such as CRC and checksum Pm A on y In Many PCs for example perform a parity check on memory every time a byte of data is read An example ofa RS232 signal using parity is shown in Figure 7 i av LSE MSE l a a a l Spams m 1 WWW Regan Mark W SevenDataEirs m m bns Data kamnespundmgm the ASCH character Figure 7 One byte of asynchronous data for seven data bits and even parity RS232 Asynchronous Protocol A r small electric quot quot eg anegative one 1 zero 0 This is illustrated in the waveform diagram of Figure 8 voltage 0 L gt lime o 1 u o 1 gure 8 Positive and negative voltages e amved To ensule that communlcataons haadwaae bulltby dllrelentvendols wlll Inlmonem n m A FIA l mm a n specl clmons as mmdardx la W modem ol tennlnal I ll c taansmlsslon Some ofthe key elements ofRSrZ3Z ale Voltage between 5 and 15 volts leplesents a o blt SPACE Voltage between 75 and 715 volts leplesents MARK Leastrslgm clmt blt taansnlltted lilst Blts e leeognlzed by ta 1 blg chaaaetet thls ls called the mm In andls lllusmztedln Flgule 9 voltage 1 51 45 l lime Idle stanl n l l u 1 Oslo ldln Figure 9 Using 1157232 a 12 7 7r le Iomr39l39lsr 3V to 712V andlogle 039 ls 3V to 12V To convelt a TIL loglc say the txansmlt data TxD MAY 7 n A w h RSVZ3ZC polt lOuF capael ols the boald ADS 5 1c howevel needs no external capaclto cllcult that ls shown ln Flgule 10 can be used wlth llttle r l and lt ls physleally smallel Elthex iculty 5V clplilul 1011 10V COMI DB9 4 1 135 F3 3MAX232 16 I l 44 1 1 a Rm 1 14 lt11 11 w m 3 13 I 12 um s M L MAXlM MAX232 quot DALLAS D8275 Figure 10 Schematic diagrams converting TTL level to R8232 levels The sender must leave the line idle for a minimum time this is usually the time to transmit one bit and is called the stop bit the standard allows one or two stop bits Although Figure 2 shows seven data bits all modern systems transmit eight bits plus the start and stop bits Bit rate is a measure of communications speed Instead of specifying the time per bit which is a fraction of a second communication systems specify the number of bits that can be transferred in a second Early RS232 connections operated at 300 bps modern systems use 19200 bps and 33600 bps Technically transmission hardware is rated in baud the number of signal changes per second For RS232 the baud rate is identical to the bit rate Other schemes can result where the bit rate is greater than the baud rate All electrical circuits require a minimum of two wires the current ows out on one wire and back on another called the ground In many applications we require data to ow in two directions at the same time e g between a terminal and a computer Simultaneous transfer in two directions is called full duplex and requires independent sending and receiving paths or channels These paths can be implemented using 3 or four conductors In contrast to full duplex there is half duplex mode one direction or the other but not at the same time and simplex mode one direction only However if there are only two conductors between two devices handshaking must be used to determine which device has permission to transmit RS232 defines a 25pin connector and specifies how the hardware uses the 25 wires for control or data For example a receiver willing to accept characters supplies a voltage on one of the control lines that the sender interprets as clear to send CTS Cheap RS232 hardware can be configured to ignore control signals and assume the other end is working This is illustrated in Figure 11 Figure 11 Fullrduplex RSrZSZ A computer transmits on pin 2 and receives on pin 3 while amodem transmits on pin 3 and receives on pin 2 Technically the computer is apiece of Data Cummumcatzun Eqmpmzm DCE and the modem is apiece ofDoto Termmal Eqmpmzm DTE Hardware Limitations 0ur earlier mveform diagrams shown in Figure 4 through Figure 8 are for the ideal cas In practice all 39 39 A 39 39 A A exact voltage or change from one in mun In addition 39 quot awire the signal loses strength Figure 12 illustrates how abit might appear on areal communication line Figure 12 Real vs ideal Voltages u t i J n pi t a iiinauaiimme For ct 4 example L 39 39 39 39 bit allowing it to accept signals like the one in Figure 12 Table 1 Glossary of Abbreviations etc CTS DCD DCE DSR DSRS Clear To Send DCE gt DTE Data Carrier Detected Tone from a modem DCE gt DTE Data Communications Equipment eg modem Data Set Ready DCE gt DTE Data Signal Rate Selector DCE gt DTE Not commonly use Data Terminal Equipment eg computer printer Data Terminal Ready DTE gt DCE Frame Ground screen or chassis No Connection Receiver external Clock input Ring Indicator ringing tone detected Ready To Send DTE gt DCE Received Data DCE gt DTE Signal Ground Secondary Clear To Send DCE gt DTE Secondary Data Carrier Detected Tone from a modem DCE gt DTE Secondary Ready To Send DTE gt DCE Secondary Received Data DCE gt DTE Secondary Transmitted Data DTE gt DTE Transmitted Data DTE gt DTE Is Your Interface a DTE or a DCE One of the stickiest areas of confusion in data communications is over the terms quottransmitquot and quotreceivequot as they pertain to DTE data terminal equipment and DCE data communication equipment In synchronous communication this confusion is particularly acute because more signals are involved So why is it that you sometimes send data on TD and other times you send data on RD Is this just a cruel form of mental torture Not really The secret lies in adopting the proper perspective In datacom the proper perspective is always from the point of view of the DTE When you sit at a PC terminal or workstation DTE and transmit data to somewhere far away you naturally do so on the TD transmit data line When your modem or CSUDSU DCE receives this incoming data it receives the data on the TD line as well Why Because the only perspective that counts in datacom is the perspective of the DTE It does not matter that the DCE thinks it is receiving data the line is still called quotTDquot Conversely when the modem or CSUDSU receives data from the outside world and sends it to the DTE it sends it on the RD line Why Because from the perspective of the DTE the data is being received So when wondering quotIs this line TD or RD Is it TC or RCquot Ask yourself quotWhat would the DTE sayquot Find out by following these steps The point of reference for all signals is the terminal or PC 1 Measure the DC voltages between DB25 pins 2 amp 7 and between pins 3 amp 7 Be sure the black lead is connected to pin 7 Signal Ground and the red lead to whichever pin you are measuring 2 Ifthe voltage on pin 2 is more negative than 3 Volts then it is a DTE otherwise it should be near zero vo ts 3 Ifthe voltage on pin 3 is more negative than 3 Volts then it is a DCE 4 If both pins 2 amp 3 have a voltage of at least 3 vols then either you are measuring incorrectly or your device is not a standard ElA232 device Call technical support 5 In general a DTE provides a voltage on TD RTS amp DTR Whereas a DCE provides voltage on RD CTS DSR amp CD Table 2 This is a standard 9 to 25 pin cable layout for asynchronous data on a PC AT serial cable DTE or DCE Modem Data Modem Data Terminal Ground Modem Set Ready Modem Send 8 5 Modern Indicator 9 22 Modern a as on a ElA574 RS232V24 pin out on a DB9 pin used for Asynchronous Data Figure 13 DB9 male connector Pin 1 is in the top left position Figure 14 Pin assignment for a DB9 RS 232 connector Table 3 RS 232 and RS 423 Specifications Mode of Operation Total Number ol Drivers and Receivers on One Line Maximum Driver Driver Output Signal Level Loaded Min Loaded Driver Output Signal Level Unloaded Max Unloaded Power Off Slew Rate Max Cabling considerations you should use cabling made for RS232 data but I have seen low speed data go over 25039 on 2 pair phone cable Level 5 cable can also be used but for best distance use a low capacitance data grade cable The standard maxim length is 5039 but if data is asynchronous you can increase that distance to as much as 50039 with a good grade of cable The RS232 signal on a single cable is impossible to screen effectively for noise By screening the entire cable we can reduce the in uence of outside noise but internally generated noise remains a problem As the baud rate and line length increase the effect of capacitance between the different lines introduces serious crosstalk this especially true on synchronous data because of the clock lines until a point is reached where the data itself is unreadable Signal Crosstalk can be reduced by using low capacitance cable and shielding each pair Using a high grade cable individually shielded low capacitance pairs the distance can be extended to 4000 feet At higher frequencies a new problem comes to light The high frequency component of the data signal is lost as the cable gets longer resulting in a rounded rather than square wave signal The maxim distance will depend on the speed and noise level around the cable run On longer runs a line driver is needed This is a simple modem used to increase the maxim distance you can run RS232 data Making sense of the speci cations Selecting data cable isn39t difficult but often gets lost in the shuf e of larger system issues Care should be taken However because intermittent problems caused by marginal cable can be very difficult to troubleshoot Beyond the obvious traits such as number of conductors and wire gauge cable specifications include a handful of less intuitive terms Characteristic Impedance Ohms A value based on the inherent conductance J 39 and 39 J of a cable that represents the impedance of an in nitely long cable When the cable is out to any length and terminated with this Characteristic Impedance measurements of the cable will be identical to values obtained from the infinite length cable That is to say that the termination of the cable with this impedance gives the cable the appearance of being infinite length allowing no re ections of the transmitted signal If termination is required in a system the termination impedance value should match the Characteristic Impedance of the cable Shunt Capacitance pFft The amount of equivalent capacitive load of the cable typically listed in a per foot basis One of the factors limiting total cable length is the capacitive load Systems with long lengths benefits from using low capacitance cable Propagation velocity of c 39 The speed at which an electrical signal travels in the cable The value given typically must be multiplied by the speed of light c to obtain units of meters per second For example a cable that lists a propagation velocity of 78 gives a velocity of 078 X 300 X 106 234 X 106 meters per second Plenum cable Plenum rated cable is fire resistant and less toxic when burning than nonplenum rated cable Check building and fire codes for requirements Plenum cable is generally more expensive due to the sheathing material used The specification recommends 24AWG twisted pair cable with a shunt capacitance of 16 pF per foot and 100 ohm characteristic impedance It can be difficult to qualify whether shielding is required in a particular system or not until problems arise We recommend erring on the safe side and using shielded cable Shielded cable is only slightly more expensive than unshielded There are many cables available meeting the recommendations of RS422 and RS485 made specifically for that application Another choice is the same cable commonly used in the twisted pair Ethernet cabling This cable commonly referred to as Category 5 cable is defined by the EINTINANSI 568 specification The extremely high volume of Category 5 cable used makes it widely available and very inexpensive often less than half the price of specialty RS 422485 cabling The cable has a maximum capacitance of 17 pFft 145 pF typical and charactenstlc lmpedahee of 100 ohms Category 5 eable ls avallable as shlelded thsted pan STP as well as unshlelded thsted palr UT and generally exceeds the recommendations maklng lt ah exeelleht cholce forRse232 systems R5232 V24V28 2110 X20 Asynchronous X21 Synchronous General The Y b A b fened descnptlon 1257232 ls ah mm mm ahdls ldehtaeal to CCITT V 24M 28 x 20blsx 21bls andISO 152110 e only allrehehee ls that CCITT has sphtthe interface lhto lts electxlcal description 28 and ameehameal part v 24 or Asynchronous x 20 bls and Synchronous x 21 bls where the ETAHA descnbes everythlng uhdehlzs232 LA Th wntteh forthe DTE slde All types ofcables we have to use ahamlhg eonventlon DTE eDCE Stxalght Cable DTE eDTE NulleModem Cable DCE eDCE Tall Clheult Cable lnlerlaoe Mechanical There are specl rm The CCITT 4 R145 1 l m 25 25 Female Figure 15 Varinlls cannectm used fur R8132 cnmmunicztinns Table 4 Connector Pin Con gurations 1Circuit 1Circuit I 17 7 RS232C Description 1RJ45 TIA 457 EIA 1CCITT 1 11 Shie1d Ground AA 1 17 1 17 1Signa1 Ground AB 1102 1 15 i 12 Transmitted Data BA 1103 167 13 13 Received Data BB 1104 157 12 14 Request To Send ECA 1105 187 17 15 Clear To Send CB 1106 177 18 16 DOB Ready 1107 117 16 120 gDTE Ready KT 11082 13714 122 Ring Indicator CE 1125 117 19 18 Received Line Signal Detector 1109 11 123 3Data Signal Rate Select GDTEDCE Sourcegt SCHCI 1111112 17 1 i 124 Transmit Signal Element Timing CDTE Source DA 1113 17 1 115 1Transmitter Signal Element Timing DCE Source DB 1114 17 1 i 117 iReceiver Signal Element Timing DCE Source DD 1115 118 Local Loopback Quality Detector LL 1141 17 121 Remote Loopback rm 1140110 1 114 Secondary Transmitted Data 11 1 8 1 116 5Secondary Received Data 1SBB 1119 119 Secondary Request To Send xSCA 1120 113 Secondary Clear To Send iSCB 1121 1 eSecondary Received Line Signal Detector 112 Data signal Rate Select CDCE Source 1SCFCI 1122112 1 125 Test Mode 1 1142 19 Reserved for Testing V i 110 Reserved for Testing 71 V 11 1 Unassigned 7 1 Asynchronous Communications and the RCM3000 Processor The RCM 3000 processor supports six serial ports that use pins on parallel ports C and G As Table 5 shows serial ports A through D are assigned to Port C alternated pin assignments for serial ports A and B use Port D All serial ports support both synchronous and asynchronous modes Output voltage limits comply with normal RCM 3000 10 pin speci cations hence driver ICs are necessary to convert serial port IO to RS232 voltage levels Serial Port A can be used to download programs This feature is commonly referred to as cold booting This port is accessed through an eight pin connector on the top 0fthe RCM 3000 module circuit card Usually this is where the programming cable is attached to the system After the program has been downloaded to the PCM 3000 memory the system can operate standalone ie with no PC support by simply resetting the processor after removing the programming cable When operating in standalone mode serial port A can be used as a conventional serial port Refer to the R3000 User s Manual Appendix A for additional information concerning the programming cable and using serial port A for conventional communications The ECE 341 lab project board makes serial ports C and D available at RS232 voltage levels Serial port D is connected to the DB9 connector for a DCE interface and serial port C is connected for a DTE interface When using the internal clock data rates up to one half of the system clock rate can be used Wow If an external clock is used the maximum clock rate is one sixth the system clock rate Conventional data rates start at 300 Baud and are available on the R3000 processor up to 460800 K Baud Table 5 Serial Port Signals Serial Port Signal Name Function Port Assignment Serial Port A l TXA Serial Transmit Out Port C 6 i i RXA x Serial Transmit In Port C 7 l CLKA 7 Clock for clocked mode bidirectional Port B1 l ATXA Alternate serial transmit out I Port D 6 i ARXA Alternate serial receive in Port D 7 1 Serial Port B l TXB 7 Serial Transmit Out Port C 4 i RXB Serial Transmit In Port C 5 l CLKB Clock for clocked mode bidirectional Port B0 if ATXB i Alternate serial transmit out Port D 4 l ARXB V Alternate serial receive in 7 Port D 5 Serial Port C l TXC Serial Transmit Out I Port C 2 l RXC 7 Serial Transmit In Port c 3 CLKC 7 Clock for clocked mode bidirectional Port F1 Serial Port D TXD Serial Transmit Out Port C 0 l RXD Serial Transmit In Port c 1 CLKD Clock for clocked mode bidirectional Port F0 Serial Port E l TXE V Serial Transmit Out 7 Port G 6 3 RXE L Serial Transmit In Port G 7 l TCLKE 7 Optional external transmit clock Port G4 l RCLKE Optional external receive clock I Port G5 Serial Port F i TXF Serial Transmit Out Port G 2 l RXF Serial Transmit In Port G 3 TCLKF Optional external transmit clock Port G0 l RCLKF Optional external receive clock Port G1 The R3000 processor supports 7 8 or 9 bit communications as well as odd even or no parity To support halfduplex serial communications there is software support to determine when the last bit of communications A common shortcoming of the Dynamic C is the lack of documentation in either the Dynamic C User s Manual or the Dynamic C Function Reference A Rabbit Semiconductor application note TN213 was written for the R2000 processor that lacks serial ports E and F The library routines shown in Table 6 are supported in RS232lib to manage two types of data streams arrays For the R3000 processor the X in the list of functions is replaced with A B C D E or F depending upon which serial port is being referred to The gets function is for text based data streams only and must be NULL terminated There is no restriction on data values for the other functions Conspicuous by its absence is the function sengets get a string of characters Such a function can be easily written using the sengetc function but requires agreement of the character that will be used to terminate the string Since the terminating character may never be sent the sengets will also need a time limit to prevent the system from being deadlocked or other processes will be starved out Starvation is when one function nominates the CPU s time Deadlock is when two processes are in contention for the same resource Fair allocation of processor time can resolve starvation issues but not deadlock problems Concurrency is a way to avoid deadlocks and starvation Concurrency is the resource management where by processes cooperate in sharing common scarce resources Dynamic C implements concurrency using cofunctions and costates hence a function cofisengets as well as others are listed in TN213 Concurrent programming is a topic covered in ECE 443 Writing the sengets function is left as an exercise for the student Table 6 Stream based library functions support in Dynamic C RS232 library Other serial port functions supported are listed below in Table 7 Only the serXopen function in Table 7 is always required Table 7 Support stream based RS 232 library function I ose The ECE 341 lab projectboard uses senal ports c andD as shown 1n that pomon ofthe sehernaae dAagram forthe ECE341 lab project board See Fxgure 1s The program shown 1n Lxstm 1 c5341 lab projectboard Input and output buffer sxzes rnust be declaredm a de nequot statement before the serXopen funeuon 15 ea11eo1 As TN213 reports Vahd sxzes futhe huerers eg1531 31 huFFPru H e ea1eu1aaans quot The eaue mLxsung 1 shows that the 1257232110 does not needto be mcludedm a usequot statement Addmonal mformanon on usmg sena1 ports on the RCM 300015 avauame 1n the eourse textpages 245 through 253 sznmL eums P re 16 Schunzli dizgnm nme ser39nluurpul an the ECE m hh pmjeclhuzx Lining 1 Snmpk pmgmm quotPu39rspquot in are SnmpksSERlALmincmry um ismnairrea mrsrrianpmn mrmrmrrmrrmmrmrrrmmrrrrmmmmrr p Thls pxagxam quotUtes a null re mlnaced suing ave sexlal pore n I nuse he run meh a Sena uemcy sueh as Hypertexmnal gran ml ensure all ehars are senc rhen ex onneee u e 2 on p 1 nneee E s R5232 5m ea Rabb 5m onneee PE S Rs 2 m r b ear 5 232 RD Rabb Can re rhe ens um or pore eonneeeeu ea usezaz 192ml um Run Hypereer 1113 Run ths program e e sage appear r de ned an an rhey ml default ea 31 and a eaunner void mainvoid static const char s quotHello Z7Worldrnquot serDopenl9200 Initialize serial or seerutss Send stream of characters to serial port D first wait until the serial buffer is empty while seerrFree l DOUTBUFSTZE then wait until the TX data register and the TX shift register are both empty while BithPortlSDSR 3 ll BithPortTSDSR 2 now we can close the serial port without cutting off TX data serDclose The bit de nitions for the serial port status register shown in Table 8 help to explain the magic numbers in the last while statement in the code above The purpose as noted in the comments of the code are to allow the data bits to shift out of the transmitserial shift register prior to closing the serial port Closing the serial port prematurely will abort the serial transmission before all of the data bits are sent as well as the nal stop bit Table 8 shows that bit elds of the serial port status register can also be used to determine the state of the serial port receive shift register Table 8 Bit de nitions for serial port status registers SXSR Bits Value Description for Asynchronous Mode 7 0 The receive buffer is empty 1 There is a byte in the receive buffer The serial port will request an interrupt while this bit is set The interrupt is cleared when the receive buffer is read 6 0 The byte in the receive buffer is data received with a valid stop bit 1 The byte in the receive buffer has a low 9th or 8th bit a ka an address bit or there is a framing error If no address bit is expected and the buffer is all zeros this is a break condition A break is a condition where the line is in a low logic state for a long time often used to signify certain events by some pieces of hardware This bit is cleared when the receive buffer is read 5 0 The receive buffer has not over owed l The receive buffer over owed This happens if the shift register and data register are both full and a start bit is detected This bit is cleared when the receive buffer is read 4 0 This bit is always zero in asynchronous mode 3 0 The transmit buffer is empty 1 The transmit buffer is full The serial port requests an interrupt when the transmitter takes a byte from the transmit buffer The interrupt is cleared when the byte is transferred into the shift register or any value which will be ignored is written to SXSR V2 0 The transmitter is idle l The transmitter is sending a byte An interrupt is generated when the transmitter clears this bit which occurs only if the transmitter is ready to start sending another byte but can39t because the transmit buffer is empty l0 0 These bits are always zero in asynchronous mode P art 2 39 W5 As stated in the beginning of this chapter there are two basic types of serial communications 39 and a 39 With 39 communications the two devices initially synchronize themselves to each other and then continually send characters to stay in sync Even when data is not really being sent a constant ow of bits allows each device to know where the other is at any given time That is each character that is sent is either actual data or an idle character Synchronous communications allows faster data transfer rates than asynchronous methods because additional bits to mark the beginning and end of each data byte are not required The serial ports on IBMstyle PCs are asynchronous devices and therefore only support asynchronous serial communications Since the receiver is explicitly told when to sample each data bit the data bits are not required to have uniform spacing There are various schemes of imbedding the clock signal into the data such as return to zero and Manchester encoding Whether using asynchronous or synchronous communications the mechanism used to synchronous consumes data channel bandwidth unless a separate data path is used for a clock signal It can be rightly argued that providing a second data channel just for the clock signal automatically consumes half of the path bandwidth capacity In the following sections of this chapter we will look at two very common synchronous serial protocols Serial Peripheral Interface SPI1 With this article the possibilities of serial communication with peripheral devices via SPI Serial Peripheral Interface will be discussed More and more serial bus systems are preferred instead of a parallel bus because of the simpler wiring As the efficiency of serial buses increases the speed advantage of the parallel data transmission gets less important The clock frequencies of SPI devices can go up to some Megahertz and more There are a lot of applications where a serial transmission is perfectly sufficient The usage of SP1 is not limited to the measuring area but is also used in the audio field The SPI this name was created by Motorola is also known as Microwire trade mark of National Semiconductor Both have the same functionality There are also the extensions QSPI Queued Serial Peripheral Interface and MicrowirePLUS The popularity of other serial bus systems like IZC CAN bus or USB shows that serial buses get used more and more The Principle The Serial Peripheral Interface is used primarily for a synchronous serial communication of host processor and peripherals However a connection of two processors via SP1 is just as well possible and is described at the end of this section In the standard configuration for a slave device see Figure 17 two control and two data lines are used The data output SDO serves on the one hand the reading back of data offers however also the possibility to cascade several devices The data output of the preceding device then forms the data input for the next IC 1 Excerpts from htygwww mctnetfagspi html This text has been altered to correct spelling and grammar or to add additional information particularly in regards to the ECE34l lab project board 20 CS SPlSlave SCKL SD39 7m4 m gure 17 SP1 slave handshaking and data There is a MASTER and a SLAVE mode The MASTER device provides the clock signal and determines the state ofthe chip select lines ie it activates the SLAVE it wants to communicate with CS and SCKL are therefore outputs The SLAVE device receives the clock and chip select from the MASTER CS and SCKL are therefore inputs This means there is one master while the number of slaves is only limited by the number of chip selects A SP1 device can be a simple s 3911 register up to an indepen ent subsystem The basic principle of a shi register is always present Command codes as well as data values are serially transferred pumped into a shift register and are then internally available for parallel processing Here we already see an important point that must be considered in the philosophy of SP1 bus systems The length of the shift registers is not xed but can differ from device to device Normally the shift registers are eight bit or integral multiples of it Of course there also exist shi registers with an odd number ofbits For example two cascaded nine bit EEPROMs can store 18 bits data 1fa SP1 device is not selected its MISO output goes into a highimpedance state hiZ so that it does not interfere with the currently activated devices When cascading several SP1 devices they are treated as one slave and therefore connected to the same chi select Thus there are two meaningful types of connection of master and slave devices Figure 18 shows the type of connection for ascading several devices Figure 13 Cascading several SP1 devices In Figure 18 the cascaded devices are evidently looked at as one larger device and receive therefore the same chip select The data output of the preceding device is tied to the data input of and the nu reu unen he he t 39 39 g g 1 master another bus stmcture has to be chosen as shown in Figure 19 Here the clock SDI a a tothe mast l L r L types may be combined device iii Slave 1 Di SDO Figure 19 Master with independent slaves It is also possible to connect two micro controllers Via SPI For such a netwo k two protocol variants are possible In the rst there is only one m ster an several slaves and in the second each micro controller can take the role ofthe master For the selection of slaves again L39r 39 Lquot 39 L me cicuiun done by so ware Only the selected slave drives its output all other slaves are in high impedance state 39 39 39 it an The first variant 4 39 nrntnrnl 39 39 quotL 39 device mntncnl 39 39 39 L tun m I u ofthe master andto address MC68HC11 provides hardware error recognition useful in multiplemaster systems There are two SPI system errors 39 P 39 at me same time The other is a collision error that occurs for example when SPI devices work with different polarities However multimaster systems with software device ID are better served usi g 12c protocol Data and Control Lines of the SP1 39 and sno M N r r The chip select line is named SS SlaveSelect With CS ChipSelect the corresponding peripheral device is selected This pin is mostly activelow In the unselected state the MISO lines are hiZ and therefore inactive The master decides with which peripheral device it wants to communicate The clock line SCLK is brought to the device whether it is selected or not The clock serves as synchronization of the data communication The majority of SPI devices provide these four lines Sometimes the SDI and SDO are multiplexed as for example in the temperature sensor LM74 from National Semiconductor Sometimes one of these lines is missing altogether A peripheral device that must or can not be con gured requires no input line but only a data output As soon as it gets selected it starts sending data provided the master the microprocessor is clocking the SCL line In some ADCs therefore the MOSI line is missing eg MCCP3001 from Microchip There are also devices that have no data output An example of this case is the COP4723LCD controllers from National Semiconductor that can be con gured but cannot send data or status messages SPI Con guration Because there is no official specification what exactly SP1 is and what not it is necessary to consult the data sheets of the components one wants to use Important are the permitted clock frequencies and the type of valid transitions There are no general rules for transitions where data should be latched Although not specified by Motorola in practice four modes are used These four modes are the combinations of CPOL and CPHA In Table 9 the four modes are listed Table 9 SP1 Modes l SPI mode CPOL CPHA 0 0 0 1 0 1 2 1 0 3 1 1 Ifthe phase ofthe clock is zero ie CPHA 0 data is latched at the rising edge ofthe clock with CPOL 0 and at the falling edge of the clock with CPOL 1 If CPHA l the polarities are reversed CPOL 0 means falling edge CPOL l rising edge The micro controllers from Motorola allow the polarity and the phase of the clock to be adjusted A positive polarity results in latching data at the rising edge of the clock However data is put on the data line already at the falling edge in order to stabilize Most peripherals which can only be slaves work with this configuration If it should become necessary to use the other polarity transitions are reversed For additional information refer to the Maxim application note for APP502 The different Peripheral Types The question is of course which peripheral types exist and which can be connected to the host processor The available types and their characteristics are now discussed Peripheral types can be subdivided into the following categories 0 Converters ADC and DAC 0 Memories EEPROM and FLASH 0 Real Time Clocks RTC o Sensors temperature pressure 0 Others signal mixer potentiometer LCD controller UART CAN controller USB controller ampli er In the three categories converters memories and RTCs there is a great variety of component Devices belonging to the last both groups are more rarely There are lots of converters with different resolutions clock frequencies and number of channels to choose from 8 10 12 up to 24 bits with clock frequencies from 30ksps up to 600ksps Memory devices are mostly EEPROM variants There are also a few SP1 ash memories Capacities range from a couple of bits up to 64KBit Clock frequencies up to 3MHz Serial EEPROMS SP1 are available for different supply voltages 27V to 5V allowing their use in lowvoltage applications The data retention time can be from 10 years to 100 years The permitted number of write accesses is 1 million cycles for most components By cascading memory devices any number of bitsword can be obtained RTCs are ideally suited for serial communication because only small amounts of data have to be transferred There is also a great variety of RTCs with supply voltages from 20V In addition to the standard functions of a quotnormalquot clock some RTCs offer an alarm function non volatile RAM etc Most RTCs come from DALLAS and EPSON CAN and USB controllers with SP1 make it easier to use these protocols on a micro controller and interfacing a LCD via SP1 saves the troublesome parallel wiring SPI and the Rabbit Semiconductor R3000 Rabbit processors have hardware support SP1 using any one of the four serial ports A through D Software support is provided in the library functions in the SPIlib Although the course text offers little in the way of background and use of SPI the Rabbit Semiconductor application note TN200 offers invaluable technical information needed to setup and use the SP1 resources There are two devices on the ECE 341 lab project board that use SP1 the MCP3208 eight channel analog to digital converter ADC and the MCP2515 CAN controller area network controller The MCP3208 ADC is used in the ECE 341 lab and the MCP2515 is addressed in ECE 443 course The section of the schematic for the ECE 431 project board is shown in Figure 20 Even though they use common MOS1 M1SO and SCL lines each device has its own device select control Pin headers JP25 and JP26 provide pinout for the SCL MOSI and M1SO lines but each has separate device select controls thus providing for two addition external slave devices Figure 2n SP1 devices and ECE m lab prnjeclhnald Dynamic C SPI Library supp on T i Mn All global n in ii ii iii in Mi spi libquot statement Even though senal portB is the default SP1 porL Lhe defme SPIisERiBquot i A andT cl eniiii i i iiiiiy iip iiniy i in synchronous mode is Form 0 Lisiing 2 SPliniLializingcndE Use Serlal Part E deflne SPIicLOCKJlODE SPLMODEiDD 3P1 deE mm a fine SPIic IVISOR 5 3P1 clock dlvlder 1 compller warnlng 7 depends upon length of Mines use quotspiiinquot 1nclude the Sn llhrary Table 10 shows the four library functions provided by the Dynamic c SP1 iibinry Tabla In SF library funnjnns 5mm H ieiers ior a serial Interface I i n tothe SP i The RCM 3000 processor is by default the master but it can be configured as a slave by including the statement def1ne SPIiSLAVE before the use spilib Refer to TN200 for additional details SPI Devices 0n the ECE 341 Lab Project Board The lab project board is equipped with a Microchip MCP 3208 eight channel 10bit analog to digital converter ADC The ADClib library that was written to support this device contains two functions ADCiinit and ReadAZD When oat ADCiinit oat Vr is called with a nonzero Vr argument the function returns a scale factor to convert the binary ADC reading into oating point realworld variable with units of volts When oat ReadA2D int Channel int Samples is called the value returned is a ratiometric realworld value relative to 50 volts When calling the ADCiread you must specify the channel number zero through seven and the number of samples to be taken in burst mode The samples taken are averaged to limit the effects of random noise on the signal Additional information on the use of the ADC will be provided in Chapter 8 InterIntegrated Circuit Communications2 2C In the early 1980 s Philips Semiconductors developed a simple bidirectional 2wire bus for efficient interIC control This bus is called the Inter1C or 12Cbus At present Philips IC range includes more than 150 CMOS and bipolar 12Cbus compatible types for performing communication functions between intelligent control devices eg microcontrollers general purpose circuits eg LCD drivers remote IO ports memories and applicationoriented circuits e g digital tuning and signal processing circuits for radio and video systems All IZCbus compatible devices incorporate an onchip interface which allows them to communicate directly with each other via the 12Cbus This design concept solves the many interfacing problems encountered when designing digital control circuits 12C has become a de facto world standard that is now implemented in over 1000 different ICs and is licensed to more than 50 companies The 2C Bus Protocol The 12C bus physically consists of 2 active wires and a ground connection The active wires called SDA and SCL are both bidirectional SDA is the Serial DAta line and SCL is the Serial CLock line Every device hooked up to the bus has its own unique address no matter whether it is an MCU LCD driver memory or ASIC Each of these chips can act as a receiver andor transmitter depending on the functionality Obviously an LCD driver is only a receiver while a memory or IO chip can be both transmitter and receiver The 12C bus is a multimaster bus as shown in Figure 21 This means that more than one IC capable of initiating a data transfer can be connected to it The 12C protocol specification states that the IC that initiates a data transfer on the bus is considered the Bus Master Consequently at that time all the other ICs are regarded to be Bus Slaves 2 Excerpts for httpwwwesacademycomfagiZc As bus masters are generally rnreroeontrouers let stake a look at a general mterrIC chat onthebusntu nun 44 ms slaves HM his WW Figure 211 c netVtmrk archimcmre Fust the McU wtll tssue a quotSta1 condttton Thts acts as an Attentton slgtal to all ofthe c nnected devtces All ICs on the bus W111 hsLen to the bus for In ommg data Then the MCU sends the 1dmt1 a or address othe devtce 1L waan to access along wtth an mdtcauon Havmg recewed the address all IC s W111 compare rt wrth therr own address If t doesnt rnateh they r r however the ehrp W111 produce a response called the aclmowledge srgnat DA A In our case the MCU W111 transrnrt data When all 1s done the MCU W111 1ssue the STOP eondrtton another transrnrssron to start any moment Before we take a hardware of the bus The 2C Bus Hardware Structure A t mi 1 clock and a ground eonneotron Both SDA and SCL are rnrtrauy btrdtrecuonal Thts means that m a pamcular deyree these hnes can be dnyen by the IC ttselfor from an orternat deyree In t p n utant outputs dependrng on the technology as shown In Frgure 22 Figumzz I39Cphysical bye ullt and an open A ll txanslstor When the bus ls IDLE the bus hnes are in the logl HIGH state note that external pullrup resistors are necessary forthls w l easily forgotten To put a chip times its output txanslstor thus pulhng the bus to aLOWlevel The devlces as seen in the gure ls actually a srnall eurrent sour or even non bullHn Wm bus ls onwpled by a chip thatrs sending a 0 then all other chlps lose therrnghtto aeeess the bus More will be explained about ths in the section about bus ar an n However the openrcollector techmque has drawback too Hyou haye along bus th5 Wlll L h um Fl ur w Vw or w srgnal on the bus the pullrup reslstor tn the rexlstent constantwhleh wlll re ect on the shapes of the signals The higherthls RC constant the slower u can go L Y L rt tn 0 wt 1 and 0 luiiueuce ni line length and bus levminzlinn nn waveimms Passive Slian Passive Lung Adlve Lung Figure 23 Alternate bus driver techniques t H ur 4 Thlscan be so baol that ghost slgnals disturb your transmission and corrupt the data you transrnrt Not even Sehrnltt mggers at the 105 inputs will be able to ehrnlnate th5 effect lnlluemz v1 Ind In unnlnlllnn Median Trancde olgnal 11w Irululd II he Iml quotIII In dllp Ilium see It um Inquot W lnpul helm a In ll an In zen ll dah nd Rnlullhg algnll Figure 2 Bus elemcal characteristics Therefore some strict electrical speci cations have been put together To overcome this problem Philips has developed an active 12C terminator This device consists of a twin charge pump and you can look at it as a dynamic resistor The moment the state changes it provides a large current low dynamic resistance to the bus so it can charge the parasitic capacitor very quickly Once the voltage has risen above a certain level the high current mode cuts out and the output current drops sharply Take a look at Figure 25 As long as the bus is kept low transistor C is on the charge pump is disabled because the gate of transistor B is kept low by transistor A V R1 Lme quotquot Capac ancei Figure 25 Quasi bidirectional output circuit As soon as the chip releases the bus A and C turn off the capacitor will start charging drawing current trough all four of the resistors l 4 The voltage drop over resistor 2 will cause the transistor B to turn on shorting out resistor 3 Since resistor 3 is a relatively low value the current will rise At a certain point in time the drop between transistor B s gate and source will not be big enough to keep it switched on It will then switch off and the charge injection will stop At that time only the external pullup resistor remains to overcome the charge leakage on the bus Please note that this is a simple explanation The actual device implements more circuitry eg to prevent quotoverchargingquot if another chip is still pulling the bus low This device can come in handy if you need to overcome several meters of 12C bus length 2C Bus Events The START and STOP conditions Prior to any transaction on the bus a START condition needs to be issued on the bus The start condition acts as a signal to all connected IC s that something is about to be transmitted on the bus As a result all connected chips will listen to the bus After a message has been completed a STOP condition is sent This is the signal for all devices on the bus that the bus is available again idle If a chip was accessed and has received data during the last transaction it will now process this information if not already processed during the reception of the message Figure 26 Signal timing for START and STOP conditions A few notes about start and stop conditions A single message can contain multiple Start conditions The use of this socalled quotrepeated startquot is common in 12C A Stop condition ALWAYS denotes the END of a transmission even if it is issued in the middle of a transaction or in the middle of a byte It is quotgood behaviorquot for a chip that in this case it disregards the information sent and resumes the quotlistening statequot waiting for a new start condition IZC Bus Events Transmitting a byte to a slave Once the start condition has been sent a byte can be transmitted by the MASTER to the SLAVE This first byte after a start condition will identify the slave on the bus address and will select the mode of operation The meaning of all following bytes depends on the slave Ilt Byte sent to slave gtl Asserted low by slave device 3 E SDA 7 k 556666 AJ CDLSB SCL START SEQUENCE Slave Address STOP SEQUENCE 5 MN Figure 27 Start of data transfer for writing to a slave device A number of addresses have been reserved for special purposes One of these addresses is reserved for the quotExtended Addressing Modequot As the 12C bus gained popularity it was soon discovered that the number of available addresses was too small Therefore one of the reserved addresses has been allocated to a new task to switch to 10bit addressing mode If a standard slave not able to resolve extended addressing receives this address it won39t do anything since it39s not its address If there are slaves on the bus that can operate in the extended lObit addressing mode they will ALL respond to the acknowledge cycle issued by the master The 30 second byte that gets transmitted by the master will then be taken in and evaluated against their address IZC Bus Events Receiving a byte from a slave Once the slave has been addressed and the slave has acknowledged this a byte can be received from the slave if the RW bit in the address was set to READ set to 39139 The protocol syntax is the same as in transmitting a byte to a slave except that now the master is not allowed to touch the SDA line Prior to sending the 8 clock pulses needed to clock in a byte on the SCL line the master releases the SDA line The slave will now take control of this line The line will then go high if it wants to transmit a 39l39 or if the slave wants to send a 39039 remain low Referring to Figure 28 all the master has to do is generate a rising edge on the SCL line 2 read the level on SDA 3 and generate a falling edge on the SCL line 4 The slave will not change the data during the time that SCL is high Otherwise a Start or Stop condition might inadvertently be generated During l and 5 the slave may change the state of the SDA line I39 i SCL i i IE E E Figure 28 Bit timing for master read operation In total this sequence has to be performed 8 times to complete the data byte Figure 29 illustrate that bytes are always transmitted MSB rst The meaning of all bytes being read depends on the slave There is no such thing as a quotuniversal status registerquot You need to consult the data sheet of the slave being addressed to know the meaning of each bit in any byte transmitted l Byte read from slave gtl Asserted low by master device B E SDA 7 ACK x 35iiii AJ 0 LSB SCL START STOP SEQUENCE SEQUENCE Figure 29 Data bit timing for a slave read operation 31 IZC Bus Events Getting Acknowledge from a slave When an address or data byte has been transmitted onto the bus then this must be ACKNOWLEDGED by the slaves In case of an address If the address matches its own then that slave and only that slave will respond to the address with an ACK In the case where a byte is transmitted to an already addressed slave then that slave will respond with an ACK as well The slave that is going to give an ACK pulls the SDA line low immediately after reception of the 8th bit transmitted or in case of an address byte immediately after evaluation of its address In practical applications this will not be noticeable Figure 30 shows the timing sequence for an acknowledge bit This means that as soon as the master pulls SCL low to complete the transmission of the bit 1 SDA will be pulled low by the slave 2 The master now issues a clock pulse on the SCL line 3 the slave will release the SDA line upon completion of this clock pulse 4 The bus is now available again for the master to continue sending data or to generate a stop condition L SDA J l E Figure 30 Slave acknowledge to the master during a master write operation In case of data being written to a slave this cycle must be completed before a stop condition can be generated The slave will be blocking the bus SDA kept low by slave until the master has generated a clock pulse on the SCL line IZC Bus Events Giving Acknowledge to a slave Upon reception of a byte from a slave the master must acknowledge this to the slave device Figure 31 shows that the master is in full control of the SDA and the SCL line After transmission of the last bit to the master 1 the slave will release the SDA line The SDA line should then go high 2 The Master will now pull the SDA line low 3 Next the master will put a clock pulse on the SCL line 4 After completion of this clock pulse the master will again release the SDA line 5 The slave will now regain control of the SDA line 6 ll 1 SDA RITE iii lai SCL Tl g iii ill IEE a E Figure 31 Master acknowledge to slave during a master read sequence 32 Note The above waveform is slightly exaggerated You will not notice SDA going high in 2 and 5 A small spike might barely be visible Note An Acknowledge of a byte received from a slave is always necessary EXCEPT 0n the last byte received If the master wants to stop receiving data from the slave it must be able to send a stop condition Since the slave regains control of the SDA line after the ACK cycle issued by the master this could lead to problems Let s assume the next bit ready to be sent to the master is a 0 The SDA line would be pulled low by the slave immediately after the master takes the SCL line low The master now attempts to generate a Stop condition on the bus It releases the SCL line first and then tries to release the SDA line which is held low by the slave Conclusion No Stop condition has been generated on the bus This condition is called aNACK NotACKnowlealge Do not confuse this with No ACKnowlealge The rules governing the 12C acknowledge are shown in Table 11 Acknowledge rules Eagn ii pn after a master has read a byte from a slave 0t acknowledge NACK No after a master has written a byte to a acknowledge slave 2C Bus Events No Acknowledge from slave to master This is not exactly a condition It is merely a state in the data ow between master and slave If after transmission of the 8th bit from the master to the slave the slave does not pull the SDA line low then this is considered a No ACK condition This means that either 0 The slave is not there in case of an address 0 The slave missed a pulse and got out of sync with the SCL line of the master 0 The bus is quotstuckquot One of the lines could be held low permanently In any case the master should abort by attempting to send a stop condition on the bus A test for a quotstuck busquot can be performed in the stop condition cycle 2C Bus Arbitration So far we have seen the operation of the bus from the master s point of view and using only one master on the bus The 12C bus was originally developed as a multimaster bus This means that more than one device initiating transfers can be active in the system When using only one master on the bus there is no real risk of corrupted data except if a slave device is malfunctioning or if there is a fault condition involving the SDA SCL bus lines This situation changes with 2 MCU39s as shown in Figure 32 When MCU 1 issues a start condition and sends an address all slaves will listen including MCU 2 which at that time is considered a slave as well If the address does not match the address of CPU 2 this device has to hold back any activity until the bus becomes idle again after a stop condition As long as the two MCU39s monitor what is happening on the bus start and stop and as long as they are aware Vhs39r l n problem Figure 32 Multiplz masm npemtinn idle happen In a realrllfe scenario This could lead lo problems Hew can yeu knnw if some Ether device is uansmining en Lhe bus 7 uan l F d m licuallm LCA Mn VY HT T T W MT 39T r Ha on V W T T other device 15 pulling the line low l a a another adenpuo start transmitting What ab am the risk or dam curmpti n L ltbacksoff ltwlll behave the same masleis are noLLhe same Thaefore lem s have a look aLFlgure 33 whecelwo MCUs snarl LIEnSrmLng at the same time smmmu r CPUI L SBA I I I I I I I mam snL rvwwmnrv1 Bus Sm m llJl ll I hl F W snL x nnnnnnnn n nnnnnnnn n r nn mm milieva m mu in 1mm sun Anden Figure 33 Dam oullisiuns mm mulliple master epemiun Thetwo MCU s are accessing a slave In wnle mode ataddress 1111001 The slave a 1m ld lhl an n ul ou Now MCUl wants to transmit 01010101 to the slave while MCU 2 wants to transmit 01100110 to the slave The moment the data bits do not match anymore because what the MCU sends is different than what is present on the bus one of them loses arbitration and backs off Obviously this is the MCU which did not get its data on the bus For as long as there has been no STOP present on the bus it won39t touch the bus and leave the SDA and SCL lines alone yellow zone The moment a STOP was detected MCU2 can attempt to transmit again From the example above we can conclude that is the master that is pulling the line LOW in an arbitration situation that always wins the arbitration The master which wanted the line to be HIGH when it is being pulled low by the other master loses the bus We call this a loss of arbitration or a backoff condition When a MCU loses arbitration it has to wait for a STOP condition to appear on the bus Then it knows that the previous transmission has been completed Clock Synchronization All masters generate their own clock on the SCL line to transfer messages on the 12C bus Data is only valid during the HIGH period of the clock A de ned clock is therefore needed for the bitbybit arbitration procedure to take place Clock synchronization is performed using the wiredAND connection of 12C interfaces to the SCL line This means that a HIGH to LOW transition on the SCL line will cause the devices concerned to start counting off their LOW period and once a device clock has gone LOW it will hold the SCL line in that state until the clock HIGH state is reached However the LOW to HIGH transition of this clock may not change the state of the SCL line if another clock is still within its LOW period The SCL line will therefore be held LOW by the device with the longest LOW period Devices with shorter LOW periods enter a HIGH waitstate during this time When all devices concerned have counted off their LOW period the clock line will be released and go HIGH There will then be no difference between the device clocks and the state of the SCL line and all the devices will start counting their HIGH periods The first device to complete its HIGH period will again pull the SCL line LOW In this way a synchronized SCL clock is generated with its LOW period determined by the device with the longest clock LOW period and its HIGH period determined by the one with the shortest clock HIGH period Using the clock synchronizing mechanism as a handshake The 12C protocol also includes a synchronization mechanism This can be used as a handshake mechanism between slow and fast devices or between masters in a multimaster session When a slow slave slow in terms of internal execution is attached to the bus then problems may occur Let s consider a serial EEPROM The actual writing process inside the EEPROM might take some time Now if you send multiple bytes to such a device the risk exists that you send new data to it before it has completed the write cycle This would corrupt the data or cause data loss The slave must have some means to tell the master that it is busy It could of course simply not respond to the acknowledge cycle This would cause the master to send a stop condition and retry That39s how it is done in hardware in EEPROMs Other cases might not be so simple Think about an N D converter It might take some time for the conversion to complete If the master would just go on it would be reading the result of the previous conversion instead of the newly acquired data Now the synchronization mechanism can come in handy This mechanism works on the SCL line only The slave that wants the master to wait simply pulls the SCL low as long as needed This is like adding quotwait statesquot to the 12C bus cycle The master is then not able to produce the ACK clock pulse because it cannot get the SCL line to go high Of course the master software must check this condition and act appropriately In this case the master simply waits until it can get the SCL line to go HIGH and then just goes on with whatever it was doing There are a number of minor drawbacks involved when implementing this If the SCL gets stuck due to an electrical failure of a circuit the master can go into deadlock Of course this can be handled by timeout counters Plus if the bus gets stuck like this the communication is not working anyway Another drawback is speed The bus is locked at that moment If you have rather long delays long conversion time in our example above then this penalizes the total bus speed a lot Other masters cannot use the bus at that time either This technique does not interfere with the previously introduced arbitration mechanism because the low SCL line will lead to backoff situations in other devices which possibly would want to quotclaimquot the bus So there is no real drawback to this technique except the loss of speed bandwidth and some software overhead in the masters You can use this mechanism between masters in a multimaster environment This can prevent other master from taking over the bus In a twomaster system this is not useful But as soon as you have three or more masters this is very handy A third master cannot interrupt a transfer between master 1 and 2 in this way For some missioncritical situations this can be a very nice feature You can make this technique rigid by not pulling only the SCL line low but also the SDA line Then any master other than the two masters talking to each other will immediately back off Before you continue you first let SDA go back high and then SCL representing a stop condition Any master which attempted to communicate in the meantime would have detected a backoff situation and would be waiting for a STOP to appear PC and the Rabbit Semiconductor R3000 Although the R3000 processor does not directly support the IZC protocol Dynamic C provides extensive support using a technique commonly referred to as bit banging Bit banging is the process of using conventional IO ports to generate the signals necessary for communications The data exchanges with the character LCD discussed earlier in this chapter is such an example As such any port pins can be used for IZC communications provided that the both SCL and SDA pins can be individually programmed for and input and output By default SCL is defined to be Port D bit 6 and the SDA line as Port D bit 7 Other Port D pins can be used by appropriately modifying the define IZCSCLBit 6 and define IZCSDABit 7 statements in libi2ci2clib The SCL line is programmed for an output only when the clock level is to be asserting a dominant state When the clock is asserting a recessive state the SCL line is made an input and depends on an external resistor to pull the SCL line to the high state This allows the master to sense that a slave or another master has pulled the line to the dominate state while the master is outputting a recessive SCL state This is required for clock synchronization that is described above The state of the SDA pin on the master is manipulated in the same manner The SDA line must be monitored by the master to determine the SDA line state for receiving an acknowledge signal from a slave or to detect bus con icts in multimaster con gurations The i2clib le in the Dynamic C library folder contains the application interface programs API3 for the 12C communications The API de nitions are de ned in Table 12 The directory for the Dynamic C 12C library functions also contains a device library that provides for interfaces for speci c 12C devices The devices library libi2ci2c7deviceslib contains drives for EEPROM PCF8575 and PCF8574 IO expanders the MAX1669 temperature and fan controller digital to analog converter MAX 5 17 518 5 19 analog to digital converter LTC 2619 This library has been extensively modified from the versions supplied with the orginal Dynamic C software to directly support devices found on the ECE 341 project board Table 12 12C API de nitions i2c7init Sets up the SCL and SDA port pins for opendrain output and initializes delay constant i2c7start7tx Implements a start S sequence by rst by setting the SCL to the recessive state and waits for possible clock stretching Data goes low while clock is high i2c7startw7tx Same as above with a delay inserted immediately after the negative transition ofthe SDA line i2c7send7ack Sends ACK sequence to slave ACK is usually sent after a successful transfer and where more bytes are to be read i2c7send7nak Sends NAK sequence to slave The NAK is usually sent when transfer from slave to master is completed i2c7read7char Reads 8 bits from slave allowing for clocks stretching on all SCL going high Thus allowing the 12C slaves to implement slower transfer rates i2c7check7ack Checks if slave pulls data low for ACK on clock pulse and allows for clocks 39 39 on SCL going high i2c7write7char Sends 8 bits to slave and checks if slave pulls data low for ACK on clock pulse Allows for clocks stretching on SCL going high i2c7stop7tx Sends a stop P sequence to the slave setting the SDA line high asserting recessive while the SCL line is recessive i2c7wr7wait Retries character write until slave responds The maximum number of attempted retries is limited by de ning i2cRetries If i2cRetries is unde ned the default number is 1000 Communications with slave devices As Figure 34 shows there are four 12C devices on the ECE 341 project board a 24LC256 serial EEPROM two PCF8574 IO expansion ICs and a DS 1628 realtime clock and thermometer We have already used the PCF8574 IO expansion IC to expand the external interrupt capability of the R3000 processor Each of the PCF8574 ICs have unique device addresses since there are two of these devices on the same I2C bus The PCF8574 datasheet 3 APT A set of routines that an application uses to request and carry out lowerlevel services performed by a computer39s operating system de nes the slave address bits as shown in Table 13 The root address is 0x70 and is offset by the inary value represented two times by the address lines A0 through A2 Table 13 PCF8574 slave address de nitions BYTE I B 7 MSE 6 5 4 3 2 1 0LSE 20 slave address L H H H A2 Al A0 PW No data bus I P7 P6 PS P4 l P3 l P2 P l PD Figure 34 shows that the A0 pin is connected to VCC and Al and A2 are connectedto ground for IC12 thus the offset that must be added to the base address 0x70 is 20x01 or 0x02 Hence the address for IC12 is 0x72 Table 13 also shows that the least signi cant bit ofthe slave address must be set high if the master is going to read data from the slave For IC13 both A0 and A1 are connectedto VCC resulting in 0x70 20x03 or a slave address of0x76 QUE or 12c BUS E as no scream anH 52L Sm Figure 34 Schematic diagram nfECE 341 prniect hoard I c devices 2 proeessor we wru look at the use ofthe 12c APIs thatrs used for the PCF857410 expander 1c There are only two drrvers needed for an rhterfaee forthrs devr aread dnver and awrrte dhver Before any 12c eorhrhuhreauohs ear take place the rdrzwrtoquot Aplmustbe eaned A Y t k ehahges srhee the 12c rrutrahzatror The PCFSSMJOXJZd shown m has the devree address and aporhterto the address that wu T expander 1c value xfthe devree ready deteeted no errors otherwrse a 710x f0xs retumed The proeess 2 2 APIS H DY r2estartwtxquot 2 that can be read from the PCF8574 To read additional bytes of data one would need to put the line ofcode if i2cireadichar ampx return 71 39 Get byte into a loop for the number of data bytes needed Additionally the master needs to send an ACK acknowledge to the slave for each byte read except for the last data byte For the last data byte the master send a no acknowledge or NAK sequence to the slave As discussed above in this chapter a NAK is sent by the master when it does not assert the SDA line dominate during the acknowledge bit time Finally the master send an 12C stop P sequence to terminate the communications Listing 3 Read driver for the PCF8574 IC nodebug int PCF8574710X7RdChar address define IZCRdBit 1 char x ifi207startw7tx return 1 7 bit address already shifted 1 bit ifiZCiwriteicharaddress l IZCRdBit return 1 ifi207readicharampx return 1 Get byte of data iZCisendinak Tell slave to stop sending data iZCistopitx return int x amp OXFF Listing 4 shows the write driver for the PCF8574 IO expander As with the read sequence the 12C begins by sending a start S command This is followed by writing the device address to the slave with the RW bit set low This command is then followed by sending the data byte When writing more than one byte of data to the slave the iZciwri39 tei char is called as many times as required If at any time if an error is detected by the iZciwri39 tei char API the function should send a stop P command and return a l to inform the calling function that there was an error in writing the data Listing 4 Write driver for the PCF8574 IC nodebug int PCF8574710X7WrChar address int data ifi207startw7tx return 1 7 bit address already shifted 1 bit ifiZCiwriteicharaddress return 1 ifi207writeicharunsigned Char data return 1 Send byte iZCistopitx return 0 Serial IO Read Chapter 10 MampM Serial Communications 2 Flavors Synchronous Asynchronous Synchronous Communications Requires clock signal Data bits may be nonuniformly spaced Can operate at faster data rates than asynchronous serial IO Clock signal synchronizes data transfers 1082004 ECE 340 Fall 2004 Lecture 23 Serial IO Asynchronous Communications No clock is required Additional overhead in message to manage synchronization Data bits must be uniformly spaced Data rates 110B 115KB Common use PC serial ports Point to point communications 1082004 ECE 340 Fall 2004 Lecture 23 Asynchronous Communications RS232 Standard Reference WEB site Voltage levels are NOT TTL Voltage 1L 25 r Space Space Logic 39039 3v1 Transition Region a Time 339r Logic 391 39 lt Mam 25v 1082004 ECE 340 Fall 2004 Lecture 23 Asynchronous Communications De nition BAUD The inverse of the period of a unit symbol Protocol 8 Information Bits a Date F39san 11TntalE39rts I Slnforrnation Bits J SDDDDDDDDPT 3955 I I I 39 MEE39 Channel E1 Fniern39l 8H 1 4 T T Ba4d Rate 03 For 95m Baud T m4 1082004 ECE 340 Fall 2004 Lecture 23 Asynchronous Communications m Baud Rate T 11211 Eit 11D 903m 3 Data Bit 3013 333 ms 1 Parity Bit 133i 833 MS 1 Stop Bit 2400 41 HS 4830 2013 u T 9600 104 us I 192013 52 us 391 I l 1 J c Dl D1 D2 33 D I D5 DIS D F39 2 Lsa 7 a 5 A use 39 39339 SFAITT 2 3 3K 2 grng In I Time Baud Rateztcui number of bits per second 1 M and E B ITS 1 B Start Bit Branth Pgrliiggmlt Triggers Local Data Bit mrxy of Oscillator njepbed Tmmmissicr Bit Rate number of im ormation bits per second Shop Bit Alum quotITI39IE Channel Ef CIency39 Brt Rate Baud Rene For Ember in the abutE case EH 1 I333 11 nehitialize 1082004 ECE 340 Fall 2004 Lecture 23 Figure 113 UART Block Diagram Transmitter Control Receiver Beside the registers the three main components of the UART are the BAUD rate generator the receiver control and the transmitter control The BAUD rate generator divides down the system clock to provide the bit clock BClk with a period equal to one bit time and also BClkX8 which has a frequency eight times the BClk frequency The TDRE transmit data register empty bit in the SCSR is set when TDR is empty When the microcontroller is ready to transmit data the following occurs 1 The microcontroller waits until TDRE 39139 and then loads a byte of data into TDR and clears TDRE 2 The UART transfers data from TDR to TSR and sets TDRE 3 The UART outputs a start bit 39039 for one bit time and then shifts TSR right to transmit the eight data bits followed by a stop bit 39139 The operation of the UART receiver is as follows 1 When the UART detects a start bit it reads in the remaining bits serially and shifts them into the RSR 2 When all the data bits and the stop bit have been received the RSR is loaded into the RDR and the Receive Data Register Full RDRF ag in the SCSR is set 3 The microcontroller checks the RDRF ag and if it is set the RDR is read and the ag is cleared The bit stream coming in on RxD is not synchronized with the local bit clock Bclk If we attempted to read RxD at the rising edge of Bclk we would have a problem if RxD changed near the clock edge We could have setup and hold time problems If the bit rate of the incoming signal differed from Bclk by a small amount we could end up reading some bits at the wrong time To avoid these problems we will sample RxD eight times during each bit time Some systems sample 16 times per bit We will sample on the rising edge of BclkX8 The arrows in Figire 116 indicate the rising edge of BclkX8 Ideally we should read the bit value at the middle of each bit time for maximum reliability When RxD rst goes to 0 we will wait for four BclkX8 periods and we should be near the middle of the start bit Then we will wait eight more BclkX8 periods which should take us near the middle of the rst data bit We continue reading once every eight BclkX8 clocks until we have read the stop bit Figure 116 Sampling RxD with BclkX8 start bit 1st data bit 2nd data bit mm l t F BclkX8iiiHHHHHHHHHHHHHHH H4 4 clocks 8 clocks 8 clocks Read data at these points p Asynchronous Communications Parity Options None Odd and Even None Parity bit is omitted Character terminated with a stop bit Even Logic level of the parity bit is set to make the total number of logic one states data plus parity bit evenly divisible by 2 Odd Logic level of the parity bit is set to make the total number of logic one states data plus parity bit not evenly divisible by 2 1082004 ECE 340 Fall 2004 Lecture 23 Ch upter 3 Input and Output Control and Detection Rev 1302008 The rst problem you will solve is one involving control of a machine You will learn how to manage two of the major processor resources CPU time and IO You will implement the process presented in Chapter 2 to systematically and methodically break the problem into tasks and solve each task individually before integrating into a fully functional system You will also learn how to manage preemptive computing to achieve more accurate timing and lower processor computational burden The First Design Challenge The rst device we will control is a stepper motor Stepper motors are commonly used in robotics for precision position control Some common applications of steppers motors are in printers copiers scanners and cameras Stepper motors do not move continuously like DC motors used in automobile electric windows or induction motors that are used in a clothes washer and dryer A stepper motor is chosen to provide an observable system in which to test the program functionality More importantly the stepper motor application represents a class of microprocessor applications involving open loop control Open loop control systems take one or more inputs and generate one operation or a xed sequence of operations The process can usually be stopped at any time without disrupting the operations of the program The stepper motor project that we will focus on uses two digital inputs that are provided by manually operated push buttons A timing input will be provided by time delay functions When these inputs are processed a sequence of outputs will be generated to make the stepper motor rotate at a speci c rate and in a speci c direction Stepper Motor Fundamentals 1 Stepper Motor Theory Stepper motors are electromechanical devices that have stable xed angular positions Motors are rated as a particular number of steps per revolution This number represents the number of full steps that is required for the motor to complete 360 degrees of rotation These full steps can be divided into half steps thus requiring two half steps to rotate that same angular displacement as a single full step Although no more circuitry is required to operate in half step mode than in full step mode additional power is required because half of the time two coils are required to be energized An exhaustive treatment of the theory of stepper motors is presented in a WEB based tutorial at httpwwwr Ilinwa quot 39 39 39 39 2 Problem Description Velocity Control of a Stepper Motor a Background Information Stepper motors can achieve precision speed control without feedback because each step always advances the angular position provided the application does not put excessive load of the motor shaft By repeatedly stepping through the phase states in the same sequence the shaft of the stepper motor will continue to rotate in the same direction The sequence that the stepper motor coils are energized to create motion is a consistent direction depending on the type of stepper motor used For your design you will use a bipolar stepper motor that is described in the reference cited above b Reading and Writing to Processor IIO Ports As stated previously there is both a hardware and software component to embedded systems Rabbit processor 10 pins are individually programmed as either inputs importing data or outputs exporting data The software directs the information using assembler programming language or a higher level language such as C code while the hardware converts the data to electrical voltages or currents using transistors The microprocessor DC characteristics are shown in Table I that has been copied from the R3000 users manual Although the processor operates on 33V power the inputs are 5 volt tolerant This allows the processor inputs to be connected directly to TTL and CMOS outputs The maximum DC current load to an external circuit of any 10 pin that has been programmed to function as an input is i10 uA For VDD equal to 33V the processors will see the input as a logic high if the voltage on the input pin is greater than 20V and as a logic low if the voltage is below 08V Table I O DC characteristics Table 56 33 Volt DC Characteristics i Symbol Parameter Test Conditions Min Typ Max Units VDD Supply Voltage 30 33 36 V absolute worst case all buffers VIH HighLevel Input Voltage i 20 V VIL LowLevel Input Voltage i i 08 V IOH 68 mA 07 X VOH H1ghLevel Output Voltage VDD VDD min VDD V IOL 68 mA VOL LowLevel Output Voltage VDD VDD min 04 V HighLevel Input Current VIN VDD HH absolute worst case all buffers VDD VDD max 10 A LowLevel Input Current VIN V55 11L absolute worst case all buffers i VDD VDD max 40 A HighImpedance State Output VIN VDD or V55 IOZ Current VDD VDD max no pull 10 10 11A P When the IO pin is programmed to function as an output when supplying 68 ma to the load the output voltage is guaranteed to be greater than 07 times the minimum supply voltage or 21V for a logic high output The output is guaranteed to be less than 04V when set for a logic low and sinking up to 68 ma Figure 1 shows that the outputs of two registers can be synchronized to insure all sixteen bits change simultaneously Most processors used today are based upon CMOS technology This results in very high input resistance but also comparatively high input capacitance The limited current drive capability of 10 pins requires nite time to charge the internal capacitance of the microprocessor pin as well as the capacitance of the external circuitry Load Data Load Clock Output Port TimerClodlt Figure 1 Output Registers for Ports D and E Higher load capacitance results in longer switching times and must be considered when switching loads at high switching rates The information concerning switching times are found in a table of IO pin AC characteristics and will be discussed in a later chapter External lrrpuf Fllierecl lnput Perlplreral Cloak Figure 2 Input port glitch filtering Output from the microprocessor must be compatible with the devices that are being driven Figure 3 and Figure 4 illustrate typical DC transfer characteristics for TTL and CMOS technology The microprocessor outputs operate between the levels shown in Table I When the pin is driving the maximum load of 68 ma the highlevel output voltage of 23lV is compatible with TTL logic devices However this is too low for CMOS devices CMOS devices typically have high impedance inputs and hence the processor outputs voltages that are approximately equal to Vdd A pullup resistor can also be added to the microprocessor output A pullup resistor connects the processor pin to VCC and is usually required for open drain outputs For the Rabbit Semiconductor processors this should be no greater than 525 V or damage will occur to the microprocessor Acceptable TTL gale Acceptable TTL gale Acpeplable CMOS gale Ameplable CMOS gale input signal levels aulpul signal levels Input signal levels nulpul signal levels 5 V 5 V 5 V High 495 v vmsv High H39Qh vm5v High 35 V Z 7 V 2 V 1 3 V 08 V 7 Low lt T a 0 V 005 v 39 W 0V Low W W Lowi 0V Figure 3 TTL 10 Characteristics Figure 4 CMOS IO Characteristics The Rabbit Semiconductor processors have both internal and external 10 ports External IO uses common data and address buses as well as common control signals External logic is required to use external 10 and their use is beyond the scope of this course Internal 10 uses dedicated pins on the microprocessor and will be exclusively discussed in this chapter Many of the microprocessor 10 pins can be used for different purposes For example Port C can be used as standard binary outputs standard binary inputs or serial communications transmit and receive data signals There are many internal registers that assign how processor 10 pins are to function Dynamic C uses functions speci cally designed for writing to and reading from 10 ports or registers Each time an 10 port is used one or more internal registers must be programmed to con gure the pin direction input or output and sometimes additional characteristics as well For most 10 ports each pin can be con gured to perform alternate functions that are associated with a special operations or features designed into the processor silicon Examples of alternate functions are serial IO PWM and external interrupts The alternate functions will be discussed later in this course Dynamic C uses the following construct for internal 10 write and read instructions 1 Port write instruction Syntax void WrPortIint Portx char Porthhadow int value Description The value of the constant or the variable is assigned to the output pins of Portx where Portx speci es the 10 address PortA through PortF are de ned in the BIOS library The same value is also written to a variable speci ed by the second variable in the argument list Although any previously declared variable can be used Shadow registers PortAShadow through PortFShadow are also declared as global variables in the BIOS library A NULL variable can be used in the event that the data written to the 10 port will never need to be retrieved Note the shadow register is passed by reference This does not mean that reading the port will return the same value that was written to the port If some of the port pins are programmed as inputs reading the port will re ect the input state of the pins assigned as input Also if the load on a given output exceeds the speci ed load current the output pin may read the incorrect value The shadow register always contains the last value written to the 10 port Example WrPortI PortE ampPortEShadow 0x56 WrPortT PortE ampPortEShadow PortEShadow l 0x20 2 Bit write instruction Syntax void BitWrPortIint ioiport char PORTShadow int value int bitcode Description This function updates shadow register at bit specified by the variable bitcode with value 0 or 1 and copies shadow to IO port WARNTNG a shadow register is REQUTRED for this function All of the Rabbit internal registers have predefined macros corresponding to the register s name For example PADR is defined to be 0x30 etc Example WrPortI PortE ampPortEShadow 1 5 This instruction has the same result as the second example above 3 Port read instruction Syntax int RdPortIint iOJaort Description This function reads an internal IO port specified by the argument All of the Rabbit Semiconductor microprocessor internal registers have predefined macros corresponding to the register s name For example PADR is defined to be 0x30 etc This action occurs whether the pin is assigned as an input or an output The logic is determined from the voltage at the TO pins using the rules defined in Table I The function returns an integer the lower 8 bits of which contain the result of reading the port specified by the first argument Example xRdPortI PortE 4 Bit read instruction Syntax int BithPortIint ioqaort int bitnumber Description The function returns 1 or 0 matching the value of the bit read from the speci ed internal IO port All of the Rabbit internal registers have prede ned macros corresponding to the register s name For example PADR is de ned to be 0x30 etc The returned value is an integer equal to 1 or 0 Example x BithPortI PortE 3 c Interface with Stepper Motor The stepper motors used in the ECE34l lab operate at 12V and require 500ma for each coil As discussed previously this exceeds the Rabbit Semiconductor processor IO capability hence a power switch is required to amplify the TO pin voltage and current The block diagram shown in Figure 5 illustrates the concept map for controlling a stepper motor using a microprocessor Port G bits zero through three are used to switch the current in the coils Notice from Figure 5 that no current flows through the coils if bits zero and one or two and three are at the same logic level Power Stepper Switch Motor PGO rdgtr3 PG1 PG2 PG3 Microprocessor Figure 5 Simpli ed block diagram of a microprocessor controlled stepper motor A detailed schematic of the ampli er circuit used to drive the stepper motor on the UI Lab project board is shown in Figure 6 The schematic shows that the L293 power switch 1C4 connects to the Rabbit RCM3000 microprocessor using 10 pins PGO through PG3 Referring to sheet 3 of the complete schematic for the UI Lab Project board UIuPLPB you will see that these lines connect to the Master Rabbit RCM 3000 processor Port G pins 0 through 3 The stepper motor connects to the UI Lab Project board at IP16 STEPPER MOTOR CONTROL Flgure 6 Detailed schematic ofmlcroprocessor interface to stepper motor d Transient protection umnicui protection Consider L 39 39 L 39 Figure 7 39 39 that steady state current I current is achieved When the switches open the current still wants to keep 39 39 cqum to L alld2 39 39 L 39 39 n L 39 39 n VDA and 57VDC and large transient voltages are eliminated L31 Figure 7 Dual switch R circuit Figure 8 Switched R circuit with my back diudes e Detecting External Inputs speed 5x313 more 1015 destgnedto operate as apusheon pusheotrtype of xpr op The buttons ground anomally htgh stgn mt t n n s LED as to sxgnals ealled extmt5quot and extmtquot These sxgnals wxll be dJSEuSSEd when mtenupts are addressed nput Power Stepper Buffer 87W n Motor 739 Q 6 m 3 3 5 o u E U o 1 o D b E E w a am as Stu ww H ms m B UTTZ 2 sNuhsJ I t 4 m4 at an l k l BluTTa 2 END LI 4 4 51 n7 5U39 WW H ms in Figm 1n Schematic diagram nhmachaniczlhuunn signalcnndivjnning r Full step mode Now that the details of the connection between the microprocessor the power switchampli er and the stepper motor are known the exact sequence of microprocessor outputs to energize the coils can be determined Referring to data sheets for stepper motors the coils must be energized in the sequence listed in Table II for full step CW rotation Energizing the coils progressing up the table will cause the stepper motor to rotate in CCW direction Notice that step 5 and 6 are identical to step 1 and 2 Repeating the 4 step sequence causes the motor to continue rotating in the same direction Stepper motors are rated by the number of steps required for the rotor shaft to make one revolution The stepper motors used in the this lab are rated at 100 steps per revolution Hence this fourstep sequence would need to be repeated 25 times for the motor shaft to make a complete revolution Table II Stepper coil energizing sequence for full step mode 9 Half step mode Half steps generate to positions of the stepper motor shaft between two full step positions The sequence to generate halfstepping is represented in Table 111 Close inspection of Table III reveals that the odd step positions are identical to positions in Table II For example Step 1 in Table III is the same as Step 1 of Table II and Step 3 in Table III is the same as Step 2 in Table II Halfstep position codes are placed between fullstep position codes Notice also that two coils are always energized in the halfstep position codes and only one coil is energized in the fullstep position codes Fullstepping is permitted by sequencing between halfstep codes without going through the intermediate fullstep code Table III Stepper coil energizing sequence for half step mode


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

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

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."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

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.