13
1 In this lecture, you will learn about what is inside the ESP32 chip and how to set up your laptop and the ESP32 module so that you can program the ESP32 in MicroPython.

In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

1

Inthislecture,youwilllearnaboutwhatisinsidetheESP32chipandhowtosetupyourlaptopandtheESP32modulesothatyoucanprogramtheESP32inMicroPython.

Page 2: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 3: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

TheCPUcoreandmemorycontainsa32-bitXtensaLX6microprocessor,whichisasiliconIP(intellectualproperty)coredesignedandownedbyTensilica,acompanyinCalifornia.ThisblockinsidetheESP32alsocontains:•  448kBoflashmemory(ROM)thatisnon-volatile(i.e.itscontentisstoredevenif

powerisremoved)•  520kBofSRAM(staticRAM)whichisusedtostoreallvariables,heapandstackThemicroprocessorisquitepower,capableofexecuting240millioninstructions(single-core)andrunningat240MHzclock.

3

Page 4: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 5: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 6: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

BeinganIoTspecificdevice,theESP32isoneofthechiponthemarkettohaveintegratedwiththemicroprocessorbothWiFiandBluetoothcommunications.Boththesecommunicationstandardsrequirebothdigitalandanaloguehardware(theradio).Again,wedonotwantyoutoworryabouttheseatthisstage.Neverthelessyouwillfindthatthissub-systemismostusefulformanystand-aloneproductsthatyoumaydesigninthefuture.WewillnotbeusingthissubsysteminElectronics1.

6

Page 7: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 8: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 9: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 10: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

BeforeyoucanusetheESP32forLab4,youneedtofirstsetupyourenvironmentforMicroPython.Thisinvolvesquiteanumberofsteps.Asaresult,IhavedividedLab4intoPartAandPartB.PartAdoesnotteachingyoumuchexceptthatyouwillgainsomeexperienceinsettingupasoftwareenvironmentthatisfairlycomplex,andlearnabouthowtoflashprogramsontotheESP32.TheIDEyouwillbeusingiscalledPyCharm.ThisissimilartoVSC,butitisdesignedpurposefullyforPythonprogramming.ThereasonIchosePyCharmisthatithasintegratedintothisthroughaMicroPythonplug-inthenecessarytoolstorunprogramsontheESP32andtoflashnewprogramscriptstoitsmemoryfromwithintheIDE.

10

Page 11: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

MicroPythonisquitealargesystemandtherearetoomuchtolearn.Itisalsogoodifyoulearntoreadinstructionsfromwebsites,ratherthanjustbeenspoonfedbyme.So,goto:https://docs.micropython.org/en/latest/

Youwillseethispage.Therearelotsofusefuldocumentshere.Explore!

11

Page 12: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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

Page 13: In this lecture, you will learn about what is inside the ... · You don’t need to know all these libraries. You should learn using this approach: 1. Learn from the example code

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.