Σχόλια 0

Το κείμενο του εγγράφου

UC Berkeley,EECS Department B.E.BoserEECS 40/42/100 Lab LAB6:Microcontroller Input/Output UID:Enter the names and SIDs for you and your lab partner into the boxes below.Name 1 SID1Name 2 SID2Be sure to come very well prepared to this laboratory to complete in three hours (or ﬁnish the following week).Type in your code ahead of time (store on the server or a USB key).MicrocontrollersMicrocontrollers are very much slimmed down computers.No disks,no virtual memory,no operating system.Think of them just like other circuit components with the added beneﬁt of being conﬁgurable with a program.Because of this microcontrollers can be coaxed to do all sorts of things simply that otherwise would require a largenumber of parts.Simple microcontrollers cost less than a dollar and hence can be used in almost any project.Indeed they can be found in toys,electric tooth brushes,appliances,cars,phones,electronic keys,you name it.Being programmable also means that they must be programmed.In this lab we concentrate on the electricalinterface of microcontrollers and their use as electronic components.The programs we use are very simple andconsist to a large part of pasting snippets of code together.In fact,much like checking the application notes ofelectronic components for circuits that do what we need,it’s always a good idea to search the web for code thatperforms the job we need or is at least a good starting point.Most of the code snippets shown in these lab guidesare copies of code fromthe manufacturer’s website.Feel free to improve on the example programs.Microcontrollers are available from many manufacturers,all with their own advantages (and quirks).In thiscourse we use the MSP430 from Texas Instruments whose strength are low power dissipation and a regular in-struction set.Figure 1 shows the architecture of the MSP430 (speciﬁcally the model MSP430F2012).The CPU block is thepart that actually performs computations (e.g.additions).Note that microcontrollers usually lack hardware formultiplication or division.These operations can be emulated in software,albeit at the price of low executionspeed.The clock systemsets the operating speed (16MHz maximumfor the controller we are using,compare thisto 2GHz or so for present day laptops).A555-timer like clock is built right into the chip;alternatively an externaloscillator can be used if higher precision is required.Flash is a nonvolatile memory for storing programs and conﬁguration data.RAMis where temporary variablesgo.Note again the contrast to full blown computers:microcontroller memory is typically a few kBytes ﬂash anda few hundred Bytes RAM.Most laptops today have at least a GByte RAM,a million kBytes.You don’t needthis in an electrical tooth brush.JTAG and Spy-Bi Wire are nifty interfaces for programming and debugging (themicrocontroller has no keyboard or LCD display).We will use this interface to talk to the controller though USBFigure 1 Block diagram of the MSP430 micro-controller.In addition to the processing unit (CPU),clock,and programming interface (Spy-Bi Wire),the chip includes program (Flash) and data (RAM)memory,digital inputs and outputs (Ports P1 andP2),Timers,and an analog-to-digital converter(ADC).1March 16,2010 LAB6 v514 http://ucbfeedback.com1Figure 2 M430F2012 pin diagram.The MSP430 comes in many versions thatinclude different amounts of Flash and RAM memory and combinations of in-put/output ports and other peripherals.Here we use a very small version withonly 14 pin that costs less than a dollar in quantity.froma desktop computer and programthe Flash memory.The Spy-Bi Wire interface is used only for development,once completed the controller works standalone fromthe programstored in the nonvolatile Flash memory.The really interesting parts are the peripherals.Ports P1 and P2 are digital I/Os that can be conﬁgured asinputs or outputs.They can be used for simple I/O with switches or LEDs;in later labs we will see much moresophisticated uses of this simple interface.The other block we will use is the ADC10,a 10-bit analog-to-digitalconverter that serves as a bridge between the usually analog “real” world and the microcontroller.For examplewe can use it to interface the strain gage circuit designed in an earlier lab to the microcontroller and make a fullblown (simple) balance with display out of the combination!Figure 2 shows the pinout of the particular MSP430 we are using in this laboratory,the MSP430F2012.It hasonly 14 pins for power (VCC) and ground (GND),the debug interface (TDIO and TCK) and ports P1 and P2.Looking carefully you will observe that there are eight pins for P1 but only two for P2.The other ones don’t ﬁtwith a 14 pin package.There also are no separate pins for the ADC.Instead,digital IOpins can be reprogrammedas ADC inputs as needed.Several dozen MSP430 microcontrollers are available with their main difference beingthe number of pins and the amount of memory.This permits you to start with a small version,and as the projectgrows move to versions with additional memory or pins without having to change the programs developed forthe smaller parts.Figure 3 Picture of the micro-controller prototyping board usedin this laboratory.In addition tothe MSP430,the board features 8LEDs and resistors with jumpersthat can optionally be connectedto IO port P1.The printed circuitboard (PCB) traces labeled “touchsensor”,together with the adjacentresistor and a simple program al-low the processor to react to ﬁngertouch input.With only 14 pins we certainly could wire up the microcontroller on a protoboard.The customboard shown inFigure 3 makes wiring even simpler.It also features LEDs for debugging and a touch interface.In addition to the microcontroller,the board features a header for interfacing with a ribbon cable to the USBinterface which is also supplying power to the board.Three capacitors and a resistor are used for ﬁltering powerand resetting the device after power is applied.These devices are speciﬁed by datasheet of the device.A headerstrip on the left side of the board exposes P1 and P2 and power for prototyping.Alternatively P1 also can be connected to on-board LEDs through jumpers.This of course makes sense only forpins that are conﬁgured as digital outputs.Removing a jumper (or setting it on a single pin as shown for P1.3 fornot losing it) makes that port available for other functions such as digital input or the ADC.The rightmost position(VCC) is for monitoring the power supply and always on when power is supplied to the board and the jumper isinserted.Jumper the upper two terminals of J3 as shown to enable power fromthe USB interface.2March 16,2010 LAB6 v514 http://ucbfeedback.comFlashing LightIn this laboratory we will familiarize ourselves with the μController board and the MSP430 development tool.Wewill start with writing the notorious “Hello World” example,which for a μController is a blinking light.a) Connect the μController PCB to the MSP430 USB-Debug-Interface (MSP-FET430UIF).Use a standard USB ca-ble to connect the debug interface to a computer with the “IAR Embedded Workbench IDE” software.Thissoftware is installed on the computers in the laboratory.Alternatively you can download it fromthe TI websiteand install on your own computer.b) Start the IAR Embedded Workbench IDE.Choose “Create new project in current workspace”.A dialog withoptions appears.We will write our programin the C language.Expand that choice,click on “main” and thenclick “OK”.The programasks you to name your project.Call it “blink”.Hit enter.c) Your screen looks as shown below,with a programalready partially written.1d) Before ﬁnishing our programwe needto conﬁgure the tool for the MSP430F2012.Choose the menu“Project→Options...” and click on the “General Options” tab.Set “Device” as shown in the screen belowby clicking on the but-ton to the right of the ﬁeld and navigating the choices.1The newest version of the software no longer generates this code and the ﬁle  no longer exists.Please enter the missing statementsyourself and replace  by .You need to do this in all your programs.3March 16,2010 LAB6 v514 http://ucbfeedback.comFigure 4 Circuit diagram for connecting an LED to aμController outputport.The resistor is needed since LEDs behave like diodes with very largecurrent ﬂowing for voltages above a threshold (around 1V).The microcon-troller output changes between 0V and the supply voltage (around 3V) forlogic low and high,respectively.Without the resistor a large current ﬂows.This can result in either theμController port or the LED to burn out.e) Still in the options dialog,verify under the “Debugger” tab that driver is set to “FET Debugger”.Also makesure that under the “FET Debugger” tab “Connection” is set to “TI USB–IF”.Click ok.Put a jumper into position 0 of J5 to connect the microcontroller port P1.0 to the leftmost LED.Figure 4 showsthe circuit diagramfor the on-board LEDs.Place a jumper also in the VCC position of J5 to verify that power is supplied to the board when you startdebugging.Nowwe write the programthat turns P1.0 on and off.a) First we to conﬁgure P1.0 as a digital output using the following instructions (see online manual for moreinformation):The ﬁrst statement sets the output to zero.It is not strictly needed here since we do not care if the LED is onor off when the microcontroller starts.However it is a good idea to always ﬁrst set an output to a known statebefore enabling it,to avoid potentially disastrous failures.The next two statements conﬁgure P1.0 as digital IO with direction set to output.As you would expect,thesame statements with BIT1 substituted for BIT0 enable P1.1 as output.Put these statements just after the code that disables the watchdog timer (don’t worry about that timer;justmake sure the code is there to turn it off).4March 16,2010 LAB6 v514 http://ucbfeedback.comb) The following statements set the output lowor high,or toggle its state:               Text after  is treated as comment and there only for documentation.If you have ever taken a programmingcourse you knowthat we are supposed to document our code but fewof us actually do it.Join the few.c) The toggle version of the above statements is appropriate for blinking a light.Since we want to do this repeat-edly we enclose the statement in a loop:                  d) The complete programlooks as follows:e) Compile it by clicking on the right most buttonin the toolbar.Carefully examine possible error messages(or ignore themand waste lots of time in frustration).Anewwindowpops up:Click thebutton (2nd row in the toolbars).When done you can stop the program by clickingormodify the code and clickto recompile and restart with.f) If everything went right the light turns on but does not blink.At best it is a little dimmer than the power LED.The reason is that the microcontroller turns the LEDon and off a fewmillion times per second,too fast for oureyes to follow.5March 16,2010 LAB6 v514 http://ucbfeedback.comg) The simplest ﬁx is to give the microcontroller a bit of extra work to slow it down.Microcontrollers are notstudents and hence do not mind.Since we will often have need for such delays,we package this function in asubroutine that we can easily reuse in other programs.Here is the code:        calling this code with the following statementcauses the microprocessor to spin 30’000 times in a loop decrementing the variable n.h) Let’s try this in our program:i) You can change the rate of the blinking by varying the argument to delay.Beware:the maximum permittedvalue is a little over 65’000 (you’ll get a warning if you exceed the maximumwhich you are free to ignore if youneed a fewhours of frustration with stuff that does not work).For longer delays you can e.g.use several delaystatements.Can you get the LEDto blink at a rate of 1Hz?If you paid attention the answer to this question is trivial.Assuming P1.0 has been conﬁgured as an output;what is the code to set it to VCC?Omit extra blanks fromyour answer.1 pt.0Analog OutputSo far we have used the μController to turn an LED on or off.Frequently an “analog” output is required,i.e.avoltage can assume any value between the supplies.Some μController contain special peripherals called digital-to-analog converters (DACs) for this purpose.The model we are using lacks this feature.However,we can emulatean analog output with a digital output by rapidly switching its value between the supply voltage and ground andadjusting the relative times the output is high and low.For example,if the output is high (VCC=3V) during 3clock cycles and then low(0V) during 2 cycles,the average value of the output is 3/5VCC=1.8 V.Likewise,if theoutput stays high for cycles and lowfor,the average output voltage is1 pt.1Write a subroutine function  that sets the output high during n cycles and lowduring 256-n cycles.Hereis a start:        6March 16,2010 LAB6 v514 http://ucbfeedback.com2177    Call this function fromyour main programin an endless loop.Write your completed code into the box below:1 pt.4Test your “DAC” in the laboratory.First verify with the oscillosope that for n=0 the output remains low(whyis there a “glitch” and how could you eliminate it?),and for n=256 the output remains high (except for a briefglitch).Then connect a ﬁrst order RC ﬁlter with R=10 kΩ and C=10 nF to the μController output and recordthe voltage voacross the resistor on the oscilloscope.Adjust n such that vo=V and ask the GSI to verify yourresult.One drawback of this DAC is that it keeps the μController busy and unavailable to do other tasks.A bettersolution uses the μController’s timer combined with a feature called interrupt to implement the delay.With thistechnique,the  function can run concurrently with other functions.We will not explore this feature here;pleasecheck the manual and sample programs (see vendor website) for more information.Bar GraphNowwe will programa function void bar(int n) that turns on LEDs 0...n-1.E.g.the call bar(3) turns on LEDs 0,1,and 2.Here is a start:                               Write your completed code into the box below:1 pt.6At the start of main,declare a variable i as follows and conﬁgure all bits of P1 as outputs (leave the code for thewatchdog timer alone) and write code that spins through the bar graph:              7March 16,2010 LAB6 v514 http://ucbfeedback.com1.3Figure 5 Circuit for digital push-button input.Make sure all LEDjumpers 0...7 are inserted and test the program(optional).Digital InputNowwill modify our code fromthe last section such that the bar graph advances one position each time a buttonis pressed.We will use P1.7 for the button input.Remove the jumper for LED7.Figure 5 shows the circuit for connecting a button to the microcontroller.Normally P1.7 is pulled to VCC(high) by the pull-up resistor Rup.Pressing the button pulls P1.7 low.The circuit is even simpler than this sincethe microcontroller has a built-in Rup,we just need to enable it.So all you need to do is connect a button betweenP1.7 and ground.Here is the code for enabling P1.0...6 as outputs and P1.7 as an input with the pull-up resistorenabled:The following statement checks for P1.7 to go low:Put this into the inﬁnite loop to control the bar graph display.Start your program and verify ﬁrst with the voltmeter that P1.7 is normally high and turns low when thebutton is pressed.When trying the programyou will notice that things do not work as expected:when pressingthe button the bar graph does not advance a single position as it should but a randomnumber of positions.Thishas two reasons:a) Just like human eyes,human hands are pretty slow on a microcontroller timescale.Once the microcontrollerhas found that P1.7 is lowand advanced the bar graph,it returns to the top of the loop,and checks again.If itﬁnds the button still pressed,it advances the bar graph again.b) Most mechanical switches and buttons have a ﬂaw called prelling:rather than just turning on and off,thebutton turns on and off rapidly in succession until it reaches the ﬁnal value.The reason is mechanical resonancein the switch.8March 16,2010 LAB6 v514 http://ucbfeedback.comThe ﬁrst problemcan be avoided by inserting a statement that checks that the button has gone back high intothe loop:           Depending on where exactly you insert the statement the bar graph advances immediately when the button ispushed or only when the button is released.The solution for the secondproblemis inserting a delay into the loop.Fortunately we wrote that delay function!Code for bar graph with button:3 pts.7Assuming P1.5 has been conﬁgured as an output;what is the code to set it to GND?opt.2Build the circuit and verify the operation (optional).Analog InputMicrocontrollers (and computers in general,for that matter) operate with digital data.However,many “real worldsignals” such as temperature are analog in nature.An analog-to-digital converter is needed to input such signalsinto a microcontroller.Analog-to-digital converters,or ADCs for short,are available as standalone electroniccomponents or built into more complex devices.Fortunately our microcontroller has an ADC built in.In this lab-oratory we will use this ADC to interface the weight scale designed in an earlier laboratory to the microcontrollerand have the bar graph display the number of weights put on the scale.ADCs compare an analog input vi,e.g.1.387V,to a reference voltage Vrefto produce a digital number repre-senting the ratio of the analog input to the reference rounded to the nearest integer.For example,the ADC in ourmicrocontroller converts analog voltages to digital numbers according to the following equation:N=round