Colophon,Raspberry

转换成 3
PiPicoPythonSDK Colophon Copyright©2020RaspberryPi(Trading)Ltd.ThedocumentationoftheRP2040microcontrollerislicensedunderaCreativeCommonsAttribution-NoDerivatives4.0International(CCBY-ND).build-date:2021-11-04build-version:150df05-clean AbouttheSDK Throughoutthetext"theSDK"referstoourRaspberryPiPicoSDK.MoredetailsabouttheSDKcanbefoundintheRaspberryPiPicoC/C++SDKbook.SourcecodeincludedinthedocumentationisCopyright©2020RaspberryPi(Trading)Ltd.andlicensedunderthe3-ClauseBSDlicense. LegalDisclaimerNotice TECHNICALANDRELIABILITYDATAFORRASPBERRYPIPRODUCTS(INCLUDINGDATASHEETS)ASMODIFIEDFROMTIMETOTIME(“RESOURCES”)AREPROVIDEDBYRASPBERRYPI(TRADING)LTD(“RPTL)"ASIS"ANDANYEXPRESSORIMPLIEDWARRANTIES,INCLUDING,BUTNOTLIMITEDTO,THEIMPLIEDWARRANTIESOFMERCHANTABILITYANDFITNESSFORAPARTICULARPURPOSEAREDISCLAIMED.TOTHEMAXIMUMEXTENTPERMITTEDBYAPPLICABLELAWINNOEVENTSHALLRPTLBELIABLEFORANYDIRECT,INDIRECT,INCIDENTAL,SPECIAL,EXEMPLARY,ORCONSEQUENTIALDAMAGES(INCLUDING,BUTNOTLIMITEDTO,PROCUREMENTOFSUBSTITUTEGOODSORSERVICES;LOSSOFUSE,DATA,ORPROFITS;ORBUSINESSINTERRUPTION)HOWEVERCAUSEDANDONANYTHEORYOFLIABILITY,WHETHERINCONTRACT,STRICTLIABILITY,ORTORT(INCLUDINGNEGLIGENCEOROTHERWISE)ARISINGINANYWAYOUTOFTHEUSEOFTHERESOURCES,EVENIFADVISEDOFTHEPOSSIBILITYOFSUCHDAMAGE.RPTLreservestherighttomakeanyenhancements,improvements,correctionsoranyothermodificationstotheRESOURCESoranyproductsdescribedinthematanytimeandwithoutfurthernotice.TheRESOURCESareintendedforskilleduserswithsuitablelevelsofdesignknowledge.UsersaresolelyresponsiblefortheirselectionanduseoftheRESOURCESandanyapplicationoftheproductsdescribedinthem.UseragreestoindemnifyandholdRPTLharmlessagainstallliabilities,costs,damagesorotherlossesarisingoutoftheiruseoftheRESOURCES.RPTLgrantsuserspermissiontousetheRESOURCESsolelyinconjunctionwiththeRaspberryPiproducts.AllotheruseoftheRESOURCESisprohibited.NolicenceisgrantedtoanyotherRPTLorotherthirdpartyintellectualpropertyright.HIGHRISKACTIVITIES.RaspberryPiproductsarenotdesigned,manufacturedorintendedforuseinhazardousenvironmentsrequiringfailsafeperformance,suchasintheoperationofnuclearfacilities,aircraftnavigationmunicationsystems,airtrafficcontrol,weaponssystemsorsafety-criticalapplications(includinglifesupportsystemsandothermedicaldevices),inwhichthefailureoftheproductscouldleaddirectlytodeath,personalinjuryorseverephysicalorenvironmentaldamage(“HighRiskActivities”).RPTLspecificallydisclaimsanyexpressorimpliedwarrantyoffitnessforHighRiskActivitiesandeptsnoliabilityforuseorinclusionsofRaspberryPiproductsinHighRiskActivities.RaspberryPiproductsareprovidedsubjecttoRPTL’sStandardTerms.RPTL’sprovisionoftheRESOURCESdoesnotexpandorotherwisemodifyRPTL’sStandardTermsincludingbutnotlimitedtothedisclaimersandwarrantiesexpressedinthem. LegalDisclaimerNotice
1 RaspberryPiPicoPythonSDK TableofContents Colophon..............................................................................................1LegalDisclaimerNotice...............................................................................1
1.TheMicroPythonEnvironment..........................................................................31.1.GettingMicroPythonforRP2040...................................................................31.2.InstallingMicroPythononRaspberryPiPico..........................................................41.3.BuildingMicroPythonFromSource.................................................................4
2.ConnectingtotheMicroPythonREPL....................................................................72.1.ConnectingfromaRaspberryPioverUSB............................................................72.2.ConnectingfromaRaspberryPiusingUART.........................................................82.3.ConnectingfromaMac..........................................................................102.4.Say"HelloWorld"................................................................................112.5.BlinkanLED....................................................................................112.6.Whatnext?
.....................................................................................11
3.TheRP2040Port....................................................................................123.1.BlinkinganLEDForever(Timer)...................................................................123.2.UART..........................................................................................133.3.ADC...........................................................................................133.4.Interrupts......................................................................................143.5.MulticoreSupport...............................................................................153.6.I2C............................................................................................153.7.SPI............................................................................................163.8.PWM..........................................................................................173.9.PIOSupport....................................................................................173.9.1.IRQ.......................................................................................193.9.2.WS2812LED(NeoPixel).....................................................................223.9.3.UARTTX..................................................................................233.9.4.SPI.......................................................................................233.9.5.PWM.....................................................................................253.9.6.Usingpioasm...............................................................................26
4.UsinganIntegratedDevelopmentEnvironment(IDE)......................................................274.1.UsingThonny...................................................................................274.1.1.BlinkingtheLEDfromThonny................................................................284.2.Usingrshell....................................................................................29 AppendixA:AppNotes.................................................................................31UsingaSSD1306-basedOLEDgraphicsdisplay.........................................................31Wiringinformation...............................................................................31ListofFiles.....................................................................................31BillofMaterials..................................................................................33UsingaSH1106-basedOLEDgraphicsdisplay...........................................................33Wiringinformation...............................................................................33ListofFiles.....................................................................................34BillofMaterials..................................................................................39UsingPIOtodriveasetofNeoPixelRing(WS2812LEDs).................................................39Wiringinformation...............................................................................39ListofFiles.....................................................................................40BillofMaterials..................................................................................41UsingUARTontheRaspberryPiPico..................................................................42Wiringinformation...............................................................................42ListofFiles.....................................................................................42BillofMaterials..................................................................................43 AppendixB:DocumentationReleaseHistory...............................................................44 TableofContents
2 RaspberryPiPicoPythonSDK Chapter1.TheMicroPythonEnvironment PythonisthefastestwaytogetstartedwithembeddedsoftwareonRaspberryPiPico.ThisbookisabouttheofficialMicroPythonportforRP2040-basedmicrocontrollerboards.MicroPythonisaPython3implementationformicrocontrollersandsmallembeddedsystems.BecauseMicroPythonishighlyefficient,andRP2040isdesignedwithadisproportionateamountofsystemmemoryandprocessingpowerforitsprice,MicroPythonisaserioustoolforembeddedsystemsdevelopment,whichdoespromiseonapproachability.Forexceptionallydemandingpiecesofsoftware,youcanfallbackontheSDK(coveredinGettingstartedwithRaspberryPiPicoandRaspberryPiPicoC/C++SDK),oranexternalCmoduleaddedtoyourMicroPythonfirmware,towringouttheverylastdropofperformance.Foreveryotherproject,MicroPythonhandlesalotofheavyliftingforyou,andletsyoufocusonwritingthecodethataddsvaluetoyourproject.TheeleratedfloatingpointlibrariesinRP2040’son-boardROMstorageareusedautomaticallybyyourPythoncode,soyoushouldfindarithmeticperformancequitesnappy.Moston-chiphardwareisexposedthroughthestandardmachinemodule,soexistingMicroPythonprojectscanbeportedwithouttoomuchtrouble.Thesecondprocessorcoreisexposedthroughthe_threadmodule.RP2040hassomeuniquehardwareyouwon’tfindonothermicrocontrollers,withtheprogrammableI/Osystem(PIO)beingtheprimeexampleofthis:aversatilehardwaresubsystemthatletsyoucreatenewI/Ointerfacesandrunthemathighspeed.Intherp2moduleyouwillfindprehensivePIOlibrarywhichletsyouwritenewPIOprogramsattheMicroPythonprompt,andinteractwiththeminrealtime,todevelopinterfacesforneworunusualpiecesofhardware(orindeedifyoujustfindyourselfwantinganextrafewserialports).MicroPythonimplementstheentirePython3.4syntax(includingexceptions,with,yieldfrom,etc.,andadditionallyasync/awaitkeywordsfromPython3.5).Thefollowingcoredatatypesareprovided:str(includingbasicUnicodesupport),bytes,bytearray,tuple,list,dict,set,frozenset,array.array,collections.namedtuple,classesandinstances.Builtinmodulesincludesys,time,andstruct,etc.NotethatonlyasubsetofPython3functionalityisimplementedforthedatatypesandmodules.MicroPythoncanexecutescriptsintextualsourceform(.pyfiles)orfrompiledbytecode,inbothcaseseitherfromanon-devicefilesystemor"frozen"intotheMicroPythonexecutable. 1.1.GettingMicroPythonforRP2040 Pre-builtBinary Apre-builtbinaryofthelatestMicroPythonfirmwareisavailablefromtheMicroPythonsectionofthedocumentation. ThefastestwaytogetMicroPythonistodownloadthepre-builtreleasebinaryfromtheDocumentationpages.Ifyoucan’tordon’twanttousethepre-builtrelease — forexample,ifyouwanttodevelopaCmoduleforMicroPython — youcanfollowtheinstructionsinSection1.3togetthesourcecodeforMicroPython,whichyoucanusetobuildyourownMicroPythonfirmwarebinary. 1.1.GettingMicroPythonforRP2040
3 RaspberryPiPicoPythonSDK 1.2.InstallingMicroPythononRaspberryPiPico RaspberryPiPicohasaBOOTSELmodeforprogrammingfirmwareovertheUSBport.HoldingtheBOOTSELbuttonwhenpoweringupyourboardwillputitintoaspecialmodewhereitappearsasaUSBMassStorageDevice.FirstmakesureyourRaspberryPiPicoisnotpluggedintoanysourceofpower:disconnectthemicroUSBcableifpluggedin,anddisconnectanyotherwiresthatmightbeprovidingpowertotheboard,e.g.throughtheVSYSorVBUSpin.NowholddowntheBOOTSELbutton,andpluginthemicroUSBcable(whichhopefullyhastheotherendpluggedintoputer).AdrivecalledRPI-RP2shouldpopup.GoaheadanddragtheMicroPythonfirmware.uf2fileontothisdrive.ThisprogramstheMicroPythonfirmwareontotheflashmemoryonyourRaspberryPiPico.ItshouldtakeafewsecondstoprogramtheUF2fileintotheflash.Theboardwillautomaticallyrebootwhenfinished,causingtheRPI-RP2drivetodisappear,andbootintoMicroPython.Bydefault,MicroPythondoesn’tdoanythingwhenitfirstboots.Itsitsandwaitsforyoutotypeinfurtherinstructions.Chapter2showshowyoucanconnectwiththeMicroPythonfirmwarenowrunningonyourboard.YoucanreadontoseehowacustomMicroPythonfirmwarefilecanbebuiltfromthesourcecode.TheGettingstartedwithRaspberryPiPicobookhasdetailedinstructionsongettingyourRaspberryPiPicointoBOOTSELmodeandloadingUF2files,incaseyouarehavingtrouble.ThereisalsoasectiongoingoverloadingELFfileswiththedebugger,incaseyourboarddoesn’thaveaneasywayofenteringBOOTSEL,oryouwouldliketodebugaMicroPythonCmoduleyouaredeveloping. NOTE IfyouarenotfollowingtheseinstructionsonaRaspberryPiPico,youmaynothaveaBOOTSELbutton.Ifthisisthecase,youshouldcheckifthereissomeotherwayofgroundingtheflashCSpin,suchasajumper,totellRP2040toentertheBOOTSELmodeonboot.Ifthereisnosuchmethod,youcanloadcodeusingtheSerialWireDebuginterface. 1.3.BuildingMicroPythonFromSource TheprebuiltbinarywhichcanbedownloadedfromtheMicroPythonsectionofthedocumentationshouldservemostusecases,butyoucanbuildyourownMicroPythonfirmwarefromsourceifyou’dliketocustomiseitslow-levelaspects. TIP IfyouhavealreadydownloadedandinstalledaprebuiltMicroPythonUF2file,youcanskipaheadtoChapter2tostartusingyourboard. IMPORTANT TheseinstructionsforgettingandbuildingMicroPythonassumeyouareusingRaspberryPiOSrunningonaRaspberryPi4,oranequivalentDebian-basedLinuxdistributionrunningonanotherplatform. It’sagoodideatocreateapicodirectorytokeepallpico-relatedcheckoutsin.Theseinstructionscreateapicodirectoryat/home/pi/pico. $cd~/$mkdirpico$cdpico 1.2.InstallingMicroPythononRaspberryPiPico
4 RaspberryPiPicoPythonSDK Thenclonethemicropythongitrepository.Theseinstructionswillfetchthelatestversionofthesourcecode. $gitclone-bmaster/micropython/micropython.git Oncethedownloadhasfinished,thesourcecodeforMicroPythonshouldbeinanewdirectorycalledmicropython.TheMicroPythonrepositoryalsocontainspointers(submodules)tospecificversionsoflibrariesitneedstorunonaparticularboard,liketheSDKinthecaseofRP2040.Weneedtoexplicitlyfetchthesetoo: $cdmicropython$gitsubmoduleupdate--init--lib/pico-sdklib/tinyusb NOTE ThefollowinginstructionsassumethatyouareusingaRaspberryPiPico.SomedetailsmaydifferifyouarebuildingfirmwareforadifferentRP2040-basedboard.Theboardvendorshoulddetailanyextrastepsneededtobuildfirmwareforthatparticularboard.Theversionwe’rebuildinghereisfairlygeneric,buttheremightbesomedifferenceslikeputtingthedefaultserialportondifferentpins,orincludingextramodulestodrivethatboard’shardware. TobuildtheRP2040MicroPythonport,you’llneedtoinstallsomeextratools.Tobuildprojectsyou’llneedCMake,across-platformtoolusedtobuildthesoftware,andtheGNUEmbeddedToolchainforArm,whichturnsMicroPython’sCsourcecodeintoabinaryprogramRP2040’sprocessorscanunderstand.build-essentialisabundleoftoolsyouneedtobuildcodenativetoyourownmachine — thisisneededforsomeinternaltoolsinMicroPythonandtheSDK.Youcaninstallalloftheseviaaptfrommandline.Anythingyoualreadyhaveinstalledwillbeignoredbyapt. $sudoaptupdate$sudoaptinstallcmake-arm-none-eabilibnewlib-arm-none-eabibuild-essential FirstweneedtobootstrapaspecialtoolforMicroPythonbuilds,thatshipswiththesourcecode: $make-Cmpy-cross WecannowbuildtheportweneedforRP2040,thatis,theversionofMicroPythonthathasspecificsupportforourchip. $cdports/rp2$make Ifeverythingwentwell,therewillbeanewdirectorycalledbuild(ports/rp2/buildrelativetothemicropythondirectory),whichcontainsthenewfirmwarebinaries.Themostimportantonesare: firmware.uf2 AUF2binaryfilewhichcandraggedontotheRPI-RP2drivethatpopsuponceyourRaspberryPiPicoisinBOOTSELmode.ThefirmwarebinaryyoucandownloadfromthedocumentationpageisaUF2file,becausethey’retheeasiesttoinstall. 1.3.BuildingMicroPythonFromSource
5 RaspberryPiPicoPythonSDK firmware.elf Adifferenttypeofbinaryfile,whichcanbeloadedbyadebugger(suchasgdbwithopenocd)overRP2040’sSWDdebugport.ThisisusefulfordebuggingeitheranativeCmoduleyou’veaddedtoMicroPython,ortheMicroPythoncoreinterpreteritself.Theactualbinarycontentsisthesameasfirmware.uf2. Youcantakealookinsideyournewfirmware.uf2usingpicotool,seetheAppendixBintheGettingstartedwithRaspberryPiPicobookfordetailsofhowtousepicotool,e.g. $picotoolinfo-abuild/firmware.uf2File/home/pi/pico/micropython/ports/rp2/build/firmware.uf2: ProgramInformation name: MicroPython version: v1.13-288-g3ce8f14e0 features: USBREPL threadsupport frozenmodules:_boot,rp2,ds18x20,onewire,uasyncio,uasyncio/core, uasyncio/event,uasyncio/funcs,uasyncio/lock,uasyncio/stream binarystart:0x10000000 binaryend: 0x10038be4 embeddeddrive:0x100a0000-0x10200000(1408K):MicroPython FixedPinInformationnone BuildInformationsdkversion:pico_board:builddate:buildattributes: 1.0.0picoJan212021MinSizeRel 1.3.BuildingMicroPythonFromSource
6 RaspberryPiPicoPythonSDK Chapter2.ConnectingtotheMicroPythonREPL WhenMicroPythonbootsforthefirsttime,itwillsitandwaitforyoutoconnectandtellitwhattodo.Youcanloada.pyfilefromputerontotheboard,butamoreimmediatewaytointeractwithitisthroughwhatiscalledthereadevaluate-printloop,orREPL(oftenpronouncedsimilarlyto"ripple"). Read MicroPythonwaitsforyoutotypeinsometext,followedbytheenterkey. EvaluateWhateveryoutypedisinterpretedasPythoncode,andrunsimmediately. Print Anyresultsofthelastlineyoutypedareprintedoutforyoutoread. Loop Gobacktothestart — promptyouforanotherlineofcode. TherearetwowaystoconnecttothisREPL,soyoumunicatewiththeMicroPythonfirmwareonyourboard:overUSB,andovertheUARTserialportonRaspberryPiPicoGPIOs. 2.1.ConnectingfromaRaspberryPioverUSB TheMicroPythonfirmwareisequippedwithavirtualUSBserialportwhichisessedthroughthemicroUSBconnectoronRaspberryPiPico.putershouldnoticethisserialportandlistitasacharacterdevice,mostlikely/dev/ttyACM0. TIP Youcanrunls/dev/tty*tolistyourserialports.Theremaybequiteafew,butMicroPython’sUSBserialwillstartwith/dev/ttyACM.Ifindoubt,unplugthemicroUSBconnectorandseewhichonedisappears.Ifyoudon’tseeanything,youcantryrebootingyourRaspberryPi. Youcaninstalltoesstheserialport: $sudoaptinstall andthenopenitassuch: $-o-D/dev/ttyACM0 Wherethe-D/dev/ttyACM0ispointingatMicroPython’sUSBserialport,andthe-oflagessentiallymeans"justdoit".There’snoneedtoworryaboutbaudrate,sincethisisavirtualserialport.Presstheenterkeyafewtimesintheterminalwhereyouopened.Youshouldseethis: >>> Thisisaprompt.MicroPythonwantsyoutotypesomethingin,andtellitwhattodo.IfyoupressCTRL-Donyourkeyboardwhilsttheterminalisfocused,youshouldseeamessagesimilartothis: 2.1.ConnectingfromaRaspberryPioverUSB
7 RaspberryPiPicoPythonSDK MPY:softrebootMicroPythonv1.13-422-g904433073on2021-01-19;RaspberryPiPicowithRP2040Type"help()"formoreinformation.>>> ThisbinationtellsMicroPythontoreboot.Youcandothisatanytime.Whenitreboots,MicroPythonwillprintoutamessagesayingexactlywhatfirmwareversionitisrunning,andwhenitwasbuilt.Yourversionnumberwillbedifferentfromtheoneshownhere. 2.2.ConnectingfromaRaspberryPiusingUART WARNING REPLoverUARTisdisabledbydefault. TheMicroPythonportforRP2040doesnotexposeREPLoveraUARTportbydefault.Howeverthisdefaultcanbechangedintheports/rp2/mpconfigport.hsourcefile.IfyouwanttousetheREPLoverUARTyou’regoingtohavetobuildMicroPythonyourself,seeSection1.3formoredetails.GoaheadanddownloadtheMicroPythonsourceandinports/rp2/mpconfigport.hchangeMICROPY_HW_ENABLE_UART_REPLto1toenableit. #defineMICROPY_HW_ENABLE_UART_REPL
(1)//usefulifthereisnoUSB ThencontinuetofollowtheinstructionsinSection1.3tobuildyourownMicroPythonUF2firmware. ThiswillallowtheREPLtobeessedoveraUARTport,throughtwoGPIOpins.ThedefaultsettingsforUARTsaretakenfromtheCSDK. Table1.DefaultUARTsettingsinMicroPython FunctionUART_BAUDRATE Default115,200 UART_BITS
8 UART_STOP
1 UART0_TX Pin0 UART0_RX Pin1 UART1_TX Pin4 UART1_RX Pin5 ThisalternativeinterfaceishandyifyouhavetroublewithUSB,ifyoudon’thaveanyfreeUSBports,orifyouareusingsomeotherRP2040-basedboardwhichdoesn’thaveanexposedUSBconnector. 2.2.ConnectingfromaRaspberryPiusingUART
8 RaspberryPiPicoPythonSDK NOTE ThisinitiallyupiestheUART0peripheralonRP2040.TheUART1peripheralisfreeforyoutouseinyourPythoncodeasasecondUART. Thenextthingyou’llneedtodoistoenableUARTserialontheRaspberryPi.Todoso,runraspi-config, $sudoraspi-config andgotoInterfacingOptions→Serialandselect"No"whenasked"Wouldyoulikealoginshelltobeessibleoverserial?
"and"Yes"whenasked"Wouldyouliketheserialporthardwaretobeenabled?
".YoushouldseesomethinglikeFigure1. Figure1.EnablingaserialUARTusingraspi-configontheRaspberryPi. Leavingraspi-configyoushouldchoose"Yes"andrebootyourRaspberryPitoenabletheserialport.YoushouldthenwiretheRaspberryPiandtheRaspberryPiPicotogetherwiththefollowingmapping: RaspberryPiGNDGPIO15(UART_RX0)GPIO14(UART_TX0) RaspberryPiPicoGNDGPIO0(UART0_TX)GPOI1(UART0_RX) IMPORTANT RXmatchestoTX,andTXmatchestoRX.Youmustn’tconnectthetwooppositeTXpinstogether,orthetwoRXpins.ThisisbecauseMicroPythonneedstolistenonthechannelthattheRaspberryPitransmitson,andviceversa. SeeFigure2. 2.2.ConnectingfromaRaspberryPiusingUART
9 RaspberryPiPicoPythonSDK Figure2.ARaspberryPi4andtheRaspberryPiPicowithUART0connectedtogether. thenconnecttotheboardusingconnectedto/dev/serial0, $-b115200-o-D/dev/serial0Ifyoupresstheenterkey,MicroPythonshouldrespondbypromptingyouformoreinput: >>> 2.3.ConnectingfromaMac Solongasyou’reusingarecentversionofmacOSlikeCatalina,driversshouldalreadybeloaded.Otherwiseseethemanufacturers'websiteforFTDIChipDrivers.ThenyoushoulduseaTerminalprogramtoconnecttoSerial-over-USB(USBCDC).Theserialportwillshowupas/dev/tty.usbmodem0000000000001Ifyoudon’talreadyhaveaTerminalprograminstalledyoucaninstallusingHomebrew, $brewinstallandconnecttotheboardasbelow. $-b115200-o-D/dev/tty.usbmodem0000000000001 2.3.ConnectingfromaMac 10 RaspberryPiPicoPythonSDK NOTE OtherTerminalapplicationslikeCoolTermorSerialcanalsobeused. 2.4.Say"HelloWorld" OnceconnectedyoucancheckthateverythingisworkingbytypingaPython"HelloWorld"intotheREPL, >>>print("Hello,Pico!
")Hello,Pico!
>>> 2.5.BlinkanLED Theon-boardLEDonRaspberryPiPicoisconnectedtoGPIOpin25.YoucanblinkthisonandofffromtheREPL.WhenyouseetheREPLpromptenterthefollowing, >>>frommachineimportPin>>>led=Pin(25,Pin.OUT) Themachinemoduleisusedtocontrolon-chiphardware.ThisisstandardonallMicroPythonports,andyoucanreadmoreaboutitintheMicroPythondocumentation.HereweareusingittotakecontrolofaGPIO,sowecandriveithighandlow.Ifyoutypethisin, >>>led.value
(1) TheLEDshouldturnon.Youcanturnitoffagainwith >>>led.value
(0) 2.6.Whatnext?
AtthispointyoushouldhaveMicroPythoninstalledonyourboard,andhavetestedyoursetupbytypingshortprogramsintotheprompttoprintsometextbacktoyou,andblinkanLED.Youcanreadontothenextchapter,whichgoesintothespecificsofMicroPythononRP2040,andwhereitdiffersfromotherplatforms.Chapter3alsohassomeshortexamplesofthedifferentAPIsofferedtointeractwiththehardware.Youcanlearnhowtosetupanintegrateddevelopmentenvironment(IDE)inChapter4,soyoudon’thavetotypeprogramsinlinebyline.YoucandivestraightintoAppendixAifyouareeagertostartconnectingwirestoabreadboard. 2.4.Say"HelloWorld" 11 RaspberryPiPicoPythonSDK Chapter3.TheRP2040Port Currentlysupportedfeaturesinclude: •REPLoverUSBandUART(onGP0/GP1).•1600kBfilesystemusinglittlefs2ontheon-boardflash.(DefaultsizeforRaspberryPiPico)•utimemodulewithsleepandticksfunctions.•ubinasciimodule.•machinemodulewithsomebasicfunctions. ◦machine.Pinclass.◦machine.Timerclass.◦machine.ADCclass.◦machine.I2Candmachine.SoftI2Cclasses.◦machine.SPIandmachine.SoftSPIclasses.◦machine.WDTclass.◦machine.PWMclass.◦machine.UARTclass.•rp2platform-specificmodule.◦PIOhardwareesslibrary◦PIOprogramassembler◦Rawflashread/writeess•Multicoresupportexposedviathestandard_threadmodule•eleratedfloatingpointarithmeticusingtheRP2040ROMlibraryandhardwaredivider(usedautomatically) DocumentationaroundMicroPythonisavailablefrom.Forexamplethemachinemodule,whichcanbeusedtoessalotofRP2040’son-chiphardware,isstandard,andyouwillfindalotoftheinformationyouneedintheonlinedocumentationforthatmodule. ThischapterwillgiveaverybrieftourofsomeofthehardwareAPIs,withcodeexamplesyoucaneithertypeintotheREPL(Chapter2)orloadontotheboardusingadevelopmentenvironmentinstalledonputer(Chapter4). 3.1.BlinkinganLEDForever(Timer) InChapter2wesawhowthemachine.PinclasscouldbeusedtoturnanLEDonandoff,bydrivingaGPIOhighandlow. >>>frommachineimportPin>>>led=Pin(25,Pin.OUT)>>>led.value
(1)>>>led.value
(0) Thisis,toputitmildy,quiteaconvolutedwayofturningalightonandoff.Alightswitchwouldworkbetter.Themachine.Timerclass,whichusesRP2040’shardwaretimertotriggercallbacksatregularintervals,savesalotoftypingifwewantthelighttoturnitselfonandoffrepeatedly,thusbringingourlevelofautomationfrom"mechanicalswitch"to"555timer". 3.1.BlinkinganLEDForever(Timer) 12 RaspberryPiPicoPythonSDK PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/blink/blink.pyLines1-
9 1frommachineimportPin,Timer
2 3led=Pin(25,Pin.OUT) 4tim=Timer() 5deftick(timer):
6 globalled
7 led.toggle()
8 9tim.init(freq=2.5,mode=Timer.PERIODIC,callback=tick) TypingthisprogramintotheREPLwillcausetheLEDtostartblinking,butthepromptwillappearagain: >>> TheTimerwecreatedwillruninthebackground,attheintervalwespecified,blinkingtheLED.TheMicroPythonpromptisstillrunningintheforeground,andwecanentermorecode,orstartmoretimers. 3.2.UART NOTE REPLoverUARTisdisabledbydefault.SeeSection2.2fordetailsofhowtoenableREPLoverUART. ExampleusageloopingUART0toUART1. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/uart/loopback/uart.pyLines1-15 1frommachineimportUART,Pin 2importtime
3 4uart1=UART(1,baudrate=9600,tx=Pin
(8),rx=Pin
(9))
5 6uart0=UART(0,baudrate=9600,tx=Pin
(0),rx=Pin
(1))
7 8txData=b'helloworld\n\r' 9uart1.write(txData) 10time.sleep(0.1) 11rxData=bytes() 12whileuart0.any()>0: 13 rxData+=uart0.read
(1) 14 15print(rxData.decode('utf-8')) Formoredetail,includingawiringdiagram,seeAppendixA. 3.3.ADC Ananalogue-to-digitalconverter(ADC)measuressomeanaloguesignalandencodesitasadigitalnumber.TheADConRP2040measuresvoltages. 3.2.UART 13 RaspberryPiPicoPythonSDK AnADChastwokeyfeatures:itsresolution,measuredindigitalbits,anditschannels,orhowmanyanaloguesignalsitcaneptandconvertatonce.TheADConRP2040hasaresolutionof12-bits,meaningthatitcantransformananaloguesignalintoadigitalsignalasanumberrangingfrom0to4095–thoughthisishandledinMicroPythontransformedtoa16-bitnumberrangingfrom0to65,535,sothatitbehavesthesameastheADConotherMicroPythonmicrocontrollers. RP2040hasfiveADCchannelstotal,fourofwhicharebroughtouttochipGPIOs:GP26,GP27,GP28andGP29.OnRaspberryPiPico,thefirstthreeofthesearebroughtouttoGPIOpins,andthefourthcanbeusedtomeasuretheVSYSvoltageontheboard. TheADC’sfifthinputchannelisconnectedtoatemperaturesensorbuiltintoRP2040. YoucanspecifywhichADCchannelyou’reusingbypinnumber,e.g. adc=machine.ADC(26)#ConnecttoGP26,whichischannel0orbychannel, adc=machine.ADC
(4)#Connecttotheinternaltemperaturesensoradc=machine.ADC
(0)#Connecttochannel0(GP26) Anexamplereadingthefourthanalogue-to-digital(ADC)converterchannel,connectedtotheinternaltemperaturesensor: PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/adc/temperature.pyLines1-14 1importmachine 2importutime
3 4sensor_temp=machine.ADC
(4) 5conversion_factor=3.3/(65535)
6 7whileTrue:
8 reading=sensor_temp.read_u16()*conversion_factor
9 10 #ThetemperaturesensormeasurestheVbevoltageofabiasedbipolardiode,connectedto thefifthADCchannel 11 #Typically,Vbe=0.706Vat27degreesC,withaslopeof-1.721mV(0.001721)perdegree. 12 temperature=27-(reading-0.706)/0.001721 13 print(temperature) 14 utime.sleep
(2) 3.4.Interrupts YoucansetanIRQlikethis: PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/irq/irq.pyLines1-4 1frommachineimportPin23p2=Pin(
2,Pin.IN,Pin.PULL_UP)4p2.irq(lambdapin:print("IRQwithflags:",pin.irq().flags()),Pin.IRQ_FALLING) 3.4.Interrupts 14 RaspberryPiPicoPythonSDK ItshouldprintoutsomethingwhenGP2hasafallingedge. 3.5.MulticoreSupport Exampleusage: PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/multicore/multicore.pyLines1-12 1importtime,_thread,machine
2 3deftask(n,delay):
4 led=machine.Pin(25,machine.Pin.OUT)
5 foriinrange(n):
6 led.high()
7 time.sleep(delay)
8 led.low()
9 time.sleep(delay) 10 print('done') 11 12_thread.start_new_thread(task,(10,0.5)) Onlyonethreadcanbestarted/runningatanyonetime,becausethereisnoRTOSjustasecondcore.TheGILisnotenabledsobothcore0andcore1canrunPythoncodeconcurrently,withcaretouselocksforshareddata. 3.6.I2C Exampleusage: PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/i2c.pyLines1-11 1frommachineimportPin,I2C23i2c=I2C(0,scl=Pin
(9),sda=Pin
(8),freq=100000)4i2c.scan()5i2c.writeto(76,b'123')6i2c.readfrom(76,4)78i2c=I2C(1,scl=Pin
(7),sda=Pin
(6),freq=100000)9i2c.scan()10i2c.writeto_mem(76,6,b'456')11i2c.readfrom_mem(76,6,4) I2Ccanbeconstructedwithoutspecifyingthefrequency,ifyoujustwantallthedefaults. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/i2c_without_freq.pyLines1-3 1frommachineimportI2C23i2c=I2C
(0)#defaultstoSCL=Pin
(9),SDA=Pin
(8),freq=400000 3.5.MulticoreSupport 15 RaspberryPiPicoPythonSDK WARNING Theremaybesomebugsreading/writingtodeviceaddressesthatdonotrespond,thehardwareseemstolockupinsomecases. Table2.DefaultI2Cpins FunctionI2CFrequencyI2C0SCLI2C0SDAI2C1SCLI2C1SDA Default400,000Pin9Pin8Pin7Pin6 3.7.SPI Exampleusage: PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/spi/spi.pyLines1-11 1frommachineimportSPI23spi=SPI(0)4spi=SPI(0,100_000)5spi=SPI(0,100_000,polarity=1,phase=1)67spi.write('test')8spi.read(5)910buf=bytearray(3)11spi.write_readinto('out',buf) NOTE Thechipselectmustbemanagedseparatelyusingamachine.Pin. Table3.DefaultSPIpins FunctionSPI_BAUDRATESPI_POLARITYSPI_PHASESPI_BITSSPI_FIRSTBITSPI0_SCKSPI0_MOSISPI0_MISOSPI1_SCKSPI1_MOSI Default1,000,000008MSBPin6Pin7Pin4Pin10Pin11 3.7.SPI 16 RaspberryPiPicoPythonSDK SPI1_MISO Pin8 3.8.PWM ExampleofusingPWMtofadeanLED: PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pwm/pwm_fade.pyLines1-25 1#ExampleusingPWMtofadeanLED.
2 3importtime 4frommachineimportPin,PWM
5 6 7#ConstructPWMobject,withLEDonPin(25). 8pwm=PWM(Pin(25))
9 10#SetthePWMfrequency. 11pwm.freq(1000) 12 13#FadetheLEDinandoutafewtimes. 14duty=
0 15direction=
1 16for_inrange(8*256): 17 duty+=direction 18 ifduty>255: 19 duty=255 20 direction=-
1 21 elifduty<0: 22 duty=
0 23 direction=
1 24 pwm.duty_u16(duty*duty) 25 time.sleep(0.001) 3.9.PIOSupport CurrentsupportallowsyoutodefineProgrammableIO(PIO)AssemblerblocksandusingtheminthePIOperipheral,moredocumentationaroundPIOcanbefoundinChapter3oftheRP2040DatasheetandChapter4oftheRaspberryPiPicoC/C++SDKbook. TheRaspberryPiPicoMicroPythonintroducesanew@rp2.asm_piodecorator,alongwitharp2.PIOclass.ThedefinitionofaPIOprogram,andtheconfigurationofthestatemachine,into2logicalparts: •Theprogramdefinition,includinghowmanypinsareusedandiftheyarein/outpins.Thisgoesinthe@rp2.asm_pio definition.ThisisclosetowhatthepioasmtoolfromtheSDKwouldgeneratefroma.piofile(buthereit’salldefinedinPython). •Theprograminstantiation,whichsetsthefrequencyofthestatemachineandwhichpinstobindto.Thesegetset whensettingaSMtorunaparticularprogram. Theaimwastoallowaprogramtobedefinedonceandtheneasilyinstantiatedmultipletimes(ifneeded)withdifferentGPIO.AnotheraimwastomakeiteasytodobasicthingswithoutgettingweigheddownintoomuchPIO/SMconfiguration. Exampleusage,toblinktheon-boardLEDconnectedtoGPIO25, 3.8.PWM 17 RaspberryPiPicoPythonSDK PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_blink.pyLines1-28 1importtime 2importrp2 3frommachineimportPin
4 5#Definetheblinkprogram.IthasoneGPIOtobindtoonthesetinstruction,whichisan outputpin. 6#Uselotsofdelaystomaketheblinkingvisiblebyeye. 7@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW) 8defblink():
9 wrap_target() 10 set(pins,1)[31] 11 nop() [31] 12 nop() [31] 13 nop() [31] 14 nop() [31] 15 set(pins,0)[31] 16 nop() [31] 17 nop() [31] 18 nop() [31] 19 nop() [31] 20 wrap() 21 22#Instantiateastatemachinewiththeblinkprogram,at2000Hz,withsetboundtoPin(25) (LEDontherp2board) 23sm=rp2.StateMachine(0,blink,freq=2000,set_base=Pin(25)) 24 25#Runthestatemachinefor3seconds.TheLEDshouldblink. 26sm.active
(1) 27time.sleep
(3) 28sm.active
(0) orviaexplicitexec. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_exec.pyLines1-27 1#ExampleusingPIOtoturnonanLEDviaanexplicitexec. 2# 3#Demonstrates: 4#-usingset_initandset_base 5#-usingStateMachine.exec
6 7importtime 8frommachineimportPin 9importrp2 10 11#Defineanemptyprogramthatusesasinglesetpin. 12@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW) 13defprog(): 14 pass 15 16 17#ConstructtheStateMachine,bindingPin(25)tothesetpin. 18sm=rp2.StateMachine(0,prog,set_base=Pin(25)) 19 20#Turnonthesetpinviaanexecinstruction. 21sm.exec("set(pins,1)") 22 23#Sleepfor500ms. 24time.sleep(0.5) 3.9.PIOSupport 18 RaspberryPiPicoPythonSDK 2526#Turnoffthesetpinviaanexecinstruction.27sm.exec("set(pins,0)") Somepointstonote, •Allprogramconfiguration(egull)isdoneinthe@asm_piodecorator.Onlythefrequencyandbasepinsareset intheStateMachineconstructor. •[n]isusedfordelay,.set(n)usedforsideset•Theassemblerwillautomaticallydetectifsidesetisusedeverywhereoronlyonafewinstructions,andsetthe SIDE_ENbitautomatically Theideaisthatforthe4setsofpins(in,out,set,sideset,excludingjmp)thatcanbeconnectedtoastatemachine,there’sthefollowingthatneedconfiguringforeachset: 1.baseGPIO 2.numberofconsecutiveGPIO 3.initialGPIOdirection(inoroutpin) 4.initialGPIOvalue(highorlow) InthedesignofthePythonAPIforPIOthese4itemsaresplitinto"declaration"(items2-4)and"instantiation"(item1).Inotherwords,aprogramiswrittenwithitems2-4fixedforthatprogram(egaWS2812driverwouldhave1outputpin)anditem1isfreetochangewithoutchangingtheprogram(egwhichpintheWS2812isconnectedto). Sointhe@asm_piodecoratoryoudeclareitems2-4,andintheStateMachineconstructoryousaywhichbasepintouse(item1).Thatmakesiteasytodefineasingleprogramandinstantiateitmultipletimesondifferentpins(youcan’treallychangeitems2-4foradifferentinstantiationofthesameprogram,itdoesn’treallymakesensetodothat). Andthesamekeywordarg(inthecaseaboutit’ssideset_pins)isusedforboththedeclarationandinstantiation,toshowthattheyarelinked. Todeclaremultiplepinsinthedecorator(thecount,ieitem2above),youuseatuple/listofvalues.Andeachiteminthetuple/listspecifieditems3and4.Forexample: 1@asm_pio(set_pins=(PIO.OUT_LOW,PIO.OUT_HIGH,PIO.IN_LOW),sideset_pins=PIO.OUT_LOW) 2deffoo():
3 ....
4 5sm=StateMachine(0,foo,freq=10000,set_pins=Pin(15),sideset_pins=Pin(22)) Inthisexample: •thereare3setpinsconnectedtotheSM,andtheirinitialstate(setwhentheStateMachineiscreated)is:output low,outputhigh,inputlow(usedforopen-drain) •thereis1sidesetpin,initialstateisoutputlow•the3setpinsstartatPin(15)•the1sidesetpinstartsatPin(22) ThereasontohavetheconstantsOUT_LOW,OUT_HIGH,IN_LOWandIN_HIGHissothatthepinvalueanddirareautomaticallysetbeforethestartofthePIOprogram(insteadofwastinginstructionwordstodoset(pindirs,1)etcatthestart). 3.9.1.IRQ ThereissupportforPIOIRQs,e.g. 3.9.PIOSupport 19 RaspberryPiPicoPythonSDK PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_irq.pyLines1-25 1importtime 2importrp2
3 4@rp2.asm_pio() 5defirq_test():
6 wrap_target()
7 nop() [31]
8 nop() [31]
9 nop() [31] 10 nop() [31] 11 irq
(0) 12 nop() [31] 13 nop() [31] 14 nop() [31] 15 nop() [31] 16 irq
(1) 17 wrap() 18 19 20rp2.PIO
(0).irq(lambdapio:print(pio.irq().flags())) 21 22sm=rp2.StateMachine(0,irq_test,freq=2000) 23sm.active
(1) 24time.sleep
(1) 25sm.active
(0) Anexampleprogramthatblinksat1HzandraisesanIRQat1Hztoprintthecurrentmillisecondtimestamp, PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_1hz.pyLines1-33 1#ExampleusingPIOtoblinkanLEDandraiseanIRQat1Hz.
2 3importtime 4frommachineimportPin 5importrp2
6 7 8@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW) 9defblink_1hz(): 10 #Cycles:1+1+6+32*(30+1)=1000 11 irq(rel
(0)) 12 set(pins,1) 13 set(x,31) [5] 14 label("delay_high") 15 nop() [29] 16 jmp(x_dec,"delay_high") 17 18 #Cycles:1+7+32*(30+1)=1000 19 set(pins,0) 20 set(x,31) [6] 21 label("delay_low") 22 nop() [29] 23 jmp(x_dec,"delay_low") 24 25 26#CreatetheStateMachinewiththeblink_1hzprogram,outputtingonPin(25). 27sm=rp2.StateMachine(0,blink_1hz,freq=2000,set_base=Pin(25)) 28 29#SettheIRQhandlertoprintthemillisecondtimestamp. 3.9.PIOSupport 20 RaspberryPiPicoPythonSDK 30sm.irq(lambdap:print(time.ticks_ms()))3132#StarttheStateMachine.33sm.active
(1) ortowaitforapinchangeandraiseanIRQ. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_pinchange.pyLines1-46 1#ExampleusingPIOtowaitforapinchangeandraiseanIRQ. 2# 3#Demonstrates: 4#-PIOwrapping 5#-PIOwaitinstruction,waitingonaninputpin 6#-PIOirqinstruction,inblockingmodewithrelativeIRQnumber 7#-settingthein_basepinforaStateMachine 8#-settinganirqhandlerforaStateMachine 9#-instantiating2xStateMachine'swiththesameprogramanddifferentpins 10 11importtime 12frommachineimportPin 13importrp2 14 15 16@rp2.asm_pio() 17defwait_pin_low(): 18 wrap_target() 19 20 wait(0,pin,0) 21 irq(block,rel
(0)) 22 wait(1,pin,0) 23 24 wrap() 25 26 27defhandler(sm): 28 #Printa(wrapping)timestamp,andthestatemachineobject. 29 print(time.ticks_ms(),sm) 30 31 32#InstantiateStateMachine(0)withwait_pin_lowprogramonPin(16). 33pin16=Pin(16,Pin.IN,Pin.PULL_UP) 34sm0=rp2.StateMachine(0,wait_pin_low,in_base=pin16) 35sm0.irq(handler) 36 37#InstantiateStateMachine(1)withwait_pin_lowprogramonPin(17). 38pin17=Pin(17,Pin.IN,Pin.PULL_UP) 39sm1=rp2.StateMachine(1,wait_pin_low,in_base=pin17) 40sm1.irq(handler) 41 42#StarttheStateMachine'srunning. 43sm0.active
(1) 44sm1.active
(1) 45 46#Now,whenPin(16)orPin(17)ispulledlowamessagewillbeprintedtotheREPL. 3.9.PIOSupport 21 RaspberryPiPicoPythonSDK 3.9.2.WS2812LED(NeoPixel) WhileaWS2812LED(NeoPixel)canbedrivenviathefollowingprogram, PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_ws2812.pyLines1-52 1#ExampleusingPIOtodriveasetofWS2812LEDs.
2 3importarray,time 4frommachineimportPin 5importrp2
6 7#ConfigurethenumberofWS2812LEDs. 8NUM_LEDS=
8 9 10 11@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW,out_shiftdir=rp2.PIO.SHIFT_LEFT,ull=True, pull_thresh=24) 12defws2812(): 13 T1=
2 14 T2=
5 15 T3=
3 16 wrap_target() 17 label("bitloop") 18 out(x,1) .side
(0)[T3-1] 19 jmp(not_x,"do_zero").side
(1)[T1-1] 20 jmp("bitloop") .side
(1)[T2-1] 21 label("do_zero") 22 nop() .side
(0)[T2-1] 23 wrap() 24 25 26#CreatetheStateMachinewiththews2812program,outputtingonPin(22). 27sm=rp2.StateMachine(0,ws2812,freq=8_000_000,sideset_base=Pin(22)) 28 29#StarttheStateMachine,itwillwaitfordataonitsFIFO. 30sm.active
(1) 31 32#DisplayapatternontheLEDsviaanarrayofLEDRGBvalues. 33ar=array.array("I",[0for_inrange(NUM_LEDS)]) 34 35#Cyclecolours. 36foriinrange(4*NUM_LEDS): 37 forjinrange(NUM_LEDS): 38 r=j*100//(NUM_LEDS-1) 39 b=100-j*100//(NUM_LEDS-1) 40 ifj!
=i%NUM_LEDS: 41 r>>=
3 42 b>>=
3 43 ar[j]=r<<16|b 44 sm.put(ar,8) 45 time.sleep_ms(50) 46 47#Fadeout. 48foriinrange(24): 49 forjinrange(NUM_LEDS): 50 ar[j]>>=
1 51 sm.put(ar,8) 52 time.sleep_ms(50) 3.9.PIOSupport 22 RaspberryPiPicoPythonSDK 3.9.3.UARTTX AUARTTXexample, PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_uart_tx.pyLines1-42 1#ExampleusingPIOtocreateaUARTTXinterface
2 3frommachineimportPin 4fromrp2importPIO,StateMachine,asm_pio
5 6UART_BAUD=115200 7PIN_BASE=10 8NUM_UARTS=
8 9 10 11@asm_pio(sideset_init=PIO.OUT_HIGH,out_init=PIO.OUT_HIGH,out_shiftdir=PIO.SHIFT_RIGHT) 12defuart_tx(): 13 #BlockwithTXdeasserteduntildataavailable 14 pull() 15 #Initialisebitcounter,assertstartbitfor8cycles 16 set(x,7).side
(0) [7] 17 #Shiftout8databits,8executioncyclesperbit 18 label("bitloop") 19 out(pins,1) [6] 20 jmp(x_dec,"bitloop") 21 #Assertbitfor8cyclestotal(incl1forpull()) 22 nop() .side
(1) [6] 23 24 25#Nowweadd8UARTTXs,onpins10to17.Usethesamebaudrateforallofthem. 26uarts=[] 27foriinrange(NUM_UARTS): 28 sm=StateMachine( 29 i,uart_tx,freq=8*UART_BAUD,sideset_base=Pin(PIN_BASE+i),out_base=Pin (PIN_BASE+i) 30 ) 31 sm.active
(1) 32 uarts.append(sm) 33 34#WecanprintcharactersfromeachUARTbypushingthemtotheTXFIFO 35defpio_uart_print(sm,s): 36 forcins: 37 sm.put(ord(c)) 38 39 40#PrintadifferentmessagefromeachUART 41fori,uinenumerate(uarts): 42 pio_uart_print(u,"HellofromUART{}!
\n".format(i)) NOTE YouneedtospecifyaninitialOUTpinstateinyourprograminordertobeabletopassOUTmappingtoyourSMinstantiation,eventhoughinthisprogramitisredundantbecausethemappingsoverlap. 3.9.4.SPI AnSPIexample. 3.9.PIOSupport 23 RaspberryPiPicoPythonSDK PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_spi.pyLines1-49 1importrp2 2frommachineimportPin
3 4@rp2.asm_pio(out_shiftdir=0,ull=True,pull_thresh=8,ush=True,push_thresh=
8, sideset_init=(rp2.PIO.OUT_LOW,rp2.PIO.OUT_HIGH),out_init=rp2.PIO.OUT_LOW) 5defspi_cpha0():
6 #NoteXmustbepreinitialisedbysetupcodebeforefirstbyte,wereloadaftersending eachbyte
7 #Wouldnormallydothisviaexec()butinthiscaseit'sintheinstructionmemoryandis onlyrunonce
8 set(x,6)
9 #Actualprogrambodyfollows 10 wrap_target() 11 pull(ifempty) .side(0x2)[1] 12 label("bitloop") 13 out(pins,1) .side(0x0)[1] 14 in_(pins,1) .side(0x1) 15 jmp(x_dec,"bitloop").side(0x1) 16 17 out(pins,1) .side(0x0) 18 set(x,6) .side(0x0)#Notethiscouldbereplacedwithmovx,yfor programmableframesize 19 in_(pins,1) .side(0x1) 20 jmp(not_osre,"bitloop").side(0x1)#FallthruifTXFempties 21 22 nop() .side(0x0)[1]#CSnbackporch 23 wrap() 24 25 26classPIOSPI: 27 28 def__init__(self,sm_id,pin_mosi,pin_miso,pin_sck,cpha=False,cpol=False,freq =1000000): 29 assert(not(cpolorcpha)) 30 self._sm=rp2.StateMachine(sm_id,spi_cpha0,freq=4*freq,sideset_base=Pin( pin_sck),out_base=Pin(pin_mosi),in_base=Pin(pin_sck)) 31 self._sm.active
(1) 32 33 #Notethiscodewilldiespectacularlycausewe'renotdrainingtheRXFIFO 34 defwrite_blocking(wdata): 35 forbinwdata: 36 self._sm.put(b<<24) 37 38 defread_blocking(n): 39 data=[] 40 foriinrange(n): 41 data.append(self._sm.get()&0xff) 42 returndata 43 44 defwrite_read_blocking(wdata): 45 rdata=[] 46 forbinwdata: 47 self._sm.put(b<<24) 48 rdata.append(self._sm.get()&0xff) 49 returnrdata 3.9.PIOSupport 24 RaspberryPiPicoPythonSDK NOTE ThisSPIprogramsupportsprogrammableframesizes(byholdingthereloadvalueforXcounterintheYregister)butcurrentlythiscan’tbeused,becausetheullthresholdisassociatedwiththeprogram,insteadoftheSMinstantiation. 3.9.5.PWM APWMexample, PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/pio_pwm.pyLines1-43 1#ExampleofusingPIOforPWM,andfadingthebrightnessofanLED
2 3frommachineimportPin 4fromrp2importPIO,StateMachine,asm_pio 5fromtimeimportsleep
6 7 8@asm_pio(sideset_init=PIO.OUT_LOW) 9defpwm_prog(): 10 pull(noblock).side
(0) 11 mov(x,osr)#KeepmostrecentpulldatastashedinX,forrecyclingbynoblock 12 mov(y,isr)#ISRmustbepreloadedwithPWMcountmax 13 label("pwmloop") 14 jmp(x_not_y,"skip") 15 nop() .side
(1) 16 label("skip") 17 jmp(y_dec,"pwmloop") 18 19 20classPIOPWM: 21 def__init__(self,sm_id,pin,max_count,count_freq): 22 self._sm=StateMachine(sm_id,pwm_prog,freq=2*count_freq,sideset_base=Pin(pin)) 23 #Useexec()toloadmaxcountintoISR 24 self._sm.put(max_count) 25 self._sm.exec("pull()") 26 self._sm.exec("mov(isr,osr)") 27 self._sm.active
(1) 28 self._max_count=max_count 29 30 defset(self,value): 31 #Minimumvalueis-1pletelyturnoff),0actuallystillproducesnarrowpulse 32 value=max(value,-1) 33 value=min(value,self._max_count) 34 self._sm.put(value) 35 36 37#Pin25isLEDonPicoboards 38pwm=PIOPWM(0,25,max_count=(1<<16)-1,count_freq=10_000_000) 39 40whileTrue: 41 foriinrange(256): 42 pwm.set(i**2) 43 sleep(0.01) 3.9.PIOSupport 25 RaspberryPiPicoPythonSDK 3.9.6.Usingpioasm AswellaswritingPIOcodeinlineinyourMicroPythonscriptyoucanusethepioasmtoolfromtheC/C++SDKtogenerateaPythonfile. $pioasm-opythoninput(output)FormoreinformationonpioasmseetheRaspberryPiPicoC/C++SDKbookwhichtalksabouttheC/C++SDK. 3.9.PIOSupport 26 RaspberryPiPicoPythonSDK Chapter4.UsinganIntegratedDevelopmentEnvironment(IDE) TheMicroPythonporttoRaspberryPiPicoandotherRP2040-basedboardsworksmonlyuseddevelopmentenvironments. 4.1.UsingThonny ThonnypackagesareavailableforLinux,MSWindows,andmacOS.Afterinstallation,usingtheThonnydevelopmentenvironmentisthesameacrossallthreeplatforms.ThelatestreleaseofThonnycanbedownloadedfromAlternativelyifyouareworkingonaRaspberryPiyoushouldinstallThonnyusingaptfrommandline, $sudoaptinstallthonny thiswilladdaThonnyicontotheRaspberryPimenu.GoaheadandselectRaspberryPi→Programming→ThonnyPythonIDEtoopenthedevelopmentenvironment.WhenopeningThonnyforthefirsttimeselect"StandardMode."ForsomeversionsthischoicewillbemadeviaapopupwhenyoufirstopenThonny.HoweverfortheRaspberryPireleaseyoushouldclickonthetextinrightofthewindowtoswitchto"RegularMode."MakesureyourRaspberryPiPicoispluggedintoputerand,clickontheword‘Python’followedbyaversionnumberatthebottom-rightoftheThonnywindow—thisisthePythoninterpreterthatThonnyiscurrentlyusing.NormallytheinterpreteristhecopyofPythonrunningonRaspberryPi,butitneedstobechangedinordertorunyourprogramsinMicroPythononyourPico,clickingthecurrentinterpreterwillopenadropdown.Select"MicroPython(RaspberryPiPico)"fromthelist,seeFigure3. Figure3.SwitchingtoMicroPython 4.1.UsingThonny 27 RaspberryPiPicoPythonSDK NOTE TheRaspberryPiPicointerpreterisonlyavailableinthelatestversionofThonny.Ifyou’rerunninganolderversionandcan’tupdateit,lookfor‘MicroPython(generic)’instead.IfyourversionofThonnyisolderstillandhasnointerpreteroptionatthebottom-rightofthewindowandyoucan’tupdateit,restartThonny,clickthe"Run"menu,andclick‘Selectinterpreter.’Clickthedrop-downarrownextto‘ThesameinterpreterthatrunsThonny(default)’,clickon‘MicroPython(generic)’inthelist,thenclickonthedrop-downarrownextto‘Port’andclickon‘BoardinFSmode’inthatlistbeforeclicking"OK"toconfirmyourchanges. YoucannowesstheREPLfromtheShellpanel, >>>print('HelloPico!
')HelloPico!
>>> seeFigure4. Figure4.Saying"HelloPico!
"fromtheMicroPythonREPLinsidetheThonnyenvironment. 4.1.1.BlinkingtheLEDfromThonny Youcanuseatimertoblinktheon-boardLED. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/blink/blink.pyLines1-
9 1frommachineimportPin,Timer
2 3led=Pin(25,Pin.OUT) 4tim=Timer() 5deftick(timer):
6 globalled
7 led.toggle()
8 9tim.init(freq=2.5,mode=Timer.PERIODIC,callback=tick) Enterthecodeinthemainpanel,thenclickonthegreenrunbutton.Thonnywillpresentyouwithapopup,clickon 4.1.UsingThonny 28 RaspberryPiPicoPythonSDK "MicroPythondevice"andenter"test.py"tosavethecodetotheRaspberryPiPico,seeFigure5. Figure5.SavingcodetotheRaspberryPiPicoinsidetheThonnyenvironment. NOTE Ifyou"saveafiletothedevice"andgiveitthespecialnamemain.py,thenMicroPythonstartsrunningthatscriptassoonaspowerissuppliedtoRaspberryPiPicointhefuture. TheprogramshoulduploadedtotheRaspberryPiPicousingtheREPL,andautomaticallystartrunning.Youshouldseetheon-boardLEDstartblinking,connectedtoGPIOpin25 4.2.Usingrshell TheRemoteShellforMicroPython(rshell)isasimpleshellwhichrunsonthehostandusesMicroPython’sREPLtosendpythoncodetotheRaspberryPiPicoinordertogetfilesysteminformation,andtocopyfilestoandfromMicroPython’sownfilesystem.Youcaninstallrshellusing, $sudoaptinstallpython3-pip$sudopip3installrshell YoucanthenconnecttoRaspberryPiPicousing, $rshell--buffer-size=512-p/dev/ttyACM0Connectingto/dev/ttyACM0(buffer-size512)...TryingtoconnecttoREPLconnectedTestingifsys.stdin.bufferexists...NRetrievingrootdirectories...Settingtime...Aug21,202015:35:18Evaluatingboard_name...pyboardRetrievingtimeepoch...Jan01,2000etorshell.UseControl-D(orthemand)toexitrshell./home/pi> 4.2.Usingrshell 29 RaspberryPiPicoPythonSDKFulldocumentationofrshellcanbefoundontheproject’sGitHubrepository. 4.2.Usingrshell 30 RaspberryPiPicoPythonSDK AppendixA:AppNotes UsingaSSD1306-basedOLEDgraphicsdisplay DisplayanimageandtextonI2CdrivenSSD1306-basedOLEDgraphicsdisplay. Wiringinformation SeeFigure6forwiringinstructions. Figure6.WiringtheOLEDtoPicousingI2C ListofFiles Alistoffileswithdescriptionsoftheirfunction;i2c_1306oled_using_defaults.py Theexamplecode. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/1306oled/i2c_1306oled_using_defaults.pyLines1-33 1#DisplayImage&textonI2Cdrivenssd1306OLEDdisplay 2frommachineimportPin,I2C 3fromssd1306importSSD1306_I2C 4importframebuf
5 6WIDTH=128 #oleddisplaywidth 7HEIGHT=32 #oleddisplayheight
8 9i2c=I2C
(0) #InitI2CusingI2C0defaults, SCL=Pin(GP9),SDA=Pin(GP8),freq=400000 10print("I2CAddress :"+hex(i2c.scan()[0]).upper())#Displaydeviceaddress 11print("I2CConfiguration:"+str(i2c)) #DisplayI2Cconfig 12 UsingaSSD1306-basedOLEDgraphicsdisplay 31 RaspberryPiPicoPythonSDK 13 14oled=SSD1306_I2C(WIDTH,HEIGHT,i2c) #Initoleddisplay 15 16#RaspberryPilogoas32x32bytearray 17buffer=bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?
\x00\x01\x86 @\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe3\x00\x00 ~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x01\xc1\x83\x80\x02A \x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc =\x80\x01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!
\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x00 8\x1c\x00\x00\x0c\x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 18 19#Loadtheraspberrypilogointotheframebuffer(theimageis32x32) 20fb=framebuf.FrameBuffer(buffer,32,32,framebuf.MONO_HLSB) 21 22#Cleartheoleddisplayincaseithasjunkonit. 23oled.fill
(0) 24 25#Blittheimagefromtheframebuffertotheoleddisplay 26oled.blit(fb,96,0) 27 28#Addsometext 29oled.text("RaspberryPi",5,5) 30oled.text("Pico",5,15) 31 32#Finallyupdatetheoleddisplaysotheimage&textisdisplayed 33oled.show() i2c_1306oled_with_freq.pyTheexamplecode,explicitlysetsafrequency. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/1306oled/i2c_1306oled_with_freq.pyLines1-33 1#DisplayImage&textonI2Cdrivenssd1306OLEDdisplay 2frommachineimportPin,I2C 3fromssd1306importSSD1306_I2C 4importframebuf
5 6WIDTH=128 #oleddisplaywidth 7HEIGHT=32 #oleddisplayheight
8 9i2c=I2C(0,scl=Pin
(9),sda=Pin
(8),freq=200000) #InitI2CusingpinsGP8&GP9 (defaultI2C0pins) 10print("I2CAddress :"+hex(i2c.scan()[0]).upper())#Displaydeviceaddress 11print("I2CConfiguration:"+str(i2c)) #DisplayI2Cconfig 12 13 14oled=SSD1306_I2C(WIDTH,HEIGHT,i2c) #Initoleddisplay 15 16#RaspberryPilogoas32x32bytearray 17buffer=bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?
\x00\x01\x86 @\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe3\x00\x00 ~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x01\xc1\x83\x80\x02A \x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc =\x80\x01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!
\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x00 8\x1c\x00\x00\x0c\x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 18 19#Loadtheraspberrypilogointotheframebuffer(theimageis32x32) 20fb=framebuf.FrameBuffer(buffer,32,32,framebuf.MONO_HLSB) 21 22#Cleartheoleddisplayincaseithasjunkonit. 23oled.fill
(0) UsingaSSD1306-basedOLEDgraphicsdisplay 32 RaspberryPiPicoPythonSDK 2425#Blittheimagefromtheframebuffertotheoleddisplay26oled.blit(fb,96,0)2728#Addsometext29oled.text("RaspberryPi",5,5)30oled.text("Pico",5,15)3132#Finallyupdatetheoleddisplaysotheimage&textisdisplayed33oled.show() BillofMaterials Table4.Alistofmaterialsrequiredfortheexample ItemBreadboardRaspberryPiPico Monochrome128x32I2COLEDDisplay Quantity11
1 Details genericpart /products/raspberry-pi-pico/ /product/931 UsingaSH1106-basedOLEDgraphicsdisplay DisplayanimageandtextonI2CdrivenSH1106-basedOLEDgraphicsdisplaysuchasthePimoroniBreakoutGarden1.12"MonoOLED/products/1-12-oled-breakout?
variant=29421050757203. Wiringinformation SeeFigure7forwiringinstructions. Figure7.WiringtheOLEDtoPicousingI2C UsingaSH1106-basedOLEDgraphicsdisplay 33 RaspberryPiPicoPythonSDK ListofFiles Alistoffileswithdescriptionsoftheirfunction;i2c_1106oled_using_defaults.py Theexamplecode. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/1106oled/i2c_1106oled_using_defaults.pyLines1-34 1#DisplayImage&textonI2CdrivenSH1106OLEDdisplay 2frommachineimportI2C,ADC 3fromsh1106importSH1106_I2C 4importframebuf
5 6 7WIDTH=128 #oleddisplaywidth 8HEIGHT=128 #oleddisplayheight
9 10i2c=I2C
(0) #InitI2CusingI2C0defaults, SCL=Pin(GP9),SDA=Pin(GP8),freq=400000 11print("I2CAddress :"+hex(i2c.scan()[0]).upper())#Displaydeviceaddress 12print("I2CConfiguration:"+str(i2c)) #DisplayI2Cconfig 13 14 15oled=SH1106_I2C(WIDTH,HEIGHT,i2c) #Initoleddisplay 16 17#RaspberryPilogoas32x32bytearray 18buffer=bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?
\x00\x01\x86 @\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe3\x00\x00 ~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x01\xc1\x83\x80\x02A \x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc =\x80\x01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!
\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x00 8\x1c\x00\x00\x0c\x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 19 20#Loadtheraspberrypilogointotheframebuffer(theimageis32x32) 21fb=framebuf.FrameBuffer(buffer,32,32,framebuf.MONO_HLSB) 22 23#Cleartheoleddisplayincaseithasjunkonit. 24oled.fill
(0) 25 26#Blittheimagefromtheframebuffertotheoleddisplay 27oled.blit(fb,96,0) 28 29#Addsometext 30oled.text("RaspberryPi",5,5) 31oled.text("Pico",5,15) 32 33#Finallyupdatetheoleddisplaysotheimage&textisdisplayed 34oled.show() i2c_1106oled_with_freq.pyTheexamplecode,explicitlysetsafrequency. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/1106oled/i2c_1106oled_with_freq.pyLines1-33 1#DisplayImage&textonI2Cdrivenssd1306OLEDdisplay 2frommachineimportPin,I2C 3fromsh1106importSH1106_I2C 4importframebuf
5 6WIDTH=128 #oleddisplaywidth UsingaSH1106-basedOLEDgraphicsdisplay 34 RaspberryPiPicoPythonSDK 7HEIGHT=32 #oleddisplayheight
8 9i2c=I2C(0,scl=Pin
(9),sda=Pin
(8),freq=200000) #InitI2CusingpinsGP8&GP9 (defaultI2C0pins) 10print("I2CAddress :"+hex(i2c.scan()[0]).upper())#Displaydeviceaddress 11print("I2CConfiguration:"+str(i2c)) #DisplayI2Cconfig 12 13 14oled=SH1106_I2C(WIDTH,HEIGHT,i2c) #Initoleddisplay 15 16#RaspberryPilogoas32x32bytearray 17buffer=bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?
\x00\x01\x86 @\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe3\x00\x00 ~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x01\xc1\x83\x80\x02A \x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc =\x80\x01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!
\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x00 8\x1c\x00\x00\x0c\x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 18 19#Loadtheraspberrypilogointotheframebuffer(theimageis32x32) 20fb=framebuf.FrameBuffer(buffer,32,32,framebuf.MONO_HLSB) 21 22#Cleartheoleddisplayincaseithasjunkonit. 23oled.fill
(0) 24 25#Blittheimagefromtheframebuffertotheoleddisplay 26oled.blit(fb,96,0) 27 28#Addsometext 29oled.text("RaspberryPi",5,5) 30oled.text("Pico",5,15) 31 32#Finallyupdatetheoleddisplaysotheimage&textisdisplayed 33oled.show() sh1106.pySH1106DriverObtainedfrom/robert-hh/SH1106 PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/i2c/1106oled/sh1106.pyLines1-226 1# 2#MicroPythonSH1106OLEDdriver,I2CandSPIinterfaces 3# 4#TheMITLicense(MIT) 5# 6#Copyright(c)2016RadomirDopieralski(@deshipu), 7# 2017RobertHammelrath(@robert-hh) 8# 9#Permissionisherebygranted,freeofcharge,toanypersonobtainingacopy 10#ofthissoftwareandassociateddocumentationfiles(the"Software"),todeal 11#intheSoftwarewithoutrestriction,includingwithoutlimitationtherights 12#touse,copy,modify,merge,publish,distribute,sublicense,and/orsell 13#copiesoftheSoftware,andtopermitpersonstowhomtheSoftwareis 14#furnishedtodoso,subjecttothefollowingconditions: 15# 16#Theabovecopyrightnoticeandthispermissionnoticeshallbeincludedin 17#allcopiesorsubstantialportionsoftheSoftware. 18# 19#THESOFTWAREISPROVIDED"ASIS",WITHOUTWARRANTYOFANYKIND,EXPRESSOR 20#IMPLIED,INCLUDINGBUTNOTLIMITEDTOTHEWARRANTIESOFMERCHANTABILITY, 21#FITNESSFORAPARTICULARPURPOSEANDNONINFRINGEMENT.INNOEVENTSHALLTHE 22#AUTHORSORCOPYRIGHTHOLDERSBELIABLEFORANYCLAIM,DAMAGESOROTHER UsingaSH1106-basedOLEDgraphicsdisplay 35 RaspberryPiPicoPythonSDK 23#LIABILITY,WHETHERINANACTIONOFCONTRACT,TORTOROTHERWISE,ARISINGFROM, 24#OUTOFORINCONNECTIONWITHTHESOFTWAREORTHEUSEOROTHERDEALINGSIN 25#THESOFTWARE. 26# 27#Samplecodesections 28#------------SPI------------------ 29#PinMapSPI 30#-3V3 - 31#-GND -Gnd 32#-GPIO11-DIN/MOSIfixed 33#-GPIO10-CLK/Sckfixed 34#-GPIO4-CS(optional,iftheonlyconnecteddevice,connecttoGND) 35#-GPIO5-D/C 36#-GPIO2-Res 37# 38#forCS,D/CandResotherportsmaybechosen. 39# 40#frommachineimportPin,SPI 41#importsh1106 42 43#spi=SPI(1,baudrate=1000000) 44#display=sh1106.SH1106_SPI(128,64,spi,Pin
(5),Pin
(2),Pin
(4)) 45#display.sleep(False) 46#display.fill
(0) 47#display.text('Testing1',0,0,1) 48#display.show() 49# 50#---------------I2C------------------ 51# 52#PinMapI2C 53#-3V3 - 54#-GND -Gnd 55#-GPIO5-CLK/SCL 56#-GPIO4-DIN/SDA 57#-GPIO2-Res 58#-GND -CS 59#-GND -D/C 60# 61# 62#frommachineimportPin,I2C 63#importsh1106 64# 65#i2c=I2C(0,scl=Pin
(5),sda=Pin
(4),freq=400000) 66#display=sh1106.SH1106_I2C(128,64,i2c,Pin
(2),0x3c) 67#display.sleep(False) 68#display.fill
(0) 69#display.text('Testing1',0,0,1) 70#display.show() 71 72frommicropythonimportconst 73importutimeastime 74importframebuf 75 76 77#afewregisterdefinitions 78_SET_CONTRAST =const(0x81) 79_SET_NORM_INV =const(0xa6) 80_SET_DISP =const(0xae) 81_SET_SCAN_DIR =const(0xc0) 82_SET_SEG_REMAP =const(0xa0) 83_LOW_COLUMN_ADDRESS=const(0x00) 84_HIGH_COLUMN_ADDRESS=const(0x10) 85_SET_PAGE_ADDRESS=const(0xB0) UsingaSH1106-basedOLEDgraphicsdisplay 36 RaspberryPiPicoPythonSDK 86 87 88classSH1106: 89 def__init__(self,width,height,external_): 90 self.width=width 91 self.height=height 92 self.external_=external_ 93 self.pages=self.height//8 94 self.buffer=bytearray(self.pages*self.width) 95 fb=framebuf.FrameBuffer(self.buffer,self.width,self.height, 96 framebuf.MVLSB) 97 self.framebuf=fb 98#setshortcutsforthemethodsofframebuf 99 self.fill=fb.fill 100 self.fill_rect=fb.fill_rect 101 self.hline=fb.hline 102 self.vline=fb.vline 103 self.line=fb.line 104 self.rect=fb.rect 105 self.pixel=fb.pixel 106 self.scroll=fb.scroll 107 self.text=fb.text 108 self.blit=fb.blit 109 110 self.init_display() 111 112 definit_display(self): 113 self.reset() 114 self.fill
(0) 115 self.poweron() 116 self.show() 117 118 defpoweroff(self): 119 self.write_cmd(_SET_DISP|0x00) 120 121 defpoweron(self): 122 self.write_cmd(_SET_DISP|0x01) 123 124 defrotate(self,flag,update=True): 125 ifflag: 126 self.write_cmd(_SET_SEG_REMAP|0x01)#mirrordisplayvertically 127 self.write_cmd(_SET_SCAN_DIR|0x08)#mirrordisplayhor. 128 else: 129 self.write_cmd(_SET_SEG_REMAP|0x00) 130 self.write_cmd(_SET_SCAN_DIR|0x00) 131 ifupdate: 132 self.show() 133 134 defsleep(self,value): 135 self.write_cmd(_SET_DISP|(notvalue)) 136 137 defcontrast(self,contrast): 138 self.write_cmd(_SET_CONTRAST) 139 self.write_cmd(contrast) 140 141 definvert(self,invert): 142 self.write_cmd(_SET_NORM_INV|(invert&1)) 143 144 defshow(self): 145 forpageinrange(self.height//8): 146 self.write_cmd(_SET_PAGE_ADDRESS|page) 147 self.write_cmd(_LOW_COLUMN_ADDRESS|2) 148 self.write_cmd(_HIGH_COLUMN_ADDRESS|0) UsingaSH1106-basedOLEDgraphicsdisplay 37 RaspberryPiPicoPythonSDK 149 self.write_data(self.buffer[ 150 self.width*page:self.width*page+self.width 151 ]) 152 153 defreset(self,res): 154 ifresisnotNone: 155 res
(1) 156 time.sleep_ms
(1) 157 res
(0) 158 time.sleep_ms(20) 159 res
(1) 160 time.sleep_ms(20) 161 162 163classSH1106_I2C(SH1106): 164 def__init__(self,width,height,i2c,res=None,addr=0x3c, 165 external_=False): 166 self.i2c=i2c 167 self.addr=addr 168 self.res=res 169 self.temp=bytearray
(2) 170 ifresisnotNone: 171 res.init(res.OUT,value=1) 172 super().__init__(width,height,external_) 173 174 defwrite_cmd(self,cmd): 175 self.temp[0]=0x80#Co=
1,D/C#=
0 176 self.temp[1]=cmd 177 self.i2c.writeto(self.addr,self.temp) 178 179 defwrite_data(self,buf): 180 self.i2c.writeto(self.addr,b'\x40'+buf) 181 182 defreset(self): 183 super().reset(self.res) 184 185 186classSH1106_SPI(SH1106): 187 def__init__(self,width,height,spi,dc,res=None,cs=None, 188 external_=False): 189 self.rate=10*1000*1000 190 dc.init(dc.OUT,value=0) 191 ifresisnotNone: 192 res.init(res.OUT,value=0) 193 ifcsisnotNone: 194 cs.init(cs.OUT,value=1) 195 self.spi=spi 196 self.dc=dc 197 self.res=res 198 self.cs=cs 199 super().__init__(width,height,external_) 200 201 defwrite_cmd(self,cmd): 202 self.spi.init(baudrate=self.rate,polarity=0,phase=0) 203 ifself.csisnotNone: 204 self.cs
(1) 205 self.dc
(0) 206 self.cs
(0) 207 self.spi.write(bytearray([cmd])) 208 self.cs
(1) 209 else: 210 self.dc
(0) 211 self.spi.write(bytearray([cmd])) UsingaSH1106-basedOLEDgraphicsdisplay 38 RaspberryPiPicoPythonSDK 212 213 defwrite_data(self,buf): 214 self.spi.init(baudrate=self.rate,polarity=0,phase=0) 215 ifself.csisnotNone: 216 self.cs
(1) 217 self.dc
(1) 218 self.cs
(0) 219 self.spi.write(buf) 220 self.cs
(1) 221 else: 222 self.dc
(1) 223 self.spi.write(buf) 224 225 defreset(self): 226 super().reset(self.res) BillofMaterials Table5.Alistofmaterialsrequiredfortheexample ItemBreadboardRaspberryPiPico Monochrome128x128I2COLEDDisplay Quantity11
1 Details genericpart /products/raspberry-pi-pico/ /products/1-12-oled-breakout?
variant=29421050757203 UsingPIOtodriveasetofNeoPixelRing(WS2812LEDs) CombinationofthePIOWS2812demowiththeAdafruit'essential'NeoPixelexamplecodetoshowoffcolorfills,chasesandofcoursearainbowswirlona16-LEDring. Wiringinformation SeeFigure8forwiringinstructions. Figure8.Wiringthe16-LEDNeoPixelRingtoPico UsingPIOtodriveasetofNeoPixelRing(WS2812LEDs) 39 RaspberryPiPicoPythonSDK ListofFiles Alistoffileswithdescriptionsoftheirfunction;neopixel_ring.py Theexamplecode. PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/pio/neopixel_ring/neopixel_ring.pyLines1-104 1#ExampleusingPIOtodriveasetofWS2812LEDs.
2 3importarray,time 4frommachineimportPin 5importrp2
6 7#ConfigurethenumberofWS2812LEDs. 8NUM_LEDS=16 9PIN_NUM=
6 10brightness=0.2 11 12@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW,out_shiftdir=rp2.PIO.SHIFT_LEFT,ull=True, pull_thresh=24) 13defws2812(): 14 T1=
2 15 T2=
5 16 T3=
3 17 wrap_target() 18 label("bitloop") 19 out(x,1) .side
(0)[T3-1] 20 jmp(not_x,"do_zero").side
(1)[T1-1] 21 jmp("bitloop") .side
(1)[T2-1] 22 label("do_zero") 23 nop() .side
(0)[T2-1] 24 wrap() 25 26 27#CreatetheStateMachinewiththews2812program,outputtingonpin 28sm=rp2.StateMachine(0,ws2812,freq=8_000_000,sideset_base=Pin(PIN_NUM)) 29 30#StarttheStateMachine,itwillwaitfordataonitsFIFO. 31sm.active
(1) 32 33#DisplayapatternontheLEDsviaanarrayofLEDRGBvalues. 34ar=array.array("I",[0for_inrange(NUM_LEDS)]) 35 36########################################################################## 37defpixels_show(): 38 dimmer_ar=array.array("I",[0for_inrange(NUM_LEDS)]) 39 fori,cinenumerate(ar): 40 r=int(((c>>8)&0xFF)*brightness) 41 g=int(((c>>16)&0xFF)*brightness) 42 b=int((c&0xFF)*brightness) 43 dimmer_ar[i]=(g<<16)+(r<<8)+b 44 sm.put(dimmer_ar,8) 45 time.sleep_ms(10) 46 47defpixels_set(i,color): 48 ar[i]=(color[1]<<16)+(color[0]<<8)+color[2] 49 50defpixels_fill(color): 51 foriinrange(len(ar)): 52 pixels_set(i,color) UsingPIOtodriveasetofNeoPixelRing(WS2812LEDs) 40 RaspberryPiPicoPythonSDK 53 54defcolor_chase(color,wait): 55 foriinrange(NUM_LEDS): 56 pixels_set(i,color) 57 time.sleep(wait) 58 pixels_show() 59 time.sleep(0.2) 60 61defwheel(pos): 62 #Inputavalue0to255togetacolorvalue. 63 #Thecoloursareatransitionr-g-b-backtor. 64 ifpos<0orpos>255: 65 return(0,0,0) 66 ifpos<85: 67 return(255-pos*3,pos*3,0) 68 ifpos<170: 69 pos-=85 70 return(0,255-pos*3,pos*3) 71 pos-=170 72 return(pos*3,0,255-pos*3) 73 74 75defrainbow_cycle(wait): 76 forjinrange(255): 77 foriinrange(NUM_LEDS): 78 rc_index=(i*256//NUM_LEDS)+j 79 pixels_set(i,wheel(rc_index&255)) 80 pixels_show() 81 time.sleep(wait) 82 83BLACK=(0,0,0) 84RED=(255,0,0) 85YELLOW=(255,150,0) 86GREEN=(0,255,0) 87CYAN=(0,255,255) 88BLUE=(0,0,255) 89PURPLE=(180,0,255) 90WHITE=(255,255,255) 91COLORS=(BLACK,RED,YELLOW,GREEN,CYAN,BLUE,PURPLE,WHITE) 92 93print("fills") 94forcolorinCOLORS: 95 pixels_fill(color) 96 pixels_show() 97 time.sleep(0.2) 98 99print("chases") 100forcolorinCOLORS: 101 color_chase(color,0.01) 102 103print("rainbow") 104rainbow_cycle
(0) BillofMaterials Table6.Alistofmaterialsrequiredfortheexample ItemBreadboard Quantity1 Detailsgenericpart UsingPIOtodriveasetofNeoPixelRing(WS2812LEDs) 41 RaspberryPiPicoPythonSDK RaspberryPiPico
1 NeoPixelRing
1 /products/raspberry-pi-pico/ /product/1463 UsingUARTontheRaspberryPiPico SenddatafromtheUART1porttotheUART0port.Otherthingstotry; uart0=UART
(0) whichwillopenaUARTconnectionatthedefaultbaudrateof115200,and uart0.readline() whichwillreaduntiltheCR(\r)andNL(\n)characters,thenreturntheline. Wiringinformation SeeFigure9forwiringinstructions. Figure9.WiringtwoofthePico’sportstogether.BesuretowireUART0TXtoUART1RXandUART0RXtoUART1TX. ListofFiles Alistoffileswithdescriptionsoftheirfunction;uart.py Theexamplecode. UsingUARTontheRaspberryPiPico 42 RaspberryPiPicoPythonSDK PicoMicroPythonExamples:/raspberrypi/pico-micropython-examples/tree/master/uart/loopback/uart.pyLines1-15 1frommachineimportUART,Pin 2importtime
3 4uart1=UART(1,baudrate=9600,tx=Pin
(8),rx=Pin
(9))
5 6uart0=UART(0,baudrate=9600,tx=Pin
(0),rx=Pin
(1))
7 8txData=b'helloworld\n\r' 9uart1.write(txData) 10time.sleep(0.1) 11rxData=bytes() 12whileuart0.any()>0: 13 rxData+=uart0.read
(1) 14 15print(rxData.decode('utf-8')) BillofMaterials Table7.Alistofmaterialsrequiredfortheexample ItemBreadboardRaspberryPiPico Quantity11 Detailsgenericpart/products/raspberry-pi-pico/ UsingUARTontheRaspberryPiPico 43 RaspberryPiPicoPythonSDK Table8.DocumentationReleaseHistory AppendixB:DocumentationReleaseHistory Release1.01.1 1.21.3 1.3.11.4 Date21/Jan/202126/Jan/2021 01/Feb/202123/Feb/2021 05/Mar/202107/Apr/2021 Description •Initialrelease •Minorcorrections•ExtrainformationaboutusingDMAwithADC•ClarifiedM0+andSIOCPUIDregisters•AddedmorediscussionofTimers•UpdateWindowsandmacOSbuildinstructions•RenamedbooksandoptimisedsizeofoutputPDFs •Minorcorrections•SmallimprovementstoPIOdocumentation•AddedmissingTIMER2andTIMER3registerstoDMA•ExplainedhowtogetMicroPythonREPLonUART•TopanytheV1.0.1releaseoftheCSDK •Minorcorrections•Changedfont•Additionaldocumentationonsink/sourcelimitsforRP2040•MajorimprovementstoSWDdocumentation•UpdatedMicroPythonbuildinstructions•MicroPythonUARTexamplecode•UpdatedThonnyinstructions•UpdatedProjectGeneratorinstructions•AddedaFAQdocument•AddederrataE7,E8andE9 •Minorcorrections•TopanytheV1.1.0releaseoftheCSDK•ImprovedMicroPythonUARTexample•ImprovedPinoutdiagram •Minorcorrections•AddederrataE10•NoteabouthowtoupdatetheCSDKfromGithub•TopanytheV1.1.2releaseoftheCSDK AppendixB:DocumentationReleaseHistory 44 RaspberryPiPicoPythonSDK Release1.4.11.51.61.6.11.7.0 1.7.1 Date13/Apr/202107/Jun/202123/Jun/202130/Sep/202103/Nov/2021 04/Nov/2021 Description •Minorcorrections•Clarifiedthatallsourcecodeinthedocumentationisunderthe 3-ClauseBSDlicense. •Minorupdatesandcorrections•UpdatedFAQ•AddedSDKreleasehistory•TopanytheV1.2.0releaseoftheCSDK •Minorupdatesandcorrections•ADCinformationupdated•AddederrataE11 •Minorupdatesandcorrections•InformationaboutB2release•UpdatederrataforB2release •Minorupdatesandcorrections•Fixedsomeregisteresstypesanddescriptions•Addedcore1launchsequenceinfo•DescribedSDK"panic"handling•Updatedpicotooldocumentation•AdditionalexamplesaddedtoAppendixA:AppNotesappendix intheRaspberryPiPicoC/C++SDKbook •TopanytheV1.3.0releaseoftheCSDK •Minorupdatesandcorrections•BetterdocumentationofUSBdoublebuffering•Picoprobebranchchanges•Updatedlinkstodocumentation Thelatestreleasecanbefoundat/pico/raspberry-pi-pico-python-sdk.pdf. AppendixB:DocumentationReleaseHistory 45

标签: #怎么看 #换行 #邮箱 #cdr #平局 #雷暴 #csgo #枪法