Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
1
Inthislecture,youwilllearnaboutwhatisinsidetheESP32chipandhowtosetupyourlaptopandtheESP32modulesothatyoucanprogramtheESP32inMicroPython.
ThemicroprocessorchipontheESP32moduleisanEspressifESP32microcontrollerchipdesignedforInternetofThings(IoT)applications.Thischipiscalledamicrocontrollerbecauseithastheprocessoritself(CPUcore),on-chipmemory,andmanyotherbuilt-incomponentsthatallowsusertoalmostbuildanentirecomputersystemononechip(calledSystem-on-ChiporSoC).
Theentirechipcanbedividedintoanumberofsub-modules.Theyare:• CoreandMemory(brainofthechip)• CryptographicHardwareEngines(forencryption&decryption)• Wirelesscommunications(wifiandbluetooth)• Powermanagementsubsystem(forlowpowerIoTapplications)• Peripheralinterfaces(forconnectionwithotherdevices)
• Extraflashmemory(SPIRAM)ThedatasheetoftheESP32canbefoundhere:https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf
2
TheCPUcoreandmemorycontainsa32-bitXtensaLX6microprocessor,whichisasiliconIP(intellectualproperty)coredesignedandownedbyTensilica,acompanyinCalifornia.ThisblockinsidetheESP32alsocontains:• 448kBoflashmemory(ROM)thatisnon-volatile(i.e.itscontentisstoredevenif
powerisremoved)• 520kBofSRAM(staticRAM)whichisusedtostoreallvariables,heapandstackThemicroprocessorisquitepower,capableofexecuting240millioninstructions(single-core)andrunningat240MHzclock.
3
OnerequirementofanIoTdeviceisultralow-power.TheESP32containsanentirelow-powermanagementsubsystemthathandlesapplicationswherespeedisNOTthemostimportantfeature.Insteaditallowsthedevicetogotosleepandwakeuponlywhennecessarytodosomebasictaskssuchastakeareadingortwo,andsendthemwirelesslyviaWiFiorBluetoothtoabase-station.Furthermore,thismodulealsocontainsaReal-timeClock(RTC)thatallowsschedulingofevents,andwakeuptheUltraLow-powerco-processor(ULP)todoitsthing!Whenevertheprocessorgoestosleep,itstoresawaywhatitsdoing(calledits“state”or“context”)inablockofrecoverymemory,sothatwhenitwakesup,theULPcanberestoredtoitsoriginalstate.
WewillnotbeusingthissubsysteminElectronics1.
4
SincetheESP32isdesignedforIoTapplications,onerequirementforsuchapplicationsisprivacyandsecurity.Thereforeinformationsentorreceivedareoftenencrypted.Doingencryptionanddecryptionusingthemicroprocessorisnotonlywasteful(becauseitwon’tbeabletootherusefulthingswhileperformingencryption/decryption),itisalsoslowwhenperformingsuchtasksusingsoftware.Worse,itispowerhungry.ThereforetheESP32integratesthreedifferentencryption/decryptionengineson-chip,whichimplementthemostcommonencryption/decryptionalgorithms.Theseare:Rivest-Shamir-Adleman(RSA),SecureHashAlgorithm(SHA)andAdvancedEncryptionStandard(AES).Don’tworryexactwhattheseare–youwillhowevercomeacrosstheminmanyapplicationslaterduringyourdegreeprogram.Finally,thissubsystemalsocontainsahardwarerandomnumbergeneratorengineforanyapplicationsthatrequireshighqualityrandomnumbers.
5
BeinganIoTspecificdevice,theESP32isoneofthechiponthemarkettohaveintegratedwiththemicroprocessorbothWiFiandBluetoothcommunications.Boththesecommunicationstandardsrequirebothdigitalandanaloguehardware(theradio).Again,wedonotwantyoutoworryabouttheseatthisstage.Neverthelessyouwillfindthatthissub-systemismostusefulformanystand-aloneproductsthatyoumaydesigninthefuture.WewillnotbeusingthissubsysteminElectronics1.
6
Thefinalsubsystemtoconsiderislarge.ItcontainsmanyseparateIPblocksthatallowstheESP32tointerfacetotheoutsideworlddirectly.Includedhereare:• I2Cinterface–thisiswhatweusetodrivetheOLEDdisplayontheHeltec
module• SPIinterface–thisisafastinterfaceanditisusedtolinkwiththe4MBSPIRAM
(extractstorageforourprograms)
• I2Sinterface–Thisisadedicatedinterfaceforaudiosignals• UART–YoulearnedaboutthisbackinLab1andinDigitalBasicslecture• SDIO,CAN–bothareotherdigitalinterfacesforvariousapplications• IR–infra-redinterfaceasusedbyremotecontrol(e.g.onyourTV)• PWM–thisgeneratesPWMsignalsfordrivingmotorsandLEDlights• Sensorinterfaces–Temperatureandtouchsensorinterfaces
• EH–Ethernetinterface• DAC–8-bitdigitalconverter(usedforSIG_GENforanalogueoutputs)• ADC–AnaloguetoDigitalconverter
ThoseshowninBLUEabovearefeaturesthatyouhaveuseorwillbeusinginElectronics1.
7
TheESP32moduleyouuseisdesignedandmanufacturedbyHeltec.InadditiontotheESP32chip,themodulealsoincludea128x640.96”OLED.ItisconnectedtotheESP32usingtheI2Cinterface.(Wewilldiscussthisinterfaceduringthelectureon“Link”later.)HereisapinoutdiagramfortheHeltecmodule.YoucanfindahighqualityPDFfileofthispinoutdiagramon:https://resource.heltec.cn/download/WiFi_Kit_32/WIFI_Kit_32_pinoutDiagram_V2.pdfNotethat:
• Almostallpinsaremultipurpose.Usercanprogramthepinsfordifferentuse.Forexamplepin26canbeusedfor:digitalinput,digitaloutput,analogueinputandanalogueoutput.
• Thecolourcodeshowsatypeofusageforapin.Forexample,GREENisfordigitalinput(i.e.toA-Dconverter),PINKisforGeneralPurposeIO(GPIO),whichisdigitalinputoroutput,BROWNisforanalogueoutput(i.e.viaaD-Aconverter).
• ThreeofthepinsarealreadyconnectedtoOLEDdisplayonthemoduleusingtheI2Cinterface.
• Therearealsodedicatedpowerpins.
8
TheESP32willbeprogrammedusingMicroPython.Theslideprovidesanoverviewoftheprogrammingenvironmentthatyouwillbeusing.1. YoumustfirstloadtheMicroPythoncodeontotheESPinternalflashROM
(showninblackontheright).2. Lateryouwillloadintotheinternalflashmemoryyourownprogramcode
(showninblue).
3. TocontroltheESP32withuPy,youcantypedirectlyintotheREPL>>>apythoncode(suchas:println(“Helloworld!”),onelineatatime.
4. AlternativelyyoucancreateauPyscriptandloadthisintoESP32flashRAM.5. TocreatetheuPyscript,youwillusethePyCharmIDEonthelaptop.This
environmentalsoprovideaneditor,abilitynavigatetheprojectdirectory,communicatewithuPyREPLdirectlyviaaterminalwindow,andevenflashyourprogramcodeontotheESP32.AllthesecanbedonewithinthePyCharmIDE.
WhenyoufirstpoweruptheESP32,uPywillexecutetheboot.pyfile.Theboot.pyfilewillrunthemain.pyfile.Themain.pywillhaveonesingleuPyline:
execfile(‘user_program.py’)
Yourprogramwillbestoredintheuserprogramfile:‘user_program.py’).(Changethenameofthefiletosuit.)Alsostoredintheon-chipflashRAM(ROM)areothermodulesthatyourprogrammayuse.Forexample,youwillbeusingoled.py,whichisthedriverfortheOLEDdisplay.
9
BeforeyoucanusetheESP32forLab4,youneedtofirstsetupyourenvironmentforMicroPython.Thisinvolvesquiteanumberofsteps.Asaresult,IhavedividedLab4intoPartAandPartB.PartAdoesnotteachingyoumuchexceptthatyouwillgainsomeexperienceinsettingupasoftwareenvironmentthatisfairlycomplex,andlearnabouthowtoflashprogramsontotheESP32.TheIDEyouwillbeusingiscalledPyCharm.ThisissimilartoVSC,butitisdesignedpurposefullyforPythonprogramming.ThereasonIchosePyCharmisthatithasintegratedintothisthroughaMicroPythonplug-inthenecessarytoolstorunprogramsontheESP32andtoflashnewprogramscriptstoitsmemoryfromwithintheIDE.
10
MicroPythonisquitealargesystemandtherearetoomuchtolearn.Itisalsogoodifyoulearntoreadinstructionsfromwebsites,ratherthanjustbeenspoonfedbyme.So,goto:https://docs.micropython.org/en/latest/
Youwillseethispage.Therearelotsofusefuldocumentshere.Explore!
11
MicroPythonprovidesmanylibraryfunctionsinordertomakeprogrammingthisboardmucheasier.Therearebasicallytwomaincategoriesoflibraryfunctions:1. AsubsetofthestandardPythonlibraryyoucanfindeverywhere(but
implementedforMicroPython).Ofthese,thetwothatyouwouldneedare:mathandsys.
2. ThereisabunchoflibraryfunctionsthatarewrittenfortheESP32specifically.Thethreethatyouneedare:machine,espandesp32.Themachinelibraryprovidestoplevelcontroloftheboard,andesp&esp32providedetailcontrol.machineisthemostimportantlibraryforyoutoknow.Almostallfunctionsweusesofarareimportedfromthemachinelibrary.
3. Thereisanotherimportantmodule:time.Thisprovidesdelayinmillisecondormicroseconds(e.g.time.sleep_ms()).
4. Thenthereisalargecollectionofperipheralspecificlibraries(theyarewrittenasobject-orientedclasslibraries).Youwillbeusingmanyfunctionsfromthese.
12
13
Themachineclasslibrariesincludesthoseshownhere.InLab4,youusedthefollowinglibraryclasses:PWM,ADC,Pin(everything),Timer(thesearefunctionstocontrolinternaltimercircuits),I2CandUART.IhaveprovidedexamplesinLab4Bforyou.Youdon’tneedtoknowalltheselibraries.Youshouldlearnusingthisapproach:1. Learnfromtheexamplecodeprovided.
2. Ifthesedonotdowhatyouneed,beclearwhatfunctionyouneedtoperform.
3. Lookforafunctioninthelibrarythatislikelytogiveyouwhatyouneeded.
4. Failingthat,askmeoryourfriendsandclassmates,oryourteamprojectsupervisor.