17
Lab #4 : 1 ECE 2036 Lab #4 Build an mbed thermostat Check-Off Deadline: Section A – Thursday, March 10th Section B – Friday, March 11th 1. Real-Time Systems Many embedded devices are also real-time systems. A real-time system needs to read in data from external sensors, perform computations based on new sensor data, and update the control outputs within a fixed period of time. A Real-Time System reads in sensor data, processes the data, and updates control outputs Examples in cars include airbags, antilock brakes, and engine controls. Autopilots in airplanes and spacecraft are another example. In many of these systems, responding too slowly will cause system failure. Most real-time systems need a response time on the order of milliseconds or even microseconds. Frequently, the control system software found in an embedded device’s firmware requires a complex state machine coded in C or C++ that has additional timing constraints. Most processors have hardware timers or perhaps even a real-time clock that software can use to provide accurate time delays. Some systems may also require more complex control system calculations such as a proportional-integral- derivative controller or PID controller. 2. The Nest Thermostat Programmable home heating and cooling thermostats are also embedded devices. Thermostats could perhaps also be considered a real-time system, but with a response in range of minutes that is several orders of magnitude slower than most applications. The Nest thermostat seen on the next page was designed by an engineer that previously designed Apple’s iPods. It uses a color LCD similar to those in cellphones and a rotating ring for user input. Menus are used to change settings and display data. This device is now available at your neighborhood Lowes, Home Depot, the Apple Store, and Amazon. Nest Labs is one of Silicon Valley’s newest startup success stories. Google recently bought Nest for $3.2B. It is an interesting example of how even common household devices are currently being re-engineered using new technology. Honeywell now has a similar thermostat, but the Nest came out first.

ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:1

ECE2036Lab#4BuildanmbedthermostatCheck-OffDeadline: SectionA–Thursday,March10th

SectionB–Friday,March11th1.Real-TimeSystems

Many embedded devices are also real-time systems. A real-time system needs to read in data fromexternal sensors, perform computations based on new sensor data, and update the control outputswithinafixedperiodoftime.

AReal-TimeSystemreadsinsensordata,processesthedata,andupdatescontroloutputs

Examples in cars include airbags, antilock brakes, and engine controls. Autopilots in airplanes andspacecraft are another example. Inmany of these systems, responding too slowly will cause systemfailure. Most real-time systems need a response time on the order of milliseconds or evenmicroseconds.

Frequently, thecontrol systemsoftware found inanembeddeddevice’s firmware requiresa complexstatemachinecodedinCorC++thathasadditionaltimingconstraints.Mostprocessorshavehardwaretimersorperhapsevenareal-timeclockthatsoftwarecanusetoprovideaccuratetimedelays.Somesystemsmay also require more complex control system calculations such as a proportional-integral-derivativecontrollerorPIDcontroller.

2.TheNestThermostat

Programmablehomeheatingand cooling thermostats arealsoembeddeddevices. Thermostats couldperhapsalsobeconsideredareal-timesystem,butwitharesponseinrangeofminutesthatisseveralorders ofmagnitude slower thanmost applications. TheNest thermostat seen on the next pagewasdesignedbyanengineerthatpreviouslydesignedApple’s iPods. ItusesacolorLCDsimilartothose incellphonesandarotatingringforuserinput.Menusareusedtochangesettingsanddisplaydata.ThisdeviceisnowavailableatyourneighborhoodLowes,HomeDepot,theAppleStore,andAmazon.NestLabsisoneofSiliconValley’sneweststartupsuccessstories.GooglerecentlyboughtNestfor$3.2B.Itisaninterestingexampleofhowevencommonhouseholddevicesarecurrentlybeingre-engineeredusingnewtechnology.Honeywellnowhasasimilarthermostat,buttheNestcameoutfirst.

Page 2: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:2

TheNestIoTThermostat

As seen in the printed circuit board (PCB) image below, the nest contains an ARM Cortex A8 32-bitprocessor,temperature,light,motion,andhumiditysensorsandWiFi.Themotionsensorsenseswhenno one is home to save energy. A learning algorithm monitors your inputs to setup automaticscheduling.WiFicanbeusedforremotecontrolviathewebandforautomaticfirmwareupdates.Thereis even a smart smoke alarm that networks with Nest and other smoke alarms called Nest Protect.DeviceslikeNest,usingnetworkingformonitoringandcontrolarepartofthenew“InternetofThings”or “IoT”. Even IoT light bulbs and switches such as the WeMo are now available. Small kitchenappliancessuchascrockpotsandcoffeepotsarestartingtoappearwithIoTfeatures.

HardwarefoundinsidetheNest

Mosthomeheatingsystemsuse24VACrelaystoturnthefan,heater,andcoolingonandoff.Adrivercircuit (http://mbed.org/users/4180_1/notebook/relays1/) converts a digital logic output signal fromtheprocessortothehighervoltageandcurrentlevelsrequiredtotriggertherelays.

II.BuildingaThermostatUsingMbed

For thisassignment,wewilluse theARMprocessoron thembedmoduleanddevelopC/C++code tobuildabasic thermostat.The IoTnetworking featureswillnotbe includedto reducethescopeof theassignment, but the mbed can support them. Instead of hooking up a driver circuit for the heatingsystem’s24Vrelays,thecontroloutputswilljustbedisplayedusingthembed’sbuilt-inLEDs.Mbed’sI/O

Page 3: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:3

devicesallhavebeensetupwitheasytouseC++ApplicationProgrammingInterface(API)callsthataredescribedinthembedhandbook(http://mbed.org/handbook/Homepage).TheAPIcodeprovidedwithmbedusesC++classesandmethodstomakethemeasiertouse.ThesearesimilartoasimpledevicedriveranditisnotnecessarytounderstandthehardwaredetailsofeachI/OdevicetodevelopcomplexC/C++ applications using mbed. Follow the hyperlinks provided in this document for additionaldocumentationandC/C++codeexamples.

A TMP36 analog temperature sensor (http://mbed.org/users/4180_1/notebook/lm61-analog-temperature-sensor/) will be used to read the temperature. Using mbed’s built-in analog to digitalconvertorandaC/C++I/OApplicationProgrammingInterface(API)call,thevoltagefromthesensorwillbeconvertedfromanalogtoafloatingpointvaluereturnedinaC/C++variable.Thistemperaturevalueisthencheckedtodeterminewhentoturnonandofftheheatingandcoolingsystems.Twoofmbed’sbuiltinLEDswillbeusedtoindicatethevalueoftheoutputsignalsthatcontroltheheating(LED4)andcooling(LED3).ItwillnotbeattachedtoanactualHVACsystemorrequireadrivercircuittocontroltherelays.

Thermostatsandcontrolsystemsmustusehysteresistoavoidrapidlyswitchingonandoff.Mechanicalsystemstaketimetorespondandwearoutfasteriftheyareconstantlyturnedonandoff.Theyneedtorunforalongerperiodoftimetoavoidexcessivemechanicalwear.Theyarealsomoreenergyefficientwithlongerruntimes.Inthecaseofathermostatforaheater,withhysteresistheheaterwouldturnonat the temperature controlpoint, but thennot turnoffuntil the temperaturehas increaseda coupledegrees. Itwouldnot turnbackonuntil the temperaturedrops a coupledegrees. This requires stateinformation(i.e.heaterisonoroff)andthencheckingadifferenttemperaturethresholdwhenturningthe device on versus turning it off. The figure below shows a simple state transition diagram for athermostat set at 75o. The plus and minus 1 degree provide the hysteresis to give an averagetemperatureof75o.Itshouldstartinthestatewheretheheaterisoff.

Heater&on& Heater&off&

T&<=&74&

T&>=&76&

If&this&condi8on&is&not&met,&then&it&stays&at&the&heater&off&state!&&

If&this&condi8on&is&not&met,&then&it&stays&at&the&heater&on&state!&&

StateDiagramforaBasicThermostatsetto75

Page 4: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:4

1.ModelingaStateMachineinC/C++Nested control structures are required to implement a complex state machine in software. As anexample,asimplestatemachineisshownbelowinC/C++thatblinksanLED.Whentheprogramruns,LED1changesevery.33seconds.

include "mbed.h" DigitalOut myled(LED1); enum Statetype { LED_off = 0, LED_on }; int main() { Statetype state = LED_off; while(1) { switch (state)

{ case LED_off: // calculate the Moore-Type Outputs myled = 0; // calculate the next state state = LED_on; break; case LED_on: // calculate the Moore-Type Outputs myled = 1; // calculate the next state state = LED_off; break; } wait(0.33); } }

AsimplestatemachineinC/C++thatblinksanLED

“LED%On”%(myled%=%1)%

“LED%off”%(myled%=0)%

AsimplestatediagramforstatemachineinaboveCcodeAninfinitewhileloopcontainingaswitch()statementhelpsstructurethecode.Theswitch()statementselects one of several cases based on the current state. Each case (i.e., state) then checks theappropriateconditionstoassignthenextstate.Anenumeratedtypeisusedforstate.Youmustusethis

Page 5: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:5

overallstructureinyourcodeforthethermostat’sstatemachine.Itwillbemorestructured,readable,andeasiertounderstand.Forjusttwounconditionalstates,anif..elsestatementcouldbeused,butwithacasestatementaddingmorestatesandinputconditionswillbeeasierasthestatemachinegetsmorecomplex(anditwillinthislab).Adefaultcasecouldbeaddedtojumptotheinitialstatejustincaseiteverenteredanundefinedstate.Wait()actually slowsdownthestatemachineclock toaroundthreeclocksper second.Without thewait() the LEDwould change so fast itwouldonly lookabitdimmer.Notethat thissimplestatemachinedoesnotcheck inputs.Foramorecomplexstatemachinewithinputs, inside each case if..else statement(s) could be used to check inputs to determine the nextstate.Eachtransitionarrowleavingastatecorrespondstooneifstatement.2.ReadingtheTemperatureSensor An TMP36 wiki page is provided that shows how to connect the TMP36 sensor and read thetemperatureusingC/C++onthembedmodule.Becarefulitlooksjustlikethe2N3904transistorinthekit,socheckthetinymarksonthecase’s flatareaforthepartnumber.StartbywiringuptheTMP36sensortombedandgettingthedemocodeatthewikipagetoworkasshown.IfyoudidnotusetheTMP36 in theearliermbed lab,use thecompiler importcode link (i.e.,boxafter sourcecode)on theTMP36 wiki page to copy over the complete project demo files for the TMP36. This will verify yourhardwareconnectionsandsensoroperationbeforetryingyournewcode.

See the breadboard theory wiki, if you have not used a breadboard before and be very carefulwhenever inserting or removing the mbed module, as the pins can easily bend and break. If thathappens,youwillneedanewmbedmodule.Itisagoodideatoputthembedonyourbreadboardonceand leave it there.A largerversionoftheTMP36breadboardsetupphotograph isalsoavailableusingthe link under the image on the TMP36 wiki page. Device placement is often a critical first step inbuildingacircuitonabreadboardandalso indesigningaprintedcircuitboard(i.e.shorterwireswithless wires crossing). Typically placing devices with a large number of connections close togethersimplifieseverything.

Looking ahead at the hardware needed for this laboratory assignment and consulting the mbed pinlayout(coloredcardinkit),theLCDneedsaserialconnection.SincetheSDcard(mightbeusedinalaterlab)andtheolderkit’sShiftbriteRGBLEDneedanSPI(SerialPeripheralInterface)interface,itprobablymakessensetoputtheLCDontherightsideofthembedusingserialpinsontherightsideofthembedmodule.TheSDcardandShiftbritecouldthengoontheleftnearertheSPIpins.TheTMP36canuseanyAnalogInpin,PushbuttonscanuseanyGPIOpin,and thespeakerwillneedaPWMpinor theanalogoutputpin,butthesedevicesneedonlyonepinandarenotascritical.TheRGBLEDneedsthreePWMpins (lower right sideofmbed).Pinsarepassedasargumentswhen thepin I/O functionsare initiallysetup,soaslongasthepinsupportsthehardwarefunctionneededtheycanbemovedaroundwithaonelinechangeinyourC/C++code.DetailsonpinassignmentsuggestionscanbefoundintheSkeletoncode provided forusewith this assignment. Instructionsondownloading this codeareprovided laterneartheendofthisdocument.Checkthecardwithpinfunctionsfirstbeforemovingpins.Usingapinforanon-supportedhardwarefunctiondoesnotcauseacompileerror;itgeneratesaruntimeerrorwhichflashestheLEDsoncethecoderuns.Besuretosetupthebreadboardbuspowerstrips.Thereisonly one open pin onmbed for gnd and 3.3V (Vout) and power will be needed for several devices.

Page 6: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:6

DoublecheckpowerpinconnectionsbeforeinsertingtheUSBcableforpower,iftheyareincorrectthatistheeasiestwaytodestroyanIC.Ifthembed’ssingleLEDgoesout,thereisapowershort.

Thetemperaturesensoroutputsavoltagethat indicatesthecurrenttemperature.Ananalog-to-digitalconverterinsidetheprocessorconvertstheanalogvoltageinputtoa12-bitintegervalueatamaximumsamplerateof200Khz.ThembedC++APIAnalogINreadsa3.3Vmaxanaloginputandscalesittoafloatvaluebetween0and1.0(i.e.,a1.0wouldbe3.3Vand0wouldbe0V).DigitalOutcanbeusedtocontroltheLEDs.UseLED4toindicatethestateoftheheater(i.e.,LED4onmeanstheheaterison).

Thembed I/OAPIsuseC/C++classes toenableusers toworkatahigher levelofabstractionwithoutdealingwiththelow-levelhardwaredetails.TheAPIisbasicallyasetofusefulCfunctionsandclasses,just likeanyadditional functionsorclassesyoumaywriteyourself.Asexample,here iswhathappensautomaticallywhenyouusetheAnalogInAPIC++classtoreadananaloginputpin:

1. ThepinisconfiguredforanaloginputoninitialuseofAnalogInintheconstructor.MostI/Opinscanhaveoneofseveraldifferentfunctionsthatarecontrolledbypinconfigurationregisters.I/OregistersonRISCprocessors are inmemoryaddresses in a special range reserved just for I/Odevices.PinsareacriticalresourceonanIC,somostI/OpinsareconfigurableonnewICs.Apincancostasmuchas100Ktransistorsinsidethechip.

2. WhenevertheAnalogInvariable is read, theeight inputanalogmultiplexor isset toselect thecorrect analog channel to read the pin. This requires writing a value to another I/O controlregisteralongwithasmalldelayfortheanalogvoltagetostabilize.

3. The A/D convertor is then started by writing a start A/D conversion bit in the A/D controlregister.

4. The software then waits in a while loop for the A/D to report back that the conversion iscomplete.ThehardwaresetsabitinanA/Dstatusregisterwhenthishappens.TheA/Dcanonlyread200K samplesper second. This is a lot slower than instructionexecution times, so codeneedstowaitfortheA/Dconversioncompletebit.

5. The AnalogIn value is then read in from the A/D data register, scaled from 0.0 to 1.0, andreturnedasthefloatvalueoftheAnalogInvariable.

A lotofdevelopment time is savedbyusingAnalogIn, there is noneed to findandunderstandall ofthesehardwaredetailsinthe800pageLPC1768User’sManualtogettheI/Odevicetowork.ThisiswhyI/Odevicedriversaretypicallyusedinlargersystems.

Sincetemperaturechangesslowly,itisengineeringoverkilltocheckthetemperatureasfastaspossibleinatightwhileloop.Inanactualsystem,runningslowercansavepowerorprovideextraCPUtimeforother tasks. On mbed, a time delay can be added usingwait(). Check the temperature sensor andupdatestatesnomorethanthreetimesasecond.

With the temperature sensorconnectedand theprogramrunning,youcansimulate theeffectof theheaterturnedonbylightlypushingdownonthesensorwithyourfinger(beingcarefulnottoknockitloosefromtheprotoboard).Yourfingeristypicallyabitcoolerthanyourcorebodytemperatureanditdoesnotcovertheentiresensor,butyoushouldbeabletowarmthesensoruptothehigh80safterafew seconds. So you can test the thermostat by setting the control point a bit higher than roomtemperaturesothattheheatcomeson(LED3).Thenbywarmingitupacoupledegreeswithyourfinger

Page 7: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:7

youshouldseetheheatturnoffafteracoupleseconds.MonitorthetemperatureusingyourLCDdisplaythatyougotworking in theearlierprelabwhile this ishappening. It isalsopossible tocooldownthesensorusinganicecubeinasmallplasticbag(becarefulnottogetwateronthebreadboardorsensorleads).Sprayingthesensorwithanaerosolcanof“dust-off”cleanercanevenbeusedtocoolthesensorbelowfreezing.

3.SkeletonProjectCodetoGetStarted

Severalstepsareneedtoaddallofthelibrariesand*.hfilestoaprojectandtherequiredincludesinmain.cpp for all of the I/O devices thatwill be used. To save you time on the assignment, a sampleprojectwithallofthesealreadyaddedandthesimplestatemachinecodeexamplethat justblinksanLEDhasbeenprovidedforyouruse.Theskeletoncodeprojectsetupisavailableat:

http://mbed.org/users/4180_1/code/mythermostat/

Itisnotrequiredtousetheskeletoncode,butitwilllikelysaveyousometimefindingallofthe*.hfilesandaddingthemoneatatime.Tousetheskeletoncode,pluginyourmbed,logontombed.org,openanewtabinthebrowserwindowandgototheURLabove.OnthewebpagethatappearsclicktheImportthis program box (upper right). It will open a compiler window and import all of the files into yourprojectareaandsetupanewcopyoftheproject.

ItalsohassomesampleI/OcodejusttoshowthatthingsaresetupOKforallofthenewI/Odevices.Itshould compilewithout errors after import (awarning or two is OK), but if you run it youwill get aruntimeerroronSDfileI/O(i.e.,allfourmbedLEDswillflash)untilyoudeletetheSDcardI/OexamplecodeorattachtheSDcardbreakoutandinsertanSDcard.YouwillnotusetheSDcardforthislab,soyouwillnotneedthispartofthecodeforthis lab;however,youmayusethis infuturelabs. YouwillalsoseeanerrormessageonthePCifyouhaveaterminalapplicationprogramrunninghookeduptothevirtualcomport.Oncethatcodeisdeleted, ifyourecompileanddownloadthestatemachinewillblinktheLED.

Youwillstillneedtoreadthehandoutandwikipagestofigureouthowtohookupthehardwareandwhatneedstobedonetofinishtheprogramtofill inthemissingcode inmain.cpp.Thecodehaspinassignmentsforthedevicesbasedontheearlierbreadboardsuggestions,butfeelfreetochangethem.Forthosewitholderkits,Shiftbrite.hdoesnothavealloftheclasscodefilled in,youwillneedtoeditthatfileandadditforthefinalpartoftheproject.NewerkitswillneedtoaddcodefortheRGBLED.Ifyou see some handy code on wiki pages or in the compiler and want to cut and paste it into yourcompilersourcecode,highlightitwiththemouse,use“controlC”tocopy,movetothepastelocation,and use “control V” to paste. The format button in the compiler is also helpful to clean up nestedcontrolstructuresandautoindentthesourcecode.

Page 8: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:8

4.LaboratoryRequirements

BasicHeaterThermostat(40%)

Implement the basic heating thermostat as described in Section 2. This should have two states,HEAT_OFFandHEAT_ON.Havetheset-pointhardcodedto75.YourprogrammustimplementaMoorestatemachine. The state transitions are determinedby the temperature sensor and set-point values.The fixedoutput ineachstate is theoutputof LED3,whichsimulates theheaterbeingonoroff.Youmaychoosetoimplementonlythis“basicthermostat”foramaximumof75%onthelab,orimplementthe“improvedthermostat”foramaximumof100%.Thefirststepinimplementingthislabshouldbetogetyoursystemworkingwiththebasicthermostat,LCD,andpushbuttons.Thesecondstepshouldbetoadd the speaker and RGB LED to your system. The third and final step should be to implement the“improved thermostat”, which consists of modifying your state machine and adding a pushbuttoncallback.Note:YouwilllosepointsifyoudonotimplementaMoore-typestatemachineasdescribedin Section II, and build all of the additional state machine code (i.e., new ifs…) inside the casestatementwithanenumeratedstatetype.Yourmain()functionshouldconsistofaninfinitewhileloopthatcontainsoneswitchstatement,withonecaseforeachstate(2statesforbasicthermostat,5statesforimprovedthermostat).

AddLCDdisplay(5%)

In thepreviousmbed labassignment, you shouldhave successfully gottenyourdisplay towork.NowyouneedtousetheLCDtoprovideusefuloutputtotheuser,bydisplayingtemperatureandthermostatstatusinformation.Displaythecurrenttemperature(intwodigits)andcurrentmode.Youmustdisplayall temperature values in Fahrenheit. Later some user input mechanism to toggle between F and Cmodeswill be added (i.e., a fourth pushbutton). The LCDmust also display the thermostat’s currentstateandthecurrenttemperatureset-point,dependingonthecurrentmode.

The LCDmust be used to receive any credit for this lab. The 5% is to grade the quality of your LCDoutput. Since youonly have around16 characters of spaceon each LCD line toworkwith, youmustcarefullydesignyourLCDoutputtodisplayallnecessary information.YourLCDoutputshouldbeverysimilartothefollowinglayoutidea(itisbasedontheNestandHoneywellthermostats):

(HEAT_ON state) (HEAT_OFF state)

TheLCDcanbeupdatedusingthesamerateasthestatemachine(i.e.onetimeattheendofthewhileloop, justbeforewait() is called). ThereareuLCDmember functioncommands to change textheight,width,andcolor.Thecommandtochangethebackgroundcolorneedsaclearscreen(i.e.,cls)totakeeffect and characterswill need to be printed again to change text color. Don’t forget about the text

Setto

XXHeating

Inside

XX

Setto

XXHeat

Inside

XX

Page 9: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:9

backgroundcolorandmodesettings.Thetemperaturedisplaycharactersmustbeatleast2Xlargerthantheothercharacters(evenlargerif it looksOK)andbothcharactercolorsandbackgroundcolorsmustbe the sameas those shown.Characters shouldbe roughly centeredon thedisplay. Switching to theLCD’shighestbaudratewillproducefasterscreenupdates.

DonotplaceanyLCDcommands,waits,orprintfsininterruptcallbackroutines.ThiscouldlockuptheLCDsinceitmightbeinthemiddleofanLCDcommandinmainwhenthepushbuttoninterruptoccurs.

AddUserInput(10%)

Use twopushbuttons tochange the temperature set-point. Onepushbuttonshould increase theset-pointbyonedegreeeachtimeitispressed.Theotherpushbuttonshoulddecreasetheset-pointbyonedegree each time it is pressed. If you did not implement pushbuttons in Assignment 2, read thepushbuttonwikipageandwatchthevideosforadditionalhelpusingpushbuttonswithmbed.

YoushouldusethePinDetectclasstoimplementpushbuttons.Thepushbuttoncallbackoptionprobablymakesthemostsense for thisproblemandthe lastexampleonthepushbuttonwikipageshowstwocallbacksfortwopushbuttons.Theusageoftheglobalvariablecountissimilartothatoftheset-pointinyourprogram. Interruptandcallbackroutinesshouldbeshort, fast,andnotuseprintf()orwait().Themainprogramcanthenreadthisglobalset-pointvariable(thatis incrementedordecrementedbythecallbackroutine),andusetheLCDfunctionslocate()andprintf()todisplaythemodifiedset-pointontheLCD.Youcanre-printtheentire2ndlinebylocatingto(0,1)beforecallingprintf().Abetterapproachthattypicallyresultsinfasterscreenupdateswouldbetolocatetoaspecificcolumninline2anduseprintf()tore-printonlytheset-point,asshownbelow:

uLCD.locate(???, 1); // Move cursor to column ??? on line 2 uLCD.printf(“%2d”, heat_setpoint); // Print the heat setpoint

ImprovedThermostatwithbothHeatingandCooling(15%)

Buildathermostatthatcontrolseitherheatingorcooling,dependingonthemodesetbytheuser.Thisthermostat has five states: OFF, HEAT_OFF, HEAT_ON, COOL_OFF, and COOL_ON and two differenttemperaturethresholds(i.e.,heat_setpointandcool_setpoint).TheOFFstateisthedefaultstateuponreset,indicatingthatthethermostatispoweredoff.TheHEAT_OFFstateindicatesthatthethermostatispoweredon,butheatingisnotturnedonbecausetheroomtemperatureisabovetheheatset-point.TheCOOL_OFFstateindicatesthatthethermostatispoweredon,butcoolingisnotturnedonbecausetheroomtemperatureisbelowthecoolset-point.

Addathirdpushbuttontobeusedasthe“modebutton”.Uponreset,themodeissettoOFF.PressingthemodebuttononceshouldchangethemodetoHEAT.PressingthemodebuttonagainshouldchangethemodetoCOOL.PressingthemodebuttonagainshouldchangethemodebacktoOFF.Thus,youwillathirdglobalvariable(i.e.,mode)whosevalueischangedbytheuserviaapushbuttoninterrupt.The

Page 10: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:10

modevariableshouldbeanintegerwiththreepossiblevalues:0(OFF),1(HEAT),or2(COOL).(Agoodprogrammer might make a “Modetype” enumeration for mode values similar to the “Statetype”enumeration for state values.) A concise way to have an integer variable (mode) cycle through thevalues0,1,and2isasfollows:

mode = (mode + 1) % 3; // Cycle forward by 1

Thismethodofcyclingthrougha listofvalues isveryuseful inmanyprogrammingsituations. If therewerefourmodestocyclethrough(0through3),youwouldsimplyusemodulo4insteadofmodulo3.

The first two pushbuttons should now control heat_setpoint if the mode is OFF or HEAT, and thecool_setpointifthemodeisCOOL.Onesolutionforhandlingthiswouldbetomakeanintegerpointernamedtemperature_setpoint,whichwouldpointateitherheat_setpointorcool_setpointdependingonthemode.Youcouldthenhavethepushbuttonscontrolandthe(dereferenced)temperature_setpoint.Thedisplayshouldshowthepropersetpointdependingonmode,also.

Thus,youwillhavethreeglobalvariables(heat_setpoint,cool_setpoint,andmode)whichactascontrolvariables for your system.The temperature sensorprovidesa fourthcontrol variable thatdeterminesthebehaviorofyourstatemachine.Yourprogram implementsaMoorestatemachine, inwhicheachstate has a fixed set of outputs (the LEDs in this lab). In each state, you look at one ormore of thecontrolvariablestodeterminethestatetransition.Forexample,intheOFFstate,thevalueofthemodevariable determines the transition (if mode == HEAT, go to HEAT_OFF, if mode == COOL, go toCOOL_OFF,ifmode==OFF,remaininOFF).TheHEAT_OFFstatecantransitionbacktoOFF(dependingonmode) or it can transition toHEAT_ON (depending on the temperature sensor and heat_setpointvalues). The HEAT_ON state can either stay put or transition to HEAT_OFF (depending on thetemperaturesensorandheat_setpointvalues).ThelogicforCOOL_OFFandCOOL_ONissimilartothelogicforHEAT_OFFandHEAT_ON.

Todeterminetheoutputs ineachstate,use the followingrules.LED3shouldbeonoroff tosimulateheatingbeingonoroff. LED4shouldbeonoroff to simulatecoolingbeingonoroff. LED1andLED2shouldindicatethecurrentmodeofthesystem.LED1offandLED2offindicatesthatthethermostatispoweredoff.LED1onandLED2offindicatesthatthethermostatisinheatmode.LED1offandLED2onindicatesthatthethermostatisincoolmode.

TheLCDoutputdisplayideasforeachofthreeadditionalstatesareshownbelow:

(COOL_ON state) (COOL_OFF state) (OFF state)

Setto

XXCooling

Inside

XX

Setto

XXCool

Inside

XX

Setto

XXOff

Inside

XX

Page 11: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:11

AddClockandTimeDependenceofTemperatureSetpoint(10%)

Most programmable thermostats allow the user to set a different temperature setpoint for differenttimesofday.Inordertoimplementthis,youneedtousetheMBEDchiptodeterminethetimeofday.ThereareanumberofCandC++functionsthatallowyoutosetanddisplaythetime.Unfortunately,theMBEDchipdoesn’tkeeptrackoftimewhenitispowereddown.Normallyyoumightuseanetworkconnectiontoqueryaserverforthecurrenttime,butwearen’timplementinganetworkconnectioninthislab,soyouwillneedtosetthetimeatthebeginningofeveryprogramyourun.TheMBEDchipusesUnixtime,whichtracksthenumberofsecondselapsedsinceJanuary1,1970.Weusethisnumberastheinputtoafunctioncalltosetthetime.Forexample:

set_time(1356729737); // Set RTC time to Wed, 28 Oct 2009 11:35:37

After the time is set initially, the MBED chip will keep track of the elapsed time as the programprogresses.Youcanaccesstheelapsedtimeusingthetime function:

time_t seconds = time(NULL);

ThefunctioncallreturnsthenumberofsecondselapsedsinceJanuary1,1970,andstoresthatnumberinavariablenamedsecondsoftypetime_t.Obviouslyitwouldbehelpfultoconvertthatnumberintoamoreusefulform,whichyoucanaccomplishusingotherfunctions.Forexample:

uLCD.printf("The time is %s \n\r", ctime(&seconds));

Thissendsareferencetovariableseconds tofunctionctime,whichreturnsastringcontainingthedateandtimeinstandardform,whichisthenprintedtotheLCDscreenintheabovecode.Itmightalsobeusefultospecificallyaccessthehour,whichyoucandoasfollows:

tm * now = localtime( &seconds);

Thiscodecreatesapointercallednowwhichpointsatadatastruct(tm)whichholdsthedate,hour,second,etc.asintegerdatamembers.Toprintthehourin24-hourformattotheLCDscreen,youcouldwrite

uLCD.printf("The hour is %I \n\r", now->tm_hour);

YoucaneasilyGooglemoreinformationonallofthesefunctionsanddatastructures.

Forthepurposeofthisproject,youmustdisplaythecurrenttimeonyourLCDinareadableway.Youmustalsoimplementaseparateheatsetpointandcoolsetpointfornighttime,whichwewilldefineasthe hours between 11 PM and 6 AM (23:00 – 6:00). You will need to create new global variablesheat_setpoint_nightandcool_setpoint_nighttostorethesesetpoints.Bydefault,heat_setpoint_nightshouldbe5degrees lessthanthedefaultheat_setpoint,andcool_setpoint_nightshouldbe5degreeswarmer than the default cool_setpoint, but you must allow the user to manually set the nighttimesetpointsbyusingthesetpointcontrolpushbuttonsatnight.Inordertodemonstratethisfunctionality,please set your initial time to be aminute or two shy of 23:00, so that the grader can observe the

Page 12: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:12

setpointautomaticallychangingat23:00.AddasmalliconortextontheLCDscreentoindicatewhenthethermostatisinnighttimemode.

AddSpeaker,forPushbuttonandStateFeedback(10%)

For user feedback, use the driver transistor and speaker tomake a very fast click soundwhenever apushbuttonispressedtoincrementordecrementtheset-point.Alsomakeashortbeepwhenthemodeischanged,heatingturnsonoroff,orcoolingturnsonoroff.ThePWMspeakerPlayNote()functionisprobably the best choice for this program. You should have used this in the earlier prelab. Threedifferentbeeptonesshouldbeplayedtodistinguishbetweenmodechanges,heatturningonoroff,andcoolingturningonoroff.

Ingeneral,interruptroutines(i.e.callbackfunctions)needtobefast,soitwouldnotbeagoodideatocallPlayNote()withinaninterruptroutineifyouwereplayingalongnote.Oneoptiontoavoidthisistohaveaglobalflagvariablethatissetintheinterruptroutine(totriggeranaction)andthenservicedinthemainloop(performtheactionandcleartheflag).Forthislab,itisacceptabletoplaythefastclicksoundsfromwithinthepushbuttoncallbacks(anextracreditoptionusingatimerinterrupttoturnoffthesoundcanfixthislater).Thelongerbeeptonesmustbeplayedinthemainloop.AgoodlocationforthesePlayNote() calls is the sameconditional statements thatyouuse todetermine state transitions.Seethespeakerwikipageforadditionalhardwareandsoftwarehelpusingspeakerswithmbed.

AddRGBLEDStateDisplay(10%)

TherealNestalsousesapassiveinfrared(PIR)motionsensortoautomaticallyturnofftheLCDwhennoone is around. Many devices also have an ambient light sensor to dim displays in dark rooms. Thisprevents annoying light pollution in rooms at night, saves some power, and prolongs the life of thedisplay.Insuchdevices,asingleRGBLEDcouldbeusedshowstatuswhenthedisplayisoff.Wedon’thavetheselightandmotionsensorsinthekit(savesabouttendollars),buttheRGBLEDinthekitcanbeaddedforthispurpose.

UseanRGBLED (left imageabove innewkits)or theshiftbrite (right image fromolderkits) toaddacolor display of the current state like the display ( i.e., heating-orange, cooling-blue, not heating orcooling-black,off-green).Forthisportion,anewC++classmustbedevelopedforasingleRGBLEDorshiftbriteandplaced ina separate*.h file.The shiftbrite should function similar to theexistingmbedAPIs,itwillcalltheSPIclass(andDigitalOut)butextenditforashiftbrite.SeetheRGBLEDorshiftbrite

Page 13: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:13

wikipageforadditionalhelpusingRGBLEDsandshiftbriteswithmbedandthembed“makingitaclass”example.Readingthecodeintheclassesdevelopedinthespeakerwikipageexampleswillalsoprovidesomemoredetails.TheRGBLEDhasaclasssetuponthewikipagebutitisnotina*.hfileyet.

ForthoseusingoldkitswithShiftbritesinthemainprogram,itwouldworksomethinglikethisafteran#include“Shiftbrite.h”:

// declare a new Shiftbrite connected to these pins using a class Shiftbrite myShiftbrite(penable, platch, pred, pgreen, pblue); … // call the class member function to set the LED color myShiftbrite.write(red, green, blue);

Afterstudyingthelinkswiththeexampleclasscodedescribedearlier,hereisanadditionalhintforthenewShiftbriteclass.Youwillneedaconstructorandamemberfunction(write)towriteanewcolortotheShiftbrite.TheSPIAPIhasthreerequiredpinarguments(oneisnotusedbutstillneeded)andtheotherexamplesonlyhaveone.Sohereisalineshowinghowthreewouldworkintheclassconstructor:Shiftbrite::Shiftbrite(PinName pin_e, PinName pin_l, PinName pin_do,

PinName pin_di, PinName pin_clk): _pin_e(pin_e), _pin_l(pin_l), _spi(pin_do, pin_di, pin_clk)

{ //setup SPI options and initialize digital outs

} Withthesealsointheclassdefinition:

private: //class sets up the 4 pins DigitalOut _pin_e; DigitalOut _pin_l; SPI _spi; }; IfyouarehookinguptheShiftbrite,thepinsontheleftside(seeletteringonPCB)mustbeused.ThepinsontherightsidegothroughalogicbuffersothatyoucanconnectlongchainsofShiftbrites.Noticethat if it is everplugged into thebreadboardupsidedown, thepowerpinsget reversed, and if thesupplydoesnotshutdownfromhighcurrentthechipburnsout!

TheRGBLEDandtheSpeakerdrawabitmorecurrentfromthepowersupplythantheotherdevices.Apowersurgecancauseamomentaryvoltagedroponthesupplyandthismightcausealowtemperaturereading the instant that they turn on at a state change. If this is a problem, the TA has some 10ufcapacitorsthatcanbeconnectedacrossthesensor’spowersupplypins(rightatthesensorpins).Thelongerleadontheelectrolyticcapacitorgoestothe+supplypin.Asmalltimedelay(<1sec?)mightalsohelp after turning themon, if the problempersists. Also the temperature reading could be averagedwith several of the last readings tominimize this issue. Another optionmight be to just throwout a

Page 14: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:14

temperaturereadingthatchangestoofastfromtheaverageandtakeanotherreading.SomembedsandPCsaremoreprone to this issueandwhen thembedprocessorchip is left setup indebugmode (foreasy use in our labs on theUSB cable) it has a bitmore internal analog noise according to the datamanuals. If itwasnot indebugmode(switchingtheanalogthingsonandoff fast insidethechip)andwasrunningoffofbatteriesorandexternalpowersupplyasitwouldbeinafinalproduct,theanalognoiseproblemgoesaway.

LCDArtisticMerit,ImprovingPlaynote,andLanguageSupport(ExtraCreditupto8%)

ExampleNest-LikeStudentLCDDisplay

TheLCDsupportsbackgroundandfontcolors,graphics(i.e.,circles,lines…),anddifferentfontsizes.Sofar, it has been used as just a color text LCD. Implement a graphical displaymore like the realNest.Photosandvideoscanbefoundatwww.nest.com.TheLCDwikipagedemocodeshowstheadditionalmemberfunctionsavailableforthis.Forfullcredit,thefollowingmustbeincluded:

1. (+1%)Somenicegraphicsinthedisplay(perhapsacircleandlinesliketherealnest?)2. (+1%) All information displayed somehow (using text, graphics, or colors) aswas seen in the

originaltext-baseddisplays.3. (+1%)Overallqualityofartisticdesignutilizingalloftheitemsabove.AtdiscretionofTAs.4. (+1%)UseatimeoutinterruptroutinetoimprovethePlaynotefunctionsothatitdoesnotwait

inthepushbuttoncallbackormainroutineforthenotetoend.ThePlaysongclasscodeontheusingaspeakerwikipageshowsanexampleofhowthisideaworks.Playnotewouldreturnafterstarting the sound and use the timer interrupt to turn off the note later (after the note’sdurationtimercountsdownandgeneratesanotherinterrupttoturnitoff).

5. (+1%)Use a jumperwire tied to a digital input pin to select a different language for the LCDdisplay.Theotherendofthewirejumperismovedfrom“gnd”to“Vu”toswitchlanguagesatpowerup.Pickalanguagethatissupportedbythedefaultcharacterset.Thejumperwirewouldbe working like a switch to select the language. In a final product, a switch or anotherpushbuttoncouldbeusedtoselectthelanguage(butatthispointwehavealreadyusedalloftheminthekit).

6. (+1%)Supporta languagenotcoveredbytheLCD’sbuilt incharacterset. It ispossibleto loadnewcharacterfontsinthedisplayfromtheSDcardonthebackoftheLCD,butittakesquiteabit of extra work and a special tool to convert the font files for the SD card. The process isdescribedintheLCDwikipage.Trythisextracreditoptionlastandonlyifyouhavetime!

Page 15: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:15

7. (+10%)ForaTAcheckoffoftheentirelabthreedays(includinganyextracredit)beforetheduedate.

Page 16: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:16

ECE2036Lab4Check-OffSheet

StudentName:_________________________________________________

Professor:_____________________________________________________

Demonstration TASignoff

BasicThermostat(Heatonly)(40%)

AddLCDdatadisplay(5%)

AddPushbuttons(10%)

ImprovedThermostat(Heat+Cool)(15%)

AddClock&TimeDependence(10%)

AddSpeaker(10%)

AddRGBLED(10%)

Extracredit:LCD,Language,etc.(upto6%)

Earlycheckoff(10%)

LatePenalty(-20%perday)

LabSubmissionInstructions:Each labmust be demonstrated to the TAby the duedate. Students should be finishedwith the labbeforethestartofTAofficehoursontheduedate,sothattheymaygetthelabchecked-offontheduedate. There canbe long lineson theduedate!This canallbeavoidedbygetting the lab checkedoffbeforethelastday.StudentscannotexpecttogetTAhelponlabduedates,astheirtimewilllikelybededicated just to lab check-offs. Only one formal check-off attempt is allowed per student, and theentire labmust be checked-off at once. If the lab gets too busy, the TAsmay setup a list ofwaitingstudentsonthelab’swhiteboard.Therewillbea20%perweekdaylatepenaltyondemos.

IntherareeventthatTAsareunableto finishallcheckoffs forstudentswaiting inthe labontheduedatewhen the TA lab hours end, add your name to the TA’s list of students in the labwaiting for acheckoff.ThensubmitthesourcecodeonT-Square(ifthisdoesnotwork,emailthesourcecodeinanattachmenttoaTA).YoumustthenreturntodemousingthepreviouslysubmittedsourcecodeduringoneofthenextthreeTAofficehourdays.Note:ONLYsubmitcodeviat-squareifyouareunabletoget

Page 17: ECE 2036 Lab 4griley.ece.gatech.edu › riley › ece2036 › handouts › Lab4.pdfrun for a longer period of time to avoid excessive mechanical wear. They are also more energy efficient

Lab#4:17

checked-offbytheduedateandtimeasdescribedabove!!!Ifyouarecheckedoffbeforethedeadline,youaredone.Justkeepthissheetforyourrecords(incasethegradeispostedincorrectly).