1.1
1.2
2.1
2.2
2.2.1
2.2.2
2.2.3
2.2.4
2.2.5
2.2.6
2.3
2.3.1
2.3.2
2.3.3
2.4
2.4.1
2.4.2
2.4.3
2.4.4
2.4.4.1
2.4.4.2
2.4.5
2.4.6
2.5
2.5.1
TableofContents
About
Preface
PycomProducts
1.GettingStarted
1.0Introduction
1.1HardwareSetup
1.1.1LoPy
1.1.2LoPy4
1.1.1SiPy
1.1.1GPy
1.1.1FiPy
1.1.1WiPy
1.2Software
1.2.1Drivers
1.2.2UpdatingFirmware
1.2.3Pymakr
1.3Programmingthemodules
1.3.1IntroductiontoMicroPython
1.3.2MicroPythonExamples
1.3.3YourfirstPymakrproject
1.3.4REPL
1.3.4.1SerialUSB
1.3.4.2Telnet
1.3.5FTP
1.3.6Safeboot
1.4DeviceRegistration
1.4.1Sigfox
1
2.5.2
2.5.3
2.5.3.1
2.5.3.2
3.1
3.1.1
3.1.2
3.2
3.3
4.1
4.2
4.2.1
4.2.2
4.2.3
4.3
4.3.1
4.3.2
4.3.3
5.1
5.2
5.2.1
5.2.2
5.2.3
5.2.4
5.2.5
1.4.2Cellular
1.4.3LoRaWAN
1.4.3.2TheThingsNetwork
1.4.3.2Objenious
2.PymakrPlugin
2.1Installation
2.1.1Atom
2.1.2VisualStudioCode
2.2Tools/Features
2.3Settings
3.Pysense&Pytrack
3.1Introduction
3.2InstallingSoftware
3.2.1UpdatingFirmware
3.2.2InstallingDrivers-Windows7
3.2.3InstallingLibraries
3.3APIReference
3.3.1Pytrack
3.3.2Pysense
3.3.3Sleep
4.Tutorials&Examples
4.1Introduction
4.2AllPycomDeviceExamples
4.2.1REPL
4.2.2WLAN
4.2.3Bluetooth
4.2.4HTTPS
4.2.5MQTT
2
5.2.6
5.2.7
5.2.8
5.2.9
5.2.10
5.2.11
5.2.12
5.2.13
5.2.14
5.2.15
5.2.16
5.3
5.3.1
5.3.2
5.3.3
5.3.4
5.3.5
5.3.6
5.3.7
5.4
5.4.1
5.4.2
5.5
5.5.1
5.5.2
5.5.3
5.5.4
5.6
5.7
6.1
6.2
4.2.6AWS
4.2.7ADC
4.2.8I2C
4.2.9OnewireDriver
4.2.10Threading
4.2.11RGBLED
4.2.12Timers
4.2.13PIRSensor
4.2.14Modbus
4.2.15OTAupdate
4.2.16RMT
4.3LoRaExamples
4.3.1LoRa-MAC(RawLoRa)
4.3.2LoRaWANwithOTAA
4.3.3LoRaWANwithABP
4.3.4LoRa-MACNano-Gateway
4.3.5LoPytoLoPy
4.3.6LoRaWANNano-Gateway
4.3.7RN2483toLoPy
4.4SigfoxExamples
4.4.1RegisterDevice
4.4.2DisengageSequenceNumber
4.5LTEExamples
4.5.1CAT-M1
4.5.2NB-IoT
4.5.3ModuleIMEI
4.5.3ModemFirmwareUpdate
4.6PytrackExamples
4.7PysenseExamples
5.Firmware&APIReference
5.1Introduction
5.2PycomModules
3
6.2.1
6.2.1.1
6.2.1.2
6.2.1.3
6.2.1.4
6.2.1.5
6.2.1.6
6.2.1.7
6.2.1.8
6.2.1.9
6.2.1.10
6.2.1.11
6.2.1.12
6.2.1.13
6.2.2
6.2.2.1
6.2.2.2
6.2.2.3
6.2.2.3.1
6.2.2.3.2
6.2.2.3.3
6.2.2.3.4
6.2.2.3.5
6.2.2.3.6
6.2.2.4
6.2.2.5
6.2.2.6
6.2.3
6.2.4
6.3
6.3.1
6.3.2
6.3.3
6.3.4
5.2.1machine
5.2.1.1ADC
5.2.1.2DAC
5.2.1.3I2C
5.2.1.4Pin
5.2.1.5PWM
5.2.1.6RTC
5.2.1.7SPI
5.2.1.8UART
5.2.1.9WDT
5.2.1.10Timer
5.2.1.11SD
5.2.1.12CAN
5.2.1.13RMT
5.2.2network
5.2.2.1WLAN
5.2.2.2Server
5.2.2.3Bluetooth
5.2.2.3.1GATT
5.2.2.3.2GATTCConnection
5.2.2.3.3GATTCService
5.2.2.3.4GATTCCharacteristic
5.2.2.3.5GATTSService
5.2.2.3.6GATTSCharacteristic
5.2.2.4LoRa
5.2.2.5Sigfox
5.2.2.6LTE
5.2.3AES
5.2.4pycom
5.3MicroPythonModules
5.3.1micropython
5.3.2uctypes
5.3.3sys
5.3.4uos
4
6.3.5
6.3.6
6.3.7
6.3.8
6.3.9
6.3.10
6.3.11
6.3.12
6.3.13
6.3.14
6.3.15
6.3.16
6.3.17
6.3.18
6.3.19
6.3.20
7.1
7.2
7.2.1
7.2.2
7.2.3
7.2.4
7.2.5
7.2.6
7.2.7
7.3
7.3.1
7.3.2
7.3.3
7.3.4
5.3.5array
5.3.6cmath
5.3.7math
5.3.8gc
5.3.9ubinascii
5.3.10ujson
5.3.11ure
5.3.12usocket
5.3.13select
5.3.14utime
5.3.15uhashlib
5.3.16ussl
5.3.17ucrypto
5.3.18ustruct
5.3.19_thread
5.3.20Builtin
6.ProductInfo
6.0Introduction
6.1DevelopmentModules
6.1.1WiPy2.0
6.1.2WiPy3.0
6.1.3LoPy
6.1.4LoPy4
6.1.5SiPy
6.1.6GPy
6.1.7FiPy
6.2OEMModules
6.2.1W01
6.2.2L01
6.2.3L04
6.2.4G01
5
7.3.5
7.3.6
7.4
7.4.1
7.4.2
7.4.3
7.4.4
7.4.5
7.4.6
7.4.6.1
7.5
8.1
8.1.1
8.1.2
8.1.3
8.1.4
8.1.5
8.1.6
8.1.7
8.2
8.2.1
8.2.2
8.2.3
8.2.4
8.3
8.3.1
8.3.2
8.3.3
8.3.4
6.2.5L01OEMBaseboardReference
6.2.6UniversalOEMBaseboardReference
6.3ExpansionBoardsandShields
6.3.1ExpansionBoard3.0
6.3.2Pytrack
6.3.3Pysense
6.3.4Pyscan
6.3.5ExpansionBoard2.0
6.3.6DeepSleepShield
6.3.6.1DeepSleepAPI
6.4Notes
7.Datasheets
7.1DevelopmentModules
7.1.1WiPy2.0
7.1.2WiPy3.0
7.1.3LoPy
7.1.4LoPy4
7.1.5SiPy
7.1.6GPy
7.1.7FiPy
7.2OEMModules
7.2.1W01
7.2.2L01
7.2.3L04
7.2.4G01
7.3ExpansionBoardsandShields
7.3.1ExpansionBoard3.0
7.3.2Pytrack
7.3.3Pysense
7.3.4ExpansionBoard2.0
6
9.1
9.2
9.3
9.3.1
9.3.2
9.4
10.1
10.2
10.3
11.1
11.2
11.3
12.1
8.Pybytes
8.1Introduction
8.2GettingStarted
8.3AddadevicetoPybytes
8.3.1ConnecttoPybytes:QuickAdd
8.3.2ConnecttoPybytes:FlashPybyteslibrarymanually
8.4Visualisedatafromyourdevice
9.DocumentationNotes
9.1Introduction
9.2Syntax
9.3REPLvsScripts
10.AdvancedTopics
10.1FirmwareDowngrade
10.2CLIUpdater
10.3SecureBootandEncryption
11.License
11.1License
7
PycomDocumentation
WelcometothePycomdocumentationsite.Thedocumentationissplitinto5sections;we
recommendreadingthroughallthesectionstofamiliariseyourselfwiththevarioustoolsand
featuresavailabletoyoutohelpyoudeveloponyourPycommodule.
Togetstarted,readthroughtheGettingStartedGuidethenfeelfreetojumpstraightintothe
tutorialsandexamplesinTutorials&Examplestobeginbuildingyourprojects.
Products
GettingStarted
Tutorials
Preface
8
ProductInfo
APIDocumentation
Pybytes
Preface
9
PycomProducts
BelowyouwillfindtablesofallPycomproducts.Thesetablesillustratethefunctionalityof
ourvariousproducts,theircompatibilitywitheachother,aswellaswhataccessoriesare
requiredtoutilisecertainfunctionality.
DevelopmentBoards
PycomProducts
10
Module WiFi Bluetooth LoRa Sigfox LTECAT-M1
NB-IoT
WiPy3.0
SiPy
GPy
LoPy
LoPy4
FiPy
Antennas
ExternalWiFi/BT
AntennaKit
LoRa&Sigfox
AntennaKit
LTE-M
AntennaKit
Accessories
Accessory
Expansion
PycomProducts
11
Board Pysense Pytrack Pyscan
PyCase
IP67Casefor
ExpansionBoard
IP67Casefor
Pysense/Pytrack/Pyscan
✔✔✔
IP67Case
(universal)
LiPoBattery
(user-supplied)
MicroUSBCable
Required
(user-supplied)
PycomProducts
12
PyscanModules
OLED
Module 2MPCamera Barcode
Reader
Fingerprint
Scanner IRImage
Sensor
OEMModules
PycomProducts
13
OEMModule
L01/W01ReferenceBoard UniversalReferenceBoard
W01
L01
L04
G01
PycomProducts
14
GettingStarted
So,you'vedecidedtoorderaPycomdevelopmentmodule.Firstlywewouldliketo
congratulateyouinmakinganexcellentdecision.Ifyouhaven'tyetplacedyourorderwe
highlyrecommendyoucheckouttheproductspagebeforeyouplaceyourordertoensure
youknowwhichaccessoriesyoumightrequire.
Step1:Settingupthehardware
Inthefirstpartofthisgettingstartedguide,wewilltakeyouthroughsettingupyourdevice.
FirstlywewillcoverhowtoconnectthemoduletoyourcomputereitherviaUSBorWiFi.
SecondlywewillexplainhowtoconnectvariousaccessoriessuchasantennasorSIMcards
toyourmodule.
Step2:Settingupyourcomputer
Nowthatyourmoduleissuccessfullyconnected,youwillneedtoinstallsomesoftwareon
yourcomputertointerfacewithit.Thesecondpartofthisguidewillguideyouthrough
installingdrivers;performingfirmwareupdatesforyourmodule/accessoriestoensureyou
havethemoststableandfeaturepackedversion;andhowtosetupthesoftwareuseto
programthedevice.
1.0Introduction
15
Step3:Usingyourmodule
Nowthatyouhaveaconnectedmoduleandalltherequiredsoftwareinstalleditistimeto
beginprogrammingyourdevice.Thispartoftheguidewillgetyoustartedwithabasic
exampleandpointyouintherightdirectionforgettingyourdeviceconnectedtoyourchosen
network.
Step4:Connectingtoanetwork
Nowthatyoufamiliarwithprogrammingyourdeviceyouwillnodoubtbekeentogetit
connectedtooneoftheadvertisedwirelessnetworks.Thisusuallyrequiressome
registration.Thisstepwilldetailhowtogetregisteredandconnectedtovariouswireless
networks.
Youcannavigatethroughthisguideusingthearrowbuttonsontheleftandrightofthe
screen(oratthebottomifyouareusingmobile).
1.0Introduction
16
Settingupthehardware
ThischapterofthedocumentationwillshowyouhowtoconnectyouPycommodule.For
eachdevicetherearedetailedinstructionsonhowtoconnectyourmoduletooneofour
baseboards,aUSBUARTadapterorWiFiaswellaswhatantennasyoumightneedto
connect.Pleaseselectyourmodulebelowtobetakentotheappropriateguide.
1.1HardwareSetup
17
1.1HardwareSetup
18
1.1HardwareSetup
19
LoPy
Basicconnection
ExpBoard2.0
ExpBoard3.0
Pysense/Pytrack/Pyscan
USBUARTAdapter
WiFi
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheLoPymoduleonthetheexpansionboardwiththeresetbuttonpointing
towardstheUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnowno
longerbevisible.
BeforeconnectingyourmoduletoanExpansionBoard3.0,youshouldupdatethe
firmwareontheExpansionBoard3.0.Instructionsonhowtodothiscanbefoundhere.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
1.1.1LoPy
20
LocatetheUSBconnectorontheexpansionboard.
InserttheLoPymoduleontheExpansionBoardwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
BeforeconnectingyourmoduletoaPysense/Pytrack/Pyscanboard,youshouldupdate
thefirmwareonthePysense/Pytrack/Pyscan.Instructionsonhowtodothiscanbe
foundhere.
LookfortheresetbuttonontheLoPymodule(locatedatacorneroftheboard,nextto
theLED).
LocatetheUSBconnectoronthePysense/Pytrack/Pyscan.
InsertthemoduleonthePysense/Pytrack/Pyscanwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
1.1.1LoPy
21
Onceyouhavecompletedtheabovestepssuccessfullyyoushouldseetheon-boardLED
blinkingblue.Thisindicatesthedeviceispoweredupandrunning.
FirstlyyouwillneedtoconnectpowertoyourLoPy.Youwillneedtosupply
3.5v-5.5vtothe Vinpin.Note:Donotfeed 3.3vdirectlytothe 3.3vsupplypin,
thiswilldamagetheregulator.
Theconnectthe RXand TXofyourUSBUARTtothe TXand RXoftheLoPy
respectively.Note:PleaseensureyouhavethesignalleveloftheUARTadaptersetto
3.3vbeforeconnectingit.
InordertoputtheLoPyintobootloadermodetoupdatethedevicefirmwareyouwill
needtoconnect P2to GND.Werecommendyouconnectabuttonbetweenthetwoto
makethissimpler.
Note:Thismethodofconnectionisnotrecommendedforfirsttimeusers.Itispossibleto
lockyourselfoutofthedevice,requiringaUSBconnection.
1.1.1LoPy
22
InordertoaccesstheLoPyviaWiFiyouonlyneedtoprovide 3.5v- 5.5vonthe
VinpinoftheLoPy:
Bydefault,whentheLoPyboots,itwillcreateaWiFiaccesspointwiththefollowing
credentials:
SSID: lopy-wlan
password: www.pycom.io
OnceconnectedtothisnetworkyouwillbeabletoaccessthetelnetandFTP
serversrunningontheLoPy.Forbothofthesethelogindetailsare:
username: micro
password: python
Antennas
LoRa
IfyouintendonusingtheLoRaconnectivityoftheLoPyyoumustconnectaLoRa
antennatoyourLoPybeforetryingtouseLoRaotherwiseyouriskdamagingthedevice.
1.1.1LoPy
23
TheLoPyonlysupportsLoRaonthe868MHzor915MHzbands.Itdoesnotsupport
433MHz.ForthisyouwillrequireaLoPy4.
FirstlyyouwillneedtoconnecttheU.FLtoSMApigtailtotheLoPyusingtheU.FL
connectoronthesamesideoftheLoPyastheLED.
Ifyouareusingapycase,youwillnextneedtoputtheSMAconnectorthroughthe
antennahole,ensuringyoualigntheflatedgecorrectly,andscrewdowntheconnector
usingtheprovidednut.
FinallyyouwillneedtoscrewontheantennatotheSMAconnector.
WiFi/Bluetooth(optional)
AllPycommodules,includingtheLoPy,comewithaon-boardWiFiantennaaswellasa
U.FLconnectorforanexternalantenna.Theexternalantennaisoptionalandonlyrequiredif
youneedbetterperformanceoraremountingtheLoPyinsuchawaythattheWiFisignalis
1.1.1LoPy
24
blocked.Switchingbetweentheantennasisdoneviasoftware,instructionsforthiscanbe
foundhere.
DeepSleepcurrentissue
TheLoPy,SiPy,andWiPy2.0experienceanissuewherethemodulesmaintainahigh
currentconsumptionindeepsleepmode.Thisissuehasbeenresolvedinallnewer
products.ThecauseforthisissueistheDCtoDCswitchmodeconverterremainsinahigh
performancemodeevenwhenthedeviceisindeepsleep.Theflashmemorychipalsodoes
notpowerdown.Amoredetailedexplanationcanbefoundhere.
1.1.1LoPy
25
LoPy4
Basicconnection
ExpBoard2.0
ExpBoard3.0
Pysense/Pytrack/Pyscan
USBUARTAdapter
WiFi
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheLoPy4moduleonthetheexpansionboardwiththeresetbuttonpointing
towardstheUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnowno
longerbevisible.
BeforeconnectingyourmoduletoanExpansionBoard3.0,youshouldupdatethe
firmwareontheExpansionBoard3.0.Instructionsonhowtodothiscanbefoundhere.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
1.1.2LoPy4
26
LocatetheUSBconnectorontheexpansionboard.
InserttheLoPy4moduleontheExpansionBoardwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
BeforeconnectingyourmoduletoaPysense/Pytrack/Pyscanboard,youshouldupdate
thefirmwareonthePysense/Pytrack/Pyscan.Instructionsonhowtodothiscanbe
foundhere.
LookfortheresetbuttonontheLoPy4module(locatedatacorneroftheboard,nextto
theLED).
LocatetheUSBconnectoronthePysense/Pytrack/Pyscan.
InsertthemoduleonthePysense/Pytrack/Pyscanwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
1.1.2LoPy4
27
Onceyouhavecompletedtheabovestepssuccessfullyyoushouldseetheon-boardLED
blinkingblue.Thisindicatesthedeviceispoweredupandrunning.
FirstlyyouwillneedtoconnectpowertoyourLoPy4.Youwillneedtosupply
3.5v-5.5vtothe Vinpin.Note:Donotfeed 3.3vdirectlytothe 3.3vsupplypin,
thiswilldamagetheregulator.
Theconnectthe RXand TXofyourUSBUARTtothe TXand RXoftheLoPy4
respectively.Note:PleaseensureyouhavethesignalleveloftheUARTadaptersetto
3.3vbeforeconnectingit.
InordertoputtheLoPy4intobootloadermodetoupdatethedevicefirmwareyouwill
needtoconnect P2to GND.Werecommendyouconnectabuttonbetweenthetwoto
makethissimpler.
1.1.2LoPy4
28
Note:Thismethodofconnectionisnotrecommendedforfirsttimeusers.Itispossibleto
lockyourselfoutofthedevice,requiringaUSBconnection.
InordertoaccesstheLoPy4viaWiFiyouonlyneedtoprovide 3.5v- 5.5vonthe
VinpinoftheLoPy4:
Bydefault,whentheLoPy4boots,itwillcreateaWiFiaccesspointwiththefollowing
credentials:
SSID: lopy4-wlan
password: www.pycom.io
OnceconnectedtothisnetworkyouwillbeabletoaccessthetelnetandFTP
serversrunningontheLoPy4.Forbothofthesethelogindetailsare:
username: micro
password: python
Antennas
LoRa/Sigfox
IfyouintendonusingtheLoRa/SigfoxconnectivityoftheLoPy4youmustconnecta
LoRa/SigfoxantennatoyourLoPy4beforetryingtouseLoRa/Sigfoxotherwiseyourisk
damagingthedevice.
1.1.2LoPy4
29
FirstlyyouwillneedtoconnecttheU.FLtoSMApigtailtotheLoPy4usingoneofthe
twotheU.FLconnectorsonthesamesideoftheLoPy4astheLED.Theoneontheleft
handsideisfor433MHz(LoRaonly),theoneoftherighthandsideisfor
868MHz/915MHz(LoRa&Sigfox).Note:ThisisdifferentfromtheLoPy.
Ifyouareusingapycase,youwillnextneedtoputtheSMAconnectorthroughthe
antennahole,ensuringyoualigntheflatedgecorrectly,andscrewdowntheconnector
usingtheprovidednut.
FinallyyouwillneedtoscrewontheantennatotheSMAconnector.
WiFi/Bluetooth(optional)
1.1.2LoPy4
30
AllPycommodules,includingtheLoPy4,comewithaon-boardWiFiantennaaswellasa
U.FLconnectorforanexternalantenna.Theexternalantennaisoptionalandonlyrequiredif
youneedbetterperformanceoraremountingtheLoPy4insuchawaythattheWiFisignal
isblocked.Switchingbetweentheantennasisdoneviasoftware,instructionsforthiscanbe
foundhere.
1.1.2LoPy4
31
SiPy
Basicconnection
ExpBoard2.0
ExpBoard3.0
Pysense/Pytrack/Pyscan
USBUARTAdapter
WiFi
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheSiPymoduleonthetheexpansionboardwiththeresetbuttonpointing
towardstheUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnowno
longerbevisible.
BeforeconnectingyourmoduletoanExpansionBoard3.0,youshouldupdatethe
firmwareontheExpansionBoard3.0.Instructionsonhowtodothiscanbefoundhere.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
1.1.1SiPy
32
LocatetheUSBconnectorontheexpansionboard.
InserttheSiPymoduleontheExpansionBoardwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
BeforeconnectingyourmoduletoaPysense/Pytrack/Pyscanboard,youshouldupdate
thefirmwareonthePysense/Pytrack/Pyscan.Instructionsonhowtodothiscanbe
foundhere.
LookfortheresetbuttonontheSiPymodule(locatedatacorneroftheboard,nextto
theLED).
LocatetheUSBconnectoronthePysense/Pytrack/Pyscan.
InsertthemoduleonthePysense/Pytrack/Pyscanwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
1.1.1SiPy
33
Onceyouhavecompletedtheabovestepssuccessfullyyoushouldseetheon-boardLED
blinkingblue.Thisindicatesthedeviceispoweredupandrunning.
FirstlyyouwillneedtoconnectpowertoyourSiPy.Youwillneedtosupply 3.5v-5.5v
tothe Vinpin.Note:Donotfeed 3.3vdirectlytothe 3.3vsupplypin,thiswill
damagetheregulator.
Theconnectthe RXand TXofyourUSBUARTtothe TXand RXoftheSiPy
respectively.Note:PleaseensureyouhavethesignalleveloftheUARTadaptersetto
3.3vbeforeconnectingit.
InordertoputtheSiPyintobootloadermodetoupdatethedevicefirmwareyouwill
needtoconnect P2to GND.Werecommendyouconnectabuttonbetweenthetwoto
makethissimpler.
Note:Thismethodofconnectionisnotrecommendedforfirsttimeusers.Itispossibleto
lockyourselfoutofthedevice,requiringaUSBconnection.
1.1.1SiPy
34
InordertoaccesstheSiPyviaWiFiyouonlyneedtoprovide 3.5v- 5.5vonthe
VinpinoftheSiPy:
Bydefault,whentheSiPyboots,itwillcreateaWiFiaccesspointwiththefollowing
credentials:
SSID: sipy-wlan
password: www.pycom.io
OnceconnectedtothisnetworkyouwillbeabletoaccessthetelnetandFTP
serversrunningontheSiPy.Forbothofthesethelogindetailsare:
username: micro
password: python
Antennas
Sigfox
IfyouintendonusingtheSigfoxconnectivityoftheSiPyyoumustconnectaSigfox
antennatoyourSiPybeforetryingtouseSigfoxotherwiseyouriskdamagingthe
device.
FirstlyyouwillneedtoconnecttheU.FLtoSMApigtailtotheSiPyusingtheU.FL
1.1.1SiPy
35
connectoronthesamesideoftheSiPyastheLED.
Ifyouareusingapycase,youwillnextneedtoputtheSMAconnectorthroughthe
antennahole,ensuringyoualigntheflatedgecorrectly,andscrewdowntheconnector
usingtheprovidednut.
FinallyyouwillneedtoscrewontheantennatotheSMAconnector.
WiFi/Bluetooth(optional)
AllPycommodules,includingtheSiPy,comewithaon-boardWiFiantennaaswellasa
U.FLconnectorforanexternalantenna.Theexternalantennaisoptionalandonlyrequiredif
youneedbetterperformanceoraremountingtheSiPyinsuchawaythattheWiFisignalis
blocked.Switchingbetweentheantennasisdoneviasoftware,instructionsforthiscanbe
foundhere.
1.1.1SiPy
36
DeepSleepcurrentissue
TheLoPy,SiPy,andWiPy2.0experienceanissuewherethemodulesmaintainahigh
currentconsumptionindeepsleepmode.Thisissuehasbeenresolvedinallnewer
products.ThecauseforthisissueistheDCtoDCswitchmodeconverterremainsinahigh
performancemodeevenwhenthedeviceisindeepsleep.Theflashmemorychipalsodoes
notpowerdown.Amoredetailedexplanationcanbefoundhere.
1.1.1SiPy
37
GPy
Basicconnection
ExpBoard2.0
ExpBoard3.0
Pysense/Pytrack/Pyscan
USBUARTAdapter
WiFi
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheGPymoduleonthetheexpansionboardwiththeresetbuttonpointing
towardstheUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnowno
longerbevisible.
BeforeconnectingyourmoduletoanExpansionBoard3.0,youshouldupdatethe
firmwareontheExpansionBoard3.0.Instructionsonhowtodothiscanbefoundhere.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
1.1.1GPy
38
LocatetheUSBconnectorontheexpansionboard.
InserttheGPymoduleontheExpansionBoardwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
BeforeconnectingyourmoduletoaPysense/Pytrack/Pyscanboard,youshouldupdate
thefirmwareonthePysense/Pytrack/Pyscan.Instructionsonhowtodothiscanbe
foundhere.
LookfortheresetbuttonontheGPymodule(locatedatacorneroftheboard,nextto
theLED).
LocatetheUSBconnectoronthePysense/Pytrack/Pyscan.
InsertthemoduleonthePysense/Pytrack/Pyscanwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
1.1.1GPy
39
Onceyouhavecompletedtheabovestepssuccessfullyyoushouldseetheon-boardLED
blinkingblue.Thisindicatesthedeviceispoweredupandrunning.
FirstlyyouwillneedtoconnectpowertoyourGPy.Youwillneedtosupply 3.5v-5.5v
tothe Vinpin.Note:Donotfeed 3.3vdirectlytothe 3.3vsupplypin,thiswill
damagetheregulator.
Theconnectthe RXand TXofyourUSBUARTtothe TXand RXoftheGPy
respectively.Note:PleaseensureyouhavethesignalleveloftheUARTadaptersetto
3.3vbeforeconnectingit.
InordertoputtheGPyintobootloadermodetoupdatethedevicefirmwareyouwill
needtoconnect P2to GND.Werecommendyouconnectabuttonbetweenthetwoto
makethissimpler.
1.1.1GPy
40
Note:Thismethodofconnectionisnotrecommendedforfirsttimeusers.Itispossibleto
lockyourselfoutofthedevice,requiringaUSBconnection.
InordertoaccesstheGPyviaWiFiyouonlyneedtoprovide 3.5v- 5.5vonthe
VinpinoftheGPy:
Bydefault,whentheGPyboots,itwillcreateaWiFiaccesspointwiththefollowing
credentials:
SSID: gpy-wlan
password: www.pycom.io
OnceconnectedtothisnetworkyouwillbeabletoaccessthetelnetandFTP
serversrunningontheGPy.Forbothofthesethelogindetailsare:
username: micro
password: python
Antennas
LTECat-M1/NB-IoT
IfyouintendonusingtheLTECAT-M1orNB-IoTconnectivityoftheGPyyoumustconnect
aLTECAT-M1/NB-IoTantennatoyourGPybeforetryingtouseLTECat-M1orNB-IoT
otherwiseyouriskdamagingthedevice.
1.1.1GPy
41
YouwillneedtoconnecttheantennatotheGPyusingtheU.FLconnectoronthesame
sideoftheGPyastheLED.
WiFi/Bluetooth(optional)
AllPycommodules,includingtheGPy,comewithaon-boardWiFiantennaaswellasa
U.FLconnectorforanexternalantenna.Theexternalantennaisoptionalandonlyrequiredif
youneedbetterperformanceoraremountingtheGPyinsuchawaythattheWiFisignalis
blocked.Switchingbetweentheantennasisdoneviasoftware,instructionsforthiscanbe
foundhere.
1.1.1GPy
42
SIMcard
IfyouintendonusingtheLTECAT-M1orNB-IoTconnectivityoftheGPyyouwillneedto
insertaSIMcardintoyourGPy.ItshouldbenotedthattheGPydoesnotsupportregular
LTEconnectivityandyoumayrequireaspecialSIM.Itisbesttocontactyourlocalcellular
providersformoreinformationonacquiringaLTECAT-M1/NB-IoTenablednanoSIM.
1.1.1GPy
43
FiPy
Basicconnection
ExpBoard2.0
ExpBoard3.0
Pysense/Pytrack/Pyscan
USBUARTAdapter
WiFi
WhenusingtheexpansionboardwithaFiPy,youwillneedtoremovetheCTSandRTS
jumpersastheseinterferewithcommunicationwiththecellularmodem.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheFiPymoduleonthetheexpansionboardwiththeresetbuttonpointing
towardstheUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnowno
longerbevisible.
BeforeconnectingyourmoduletoanExpansionBoard3.0,youshouldupdatethe
firmwareontheExpansionBoard3.0.Instructionsonhowtodothiscanbefoundhere.
1.1.1FiPy
44
WhenusingtheexpansionboardwithaFiPy,youwillneedtoremovetheCTSandRTS
jumpersastheseinterferewithcommunicationwiththecellularmodem.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheFiPymoduleontheExpansionBoardwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
BeforeconnectingyourmoduletoaPysense/Pytrack/Pyscanboard,youshouldupdate
thefirmwareonthePysense/Pytrack/Pyscan.Instructionsonhowtodothiscanbe
foundhere.
LookfortheresetbuttonontheFiPymodule(locatedatacorneroftheboard,nextto
theLED).
LocatetheUSBconnectoronthePysense/Pytrack/Pyscan.
InsertthemoduleonthePysense/Pytrack/Pyscanwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
1.1.1FiPy
45
Onceyouhavecompletedtheabovestepssuccessfullyyoushouldseetheon-boardLED
blinkingblue.Thisindicatesthedeviceispoweredupandrunning.
FirstlyyouwillneedtoconnectpowertoyourFiPy.Youwillneedtosupply 3.5v-5.5v
tothe Vinpin.Note:Donotfeed 3.3vdirectlytothe 3.3vsupplypin,thiswill
damagetheregulator.
Theconnectthe RXand TXofyourUSBUARTtothe TXand RXoftheFiPy
respectively.Note:PleaseensureyouhavethesignalleveloftheUARTadaptersetto
3.3vbeforeconnectingit.
InordertoputtheFiPyintobootloadermodetoupdatethedevicefirmwareyouwill
needtoconnect P2to GND.Werecommendyouconnectabuttonbetweenthetwoto
makethissimpler.
Note:Thismethodofconnectionisnotrecommendedforfirsttimeusers.Itispossibleto
lockyourselfoutofthedevice,requiringaUSBconnection.
InordertoaccesstheFiPyviaWiFiyouonlyneedtoprovide 3.5v- 5.5vonthe
1.1.1FiPy
46
VinpinoftheFiPy:
Bydefault,whentheFiPyboots,itwillcreateaWiFiaccesspointwiththefollowing
credentials:
SSID: fipy-wlan
password: www.pycom.io
OnceconnectedtothisnetworkyouwillbeabletoaccessthetelnetandFTP
serversrunningontheFiPy.Forbothofthesethelogindetailsare:
username: micro
password: python
Antennas
LoRa/Sigfox
IfyouintendonusingtheLoRa/SigfoxconnectivityoftheFiPyyoumustconnecta
LoRa/SigfoxantennatoyourFiPybeforetryingtouseLoRa/Sigfoxotherwiseyourisk
damagingthedevice.
1.1.1FiPy
47
TheFiPyonlysupportsLoRaonthe868MHzor915MHzbands.Itdoesnotsupport
433MHz.ForthisyouwillrequireaLoPy4.
FirstlyyouwillneedtoconnecttheU.FLtoSMApigtailtotheFiPyusingtheU.FL
connectoronthesamesideoftheFiPyastheLED.
Ifyouareusingapycase,youwillnextneedtoputtheSMAconnectorthroughthe
antennahole,ensuringyoualigntheflatedgecorrectly,andscrewdowntheconnector
usingtheprovidednut.
FinallyyouwillneedtoscrewontheantennatotheSMAconnector.
LTECat-M1/NB-IoT
IfyouintendonusingtheLTECAT-M1orNB-IoTconnectivityoftheFiPyyoumustconnect
aLTECAT-M1/NB-IoTantennatoyourFiPybeforetryingtouseLTECat-M1orNB-IoT
otherwiseyouriskdamagingthedevice.
1.1.1FiPy
48
YouwillneedtoconnecttheantennatotheFiPyusingtheU.FLconnectorontheunder
sideoftheFiPy.
WiFi/Bluetooth(optional)
AllPycommodules,includingtheFiPy,comewithaon-boardWiFiantennaaswellasa
U.FLconnectorforanexternalantenna.Theexternalantennaisoptionalandonlyrequiredif
youneedbetterperformanceoraremountingtheFiPyinsuchawaythattheWiFisignalis
blocked.Switchingbetweentheantennasisdoneviasoftware,instructionsforthiscanbe
foundhere.
1.1.1FiPy
49
SIMcard
IfyouintendonusingtheLTECAT-M1orNB-IoTconnectivityoftheFiPyyouwillneedto
insertaSIMcardintoyourFiPy.ItshouldbenotedthattheFiPydoesnotsupportregular
LTEconnectivityandyoumayrequireaspecialSIM.Itisbesttocontactyourlocalcellular
providersformoreinformationonacquiringaLTECAT-M1/NB-IoTenablednanoSIM.
1.1.1FiPy
50
WiPy
Basicconnection
ExpBoard2.0
ExpBoard3.0
Pysense/Pytrack/Pyscan
USBUARTAdapter
WiFi
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
LocatetheUSBconnectorontheexpansionboard.
InserttheWiPymoduleonthetheexpansionboardwiththeresetbuttonpointing
towardstheUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnowno
longerbevisible.
BeforeconnectingyourmoduletoanExpansionBoard3.0,youshouldupdatethe
firmwareontheExpansionBoard3.0.Instructionsonhowtodothiscanbefoundhere.
Lookfortheresetbuttononthemodule(locatedatacorneroftheboard,nexttothe
LED).
1.1.1WiPy
51
LocatetheUSBconnectorontheexpansionboard.
InserttheWiPymoduleontheExpansionBoardwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
BeforeconnectingyourmoduletoaPysense/Pytrack/Pyscanboard,youshouldupdate
thefirmwareonthePysense/Pytrack/Pyscan.Instructionsonhowtodothiscanbe
foundhere.
LookfortheresetbuttonontheWiPymodule(locatedatacorneroftheboard,nextto
theLED).
LocatetheUSBconnectoronthePysense/Pytrack/Pyscan.
InsertthemoduleonthePysense/Pytrack/Pyscanwiththeresetbuttonpointingtowards
theUSBconnector.Itshouldfirmlyclickintoplaceandthepinsshouldnownolonger
bevisible.
1.1.1WiPy
52
Onceyouhavecompletedtheabovestepssuccessfullyyoushouldseetheon-boardLED
blinkingblue.Thisindicatesthedeviceispoweredupandrunning.
FirstlyyouwillneedtoconnectpowertoyourWiPy.Youwillneedtosupply
3.5v-5.5vtothe Vinpin.Note:Donotfeed 3.3vdirectlytothe 3.3vsupplypin,
thiswilldamagetheregulator.
Theconnectthe RXand TXofyourUSBUARTtothe TXand RXoftheWiPy
respectively.Note:PleaseensureyouhavethesignalleveloftheUARTadaptersetto
3.3vbeforeconnectingit.
InordertoputtheWiPyintobootloadermodetoupdatethedevicefirmwareyouwill
needtoconnect P2to GND.Werecommendyouconnectabuttonbetweenthetwoto
makethissimpler.
Note:Thismethodofconnectionisnotrecommendedforfirsttimeusers.Itispossibleto
lockyourselfoutofthedevice,requiringaUSBconnection.
1.1.1WiPy
53
InordertoaccesstheWiPyviaWiFiyouonlyneedtoprovide 3.5v- 5.5vonthe
VinpinoftheWiPy:
Bydefault,whentheWiPyboots,itwillcreateaWiFiaccesspointwiththefollowing
credentials:
SSID: wipy-wlan
password: www.pycom.io
OnceconnectedtothisnetworkyouwillbeabletoaccessthetelnetandFTP
serversrunningontheWiPy.Forbothofthesethelogindetailsare:
username: micro
password: python
Antennas
WiFi/Bluetooth(optional)
AllPycommodules,includingtheWiPy,comewithaon-boardWiFiantennaaswellasa
U.FLconnectorforanexternalantenna.Theexternalantennaisoptionalandonlyrequiredif
youneedbetterperformanceoraremountingtheWiPyinsuchawaythattheWiFisignalis
blocked.Switchingbetweentheantennasisdoneviasoftware,instructionsforthiscanbe
foundhere.
1.1.1WiPy
54
DeepSleepcurrentissue
TheLoPy,SiPy,andWiPy2.0experienceanissuewherethemodulesmaintainahigh
currentconsumptionindeepsleepmode.Thisissuehasbeenresolvedinallnewer
products.ThecauseforthisissueistheDCtoDCswitchmodeconverterremainsinahigh
performancemodeevenwhenthedeviceisindeepsleep.Theflashmemorychipalsodoes
notpowerdown.Amoredetailedexplanationcanbefoundhere.
WiPy2.0vsWiPy3.0
TheWiPy3.0isanupgradedversionoftheWiPy2.0withthefollowingchanges:
TheFLASHhasbeenupgradedfrom4MBto8MB.
TheRAMhasbeenupgradedfrom512KBto4MB.
Thedeepsleepcurrentconsumptionissuehasbeenfixed
TheantennaselectpinhasmovedtoGPIO21(P12)
1.1.1WiPy
55
Settingupyourcomputer
Togetyouupandrunning,Pycomprovidesasuiteoftoolstoassistwithdevelopingand
programmingyourPycomDevices:
1. Drivers:IfyouareusingMicrosoftWindows,youmightberequiredtoinstalldriversfor
ourproductstofunctioncorrectly.
2. Pycomfirmwareupdateutility:Thistoolautomatestheprocessofupgradingthe
firmwareofyourPycomdevice.Itisimportantthatyouusethistoolbeforeyouattempt
touseyourdevice.Notonlytoensureyouhavethemoststableandfeaturepacked
firmware,butalsotoensureallthefunctionalityofyourdeviceisenable.E.g.thistool
alsoactivatesyourtwoyearfreesigfoxconnectivity.
3. DevelopmentEnvironment:Pymakrisaplug-inforAtomandVisualStudioCode
developedbyPycomtomakedevelopmentforPycommodulessupereasy.Itallows
youtouseyourfavouritetexteditorwhilesimplifyingtheprocessofuploadingcodeto
thedevice.
1.2Software
56
Drivers
Linux
YoushouldnotneedtoinstallanydriversforourdevicestoberecognisedbyLinux.You
mayhoweverneedtoadjustpermissionstomakesureyouhaveaccesstotheserialport.
Onmostdistributionsthiscanbedonebyaddingyourusertothe dialoutusergroup.
Pleasecheckthespecificinstructionsforyourlinuxdistributionforhowtodothis.
macOS
OnmacOSyoushouldn'tneedtodoanythingspecialtogetourdevicetowork.
Windows
AllourproductswillworkoutoftheboxforWindows8/10/+.IfusingWindows7,driversto
supportthePysense/Pytrack/Pyscan/ExpansionBoard3.0boardswillneedtobeinstalled.
Download
Pleasedownloadthedriversoftwarefromthelinkbelow.
Pysense/Pytrack/Pyscan/ExpansionBoard3.0SerialDriver
Installation
FirstnavigateopentheWindowsstartmenuandsearch/navigateto`DeviceManager.You
shouldseeyourPytrack/Pysenseinthedropdownunderotherdevices.
1.2.1Drivers
57
Rightclickthedeviceandselect UpdateDriverSoftware.
SelecttheoptiontoBrowsemycomputerfordriversoftware.
1.2.1Drivers
58
Nextyouwillneedtonavigatetowhereyoudownloadedthedriverto(e.g.Downloads
Folder).
Specifythefolderinwhichthedriversarecontained.Ifyouhaven'textractedthe .zipfile,
pleasedothisbeforeselectingthefolder.
1.2.1Drivers
59
Youmayreceiveawarning,suggestingthatWindowscan'tverifythepublisherofthisdriver.
Click Installthisdriversoftwareanywayasthislinkpointstoourofficialdriver.
Iftheinstallationwassuccessful,youshouldnowseeawindowspecifyingthatthedriver
wascorrectlyinstalled.
1.2.1Drivers
60
Toconfirmthattheinstallationwascorrect,navigatebacktothe DeviceManagerandclick
thedropdownforotherdevices.Thewarninglabelshouldnowbegoneand
Pytrack/Pysenseshouldbeinstalled.
1.2.1Drivers
61
FirmwareUpdateTools
Westronglyrecommendyoutoupgradeyourfirmwaretothelatestversionasweare
constantlymakingimprovementsandaddingnewfeaturestothedevices.
Herearethedownloadlinkstotheupdatetool.Pleasedownloadtheappropriateonefor
yourOSandfollowtheinstructionsonthescreen.
Windows
macOS(10.11orHigher)
Linux(requires dialogand python-serialpackage)
Previousversionsoffirmwareareavailablefordownloadhere.
UpdatingDeviceFirmware
Thebasicfirmwareupgradeprocedurecanbefoundbelow,pleasefollowthesesteps
carefully:
ExpansionBoard2.0
Pysense/Pytrack/Pyscan/ExpansionBoard3.0
1. Disconnectyourdevicefromyourcomputer
2. InsertmoduleintotheExpansionBoard
3. Connectajumpercableorwirebetween G23and GND
4. ReconnecttheboardviaUSBtoyourcomputer,thisputsthedevicein‘firmwareupdate
mode’.
5. RuntheFirmwareUpgradetool
1.2.2UpdatingFirmware
62
6. Removethe G23to GNDjumpercable/wire
7. Rebootthedevice(buttonorpoweroffthenon),yourdeviceisnowreadytouse
Ifyouarehavinganyissues,makesuretheTXandRXjumpersarepresentonyour
ExpansionBoard,asthejumperssometimescomelooseintheboxduringtransport.
Withoutthesejumpers,theupdaterwillfail.
WhenusingaPysense/Pytrack/Pyscan/ExpansionBoard3.0toupdateyourmoduleyouare
notrequiredtomakeaconnectionbetween G23and GND,the
Pysense/Pytrack/Pyscan/ExpansionBoard3.0willdothisautomatically.
1. BeforeconnectingyourmoduletoaPysense/Pytrackboard,youshouldupdatethe
firmwareonthePysense/Pytrack.Instructionsonhowtodothiscanbefoundhere.
2. Disconnectyourdevicefromyourcomputer
3. InsertmoduleintoExpansionBoard
4. ReconnecttheboardviaUSBtoyourcomputer
5. RuntheFirmwareUpgradetool
1.2.2UpdatingFirmware
63
6. DisconnecttheUSBcablefromtheboardandreconnectit,yourdeviceisnowreadyto
use
Afteryou’redonewithupgrading,youcanusethePymakrPluginstouploadandrun
programsinyourdevice.
1.2.2UpdatingFirmware
64
PymakrPlugins
TomakeitaseasyaspossiblePycomhasdevelopedapluginfortwopopulartexteditors,
calledPymakr.Thesepluginshavebeenbuiltandareavailableforthefollowingplatforms:
1.2.3Pymakr
65
1.2.3Pymakr
66
Usingyourmodule
Nowthatyouhaveconnectedandupdatedyourpycommoduleandinstalledalltherequired
softwareonyourcomputer,wecanbeginprogrammingyourPycommodule.
IfthisisyourfirsttimeusingaPycommodulewehighlyrecommendyoureadthroughthe
followingpages:
IntroductiontoMicroPython:ThispagewillexplainwhatMicropythonisandits
relationtoPython.
MicroPythonExamples:WealsorecommendyoubrowsetheseshortMicroPython
examplestofamiliariseyourselfwithitssyntax.Thisisnotmeantasacomprehensive
guidetoMicroPythonprogrammingbutratherareferencetothosewhoalreadyknow
programming.Ifyouarenewtopython,orprogrammingalltogether,wehighly
recommendsearchingtheinternetforPythontutorials.Therearemanyverygood
tutorialsavailableforfreeandtheskillsyoulearnwillbeeasilytransferabletoour
platform.
YourfirstPymakrproject:OnceyouunderstandwhatMicroPythonis,thisguidewill
takeyouthroughsettingupyourfirstPymakrprojecttoblinktheon-boardRGBLED.
ThisguidewillexplainthestructureofaMicroPythonprojectaswellashowtouploadit
toyourmodule.
OnceyouarefamiliarwithMicroPythonandPymakr,therecommendedwayofuploading
codetoyourmodule,youcanexplorethepagesbelow.Thesewilldiscussingreaterdetail
thevariousmechanismsforrunningcodeonyourdeviceaswellashowtorecoveritif
somethinggoeswrong.
REPL:TheREPL(ReadEvaluatePrintLoop)isaninteractiveterminalthatallowsyou
totypeinandtestyourcodedirectlyonthedevice,justlikeinteractivepython
interpreter.ItcanbeaccessedviaUARTorTelnet.Thisisaccessedeasiestbyusing
Pymakrbutifyouwishtouseothertools,thispagewillexplainhow.
FTP:AllPycommodulesstartupwithaWiFiaccesspointenabled,andasimpleFTP
serverrunningonit.OnceconnectedtotheWiFinetwork,youcanuseFTPtotransfer
filesovertoyourdevicewirelessly.Thiscanbeveryusefulifyoudonothavephysical
accesstoyourdevice.
SafeBoot:Itispossiblethatsomecodeyouuploadtoyourmodulewillpreventyou
accessingtheREPLorFTPserver,preventingyoufromupdatingyourscripts.This
guidewilldetailhowtosafebootyourmoduleandhowtoremovetheoffendingscripts
1.3Programmingthemodules
67
fromit.
1.3Programmingthemodules
68
IntroductiontoMicroPython
OurboardsworkwithMicroPython;aPython3.5implementationthatisoptimisedtorunon
microcontrollers.Thisallowsformuchfasterandmoresimpledevelopmentprocessthan
usingC.
BootingintoMicroPython
Whenbooting,twofilesareexecutedautomatically:first boot.pyandthen main.py.These
areplacedinthe /flashfolderontheboard.Anyotherfilesorlibrariescanbeplacedhere
aswell,andcanbeincludedorusedfrom boot.pyor main.py.
Thefolderstructurein /flashlookslikethepicturebelow.Thefilescanbemanagedeither
usingFTPorusingthePymakrPlugin.
Tips&Tricks
MicropythonsharesmajorityofthesamesyntaxasPython3.5.Theintentionofthisdesign
istoprovidecompatibilityupwardsfromMicropythontoPython3.5,meaningthatcode
writtenforMicropythonshouldworkinasimilarmannerinPython3.5.Therearesomeminor
variationsandtheseshouldtakenviewedasimplementationdifferences.
1.3.1IntroductiontoMicroPython
69
MicropythonalsohasanumberofMicropythonspecificlibrariesforaccessinghardware
levelfeatures.SpecificsrelatingtothoselibrariescanbefoundintheFirmwareAPI
Referencesectionofthisdocumentation.
Micropython,unlikeC/C++orArduino,doesnotusebraces{}toindicateblocksof
codespecifiedforclassandfunctiondefinitionsorflowcontrol.Blocksofcodeare
denotedbylineindentation,whichisstrictlyenforced.
Thenumberofspacesintheindentationisvariablebutallstatementswithinablock
mustbeindentedthesameamount.
1.3.1IntroductiontoMicroPython
70
MicroPythonExamples
TogetyoustartedwithPython(MicroPython)syntax,we'veprovidedyouwithanumberof
codeexamples.
VariableAssignment
AswithPython3.5,variablescanbeassignedtoandreferenced.Belowisanexampleof
settingavariableequaltoastringandthenprintingittotheconsole.
variable="HelloWorld"
print(variable)
ConditionalStatements
Conditionalstatementsallowcontroloverwhichelementsofcoderundependingonspecific
cases.Theexamplebelowshowshowatemperaturesensormightbeimplementedincode.
temperature=15
target=10
iftemperature>target:
print("TooHigh!")
eliftemperature<target:
print("TooLow!")
else:
print("Justright!")
Loops(For&Whileloop)
Loopsareanotherimportantfeatureofanyprogramminglanguage.Thisallowsyoutocycle
yourcodeandrepeatfunctions/assignments/etc.
forloopsallowyoutocontrolhowmanytimesablockofcoderunsforwithinarange.
x=0
foryinrange(0,9):
x+=1
print(x)
1.3.2MicroPythonExamples
71
whileloopsaresimilarto forloops,howevertheyallowyoutorunaloopuntilaspecific
conditionalis true/false.Inthiscase,theloopchecksif xislessthan 9eachtimethe
looppasses.
x=0
whilex<9:
x+=1
print(x)
Functions
Functionsareblocksofcodethatarereferredtobyname.Datacanbepassedintoittobe
operatedon(i.e.theparameters)andcanoptionallyreturndata(thereturnvalue).Alldata
thatispassedtoafunctionisexplicitlypassed.
Thefunctionbelowtakestwonumbersandaddsthemtogether,outputtingtheresult.
defadd(number1,number2):
returnnumber1+number2
add(1,2)#expectaresultof3
Thenextfunctiontakesaninputnameandreturnsastringcontainingawelcomephrase.
defwelcome(name):
welcome_phrase="Hello,"+name+"!"
print(welcome_phrase)
welcome("Alex")#expect"Hello,Alex!"
DataStructures
Pythonhasanumberofdifferentdatastructuresforstoringandmanipulatingvariables.The
maindifference(regardingdatastructures)betweenCandPythonisthatPythonmanages
memoryforyou.Thismeansthere’snoneedtodeclarethesizesoflists,dictionaries,
strings,etc.
Lists
Adatastructurethatholdsanorderedcollection(sequence)ofitems.
1.3.2MicroPythonExamples
72
networks=['lora','sigfox','wifi','bluetooth','lte-m']
print(networks[2])#expect'wifi'
Dictionaries
Adictionaryislikeanaddress-bookwhereyoucanfindtheaddressorcontactdetailsofa
personbyknowingonlyhis/hername,i.e.keys(names)areassociatewithvalues(details).
address_book={'Alex':'2604CrosswindDrive','Joe':'1301HillviewDrive','Chris':'323
6GoldleafLane'}
print(address_book['Alex'])#expect'2604CrosswindDrive'
Tuple
Similartolistsbutareimmutable,i.e.youcannotmodifytuplesafterinstantiation.
pycom_devices=('wipy','lopy','sipy','gpy','fipy')
print(pycom_devices[0])#expect'wipy'
FormorePythonexamples,checkoutthesetutorials.Beawareoftheimplementation
differencesbetweenMicroPythonandPython3.5.
1.3.2MicroPythonExamples
73
YourFirstPymakrProject
ThisguidewilltakeyouthroughhowtosetupyourfirstprojectwithPymakrandmakethe
on-boardRGBLEDflashvariouscolours.
CreatingaprojectinPymakr
1. Firstlyyouwillneedtocreateanew,empty,directoryonyourcomputer.Forthis
examplewewillcreateonecalled RGB-Blink.
2. NextyouwillneedtoopeneitherAtomorVisualStudioCodedependingonwhichyou
setuppreviously.
3. Oncethetexteditorhasloadedyouwillneedtoclick File> Open,andopenthe
directoryyoucreatedinstep1
IfyouareusingAtom,itisimportanttocheckatthispointthatAtomhas
successfullyidentifiedtheproject.Thenameofthedirectoryyoucreatedinstep1
(RGB-Blinkinthiscase)shouldbeshowninthePymakrpanelikeso:
Ifthisisnotthecaseyoucanpress alt-ctrl-ronWindows/Linuxor ctrl-alt-
cmd-lonmacOS,inordertoreloadAtomandfixtheissue.
4. Nowthatyouhaveaprojectcreated,weneedtoaddsomefilestoit.Astandard
MicroPythonprojecthasthefollowingstructure:
RGB-Blink
|-lib
||-some_library.py
|-boot.py
|-main.py
boot.pyThisisthefirstscriptthatrunsonyourmodulewhenitturnson.Thisis
oftenusedtoconnectamoduleaaWiFinetworksothatTelnetandFTPcanbe
usedwithoutconnectingtotheWiFiAPcreatedbythemoduleandnotclutteringup
the main.pyfile.Asabeginneryoudonotneedtousea boot.py.
1.3.3YourfirstPymakrproject
74
main.pyThisscriptrunsdirectlyafter boot.pyandshouldcontainthemaincode
youwishtorunonyourdevice.
libItisoftenagoodideatosplitoutre-usablecodeintolibraries.Ifyouwantto
createoruselibrariescreatedbyothers,youwillneedtocreatea libdirectory
andputthelibraryfilesinthis.Itisimportantthatyouput .pyfilesdirectlyinto
libratherthancreatingadirectorytree.BydefaultMicroPythonwillnotdetect
anylibrarieswithinsub-directories.
Forthisexample,youwilljustneedtocreatea main.pyfile.
Nowthattheprojectstructureissetup,youmaywishtoconfigureprojectspecificsettingsfor
Pymakre.g.Whichserialporttouse.OnAtomyouneedtoclickthe ^buttononthe
Pymakrpane,thenclick ProjectSettings.OnVisualStudioCodeyouneedtoclickthe
Allcommandsbuttononthebottomofthewindows,thenclick Pymakr>ProjectSettings.
Thiscreatesafilecalled pymakr.confinsideyourprojectandpopulatesitwithdefault
settingscopiedoverfromyourglobalsettings.Adetailedexplanationofthesesettingscan
befoundhere.
Controllingtheon-boardLED
Nowthatyouhavesetupandconfiguredyourproject,wecanmoveontoprogrammingyour
module.Thefirstthingwewillneedtodoisimportsomelibrariesinordertointeractwiththe
on-boardLED.ThePycomfirmwarecomeswithalargeamountoflibrariesforstandard
functionalitybuilt-in.YoucanfindoutmoreabouttheseintheAPIdocumentation.Forthis
exampleyouwillneedtoopenthe main.pyfileandaddthefollowingcode:
importpycom
importtime
Thiswillimporttwolibraries, PycomwhichisresponsibleforPycomspecificfeatures,such
astheon-boardLEDand timewhichisastandardlibraryusedtiminganddelays.
YoumayhavenoticedthatwhenyoupowerupyourPycommodule,theon-boardLED
blinksblueonaregularbasis.This"heartbeat"isusedasawayofknowthatyourmodule
haspoweredupandstartedcorrectly.BeforewecanchangethecolourofthisLEDweneed
todisablethisheartbeat.Belowyourimportsyouwillneedtoaddthefollowing:
pycom.heartbeat(False)
1.3.3YourfirstPymakrproject
75
Nowit'stimetotestyourcode.OnthePymakrpane/bottomofthewindowyouwillseea
runbutton.(Ifyouhaven'tconnectedtoyourdeviceyet,youwillneedtodothatfirst).
Whenyouclicktherunbutton,thecodeinthecurrentlyopenfilewillbeexecutedonthe
device,butitwon'tcopyittothedevice.Afterrunningthiscode,youshouldseethatthaton-
boardLEDstopsblinkingblue.
NowthatwecanconfirmthedeviceisconnectedandPymakrisabletoruncodeonit,we
cancompleteourscripttoblinktheLEDlikeso:
importpycom
importtime
pycom.heartbeat(False)
whileTrue:
pycom.rgbled(0xFF0000)#Red
time.sleep(1)
pycom.rgbled(0x00FF00)#Green
time.sleep(1)
pycom.rgbled(0x0000FF)#Blue
time.sleep(1)
Onceyouruntheabovescript,itwillrunforever.Youwillnoticethispreventsyoufrom
accessingtheinteractiveREPLonthedevice(Youcannotseethe >>>prompt).Inorderto
stopthescript,clickontothePymakrterminal,andpress ctrl-conyourkeyboard.This
shouldstopthescriptrunningandreturnyoutotheinteractiveREPL.
Uploadingtoyourmodule
IntheprevioussectionwegotcoderunningononyourPycommoduleusingthe run
featureofPymakr.Thisisusefulforquicktestingbuthasacoupleofdrawbacks.Firstlythe
codedoesnotremainonthedevicepermanently.Ifyourebootthedevice,itwillnolonger
berunningyourcode.Secondly,itwillonlyworkifyouareusinglibrariesbuiltintothe
firmware.Ifyouneedanyextralibraries,theseneedtobecopiedtothedevicefirst.Thisis
wherethe uploadfeaturecomesin.Ifinsteadof runyouclick upload,Pymakrwill
uploadallthefilesintheproject(solongastheirtypeisinthe sync_file_typessettingfor
yourproject).Thesethenpersistonyourdeviceevenbetweenreboots,andallowsyouto
uselibrariesfromthe libfolderinyourproject.
Ifyouneedtoremovefilesfromyourdeviceyouhavetwooptions,eitherconnectviaFTP
andmanageyourfilesthatwayorformatthedevice'sinternalflashlikeso:
1.3.3YourfirstPymakrproject
76
importos
os.mkfs('/flash')
1.3.3YourfirstPymakrproject
77
REPL(ReadEvaluatePrintLoop)
REPLstandsforReadEvaluatePrintLoop,andisthenamegiventotheinteractive
MicroPythonpromptthatisaccessibleonthePycomdevices.UsingtheREPLisbyfarthe
easiestwaytotestoutPythoncodeandruncommands.YoucanusetheREPLinaddition
towritingscriptsin main.py.
ThefollowingpageswillexplainhowtousetheREPLwithbothSerialUSBandTelnet
connections.
TheREPLincludesthefollowingfeatures:
Inputhistory:usearrowupandarrowdowntoscrollthroughthehistory
Tabcompletion:presstabtoauto-completevariablesormodulenames
Haltanyexecutingcode:with Ctrl-C
Copy/pastecodeoroutput: Ctrl-Cand Ctrl-V
ThereareanumberofusefulshortcutsforinteractingwiththeMicroPythonREPL.See
belowforthekeycombinations;
Ctrl-AonablanklinewillenterrawREPLmode.Thisissimilartopermanent
pastemode,exceptthatcharactersarenotechoedback.
Ctrl-BonablanklikegoestonormalREPLmode.
Ctrl-Ccancelsanyinput,orinterruptsthecurrentlyrunningcode.
Ctrl-Donablanklinewilldoasoftreset.
Ctrl-Eenters‘pastemode’thatallowsyoutocopyandpastechunksoftext.Exit
thismodeusing Ctrl-D.
Ctrl-Fperformsa"safe-boot"ofthedevicethatprevents boot.pyand main.py
fromexecuting
1.3.4REPL
78
SerialUSBREPL(UART)
TousetheREPL,aPycomdevicemustbeconnectedtothehostcomputerwithaUSB
connectioneithertoanExpansionBoardortoserialconverter(adiagramofhowtodothis
canbefoundthethegettingstartedpageforyourmodule).
InordertoconnecttotheREPLoverUSBserial,therearemultiplemethods.Detailedbelow
aretheexplanationsofhowtodoitinMacOS,LinuxandWindows.
Allplatforms
ByfartheeasiestwaytoaccesstheUSBUARTREPLisviatheourPymakrplug-infor
AtomandVisualStudioCode.Thisaddsapanetothebottomoftheeditorsthatallowsyou
todirectlyaccesstheREPLandanyoutputfromthedevice.Detailedinstructionsonhowto
setupPymakrcanbefoundhere.
macOSandLinux
ToopenaserialUSBconnectionfrommacOS,anyserialtoolmaybeused;inthisexample,
theterminaltool screenwillbeused.
Openaterminalinstanceandrunthefollowingcommands:
$screen/dev/tty.usbmodem*115200
Uponexiting screen,press CTRL-ACTRL-\.Ifthekeyboarddoesnotsupportthe \-key
(i.e.anobscurecombinationfor \like ALT-SHIFT-7isrequired),thekeycombinationcan
beremappedforthe quitcommand:
create ~/.screenrc
addbind qtothe exitcommand
Thiswillallowscreentoexitedbypressing CTRL-AQ.
OnLinux, picocomor minicommaybeusedinsteadof screen.Theusbserial
addressmightalsobelistedas /dev/ttyUSB01orahigherincrementfor ttyUSB.
Additionally,theelevatedpermissionstoaccessthedevice(e.g.groupuucp/dialoutor
use sudo)mayberequired.
1.3.4.1SerialUSB
79
Windows
AterminalemulatorisneededtoopentheconnectionfromWindows;theeasiestoptionisto
downloadthefreeprogram,PuTTY.
COMPort
TousePuTTYtheserialport(COMport)inwhichthePycomdeviceisconnected,mustbe
located.InWindows,thisinformationcanbefoundfromthe'DeviceManager'program.
1. OpentheWindowsstartmenuandsearchfor'DeviceManager'
2. TheCOMportforthePycomdevicewillbelistedas'USBSerialDevice'orasimilar
name
3. Copy/WritedowntheassociatedCOMport(e.g. COM4)
UsingPutty
1. WithPuTTYopen,clickon Sessionintheleft-handpanel
2. Nextclickthe SerialradiobuttonontherightandentertheassociatedCOMport(e.g.
COM4)inthe SerialLinebox
3. Finally,clickthe Openbutton
1.3.4.1SerialUSB
80
TelnetREPL
Pycomdevicesalsosupportaconnectionvia telnet,usingthedevice'sonboard
WiFi/WLAN.Connecttothedevice'sWiFiAccessPoint(AP)andusingthefollowing
credentialstoconnecttotheAP.TheWiFi SSIDwillappearuponpoweringonaPycom
Deviceforthefirsttime(e.g. lopy-).Tore-enablethisfeatureatalaterdate,pleasesee
network.WLAN.
password: www.pycom.io
TelnetServer
Additionally,tousetheMircoPythonREPLovertelnet,furtherauthenticationisrequired.The
defaultcredentialsforthetelnetserverare:
username: micro
password: python
Seenetwork.serverforinfoonhowtochangethedefaultauthentication.
Allplatforms
ByfartheeasiestwaytoaccesstheTelnetREPLisviatheourPymakrplug-inforAtomand
VisualStudioCode.Thisaddsapanetothebottomoftheeditorsthatallowsyoutodirectly
accesstheREPLandanyoutputfromthedevice.Detailedinstructionsonhowtosetup
Pymakrcanbefoundhere.
macOSandLinux
OncethehostmachineisconnectedtothePycomdevice'sAccessPoint,atelnet
connectionmaybeopenedfromaterminalinstance.
$telnet192.168.4.1
Uponconnection,thetelnetprogramwillpromptforthe usernameand passwordinthe
sectionabove.
Windows
1.3.4.2Telnet
81
AterminalemulatorisneededtoopenatelnetconnectionfromWindows;theeasiestoption
istodownloadthefreeprogram,PuTTY.
1. WithPuTTYopen,selecttelnetasconnectiontypeandleavethedefaultport( 23)
2. NextentertheIPaddressofthePycomdevice(e.g. 192.168.4.1)
3. Finallyclick Open
WhenusingaPycomdevicewithapersonal,homeorofficeWiFiaccesspoint,the
telnetconnectionmaystillbeused.Inthisinstance,theuserwillneedtodeterminethe
Pycomdevice'slocalIPaddressandsubstitutethisfor 192.168.4.1,referredtointhe
earliersections.
1.3.4.2Telnet
82
FTP(LocalFileSystem)
ThereisasmallinternalfilesystemaccessiblewitheachPycomdevice,called /flash.
Thisisstoredwithintheexternalserialflashmemory.IfamicroSDcardisalsoconnected
andmounted,itwillbeavailableaswell.Whenthedevicestartsup,itwillalwaysbootfrom
the boot.pylocatedinthe /flashfilesystem.
ThefilesystemisaccessibleviathenativeFTPserverrunningoneachPycomdevice.
OpenanFTPclientandconnectto:
url: ftp://192.168.4.1
username: micro
password: python
Seenetwork.serverforinformationonhowtochangethedefaults.Therecommendedclients
are:
macOS/Linux:defaultFTPclient
Windows:FilezillaandFireFTP
Forexample,fromamacOS/Linuxterminal:
$ftp192.168.4.1
TheFTPserverdoesn’tsupportactivemode,onlypassivemode.Therefore,ifusingthe
nativeunixFTPclient,immediatelyafterloggingin,runthefollowingcommand:
ftp>passive
TheFTPserveronlysupportsoneconnectionatatime.IfusingotherFTPclients,please
checktheirdocumentationforhowtolimitthemaximumallowedconnectionstooneata
time.
FileZilla
IfusingFileZilla,it'simportanttoconfigurethesettingscorrectly.
Donotusethequickconnectbutton.Instead,openthesitemanagerandcreateanew
configuration.Withinthe Generaltab,ensurethatencryptionissetto: OnlyuseplainFTP
(insecure).
1.3.5FTP
83
Inthe TransferSettingstab,limitthemaxnumberofconnectionstoone.OtherFTPclients
maybehaveinasimilarways;visittheirdocumentationformorespecificinformation.
1.3.5FTP
84
BootModes
Ifpoweringupnormallyoruponpressingtheresetbutton,aPycommodulewillbootinto
standardmode;the boot.pyfilewillbeexecutedfirst,followedby main.py.Itispossibleto
alterthebootprocedureofthemodulebytyingcertainpins highor lowwhenthemodule
boots.
Bootloader
Ifyouupdatedyourdevicebeforeusingit,youhavealreadyputthedeviceintobootloader
mode.Thisisachievedbyconnecting G23to GNDwhilethedeviceboots.Ifyouuseda
Pysense/Pytracktoupdate,itdidthisautomaticallyforyou.Youonlyneedtoputyour
Pycommoduleintobootloadermodeifyouareupdatingitsfirmware,orareprogramming
yourownlowlevelcode.ThisisnotrequiredifyouareupdatingyourMicroPythoncode.
SafeBoot
SometimesthecodeyouhavewrittenwillpreventyougainingaccesstotheREPLor
preventyouupdatingyourcode.Someexamplemaybe:
YoudisabledtheWiFi/UART
YourcodegetsstuckbeforereachingtheREPL
Yousetasocketasblockingbutneverreceiveanydata
Inordertofixthisyoucansafebootyourmodule.Thiswillprevent boot.pyand main.py
frombeingexecutedandwilldropyoustraightintotheinteractiveREPL.Afterreset,if P12
pinisheld high(i.e.connectittothe 3V3outputpin),theheartbeatLEDwillbegin
flashingorangeslowly.Ifafter3secondsthepinisstillheldhigh,theLEDwillstartblinking
faster.Inthismodethemodulewilldothesameaspreviouslyexplainedbutitwillalsoselect
thepreviousOTAimagetobootifyouhaveupdatedthemoduleviatheOTAupdate
procedure(updatesperformedviathefirmwareupdatetooldonotcount).Thisisusefulif
youflashedaOTAupdatethatbreaksthedevice.
Pin P12releasedduring:
1st3secswindow 2nd3secswindow
Disable boot.pyand main.py sameaspreviousbutusingpreviousOTAfirmware
Theselectionmadeduringsafebootisnotpersistent,thereforeafterthenextnormalreset,
thelatestfirmwarewillproceedtorunagain.
1.3.6Safeboot
85
Ifproblemsoccurwithinthefilesystemoryouwishtofactoryresetyourmoduletoremove
yourcode,runfollowingcodeintheREPL:
>>>importos
>>>os.mkfs('/flash')
Beaware,resettingtheflashfilesystemwilldeleteallfilesinsidetheinternaldevice
storage(nottheSDcard)andtheycannotberecovered.
Reset
Pycomdevicessupportbothsoftandhardresets.Asoftresetclearsthestateofthe
MicroPythonvirtualmachinebutleaveshardwareperipheralsunaffected.Todoasoftreset,
press Ctrl+DontheREPLorfromwithinascript,run:
>>>importsys
>>>sys.exit()
Ahardresetisthesameasperformingapowercycletothedevice.Inordertohardreset
thedevice,pressthe resetswitchorrun:
>>>importmachine
>>>machine.reset()
1.3.6Safeboot
86
RegisteringaPycomDevice
Someofourdevicesrequireregistrationbeforeyoucanutilisespecificfeaturessuchas
certaintypesofnetworking.Pleaseseethelistbelowforsetupguidestoensurethatyour
deviceisregisteredandactivatedonthevariousplatformsrequiredtoaccessallofthe
availablefeatures.
NotallPycomdevicesrequireactivation;mostfeaturesworkimmediatelyoutofthe
box!
1.4DeviceRegistration
87
RegisteringwithSigfox
ToensurethedevicehasbeenprovisionedwithDeviceIDandPACnumber,pleaseupdate
tothelatestfirmware.
InordertosendaSigfoxmessage,thedeviceneedtoregisterwiththeSigfoxBackend.
Navigatetohttps://backend.sigfox.com/activatetofindthelistofSigfoxenabled
developmentkits.
Select Pycomtoproceed.
NextchooseaSigfoxOperatorforthecountrywherethedevicewillbeactivated.Findthe
specificcountryandselecttheoperatortocontinue.
1.4.1Sigfox
88
Nowneedtoenterthedevice'sDeviceIDandPACnumber.
TheDeviceIDandPACnumberareretrievablethroughacoupleofcommandsviathe
REPL.
fromnetworkimportSigfox
importbinascii
#initaliseSigfoxforRCZ1(YoumayneedadifferentRCZRegion)
sigfox=Sigfox(mode=Sigfox.SIGFOX,rcz=Sigfox.RCZ1)
#printSigfoxDeviceID
print(binascii.hexlify(sigfox.id()))
#printSigfoxPACnumber
print(binascii.hexlify(sigfox.pac()))
See SigfoxformoreinfoabouttheSigfoxClassandwhichRCZregiontouse.
1.4.1Sigfox
89
Oncethedevice'sDeviceIDandPACnumberhavebeenentered,createanaccount.
Providetherequiredinformationincludingemailaddressandclicktocontinue.
AnemailconfirmingthecreationofaSigfoxBackendaccountandthesuccessful
registrationofthedeviceshouldarriveattheusersinbox.
1.4.1Sigfox
90
Cellularregistration
InordertouseyourGPy/FiPyonacellularnetworkyouarerequiredtogetaSIMcardfrom
alocalprovider.Note:ThismightdifferfromastandardSIMyoucanbuyinastore,our
devicesdonotsupportstandardLTE.
CurrentlywearenotabletoprovideanyspecificdetailsabouthowtogetsuchaSIMcard
andhowtoregisteritasmostdeploymentsareclosedtrials,eachcarrierhasit’sownrules
(forexample,whethertheyrequirespecialSIMsornot).
WerecommendcontactingyourlocalcellularproviderstochecktheirplanssurroundingLTE
CAT-M1andNB-IoT.Bycontactingthem,youwillshowthecarriersthatthereislocal
interestindeployingsuchnetworks.
Youcanfindamapofdeployednetworksandopenlabshere.
1.4.2Cellular
91
LoRaWANRegistration
RawLoRa
WhenusingrawLoRa,youdonothavetoregisteryourmoduleinanyway.Themodules
cantalktoeachotherdirectly.
LoRaWAN
InordertoconnectyourLoRacapablePycommoduletoaLoRaWANnetworkyouwillhave
toregisteryourdevicewiththedesirednetwork.Weareunabletoprovideinstructionsforall
LoRaWANnetworksbutbelowyouwillfindsomegenericinstructions,alongwithlinkstoany
specificguidesweareawareof.
Genericinstructions
Firstlyyouwillneedtogetyourmodules DeviceEUI,thiscanbeachievedusingthe
followingcode:
fromnetworkimportLoRa
importubinascii
lora=LoRa(mode=LoRa.LORAWAN)
print(ubinascii.hexlify(lora.mac()).upper().decode('utf-8'))
Theoutputwillbeahexstringlike: 70B3D5499585FCA1.Onceyouhavethisyouwillneedto
provideittoyourLoRaWANnetworkwhichwillthenprovideyouwiththedetailsneedto
connectviaOver-the-AirActivation(OTAA)orActivationbyPersonalisation(ABP)
OTAA
IfyouwishtoconnectviaOTAA(whichistherecommendedmethod)thenetworkwill
provideyouwithan ApplicationEUIand ApplicationKey.Theformeridentifieswhat
applicationyourdeviceisconnectingto,thelatterisasharedsecretkeyuniquetoyour
devicetogeneratethesessionkeysthatproveitsidentitytothenetwork.Onceyouhave
theseyoucanusetheLoRaWANOTAAexamplecodetoconnecttothenetwork.
ABP
1.4.3LoRaWAN
92
WithABPtheencryptionkeysenablingcommunicationwiththenetworkarepreconfiguredin
thedevice.Thenetworkwillneedtoprovideyouwitha DeviceAddress, NetworkSession
Keyand ApplicationSessionKey.OnceyouhavetheseyoucanusetheLoRaWANABP
examplecodetoconnecttothenetwork.
Networks
1.4.3LoRaWAN
93
IfyoucannotfindyourfavouriteLoRaWANnetworkinthelistabove,pleaseconsider
writingatutorialforhowtoconnectaPycommodulewithitandcontributeittothis
documentationviaaGitHubpullrequest.
1.4.3LoRaWAN
94
TheThingsNetwork
InordertouseTheThingsNetwork(TTN)youshouldnavigatetotheirwebsiteand
create/registeranaccount.Enterausernameandanemailaddresstoverifywiththeir
platform.
Onceanaccounthasbeenregistered,youcanregisteryourPycommoduleaseitheranode
oranano-gateway.Thestepsbelowwilldetailhowtodothis.
Createanapplication
Inordertoregisteryourdevicetoconnecttothethingsnetwork,youmustfirstcreatean
applicationforthesedevicestobelongto.ThiswaytheNetworkwillknowwheretosendthe
devicesdatato.
1.4.3.2TheThingsNetwork
95
Selectingthe ApplicationstabatthetopoftheTTNconsole,willbringupascreenfor
registeringapplications.Clickregisterandanewpage,similartotheonebelow,willopen.
Enteraunique ApplicationIDaswellasaDescription&HandlerRegistration.
NowthePycommodulenodescanberegisteredtosenddatauptothenewApplication.
RegisteraDevice
Toconnectnodestoathingsnetworkgateway,devicesneedtobeaddedtotheapplication.
Todothis,navigatetothe Devicestabonthe Applicationhomepageandclickthe
RegisterDevicebutton.
Inthe RegisterDevicepanel,completetheformsforthe DeviceIDandthe DeviceEUI.
The DeviceIDisuserspecifiedandisuniquetothedeviceinthisapplication.The Device
EUIshouldbeagloballyuniqueidentifierforthedevice.Youcanrunthefollowingonyou
PycommoduletoretrieveitsEUI.
1.4.3.2TheThingsNetwork
96
fromnetworkimportLoRa
importubinascii
lora=LoRa()
print("DevEUI:%s"%(ubinascii.hexlify(lora.mac()).decode('ascii')))
Oncethedevicehasbeenadded,changethe ActivationMethodbetween OTAAand ABP
dependingonuserpreference.Thisoptioncanbefoundunderthe Settingstab.
RegisteraNano-Gateway
YoucanalsosetupyourPycommoduletoactasagatewaywithTheThingsNetwork.The
coderequiredtodothiscanbefoundhere.
InsidetheTTNConsole,therearetwooptions, Applicationsand Gateways.Select
Gatewaysandthenclickon registerGateway.Thiswillallowforthesetupandregistration
ofanewnano-gateway.
OntheRegisterGatewaypage,youwillneedtosetthefollowingsettings:
1.4.3.2TheThingsNetwork
97
Theseareuniquetoeachgateway,locationandcountryspecificfrequency.Pleaseverify
thatcorrectsettingsareselectedotherwisethegatewaywillnotconnecttoTTN.
Youneedtotickthe"I'musingthelegacypacketforwarder"toenabletheright
settings.ThisisbecausetheNano-Gatewayusesthe'defacto'standardSemtechUDP
protocol.
Option Value
Protocol PacketForwarder
GatewayEUI UserDefined(mustmatch config.py)
Description UserDefined
FrequencyPlan SelectCountry(e.g.EU-868MHz)
Location UserDefined
AntennaPlacement IndoororOutdoor
MostLoRaWANnetworkserversexpectaGatewayIDintheformofaunique64-bit
hexadecimalnumber(calledaEUI-64).TherecommendedpracticeistoproducethisID
fromyourboardbyexpandingtheWiFiMACaddress(a48-bitnumber,calledMAC-48).You
canobtainthatbyrunningthiscodepriortoconfiguration:
1.4.3.2TheThingsNetwork
98
fromnetworkimportWLAN
importbinascii
wl=WLAN()
binascii.hexlify(wl.mac())[:6]+'FFFE'+binascii.hexlify(wl.mac())[6:]
Oncethesesettingshavebeenapplied,click RegisterGateway.AGatewayOverviewpage
willappear,withtheconfigurationsettingsshowing.Nextclickonthe GatewaySettingsand
configuretheRouteraddresstomatchthatofthegateway(default:
router.eu.thethings.network).
The Gatewayshouldnowbeconfigured.
1.4.3.2TheThingsNetwork
99
ConnectingtoObjeniousLoRaWAN'Spot'
network
Identifiers
ToconnectaPycomLoRadevice(LoPy,LoPy4,FiPy)toObjeniousyou'llneedtoprovision
it.Thisrequiresthreepiecesofinformation
DeviceEUI(DevEUI)
ApplicationEUI(AppEUI)
ApplicationKey(AppKey)
DeviceEUI
Thiscomesfromthedeviceitselfandcanbeobtainedfrom lora.mac().
Toobtaintherequiredhexadecimalrepresentationyoucanrunthefollowingcodeonyour
LoPy:
fromnetworkimportLoRa
importubinascii
lora=LoRa()
print("DevEUI:%s"%(ubinascii.hexlify(lora.mac()).decode('ascii')))
ApplicationEUIandApplicationKey
ApplicationEUIandKeyaretwoLoRaWANparametersthatshouldideallybygeneratedby
you,ifsupplyingdevicestoendcustomers.
TheApplicationEUIisaEUI-64(8bytes)identifierwhichshouldbeuniversallyunique-it's
usuallyallocatedfromaMA-SblockpurchasedfromtheIEEERegistrationAuthority.
TheApplicationKeyshouldbearandomlygenerated,secure,128bit(16byte)token.
FortestingpurposesweprovideascriptwhichgeneratesarandomApplicationEUIfromour
assignmentandaseriesofApplicationKeys:
EUI/Keygeneratorfortesting
(note:theApplicationEUIproducedbythisscriptisnotguaranteedtobeunique)
1.4.3.2Objenious
100
TousethescriptmakesureyouareusingPython3.6onyourcomputerandrunit(onyour
computer,notonthePycomboard)as:
pythongenerate_keys.py1
Theoutputwillbesimilarto:
AppEUI:70b3d54923e36a89
AppKeys:
78fe712d96f46784a98b574a8cd616fe
IfyouareregisteringmultipledevicesyoucangeneratemoreApplicationsKeysbychanging
1toyourdesirednumberofdevices.
Provisioning
Onceyouhavethethreeidentifiersforyourdeviceyouneedtoregisterthemonthe
Objeniusportal.
Follow"Importerdescapteurs"under"StatucdoParc"andselect"ProvisioningUnitaire":
OncetheregiveyourdeviceanameandentertheDevEUI,AppEUIandAppKeyobtained
fromthestepsabove:
1.4.3.2Objenious
101
1.4.3.2Objenious
102
PymakrPlugins
TomakeitaseasyaspossiblePycomhasdevelopedapluginfortwopopulartexteditors,
calledPymakr.Thesepluginshavebeenbuiltandareavailableforthefollowingplatforms:
2.1Installation
103
2.1Installation
104
PymakrPluginInstallationforAtom
Forbeginners,usersgettingstartedwithMicroPython&PycomaswellasAtomtexteditor
users,werecommendthePymakrPluginforAtom.Thissectionwillhelpyougetstarted
usingtheAtomTextEditor&PymakrPlugin.
PleasefollowthesestepstoinstallthePymakrPlugin:
1. EnsurethatyouhaveAtominstalledandopen.
2. NavigatetotheInstallpage,via Atom>Preferences>Install
2.1.1Atom
105
3. Searchfor PymakrandselecttheofficialPycomPymakrPlugin.
4. YoushouldnowseeandclicktheInstallbutton.Thiswilldownloadandinstallthe
PymakrPlugin.
5. That’sit!You’veinstalledthePymakrPluginforAtom.
2.1.1Atom
106
ConnectingviaSerialUSB
AfterinstallingthePymakrPlugin,youneedtotakeafewsecondstoconfigureitforfirst
timeuse.Pleasefollowthesesteps:
1. ConnectyourPycomdevicetoyourcomputerviaUSB.IfyouareusinganExpansion
Board2.0,andhavejustfinishedafirmwareupgrade,besuretoremovethewire
betweenGNDandG23andresetyourdevicebypressingthebutton.Note:youdon't
needthewireforExpansionBoard3.0
2. OpenAtomandensurethatthePymakrPluginhascorrectlyinstalled.
3. OpenthePymakrconsolebyclickingthe ^button,locatedinthelowerrightsideof
theAtomwindow.
4. Click, Morefollowedby GetSerialPorts.Thiswillcopytheserialaddressofyour
expansionboardtoyourclipboard.
2.1.1Atom
107
5. Navigateto Settings>GlobalSettings
6. Pastetheserialaddressyoucopiedearlierintothetextfield DeviceAddress
7. PressconnectandthePymakrconsoleshouldshowthreearrows >>>,indicatingthat
youareconnected
2.1.1Atom
108
Thesesettingscanalsobeappliedonaperprojectbasisbyclicking Settingsthen
ProjectSettings.ThiswillopenaJSONfilewhichyoucanedittoenteryourdesired
settings.
ThisprocessiseasiestwitheitheraPycomExpansionBoardoraPytrack/Pysenseas
theaddressesareautomaticallyselected.ForexternalproductssuchasFTDIUSB
SerialCables,theserialaddressmayneedtobecopiedmanually.Additionally,thereset
buttononthedevicemayalsoneedtobepressedbeforeaconnectionmessage
appears.
ConnectingviaTelnet
AfterinstallingthePymakrPlugin,adevicemaybeconnectedviathetelnetinterface.
Pleaseseethefollowingsteps:
1. EnsurethatPycomdeviceisturnedon
2. ConnectthehostcomputertotheWiFiAccessPointnamedafteryourboard(theSSID
willbeasfollowse.g. lopy-wlan-xxxx, wipy-wlan-xxxx,etc.).Thepasswordis
www.pycom.io.
3. Followthestepsasaboveinthe"ConnectingviaSerialUSB"sectionbutenter
192.168.4.1astheaddress.
4. Thedefaultusernameandpasswordare microand python,respectively.
5. Click ConnectinthePymakrpane,Pymakrwillnowconnectviatelnet.
2.1.1Atom
109
2.1.1Atom
110
PymakrPluginInstallationforVisual
StudioCode
PycomalsosupportsMicrosoft'sVisualStudioCodeIDEplatformwiththePymakrPlugin.To
downloadVisualStudioCode,navigatetoVSCode.
YouwillalsoneedNodeJSinstalledonyourPC.PleasedownloadthelatestLTSversion
availablefromtheNodeJSwebsite.
PleasefollowthesestepstoinstallthePymakrVSCodeExtension:
1. EnsurethatyouhaveVSCodeinstalledandopen.
2. NavigatetotheExtensionspage,usingthe5thbuttonintheleftnavigation
3. Searchfor Pymakrandclicktheinstallbuttonnexttoit.
2.1.2VisualStudioCode
111
4. Withinafewminutes,areloadbuttonshouldappear.PressittoreloadVSCode.
2.1.2VisualStudioCode
112
5. That’sit!You’veinstalledthePymakrExtensionforVSCode
2.1.2VisualStudioCode
113
ConnectingviaSerialUSB
AfterinstallingthePymakrPlugin,youneedtotakeafewsecondstoconfigureitforfirst
timeuse.Pleasefollowthesesteps:
1. ConnectyourPycomdevicetoyourcomputerviaUSB.Ifyouareusinganexpansion
board,andhavejustfinishedafirmwareupgrade,besuretoRemovethewire
betweenGNDandG23andresetyourdevicebypressingthebutton.
2. OpenVisualStudioCodeandensurethatthePymakrPluginhascorrectlyinstalled.
3. Click AllcommandsonthebottomoftheVisualStudioCodewindow
4. Inthelistthatappears,click Pymakr>Extra>ListSerialPorts
5. Thiswilllisttheavailableserialports.IfPymakrisabletoauto-detectwhichtouse,this
willbecopiedtoyourclipboard.Ifnotpleasemanuallycopythecorrectserialport.
6. Onceagainclick Allcommands,thenclick Pymakr>GlobalSettings.Thiswillopena
JSONfile.Pastetheserialaddressyoucopiedearlierintothefield addressandsave
thefile.
2.1.2VisualStudioCode
114
7. FinallyclosetheJSONfile,click Allcommands,then Pymakr>Connecttoconnectyour
device.ThePymakrconsoleshouldshowthreearrows >>>,indicatingthatyouare
connected
Thesesettingscanalsobeappliedonaperprojectbasisbyclicking Allcommandsthen
Pymakr>ProjectSettings.ThiswillopenaJSONfilewhichyoucanedittoenteryour
desiredsettingsforthecurrentlyopenproject.
ThisprocessiseasiestwitheitheraPycomExpansionBoardoraPytrack/Pysenseas
theaddressesareautomaticallyselected.ForexternalproductssuchasFTDIUSB
SerialCables,theserialaddressmayneedtobecopiedmanually.Additionally,thereset
buttononthedevicemayalsoneedtobepressedbeforeaconnectionmessage
appears.
ConnectingviaTelnet
AfterinstallingthePymakrPlugin,adevicemaybeconnectedviathetelnetinterface.
Pleaseseethefollowingsteps:
1. EnsurethatPycomdeviceisturnedon
2. ConnectthehostcomputertotheWiFiAccessPointnamedafteryourboard(theSSID
willbeasfollowse.g. lopy-wlan-xxxx, wipy-wlan-xxxx,etc.).Thepasswordis
www.pycom.io.
3. Followthestepsasaboveinthe"ConnectingviaSerialUSB"sectionbutenter
192.168.4.1astheaddress.
2.1.2VisualStudioCode
115
4. Thedefaultusernameandpasswordare microand python,respectively.
5. FinallyclosetheJSONfile,click Allcommands,then Pymakr>Connect,Pymakrwill
nowconnectviatelnet.
2.1.2VisualStudioCode
116
ToolsandFeatures
Console(REPL)
MicroPythonhasaninteractivecodetoolknownastheREPL(ReadEvaluatePrintLine).
TheREPLallowsyoutoruncodeonyourdevice,linebyline.Tobegincoding,gotothe
PymakrPluginConsoleandstarttypingyourcode.StartbymakingtheLEDchangecolour.
importpycom#weneedthismoduletocontroltheLED
pycom.heartbeat(False)#disabletheblueblinking
pycom.rgbled(0x00ff00)#maketheLEDlightupgreenincolour
YoucanchangethecolourbyadjustingthehexRGBvalue.
pycom.rgbled(0xff0000)#nowmaketheLEDlightupredincolour
Theconsolecanbeusedtorunanypythoncode,alsofunctionsorloops.
Use print()tooutputcontentsofvariablestotheconsoleforyoutoread.Returnedvalues
fromfunctionswillalsobedisplayediftheyarenotcaughtinavariable.Thiswillnothappen
forcoderunningfromthemainorbootfiles.Hereyouneedtouse print()tooutputtothe
console.
Notethatafterwritingorpastinganyindentedcodelikeafunctionorawhileloop,the
userwillhavetopressenteruptothreetimestotellMicroPythonthecodeistobe
closed(thisisstandardMicroPython&Pythonbehaviour).
AlsobeawarethatcodewrittenintotheREPLisnotsavedafterthedeviceispowered
off/onagain.
Run
Totestcodeonadevice,createanew .pyfileoropenanexistingone,typethedesired
code,savethefileandthenpressthe Runbutton.Thiswillrunthecodedirectlyontothe
PycomboardandoutputtheresultsofthescripttotheREPL.
2.2Tools/Features
117
Changesmadetofileswon’tbeautomaticallyuploadedtotheboarduponrestartingor
exitingthe Runfeature,asthePycomboardwillnotstorethiscode.Inordertopush
thecodepermanentlytoadevice,usethe Uploadfeature.
Projects
PymakrPluginsupportsuserprojects,allowingforpre-configuredsettingssuchasdefault
serialaddress/credentials,filestobeignoredandfolderstosync.
pymakr.conf
PymakrPluginsupportslocalprojectsettingsusingafilecalled pymakr.conf.Thiscanbe
usedtostorethedefaultserialaddressofadevice,whichfilestoignoreandothersettings.
Anexample pymakr.confisshownbelow:
{
"address":"/dev/cu.usbserial-AB001234",
"username":"micro",
"password":"python",
"sync_folder":"scripts"
}
Upload
ThePymakrPluginshaveafeaturetosyncanduploadcodetoadevice.Thiscanbeused
forbothuploadingcodetoadeviceaswellastestingoutscriptsbyrunningthemliveonthe
device.Thefollowingstepsdemonstratehowtousethisfeature.
Tostartusingthe Uploadfeature,ensurethataprojectfolderhasbeencreatedforthe
device.Forexample,ifusingthe pymakr.conffromabove,thisprojectfoldershouldbe
named scripts.Thisfoldershouldhavethefollowingstructure:
Libraryfilesshouldbeplacedintothe libfolder,certificatesintothe certfolderandso
on.The Uploadbuttonwilltakethehighestlevelfolder(currentlyopen)anduploadthisto
theconnectedPycomdevice.Thefileswillbepushedtothedeviceinexactlythesame
2.2Tools/Features
118
structureaswithinthecodeeditor'sfiledirectory.
More
Clickingthe MorebuttonwithinthePymakrPluginallowsforsomeadditionalfeatures.See
theoptionsbelowforspecificfunctionality.
GetFirmwareVersion
RetrievesthefirmwareversionofthePycomdeviceconnectedtothePymakrPlugin
instance.
GetWiFiAPSSID
RetrievesthedefaultWiFiAccessPointSSIDofthePycomdeviceconnectedtothePymakr
Plugininstance.
GetSerialPorts
RetrievesthevariousserialportsthatareavailabletothePymakrPlugininstance.
2.2Tools/Features
119
Pymakrsettings
BelowyouwillfindadescriptionofthevarioussettingsavailableforPymakr.
address
ThisistheaddressofthePycommoduleyouwantPymakrcanconnectto.Thiscanbe
eitheraserialport(e.g COM1onwindowsor /dev/cu.usbserial-DQ0054ESonLinux/macOS)
oranIPaddress(Telnet)(e.g. 192.168.4.1ifconnectedtotheAPcreatedbythePycom
module).
username
IfaIPaddresswasprovidedforthe addressthereforePymakrisconnectingviaTelnet,you
willalsoneedtoprovideausername,thedefaultis micro.
password
IfanIPaddresswasprovidedfortheaddress,PymakrisconnectingviaTelnet.Youwillalso
needtoprovideapassword,thedefaultis python.
sync_folder
Ifleftblank,alldirectoriesinsidetheprojectwillbesyncedtothedevicewhentheuserclicks
upload.Ifdirectoriesarespecified,onlythesedirectorieswillbesynced,allotherswillbe
ignored
open_on_start
Ifsetto true,thePymakrconsolewillopenandtrytoconnectwhentheeditorisstarted,or
aprojectisopened.
safe_boot_on_upload
2.3Settings
120
Ifsetto true,Pymakrwillreboottheconnecteddeviceintosafe-modebeforeuploading.
ThisisusefulifyourcodeusesalotofRAMcausingissueswiththeuploadprocedure.
Thisfeatureisonlyavailableonmodulesrunningfirmwareversion 1.17.0.b1orhigher.
sync_file_types
Onlyfilesendingwiththeextensionslistedinthissettingwillbesyncedtothedevicewhen
performinganupload.Allotherfilesareignored.Bydefaultthisissettoinclude: py,txt,
log,json,xml
ctrl_c_on_connect
Ifsetto true,Pymakrwillsentthe ctrl-csignaltotheconnectedmodulebefore
uploading.Thisshouldstopthescriptcurrentlyrunningonthedeviceandimprovethe
reliabilityoftheuploadprocess.
2.3Settings
121
Pytrack&Pysense
InadditiontotheExpansionBoard,Pycomalsoofferstwoadditionalsensorboards,which
areidealforquicklybuildingafullyfunctioningIoTsolution!Whethertheapplicationis
environmentsensingorassettracking,theseadditionalboardssupportavarietyofsensors.
Pytrack
PytrackisalocationenabledversionoftheExpansionBoard,intendedforuseinGPS
applicationssuchasassettrackingormonitoring.
Features&Hardware
ThePytrackishasanumberoffeaturesincludingGPS,3-AxisAccelerometerandBattery
Charger.Seethelistbelowfordetailedspecificsabouteachsensor,includingdatasheets.
SerialUSB
3-AxisAccelerometer(LIS2HH12)
BatteryCharger(BQ24040withJSTconnector)
GPSandGLONASS(L76-L)
MicroSDCardReader
AlloftheincludedsensorsareconnectedtothePycomdeviceviatheI2Cinterface.These
pinsarelocatedatP22(SDA)andP21(SCL).
Pysense
3.1Introduction
122
PysenseisasensorpackedversionoftheExpansionBoard,intendedforusein
environmentsensingapplicationssuchastemperature,humiditymonitoring,andlight
sensing.
Features&Hardware
ThePysenseispackedwithanumberofsensorsandhardware,seethelistbelowfor
detailedspecificsabouteachsensor,includingdatasheets.
SerialUSB
3-AxisAccelerometer(LIS2HH12)
BatteryCharger(BQ24040withJSTconnector)
DigitalAmbientLightSensor(LTR-329ALS-01)
HumidityandTemperatureSensor(SI7006-A20)
BarometricPressureSensorwithAltimeter(MPL3115A2)
MicroSDCardReader
AlloftheincludedsensorsareconnectedtothePycomdeviceviatheI2Cinterface.These
pinsarelocatedat GPI09(SDA)and GPI08(SCL).
3.1Introduction
123
InstallingSoftware
Asthedevelopmentforthesedevicesareongoingwithadditionalfeaturesbeingadded,
everyweek,itisessentialtoensureyoufrequentlycheckforupdatesonthe
Pytrack/Pysense.Aswellasupdatingthedevicefirmware,itisimportanttocheckthe
GitHubrepositoryfortherespectivelibraryfilesastheyasalsobeingupdated,toinclude
additionalfeatures/functionality.
3.2InstallingSoftware
124
UpdatingFirmware
ToupdatethefirmwareonthePysense/Pytrack/Pyscan/ExpansionBoardv3,pleaseseethe
followinginstructions.ThefirmwareofPysense/Pytrack/Pyscan/ExpansionBoardv3canbe
updatedviatheUSBportusingtheterminaltool, DFU-util.
ThelatestfirmwareDFUfilecanbedownloadedfromthelinksbelow:
PytrackDFU
PysenseDFU
ExpansionBoardDFU
Whileinthenormal,applicationmode,thePysense/Pytrack/Pyscan/ExpansionBoardv3
requireaSerialUSBCDCdriver,inDFU,bootloadermode,theDFUdriverisrequired.
Below,theUSBProductIDisdepictedforeachcase.
Board DFUbootloader(update
mode)
Applicationfirmware(normal
mode)
Pytrack 0xF014 0xF013
Pysense 0xF011 0xF012
Pyscan 0xEF37 0xEF38
ExpansionBoard
v3 0xEF99 0xEF98
Note:USBVendorIDisalways 0x04D8.
InstallingtheDFU-utilTools
macOS
Ifusing homebrew:
$brewinstalldfu-util
Ifusing MacPorts:
portinstalllibusbdfu-util
Linux
3.2.1UpdatingFirmware
125
UbuntuorDebian:
$sudoapt-getinstalldfu-util
Fedora:
$sudoyuminstalldfu-util
Arch:
$sudopacman-Sydfu-util
Windows
DFU-utilv0.9–TooltouploadthefirmwaretothePytrack/Pysense
Zadig–InstallertoolforthePytrack/PysenseboardDFUFirmware
TouploadedthelatestDFUfirmwaretothePytrack/Pysense,firstinstalltheDFUdrivers
tothehostcomputer.OpenZadigandselect libusbKasthedriver.
Toinstallthedrivers,thePytrack/PysenseboardmustbeinDFU-mode:
1. DisconnecttheUSBcable
2. Holddownthebuttonontheshield
3. ConnecttheUSBcable
4. Keepthebuttonpressedforatleastonesecond
5. Releasethebutton.WhentheboardisconnectedinDFU-mode,itwillbeinthisstate
for7seconds.
6. Clickthe “InstallDriverbuttonimmediately.Ifthedriverwasunsuccessful,repeat
fromstep1.
HeretheUSBIDhastobetheDFU-bootloaderone( 0xF014forPytrackor 0xF011
forPysense).
ThisisasuccessfulDFUdriverinstallationforPytrack:
3.2.1UpdatingFirmware
126
OpenthecommandpromptandnavigatetothedirectorywheretheDFU-utilandthe
firmwarewasdownloaded(mustbeinsamedirectory).Repeattheproceduretogetthe
boardinDFU-modeandrunthecommandbelowbutreplace X.X.Xwiththefirmware
versionandreplacePysensewithPytrackifitisthePytrackthatistobeupdated(e.g:
pytrack_0.0.8.dfu):
dfu-util-static.exe-Dpysense_X.X.X.dfu
Iftheupdatewassuccessful,amessage,"Done!"shouldappearinthebottomofthe
commandprompt.
Double-checkSerialUSB(CDC)driverisinstalledinApplicationmode:if,bymistake,
the libusbkdriverwasinstalledwhiletheUSBIDistheApplicationmode( 0xF013for
Pytrackor 0xF012forPysense),thenthe SerialUSB(CDC)driverhastobeinstalledfor
applicationmode.ThiswillallowWindowstoallocateaCOMport,whichisrequiredfor
REPLconsole.
3.2.1UpdatingFirmware
127
UsingDFU-utilwithPytrack,PysenseandExpansionBoard
v3
Toenterupdatemodefollowthesesteps:
1. Unplugthedevice
2. Pressthebuttonandkeepitheld(ontheExpansionBoardthe S1button)
3. PlugintheUSBcabletothehostcomputerandwait1secondbeforereleasingthe
button
4. Afterthisyouwillhaveapproximately7secondstoruntheDFU-utiltool
MacOSandLinux:
$dfu-util-Dpytrack_0.0.8.dfu
Anoutput,similartotheonebelow,willappearuponsuccessfulinstallation:
3.2.1UpdatingFirmware
128
dfu-util0.9
Copyright2005-2009WestonSchmidt,HaraldWelteandOpenMokoInc.
Copyright2010-2016TormodVoldenandStefanSchmidt
ThisprogramisFreeSoftwareandhasABSOLUTELYNOWARRANTY
Pleasereportbugstohttp://sourceforge.net/p/dfu-util/tickets/
MatchvendorIDfromfile:04d8
MatchproductIDfromfile:f014
OpeningDFUcapableUSBdevice...
ID04d8:f014
Run-timedeviceDFUversion0100
ClaimingUSBDFURuntimeInterface...
Determiningdevicestatus:state=dfuIDLE,status=0
dfu-util:WARNING:RuntimedevicealreadyinDFUstate?!?
ClaimingUSBDFUInterface...
SettingAlternateSetting#0...
Determiningdevicestatus:state=dfuIDLE,status=0
dfuIDLE,continuing
DFUmodedeviceDFUversion0100
Devicereturnedtransfersize64
CopyingdatafromPCtoDFUdevice
Download[=========================]100%16384bytes
Downloaddone.
state(2)=dfuIDLE,status(0)=Noerrorconditionispresent
Done!
Debugging
Using lsusbcommand,thePytrack/Pysensedeviceshouldbevisibleinbothnormaland
bootloadermodes.
Forexemple,aPytrackboardisvisibleaseither:
Bus020Device004:ID04d8:f014MicrochipTechnologyInc.ApplicationSpecific
Device
thisisbootloadermode( f014isUSBPID),activejustfor7-8seconds,ifthereset
buttonwasjustpressedbeforepluggingUSBconnector.
Bus020Device005:ID04d8:f013MicrochipTechnologyInc.PytrackSerial:Pyabcde0
thisisnormal,applicationmode( f013isUSBPID),thismeansthebootloader
verifiedapplicationpartitionanditboot-upcorrectly.
3.2.1UpdatingFirmware
129
Windows7Drivers
PytrackandPysensewillworkoutoftheboxforWindows8/10/+,macOSaswellasLinux.
IfusingWindows7,driverstosupporttheboardswillneedtobeinstalled.
Pleasefollowtheinstructionsbelowtoinstalltherequireddrivers.
Download
Pleasedownloadthedriversoftwarefromthelinkbelow.
Pytrack/Pysense/Pyscan/Expansionboard3Driver
Installation
FirstnavigateopentheWindowsstartmenuandsearch/navigateto DeviceManager.You
shouldseeyourPytrack/Pysenseinthedropdownunderotherdevices.
Rightclickthedeviceandselect UpdateDriverSoftware.
3.2.2InstallingDrivers-Windows7
130
SelecttheoptiontoBrowsemycomputerfordriversoftware.
Nextyouwillneedtonavigatetowhereyoudownloadedthedriverto(e.g.Downloads
Folder).
3.2.2InstallingDrivers-Windows7
131
Specifythefolderinwhichthedriversarecontained.Ifyouhaven'textractedthe .zipfile,
pleasedothisbeforeselectingthefolder.
Youmayreceiveawarning,suggestingthatwindowscan'tverifythepublisherofthisdriver.
Click Installthisdriversoftwareanywayasthislinkpointstoourofficialdriver.
3.2.2InstallingDrivers-Windows7
132
Iftheinstallationwassuccessful,youshouldnowseeawindowspecifyingthatthedriver
wascorrectlyinstalled.
Toconfirmthattheinstallationwascorrect,navigatebacktothe DeviceManagerandclick
thedropdownforotherdevices.Thewarninglabelshouldnowbegoneand
Pytrack/Pysenseshouldbeinstalled.
3.2.2InstallingDrivers-Windows7
133
3.2.2InstallingDrivers-Windows7
134
InstallingLibraries
ToutilisethesensorsonthePytrackandPysense,Pycomhaswrittenlibrariestomake
readingto/fromthevarioussensorsaccessibleviaanAPI.Theselibrariesresideatthe
PycomGitHubrepositoryandthelatestversionscanbefoundunderthereleasespage.
GitHubRepository
Downloadtherepositoryasa .zipfile,navigatetothecorrectdevice(Pysense/Pytrack),
extractthefilesandthenuploadthedesiredfilestothedeviceintheinstructionsbelow.
UploadingtheLibrariestoaDevice
Theselibrariesshouldbeuploadedtoadevice(LoPy,SiPy,WiPy2.0,etc.)inthesame
processasastandardMicroPythonlibrary.Thevarious .pyfilesshouldbeplacedintothe
/libfolderonthedevice.Forexample,ifusingthePysenseandtheuserwishestoenable
theonlyAccelerometerandtheLightSensor,theyshouldplacethefollowing .pyfilesinto
thedevice's /libfolder:
-pysense.py
-LIS2HH12.py
-LTR329ALS01.py
Addasmanyorasfewofthelibrariesthatarerequired.
InadditiontothePysenseorPytrackspecificlibraries,youalsoneedtouploadthe
pycoproc.pyfilefromthe _lib/pycoproc_folderinsidethelibrariesarchive.
ThePytrackandPysenseboardsbehavethesameastheExpansionBoard. Upload,
RunanduploadcodetoPycommodulesviathePymakrPlugin,inexactlythesame
process.
Importing/UsingtheLibraries
Oncethelibrariesareuploadedtothedevice,theycanbeused/importedasatypical
MicroPythonlibrarywouldbe.Forexample,importingandusingthelightsensoronthe
Pysense:
3.2.3InstallingLibraries
135
frompysenseimportPysense
fromLTR329ALS01importLTR329ALS01
py=Pysense()
lt=LTR329ALS01(py)
print(lt.light())
3.2.3InstallingLibraries
136
APIReference
Tosimplifyusability,APIsforthelibrarieshavebeencreated,abstractingawaythelowlevel
interactionswiththesensors.Thenextfollowingpagesrefertotherespectivelibrariesfor
thePytrackandPysense.
3.3APIReference
137
PytrackAPI
ThischapterdescribesthevariouslibrarieswhicharedesignedforthePytrackboard.This
includesdetailsaboutthevariousmethodsandclassesavailableforeachofthePytrack’s
sensors.
3-AxisAccelerometer(LIS2HH12)
Pytrackhasa3-AxisAccelerometerthatprovidesoutputsforaccelerationaswellasroll,
pitchandyaw.
Constructors
classLIS2HH12(pytrack=None,sda='P22',scl='P21')
Createsa LIS2HH12object,thatwillreturnvaluesforacceleration,roll,pitchandyaw.
ConstructormustbepassedaPytrackorI2Cobjecttosuccessfullyconstruct.
Methods
LIS2HH12.acceleration()
Readtheaccelerationfromthe LIS2HH12.Returnsatuplewiththe3valuesofacceleration
(G).
LIS2HH12.roll()
Readthecurrentrollfromthe LIS2HH12.Returnsafloatindegreesintherange-180to
180.
LIS2HH12.pitch()
Readthecurrentpitchfromthe LIS2HH12.Returnsafloatindegreesintherange-90to90.
Oncetheboardtiltsbeyondthisrangethevalueswillrepeat.Thisisduetoalackofyaw
measurement,makingitnotpossibletoknowtheexactorientationoftheboard.
GPSwithGLONASS(QuectelL76-LGNSS)
PytrackhasaGPS(withGLONASS)thatprovidesoutputslongitude/latitude,speedand
otherinformationaboutthePytrack'slocation.
3.3.1Pytrack
138
Constructors
classL76GNSS(pytrack=None,sda='P22',scl='P21',timeout=None)
Createsa L76GNSSobject,thatwillreturnvaluesforlongitudeandlatitude.Constructormust
bepassedaPytrackorI2Cobjecttosuccessfullyconstruct.Setthe timeouttoatime
period(inseconds)fortheGPStosearchforalock.Ifalockisnotfoundbythetimethe
timeouthasexpired,the coordinatesmethodwillreturn (None,None).
Methods
L76GNSS.coordinates(debug=False)
Readthelongitudeandlatitudefromthe L76GNSS.Returnsatuplewiththelongitudeand
latitude.With debugsetto TruetheoutputfromtheGPSisverbose.
Pleasenotethatmorefunctionalityisbeingaddedweeklytotheselibraries.Ifarequired
featureisnotavailable,feelfreetocontributewithapullrequestattheLibrariesGitHub
repository
3.3.1Pytrack
139
PysenseAPI
ThischapterdescribesthevariouslibrarieswhicharedesignedforthePysenseBoard.This
includesdetailsaboutthevariousmethodsandclassesavailableforeachofthePysense’s
sensors.
3-AxisAccelerometer(LIS2HH12)
Pysensehasa3-AxisAccelerometerthatprovidesoutputsforaccelerationaswellasroll,
pitchandyaw.
Constructors
classLIS2HH12(pysense=None,sda='P22',scl='P21')
Createsa LIS2HH12object,thatwillreturnvaluesforacceleration,roll,pitchandyaw.
ConstructormustbepassedaPysenseorI2Cobjecttosuccessfullyconstruct.
Methods
LIS2HH12.acceleration()
Readtheaccelerationfromthe LIS2HH12.Returnsatuplewiththe3valuesofacceleration
(G).
LIS2HH12.roll()
Readthecurrentrollfromthe LIS2HH12.Returnsafloatindegreesintherange-180to
180.
LIS2HH12.pitch()
Readthecurrentpitchfromthe LIS2HH12.Returnsafloatindegreesintherange-90to90.
Oncetheboardtiltsbeyondthisrangethevalueswillrepeat.Thisisduetoalackofyaw
measurement,makingitnotpossibletoknowtheexactorientationoftheboard.
DigitalAmbientLightSensor(LTR-329ALS-01)
Pysensehasaduallightsensorthatprovidesoutputsforexternallightlevelsinlux.Seethe
datasheetformoreinformationaboutthewavelengthsofthetwosensors.
3.3.2Pysense
140
Constructors
classLTR329ALS01(pysense=None,sda='P22',scl='P21',gain=ALS_GAIN_1X,
integration=ALS_INT_100,rate=ALS_RATE_500)
Createsa LTR329ALS01object,thatwillreturnvaluesforlightinlux.Constructormustbe
passedaPysenseorI2Cobjecttosuccessfullyconstruct.
Methods
LTR329ALS01.light()
Readthelightlevelsofboth LTR329ALS01sensors.Returnsatuplewithtwovaluesforlight
levelsinlux.
Arguments
Thefollowingargumentsmaybepassedintotheconstructor.
gain
ALS_GAIN_1X,ALS_GAIN_2X,ALS_GAIN_4X,ALS_GAIN_8X,ALS_GAIN_48X,
ALS_GAIN_96X
integration
ALS_INT_50,ALS_INT_100,ALS_INT_150,ALS_INT_200,ALS_INT_250,ALS_INT_300,
ALS_INT_350,ALS_INT_400
rate
ALS_RATE_50,ALS_RATE_100,ALS_RATE_200,ALS_RATE_500,ALS_RATE_1000,
ALS_RATE_2000
HumidityandTemperatureSensor(SI7006A20)
PysensehasaHumidityandTemperaturesensorthatprovidesvaluesofrelativehumidity
andexternaltemperature.
Constructors
classSI7006A20(pysense=None,sda='P22',scl='P21')
Createsa SI7006A20object,thatwillreturnvaluesforhumidity(%)andtemperature('C).
ConstructormustbepassedaPysenseorI2Cobjecttosuccessfullyconstruct.
3.3.2Pysense
141
Methods
SI7006A20.humidity()
Readtherelativehumidityofthe SI7006A20.Returnsafloatwiththepercentagerelative
humidity.
SI7006A20.temperature()
Readtheexternaltemperatureofthe SI7006A20.Returnsafloatwiththetemperature.
BarometricPressureSensorwithAltimeter(MPL3115A2)
PysensehasaBarometricPressuresensorthatprovidesreadingsforpressure,altitudeas
wellasanadditionaltemperaturesensor.
Constructors
classMPL3115A2(pysense=None,sda='P22',scl='P21',mode=PRESSURE)
Createsa MPL3115A2object,thatwillreturnvaluesforpressure(Pa),altitude(m)and
temperature('C).ConstructormustbepassedaPysenseorI2Cobjecttosuccessfully
construct.
Methods
MPL3115A2.pressure()
Readtheatmosphericpressureofthe MPL3115A2.Returnsafloatwiththepressurein(Pa).
MPL3115A2.altitude()
Readthealtitudeofthe MPL3115A2.Returnsafloatwiththealtitudein(m).
MPL3115A2.temperature()
Readthetemperatureofthe MPL3115A2.Returnsafloatwiththetemperaturein('C).
Arguments
Thefollowingargumentsmaybepassedintotheconstructor.
mode
3.3.2Pysense
142
PRESSURE,ALTITUDE
Pleasenotethatmorefunctionalityisbeingaddedweeklytotheselibraries.Ifarequired
featureisnotavailable,feelfreetocontributewithapullrequestattheLibrariesGitHub
repository
3.3.2Pysense
143
SleepandWakeupforPytrack/Pysense
API
Thischapterdescribesthevariousmethodsforsleepandwakeupwhichareembeddedin
PytrackandPysenselibraries.BothPytrackandPysensehavethesamemethods,although
theappropriateclass,either pytrackor pysense,hastobeinstantiated.
QuickUsageExample
ThefollowingexampleisalsoavailableatSleepWakeupExampleLibrariesGitHub
repository
3.3.3Sleep
144
#frompytrackimportPytrack
frompysenseimportPysense
fromLIS2HH12importLIS2HH12
importtime
#py=Pytrack()
py=Pysense()
#displaytheresetreasoncodeandthesleepremaininginseconds
#possiblevaluesofwakeupreasonare:
#WAKE_REASON_ACCELEROMETER=1
#WAKE_REASON_PUSH_BUTTON=2
#WAKE_REASON_TIMER=4
#WAKE_REASON_INT_PIN=8
print("Wakeupreason:"+str(py.get_wake_reason()))
print("Approximatesleepremaining:"+str(py.get_sleep_remaining())+"sec")
time.sleep(0.5)
#enablewakeupsourcefromINTpin
py.setup_int_pin_wake_up(False)
acc=LIS2HH12()
#enableactivityandalsoinactivityinterrupts,usingthedefaultcallbackhandler
py.setup_int_wake_up(True,True)
#settheaccelerationthresholdto2000mG(2G)andthemindurationto200ms
acc.enable_activity_interrupt(2000,200)
#gotosleepfor5minutesmaximumifnoaccelerometerinterrupthappens
py.setup_sleep(300)
py.go_to_sleep()
Methods
pytrack.get_sleep_remaining()
Intheeventofasleepsessionthatwasawokenbyanasynchronousevent(Accelerometer,
INTpinorResetbutton)theapproximatesleepremaininginterval(expressedinseconds)
canbefoundout.Theuserhastomanuallyuse setup_sleep()toconfigurethenextsleep
interval.
pytrack.get_wake_reason()
Returnsthelastwakeupreason.Possiblevaluesare:
3.3.3Sleep
145
#WAKE_REASON_ACCELEROMETER=1#Accelerometeractivity/inactivitydetection
#WAKE_REASON_PUSH_BUTTON=2#Pytrack/Pysenseresetbuttom
#WAKE_REASON_TIMER=4#Normaltimeoutofthesleepinterval
#WAKE_REASON_INT_PIN=8#INTpin
Note:the WAKE_REASON_INT_PINcanbeusedifthePIC_RC1pin(pin#6onExternalIO
Header)istoggled.
Asintheaboveexample,thismethodshouldbecalledatthebeginningofthescript,tofind
outthereset(wakeup)reason.
pytrack.go_to_sleep([gps=True])
Putstheboardinsleepmode,fortheduration,whichhastobesetpreviouslywith
pytrack.setup_sleep(timout_sec).TheoptionalbooleanparametersetstheGPSstate
duringsleep.
MicroPythoncode,whichisafterthisfunction,isnotexecuted,aswakeupwillrestart
MicroPython.
pytrack.setup_int_wake_up(rising,falling])
Enablesaswakeupsource,theaccelerometerINTpin(PIC-RA5).Thebooleanparameters
willindicaterisingedge(activitydetection)and/orfallingedge(inactivitydetection)is
configured.
Theaccelerometer(class LIS2HH12)hastobealsoconfiguredforacertainacceleration
thresholdandduration.Codesnippet:
frompytrackimportPytrack
fromLIS2HH12importLIS2HH12
py=Pytrack()
acc=LIS2HH12()
#enableactivityandalsoinactivityinterrupts,usingthedefaultcallbackhandler
py.setup_int_wake_up(True,True)
#settheaccelerationthresholdto2000mG(2G)andthemindurationto200ms
acc.enable_activity_interrupt(2000,200)
pytrack.setup_int_pin_wake_up([rising_edge=True])
Enablesaswakeupsource,theINTpic(PIC-RC1,pin#6onExternalIOHeader).Either
risingorfallingedgehastobeset,bydefaultit'srisingedge.
3.3.3Sleep
146
pytrack.setup_sleep(time_seconds)
Setsthesleepinterval,specifiedinseconds.Theactualsleepwillbestartedbycalling
go_to_sleep()method.
Pleasenotethatmorefunctionalityisbeingaddedweeklytotheselibraries.Ifarequired
featureisnotavailable,feelfreetocontributewithapullrequestattheLibrariesGitHub
repository
3.3.3Sleep
147
TutorialsandExamples
ThissectioncontainstutorialsandexamplesforusewithPycommodulesandExpansion
boards.
GeneralPycomtutorialscontainstutorialsthatmayberunonanyPycomdevice,suchas
connectingtoaWiFinetwork,Bluetooth,controllingI/Opinsetc.Latersectionsarespecific
totheLoPyandSiPydevicessuchassettingupaLoRanodeorconnectingtotheSigfox
network.ThefinalsectionsarerelatedtoexamplesusingthePytrackandPysense.
Beforestarting,ensurethatanyPycomdevicesarerunningthelatestfirmware;for
instructionsseeFirmwareUpdates.
Thesourcecodeforthesetutorials,alongwiththerequiredlibrariescanbefoundininthe
pycom-librariesrepository.
4.1Introduction
148
AllPycomDeviceExamples
ThissectioncontainsgenericexamplesthatwillworkacrossallPycomdevicesand
ExpansionBoards.
4.2AllPycomDeviceExamples
149
UsingtheREPLPrompt
UsingthePymakrPlugin,openandconnectadeviceoruseserialterminal(PuTTY,screen,
picocom,etc).Uponconnecting,thereshouldbeablankscreenwithaflashingcursor.Press
EnterandaMicroPythonpromptshouldappear,i.e. >>>.Let’smakesureitisworkingwith
theobligatorytest:
>>>print("HelloLoPy!")
HelloLoPy!
Intheexampleabove,the >>>charactersshouldnotbetyped.Theyaretheretoindicate
thatthetextshouldbeplacedaftertheprompt.Oncethetexthasbeenentered
print("HelloLoPy!")andpressed Enter,theoutputshouldappearonscreen,identicalto
theexampleabove.
BasicPythoncommandscanbetestedoutinasimilarfashion.
Ifthisisnotworking,tryeitherahardresetorasoftreset;seebelow.
Herearesomeotherexample,utilisingthedevice'shardwarefeatures:
>>>frommachineimportPin
>>>led=Pin('G16',mode=Pin.OUT,value=1)
>>>led(0)
>>>led(1)
>>>led.toggle()
>>>1+2
3
>>>5/2
2.5
>>>20*'py'
'pypypypypypypypypypypypypypypypypypypypy'
ResettingtheDevice
Ifsomethinggoeswrong,thedevicecanberesetwithtwomethods.Thefirstistopress
CTRL-DattheMicroPythonprompt,whichwillperformasoftreset.Amessage,asfollowing,
willappear:
4.2.1REPL
150
>>>
PYB:softreboot
MicroPythonv1.4.6-146-g1d8b5e5on2016-10-21;LoPywithESP32
Type"help()"formoreinformation.
>>>
Ifthatstillisn’tworkingahardresetcanbeperformed(power-off/on)bypressingthe RST
switch(thesmallblackbuttonnexttotheRGBLED).Usingtelnet,thiswillendthesession,
disconnectingtheprogramthatwasusedtoconnecttothePycomDevice.
4.2.1REPL
151
WLAN
TheWLANisasystemfeatureofallPycomdevices,thereforeitisenabledbydefault.
InordertoretrievethecurrentWLANinstance,run:
>>>fromnetworkimportWLAN
>>>wlan=WLAN()#wecalltheconstructorwithoutparams
Thecurrentmode( WLAN.APafterpowerup)maybecheckedbyrunning:
>>>wlan.mode()
WhenchangingtheWLANmode,iffollowingtheinstructionsbelow,theWLAN
connectiontothePycomdevicewillbebroken.Thismeanscommandswillnotrun
interactivelyoverWiFi.
Therearetwowaysaroundthis:
1. Putthissetupcodeintothe boot.pyfileofthePycomdevicesothatitgets
executedautomaticallyafterreset.
2. DuplicatetheREPLonUART.ThiswaycommandscanberunviaSerialUSB.
ConnectingtoaRouter
TheWLANnetworkclassalwaysbootsin WLAN.APmode;toconnectittoanexisting
network,theWiFiclassmustbeconfiguredasastation:
fromnetworkimportWLAN
wlan=WLAN(mode=WLAN.STA)
Nowthedevicemayproceedtoscanfornetworks:
4.2.2WLAN
152
nets=wlan.scan()
fornetinnets:
ifnet.ssid=='mywifi':
print('Networkfound!')
wlan.connect(net.ssid,auth=(net.sec,'mywifikey'),timeout=5000)
whilenotwlan.isconnected():
machine.idle()#savepowerwhilewaiting
print('WLANconnectionsucceeded!')
break
AssigningaStaticIPAddressatBootUp
Iftheuserswantstheirdevicetoconnecttoahomerouteruponbootup,usingwithafixed
IPaddress,usethefollowingscriptas /flash/boot.py:
importmachine
fromnetworkimportWLAN
wlan=WLAN()#getcurrentobject,withoutchangingthemode
ifmachine.reset_cause()!=machine.SOFT_RESET:
wlan.init(mode=WLAN.STA)
#configurationbelowMUSTmatchyourhomeroutersettings!!
wlan.ifconfig(config=('192.168.178.107','255.255.255.0','192.168.178.1','8.8.8.
8'))
ifnotwlan.isconnected():
#changethelinebelowtomatchyournetworkssid,securityandpassword
wlan.connect('mywifi',auth=(WLAN.WPA2,'mywifikey'),timeout=5000)
whilenotwlan.isconnected():
machine.idle()#savepowerwhilewaiting
Noticehowwecheckfortheresetcauseandtheconnectionstatus,thisiscrucialin
ordertobeabletosoftresettheLoPyduringatelnetsessionwithoutbreakingthe
connection.
MultipleNetworksusingaStaticIPAddress
Thefollowingscriptholdsalistwithnetsandanoptionallistof wlan_configtosetafixedIP
4.2.2WLAN
153
importos
importmachine
uart=machine.UART(0,115200)
os.dupterm(uart)
known_nets={
'<net>':{'pwd':'<password>'},
'<net>':{'pwd':'<password>','wlan_config':('10.0.0.114','255.255.0.0','10.0
.0.1','10.0.0.1')},#(ip,subnet_mask,gateway,DNS_server)
}
ifmachine.reset_cause()!=machine.SOFT_RESET:
fromnetworkimportWLAN
wl=WLAN()
wl.mode(WLAN.STA)
original_ssid=wl.ssid()
original_auth=wl.auth()
print("Scanningforknownwifinets")
available_nets=wl.scan()
nets=frozenset([e.ssidforeinavailable_nets])
known_nets_names=frozenset([keyforkeyinknown_nets])
net_to_use=list(nets&known_nets_names)
try:
net_to_use=net_to_use[0]
net_properties=known_nets[net_to_use]
pwd=net_properties['pwd']
sec=[e.secforeinavailable_netsife.ssid==net_to_use][0]
if'wlan_config'innet_properties:
wl.ifconfig(config=net_properties['wlan_config'])
wl.connect(net_to_use,(sec,pwd),timeout=10000)
whilenotwl.isconnected():
machine.idle()#savepowerwhilewaiting
print("Connectedto"+net_to_use+"withIPaddress:"+wl.ifconfig()[0])
exceptExceptionase:
print("Failedtoconnecttoanyknownnetwork,goingintoAPmode")
wl.init(mode=WLAN.AP,ssid=original_ssid,auth=original_auth,channel=6,anten
na=WLAN.INT_ANT)
ConnectingtoaWPA2-Enterprisenetwork
ConnectingwithEAP-TLS:
Beforeconnecting,obtainandcopythepublicandprivatekeystothedevice,e.g.under
location /flash/cert.Ifitisrequiredtovalidatetheserver’spublickey,anappropriateCA
certificate(chain)mustalsobeprovided.
4.2.2WLAN
154
fromnetworkimportWLAN
wlan=WLAN(mode=WLAN.STA)
wlan.connect(ssid='mywifi',auth=(WLAN.WPA2_ENT,),identity='myidentity',ca_certs='/f
lash/cert/ca.pem',keyfile='/flash/cert/client.key',certfile='/flash/cert/client.crt'
)
ConnectingwithEAP-PEAPorEAP-TTLS:
IncaseofEAP-PEAP(orEAP-TTLS),theclientkeyandcertificatearenotnecessary,onlya
usernameandpasswordpair.Ifitisrequiredtovalidatetheserver’spublickey,an
appropriateCAcertificate(chain)mustalsobeprovided.
fromnetworkimportWLAN
wlan=WLAN(mode=WLAN.STA)
wlan.connect(ssid='mywifi',auth=(WLAN.WPA2_ENT,'username','password'),identity='my
identity',ca_certs='/flash/cert/ca.pem')
4.2.2WLAN
155
Bluetooth
Atpresent,basicBLEfunctionalityisavailable.Morefeatureswillbeimplementedinthe
nearfuture,suchaspairing.Thispagewillbeupdatedinlinewiththesefeatures.
Fullinfoon bluetoothcanbefoundwithinBluetoothpageoftheFirmwareAPIReference.
ScanforBLEDevices
Scanforalloftheadvertisingdeviceswithinrangeofthescanningdevice.
bluetooth.start_scan(10)#startsscanningandstopafter10seconds
bluetooth.start_scan(-1)#startsscanningindefinitelyuntilbluetooth.stop_scan()i
scalled
RawDatafromaBLEDevice
Aquickusageexamplethatscansandprintstherawdatafromadvertisements.
fromnetworkimportBluetooth
bluetooth=Bluetooth()
bluetooth.start_scan(-1)#startscanningwithnotimeout
whileTrue:
print(bluetooth.get_adv())
ConnecttoaBLEDevice
Connectingtoadevicethatissendingadvertisements.
4.2.3Bluetooth
156
fromnetworkimportBluetooth
importubinascii
bluetooth=Bluetooth()
#scanuntilwecanconnecttoanyBLEdevicearound
bluetooth.start_scan(-1)
adv=None
whileTrue:
adv=bluetooth.get_adv()
ifadv:
try:
bluetooth.connect(adv.mac)
except:
#startscanningagain
bluetooth.start_scan(-1)
continue
break
print("Connectedtodevicewithaddr={}".format(ubinascii.hexlify(adv.mac)))
ConnecttoaBLEDeviceandRetrieveData
Connectingtoadevicenamed'HeartRate'andreceivingdatafromit’sservices.
4.2.3Bluetooth
157
fromnetworkimportBluetooth
importtime
bt=Bluetooth()
bt.start_scan(-1)
whileTrue:
adv=bt.get_adv()
ifadvandbt.resolve_adv_data(adv.data,Bluetooth.ADV_NAME_CMPL)=='HeartRate':
try:
conn=bt.connect(adv.mac)
services=conn.services()
forserviceinservices:
time.sleep(0.050)
iftype(service.uuid())==bytes:
print('Readingcharsfromservice={}'.format(service.uuid()))
else:
print('Readingcharsfromservice=%x'%service.uuid())
chars=service.characteristics()
forcharinchars:
if(char.properties()&Bluetooth.PROP_READ):
print('char{}value={}'.format(char.uuid(),char.read()))
conn.disconnect()
break
except:
pass
else:
time.sleep(0.050)
RetrievetheName&ManufacturerfromaBLEDevice
Using resolve_adv_data()toattempttoretrievethenameandmanufacturerdatafromthe
advertiser.
4.2.3Bluetooth
158
importubinascii
fromnetworkimportBluetooth
bluetooth=Bluetooth()
bluetooth.start_scan(20)
whilebluetooth.isscanning():
adv=bluetooth.get_adv()
ifadv:
#trytogetthecompletename
print(bluetooth.resolve_adv_data(adv.data,Bluetooth.ADV_NAME_CMPL))
mfg_data=bluetooth.resolve_adv_data(adv.data,Bluetooth.ADV_MANUFACTURER_DAT
A)
ifmfg_data:
#trytogetthemanufacturerdata(Apple'siBeacondataissenthere)
print(ubinascii.hexlify(mfg_data))
4.2.3Bluetooth
159
HTTPS
Basicconnectionusing ssl.wrap_socket().
importsocket
importssl
s=socket.socket()
ss=ssl.wrap_socket(s)
ss.connect(socket.getaddrinfo('www.google.com',443)[0][-1])
Belowisanexampleusingcertificateswiththeblynkcloud.
Certificatewasdownloadedfromtheblynkexamplesfolderandplacedin /flash/cert/on
thedevice.
importsocket
importssl
s=socket.socket()
ss=ssl.wrap_socket(s,cert_reqs=ssl.CERT_REQUIRED,ca_certs='/flash/cert/ca.pem')
ss.connect(socket.getaddrinfo('cloud.blynk.cc',8441)[0][-1])
Formoreinfo,checkthe sslmoduleintheAPIreference.
4.2.4HTTPS
160
MQTT
MQTTisalightweightmessagingprotocolthatisidealforsendingsmallpacketsofdatato
andfromIoTdevicesviaWiFi.
ThebrokerusedinthisexampleistheIOAdafruit)platform,whichisfreeandallowsfor
tinkeringwithMQTT.
VisitIOAdafruitandcreateanaccount.You'llneedtogetholdofanAPIKeyaswellasyour
credentials.VisitthisguideformoreinformationaboutMQTTandhowtouseitwith
Adafruit'sBroker.
ThisexamplewillsendamessagetoatopicontheAdafruitMQTTbrokerandthenalso
subscribetothesametopic,inordertoshowhowtousethesubscribefunctionality.
frommqttimportMQTTClient
fromnetworkimportWLAN
importmachine
importtime
defsub_cb(topic,msg):
print(msg)
wlan=WLAN(mode=WLAN.STA)
wlan.connect("yourwifinetwork",auth=(WLAN.WPA2,"wifipassword"),timeout=5000)
whilenotwlan.isconnected():
machine.idle()
print("ConnectedtoWiFi\n")
client=MQTTClient("device_id","io.adafruit.com",user="your_username",password="you
r_api_key",port=1883)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic="youraccount/feeds/lights")
whileTrue:
print("SendingON")
client.publish(topic="youraccount/feeds/lights",msg="ON")
time.sleep(1)
print("SendingOFF")
client.publish(topic="youraccount/feeds/lights",msg="OFF")
client.check_msg()
time.sleep(1)
4.2.5MQTT
161
4.2.5MQTT
162
AmazonWebServices
TheAWSIoTplatformenablesdevicestoconnecttotheAmazoncloudandletsapplications
inthecloudinteractwithInternet-connectedthings.CommonIoTapplicationseithercollect
andprocesstelemetryfromdevicesorenableuserstocontroladeviceremotely.Things
reporttheirstatebypublishingmessages,inJSONformat,onMQTTtopics.
FormoreinformationseethisPDFFile.
GettingStartedwithAWSIoT
Creatingthemessagebroker(Amazonwebsite):
SignintotheAWSManagementConsole
NavigatetotheIoTConsolebyclickingontheAWSIoTlink
Intheleftnavigationpane,chooseRegister/Manage
Clickonthecreatebutton,giveyourdeviceanameandpresscreate
Clickonthedevicethathasbeencreated
OntheDetailspage,intheleftnavigationpane,chooseSecurity
OntheCertificatespage,chooseCreatecertificate
Downloadallthecertificates,thenpresstheActivateandtheAttachaPolicybuttons.
Seeimage
ClickontheCreateNewPolicybutton
OntheCreatePolicypage,chooseapolicynameandtheactionstoauthorise.
Gotothecertificatespage,clickonthethreedotsofyourcertificateandattachthe
policytothecertificateasshowninthediagram
Settingupthedevice(Pycomdevice):
DownloadthelatestsamplecodefromthePycomGitHubRepository.
ConnecttothedeviceviaFTPandputtherootCAcertificate,theclientcertificate
(*.pem.crt)andtheprivatekey( *.private.pem.key)inthe /flash/certfolder.
UpdatetheconfigfilewithyourWiFisettings,theAWSHostandthecertificatepaths.
Putthe config.pyandthe main.pyinthedeviceflash
Configuration( config.py):
4.2.6AWS
163
ThisfilecontainstheWiFi,certificatepathsandapplicationspecificsettingsthatneedtobe
updatedbytheuser.
#WiFiconfiguration
WIFI_SSID='my_wifi_ssid'
WIFI_PASS='my_wifi_password'
#AWSgeneralconfiguration
AWS_PORT=8883
AWS_HOST='aws_host_url'
AWS_ROOT_CA='/flash/cert/aws_root.ca'
AWS_CLIENT_CERT='/flash/cert/aws_client.cert'
AWS_PRIVATE_KEY='/flash/cert/aws_private.key'
##################Subscribe/Publishclient#################
CLIENT_ID='PycomPublishClient'
TOPIC='PublishTopic'
OFFLINE_QUEUE_SIZE=-1
DRAINING_FREQ=2
CONN_DISCONN_TIMEOUT=10
MQTT_OPER_TIMEOUT=5
LAST_WILL_TOPIC='PublishTopic'
LAST_WILL_MSG='ToAll:Lastwillmessage'
#######################Shadowupdater########################
#THING_NAME="mythingname"
#CLIENT_ID="ShadowUpdater"
#CONN_DISCONN_TIMEOUT=10
#MQTT_OPER_TIMEOUT=5
#######################DeltaListener########################
#THING_NAME="mythingname"
#CLIENT_ID="DeltaListener"
#CONN_DISCONN_TIMEOUT=10
#MQTT_OPER_TIMEOUT=5
#######################ShadowEcho########################
#THING_NAME="mythingname"
#CLIENT_ID="ShadowEcho"
#CONN_DISCONN_TIMEOUT=10
#MQTT_OPER_TIMEOUT=5
Subscibe/Publish( main.py)
Tosubscribetoatopic:
GototheAWSIotpage,clickonmanageandchooseyourdevice
Fromthelefthandside,chooseActivityandthenclickMQTTclient.
Choosethetopicnameyouenteredintheconfigurationfile.
4.2.6AWS
164
Messagesshouldbepublishedasshowninthediagram
#userspecifiedcallbackfunction
defcustomCallback(client,userdata,message):
print("Receivedanewmessage:")
print(message.payload)
print("fromtopic:")
print(message.topic)
print("--------------\n\n")
#configuretheMQTTclient
pycomAwsMQTTClient=AWSIoTMQTTClient(config.CLIENT_ID)
pycomAwsMQTTClient.configureEndpoint(config.AWS_HOST,config.AWS_PORT)
pycomAwsMQTTClient.configureCredentials(config.AWS_ROOT_CA,config.AWS_PRIVATE_KEY,co
nfig.AWS_CLIENT_CERT)
pycomAwsMQTTClient.configureOfflinePublishQueueing(config.OFFLINE_QUEUE_SIZE)
pycomAwsMQTTClient.configureDrainingFrequency(config.DRAINING_FREQ)
pycomAwsMQTTClient.configureConnectDisconnectTimeout(config.CONN_DISCONN_TIMEOUT)
pycomAwsMQTTClient.configureMQTTOperationTimeout(config.MQTT_OPER_TIMEOUT)
pycomAwsMQTTClient.configureLastWill(config.LAST_WILL_TOPIC,config.LAST_WILL_MSG,1)
#ConnecttoMQTTHost
ifpycomAwsMQTTClient.connect():
print('AWSconnectionsucceeded')
#Subscribetotopic
pycomAwsMQTTClient.subscribe(config.TOPIC,1,customCallback)
time.sleep(2)
#Sendmessagetohost
loopCount=0
whileloopCount<8:
pycomAwsMQTTClient.publish(config.TOPIC,"NewMessage"+str(loopCount),1)
loopCount+=1
time.sleep(5.0)
Shadowupdater( main.py)
4.2.6AWS
165
#userspecifiedcallbackfunctions
defcustomShadowCallback_Update(payload,responseStatus,token):
ifresponseStatus=="timeout":
print("Updaterequest"+token+"timeout!")
ifresponseStatus=="accepted":
payloadDict=json.loads(payload)
print("Updaterequestwithtoken:"+token+"accepted!")
print("property:"+str(payloadDict["state"]["desired"]["property"]))
ifresponseStatus=="rejected":
print("Updaterequest"+token+"rejected!")
defcustomShadowCallback_Delete(payload,responseStatus,token):
ifresponseStatus=="timeout":
print("Deleterequest"+token+"timeout!")
ifresponseStatus=="accepted":
print("Deleterequestwithtoken:"+token+"accepted!")
ifresponseStatus=="rejected":
print("Deleterequest"+token+"rejected!")
#configuretheMQTTclient
pycomAwsMQTTShadowClient=AWSIoTMQTTShadowClient(config.CLIENT_ID)
pycomAwsMQTTShadowClient.configureEndpoint(config.AWS_HOST,config.AWS_PORT)
pycomAwsMQTTShadowClient.configureCredentials(config.AWS_ROOT_CA,config.AWS_PRIVATE_K
EY,config.AWS_CLIENT_CERT)
pycomAwsMQTTShadowClient.configureConnectDisconnectTimeout(config.CONN_DISCONN_TIMEOUT
)
pycomAwsMQTTShadowClient.configureMQTTOperationTimeout(config.MQTT_OPER_TIMEOUT)
#ConnecttoMQTTHost
ifpycomAwsMQTTShadowClient.connect():
print('AWSconnectionsucceeded')
deviceShadowHandler=pycomAwsMQTTShadowClient.createShadowHandlerWithName(config.THIN
G_NAME,True)
#DeleteshadowJSONdoc
deviceShadowHandler.shadowDelete(customShadowCallback_Delete,5)
#Updateshadowinaloop
loopCount=0
whileTrue:
JSONPayload='{"state":{"desired":{"property":'+str(loopCount)+'}}}'
deviceShadowHandler.shadowUpdate(JSONPayload,customShadowCallback_Update,5)
loopCount+=1
time.sleep(5)
DeltaListener( main.py)
4.2.6AWS
166
#CustomShadowcallback
defcustomShadowCallback_Delta(payload,responseStatus,token):
payloadDict=json.loads(payload)
print("property:"+str(payloadDict["state"]["property"]))
print("version:"+str(payloadDict["version"]))
#configuretheMQTTclient
pycomAwsMQTTShadowClient=AWSIoTMQTTShadowClient(config.CLIENT_ID)
pycomAwsMQTTShadowClient.configureEndpoint(config.AWS_HOST,config.AWS_PORT)
pycomAwsMQTTShadowClient.configureCredentials(config.AWS_ROOT_CA,config.AWS_PRIVATE_K
EY,config.AWS_CLIENT_CERT)
pycomAwsMQTTShadowClient.configureConnectDisconnectTimeout(config.CONN_DISCONN_TIMEOUT
)
pycomAwsMQTTShadowClient.configureMQTTOperationTimeout(config.MQTT_OPER_TIMEOUT)
#ConnecttoMQTTHost
ifpycomAwsMQTTShadowClient.connect():
print('AWSconnectionsucceeded')
deviceShadowHandler=pycomAwsMQTTShadowClient.createShadowHandlerWithName(config.THIN
G_NAME,True)
#Listenondeltas
deviceShadowHandler.shadowRegisterDeltaCallback(customShadowCallback_Delta)
#Loopforever
whileTrue:
time.sleep(1)
4.2.6AWS
167
ADC
ThisexampleisasimpleADCsample.Formoreinformationpleasesee ADC.
frommachineimportADC
adc=ADC(0)
adc_c=adc.channel(pin='P13')
adc_c()
adc_c.value()
Calibration
CurrentlytheESP32'sADCisnotcalibratedfromthefactory.Thismeansitmustbe
calibratedeachtimeyouwishtouseit.Todothisyoumustfirstlymeasuretheinternal
voltagereference.Thefollowingcodewillconnectthe1.1vreferenceto P22
frommachineimportADC
adc=ADC()
#OutputVrefofP22
adc.vref_to_pin('P22')
Nowthatthevoltagereferenceisexternallyaccessibleyoushouldmeasureitwiththemost
accuratevoltmeteryouhaveaccessto.Notedownthereadinginmillivolts,e.g. 1120.To
disconnectthe1.1vreferencefrom P22pleaseresetyourmodule.Youcannowcalibrate
theADCbytellingitthetruevalueoftheinternalreference.Youshouldthencheckyour
calibrationbyconnectingtheADCtoaknownvoltagesource.
#Setcalibration-seenoteabove
adc.vref(1100)
#Checkcalibrationbyreadingaknownvoltage
adc_c=adc.channel(pin='P16',attn=ADC.ATTN_11DB)
print(adc_c.voltage())
4.2.7ADC
168
I2C
ThefollowingexamplereceivesdatafromalightsensorusingI2C.Sensorusedisthe
BH1750FVIDigitalLightSensor.
importtime
frommachineimportI2C
importbh1750fvi
i2c=I2C(0,I2C.MASTER,baudrate=100000)
light_sensor=bh1750fvi.BH1750FVI(i2c,addr=i2c.scan()[0])
while(True):
data=light_sensor.read()
print(data)
time.sleep(1)
DriversfortheBH1750FVI
Placethissamplecodeintoafilenamed bh1750fvi.py.Thiscanthenbeimportedasa
library.
#SimpledriverfortheBH1750FVIdigitallightsensor
classBH1750FVI:
MEASUREMENT_TIME=const(120)
def__init__(self,i2c,addr=0x23,period=150):
self.i2c=i2c
self.period=period
self.addr=addr
self.time=0
self.value=0
self.i2c.writeto(addr,bytes([0x10]))#startcontinuos1Luxreadingsevery1
20ms
defread(self):
self.time+=self.period
ifself.time>=MEASUREMENT_TIME:
self.time=0
data=self.i2c.readfrom(self.addr,2)
self.value=(((data[0]<<8)+data[1])*1200)//1000
returnself.value
4.2.8I2C
169
LightsensorandLoRa
Thisisthesamecode,withaddedLoRaconnectivity,sendingtheluxvaluefromthelight
sensortoanotherLoRaenableddevice.
importsocket
importtime
importpycom
importstruct
fromnetworkimportLoRa
frommachineimportI2C
importbh1750fvi
LORA_PKG_FORMAT="!BH"
LORA_CONFIRM_FORMAT="!BB"
DEVICE_ID=1
pycom.heartbeat(False)
lora=LoRa(mode=LoRa.LORA,tx_iq=True,region=LoRa.EU868)
lora_sock=socket.socket(socket.AF_LORA,socket.SOCK_RAW)
lora_sock.setblocking(False)
i2c=I2C(0,I2C.MASTER,baudrate=100000)
light_sensor=bh1750fvi.BH1750FVI(i2c,addr=i2c.scan()[0])
while(True):
msg=struct.pack(LORA_PKG_FORMAT,DEVICE_ID,light_sensor.read())
lora_sock.send(msg)
pycom.rgbled(0x150000)
wait=5
while(wait>0):
wait=wait-0.1
time.sleep(0.1)
recv_data=lora_sock.recv(64)
if(len(recv_data)>=2):
status,device_id=struct.unpack(LORA_CONFIRM_FORMAT,recv_data)
if(device_id==DEVICE_IDandstatus==200):
pycom.rgbled(0x001500)
wait=0
time.sleep(1)
4.2.8I2C
170
4.2.8I2C
171
OnewireDriver
ThistutorialexplainshowtoconnectandreaddatafromaDS18x20temperaturesensor.
Theonewirelibraryisalsoavailableatthepycom-librariesGitHubRepository.
Basicusage
importtime
frommachineimportPin
fromonewireimportDS18X20
fromonewireimportOneWire
#DS18B20datalineconnectedtopinP10
ow=OneWire(Pin('P10'))
temp=DS18X20(ow)
whileTrue:
print(temp.read_temp_async())
time.sleep(1)
temp.start_conversion()
time.sleep(1)
Library
#!/usr/bin/envpython3
"""
OneWirelibraryforMicroPython
"""
importtime
importmachine
classOneWire:
CMD_SEARCHROM=const(0xf0)
CMD_READROM=const(0x33)
CMD_MATCHROM=const(0x55)
CMD_SKIPROM=const(0xcc)
def__init__(self,pin):
self.pin=pin
self.pin.init(pin.OPEN_DRAIN,pin.PULL_UP)
defreset(self):
"""
4.2.9OnewireDriver
172
Performtheonewireresetfunction.
ReturnsTrueifadeviceassertedapresencepulse,Falseotherwise.
"""
sleep_us=time.sleep_us
disable_irq=machine.disable_irq
enable_irq=machine.enable_irq
pin=self.pin
pin(0)
sleep_us(480)
i=disable_irq()
pin(1)
sleep_us(60)
status=notpin()
enable_irq(i)
sleep_us(420)
returnstatus
defread_bit(self):
sleep_us=time.sleep_us
enable_irq=machine.enable_irq
pin=self.pin
pin(1)#halfofthedevicesdon'tmatchCRCwithoutthisline
i=machine.disable_irq()
pin(0)
sleep_us(1)
pin(1)
sleep_us(1)
value=pin()
enable_irq(i)
sleep_us(40)
returnvalue
defread_byte(self):
value=0
foriinrange(8):
value|=self.read_bit()<<i
returnvalue
defread_bytes(self,count):
buf=bytearray(count)
foriinrange(count):
buf[i]=self.read_byte()
returnbuf
defwrite_bit(self,value):
sleep_us=time.sleep_us
pin=self.pin
i=machine.disable_irq()
pin(0)
sleep_us(1)
4.2.9OnewireDriver
173
pin(value)
sleep_us(60)
pin(1)
sleep_us(1)
machine.enable_irq(i)
defwrite_byte(self,value):
foriinrange(8):
self.write_bit(value&1)
value>>=1
defwrite_bytes(self,buf):
forbinbuf:
self.write_byte(b)
defselect_rom(self,rom):
"""
Selectaspecificdevicetotalkto.Passinromasabytearray(8bytes).
"""
self.reset()
self.write_byte(CMD_MATCHROM)
self.write_bytes(rom)
defcrc8(self,data):
"""
ComputeCRC
"""
crc=0
foriinrange(len(data)):
byte=data[i]
forbinrange(8):
fb_bit=(crc^byte)&0x01
iffb_bit==0x01:
crc=crc^0x18
crc=(crc>>1)&0x7f
iffb_bit==0x01:
crc=crc|0x80
byte=byte>>1
returncrc
defscan(self):
"""
ReturnalistofROMsforallattacheddevices.
EachROMisreturnedasabytesobjectof8bytes.
"""
devices=[]
diff=65
rom=False
foriinrange(0xff):
rom,diff=self._search_rom(rom,diff)
ifrom:
devices+=[rom]
ifdiff==0:
4.2.9OnewireDriver
174
break
returndevices
def_search_rom(self,l_rom,diff):
ifnotself.reset():
returnNone,0
self.write_byte(CMD_SEARCHROM)
ifnotl_rom:
l_rom=bytearray(8)
rom=bytearray(8)
next_diff=0
i=64
forbyteinrange(8):
r_b=0
forbitinrange(8):
b=self.read_bit()
ifself.read_bit():
ifb:#therearenodevicesorthereisanerroronthebus
returnNone,0
else:
ifnotb:#collision,twodeviceswithdifferentbitmeaning
ifdiff>ior((l_rom[byte]&(1<<bit))anddiff!=i):
b=1
next_diff=i
self.write_bit(b)
ifb:
r_b|=1<<bit
i-=1
rom[byte]=r_b
returnrom,next_diff
classDS18X20(object):
def__init__(self,onewire):
self.ow=onewire
self.roms=[romforrominself.ow.scan()ifrom[0]==0x10orrom[0]==0x28
]
defisbusy(self):
"""
CheckswetheroneoftheDS18x20devicesonthebusisbusy
performingatemperatureconversion
"""
returnnotself.ow.read_bit()
defstart_conversion(self,rom=None):
"""
StartthetempconversionononeDS18x20device.
Passthe8-bytebytesobjectwiththeROMofthespecificdeviceyouwanttor
ead.
IfonlyoneDS18x20deviceisattachedtothebusyoumayomittheromparamet
er.
"""
rom=romorself.roms[0]
4.2.9OnewireDriver
175
ow=self.ow
ow.reset()
ow.select_rom(rom)
ow.write_byte(0x44)#ConvertTemp
defread_temp_async(self,rom=None):
"""
ReadthetemperatureofoneDS18x20deviceiftheconversioniscomplete,
otherwisereturnNone.
"""
ifself.isbusy():
returnNone
rom=romorself.roms[0]
ow=self.ow
ow.reset()
ow.select_rom(rom)
ow.write_byte(0xbe)#Readscratch
data=ow.read_bytes(9)
returnself.convert_temp(rom[0],data)
defconvert_temp(self,rom0,data):
"""
Converttherawtemperaturedataintodegreescelsiusandreturnasafixedpo
intwith2decimalplaces.
"""
temp_lsb=data[0]
temp_msb=data[1]
ifrom0==0x10:
iftemp_msb!=0:
#convertnegativenumber
temp_read=temp_lsb>>1|0x80#truncatebit0byshifting,fillh
ighbitwith1.
temp_read=-((~temp_read+1)&0xff)#nowconvertfromtwo'scomple
ment
else:
temp_read=temp_lsb>>1#truncatebit0byshifting
count_remain=data[6]
count_per_c=data[7]
temp=100*temp_read-25+(count_per_c-count_remain)//count_per_c
returntemp
elifrom0==0x28:
return(temp_msb<<8|temp_lsb)*100//16
else:
assertFalse
4.2.9OnewireDriver
176
Threading
MicroPythonsupportsspawningthreadsbythe _threadmodule.Thefollowingexample
demonstratestheuseofthismodule.Athreadissimplydefinedasafunctionthatcan
receiveanynumberofparameters.Below3threadsarestarted,eachoneperformaprintat
adifferentinterval.
import_thread
importtime
defth_func(delay,id):
whileTrue:
time.sleep(delay)
print('Runningthread%d'%id)
foriinrange(3):
_thread.start_new_thread(th_func,(i+1,i))
UsingLocks:
import_thread
a_lock=_thread.allocate_lock()
witha_lock:
print("a_lockislockedwhilethisexecutes")
4.2.10Threading
177
RGBLED
BydefaulttheheartbeatLEDflashesinbluecolouronceevery4stosignalthatthesystem
isalive.Thiscanbeoverriddenthroughthe pycommodule.
importpycom
pycom.heartbeat(False)
pycom.rgbled(0xff00)#turnontheRGBLEDingreencolour
TheheartbeatLEDisalsousedtoindicatethatanerrorwasdetected.
ThefollowingpieceofcodeusestheRGBLEDtomakeatrafficlightthatrunsfor10cycles.
importpycom
importtime
pycom.heartbeat(False)
forcyclesinrange(10):#stopafter10cycles
pycom.rgbled(0x007f00)#green
time.sleep(5)
pycom.rgbled(0x7f7f00)#yellow
time.sleep(1.5)
pycom.rgbled(0x7f0000)#red
time.sleep(4)
Hereistheexpectedresult:
4.2.11RGBLED
178
4.2.11RGBLED
179
Timers
Detailedinformationaboutthisclasscanbefoundin Timer.
Chronometer
TheChronometercanbeusedtomeasurehowmuchtimehaselapsedinablockofcode.
Thefollowingexampleusesasimplestopwatch.
frommachineimportTimer
importtime
chrono=Timer.Chrono()
chrono.start()
time.sleep(1.25)#simulatethefirstlaptook1.25seconds
lap=chrono.read()#readelapsedtimewithoutstopping
time.sleep(1.5)
chrono.stop()
total=chrono.read()
print()
print("\ntheracertook%fsecondstofinishtherace"%total)
print("%fsecondsinthefirstlap"%lap)
print("%fsecondsinthelastlap"%(total-lap))
Alarm
TheAlarmcanbeusedtogetinterruptsataspecificinterval.Thefollowingcodeexecutesa
callbackeverysecondfor10seconds.
4.2.12Timers
180
frommachineimportTimer
classClock:
def__init__(self):
self.seconds=0
self.__alarm=Timer.Alarm(self._seconds_handler,1,periodic=True)
def_seconds_handler(self,alarm):
self.seconds+=1
print("%02dsecondshavepassed"%self.seconds)
ifself.seconds==10:
alarm.callback(None)#stopcountingafter10seconds
clock=Clock()
Therearenorestrictionstowhatcanbedoneinaninterrupt.Forexample,itispossible
toevendonetworkrequestswithaninterrupt.However,itisimportanttokeepinmind
thatinterruptsarehandledsequentially,soit’sgoodpracticetokeepthemshort.More
informationcanbefoundin InterruptHandling.
4.2.12Timers
181
PIRSensor
ThiscodereadsPIRsensortriggersfromthissimplePIRsensorandsendsanHTTP
requestforeverytrigger,inthiscasetoaDomoticzinstallation.Whenmotionisconstantly
detected,thisPIRsensorkeepsthepinhigh,inwhichcasethiscodewillkeepsending
HTTPrequestsevery10seconds(configurablewiththehold_timevariable).
Main( main.py)
importtime
fromnetworkimportWLAN
frommachineimportPin
fromdomoticzimportDomoticz
wl=WLAN(WLAN.STA)
d=Domoticz("<ip>",8080,"<hash>")
#config
hold_time_sec=10
#flags
last_trigger=-10
pir=Pin('G4',mode=Pin.IN,pull=Pin.PULL_UP)
#mainloop
print("Startingmainloop")
whileTrue:
ifpir()==1:
iftime.time()-last_trigger>hold_time_sec:
last_trigger=time.time()
print("Presencedetected,sendingHTTPrequest")
try:
return_code=d.setVariable('Presence:LivingRoom','1')
print("Requestresult:"+str(return_code))
exceptExceptionase:
print("Requestfailed")
print(e)
else:
last_trigger=0
print("Nopresence")
time.sleep_ms(500)
print("Exitedmainloop")
4.2.13PIRSensor
182
Boot( boot.py)
FormoreWiFiscripts,seethewlanstepbysteptutorial.
importos
importmachine
uart=machine.UART(0,115200)
os.dupterm(uart)
known_nets={
'NetworkID':{'pwd':'<password>','wlan_config':('10.0.0.8','255.255.0.
0','10.0.0.1','10.0.0.1')},
}
fromnetworkimportWLAN
wl=WLAN()
ifmachine.reset_cause()!=machine.SOFT_RESET:
wl.mode(WLAN.STA)
original_ssid=wl.ssid()
original_auth=wl.auth()
print("Scanningforknownwifinets")
available_nets=wl.scan()
nets=frozenset([e.ssidforeinavailable_nets])
known_nets_names=frozenset([keyforkeyinknown_nets])
net_to_use=list(nets&known_nets_names)
try:
net_to_use=net_to_use[0]
net_properties=known_nets[net_to_use]
pwd=net_properties['pwd']
sec=[e.secforeinavailable_netsife.ssid==net_to_use][0]
if'wlan_config'innet_properties:
wl.ifconfig(config=net_properties['wlan_config'])
wl.connect(net_to_use,(sec,pwd),timeout=10000)
whilenotwl.isconnected():
machine.idle()#savepowerwhilewaiting
print("Connectedto"+net_to_use+"withIPaddress:"+wl.ifconfig()[0])
exceptExceptionase:
print("Failedtoconnecttoanyknownnetwork,goingintoAPmode")
wl.init(mode=WLAN.AP,ssid=original_ssid,auth=original_auth,channel=6,anten
na=WLAN.INT_ANT)
DomoticzWrapper( domoticz.py)
4.2.13PIRSensor
183
importsocket
classDomoticz:
def__init__(self,ip,port,basic):
self.basic=basic
self.ip=ip
self.port=port
defsetLight(self,idx,command):
returnself.sendRequest("type=command&param=switchlight&idx="+idx+"&switchcmd="
+command)
defsetVariable(self,name,value):
returnself.sendRequest("type=command&param=updateuservariable&vtype=0&vname="
+name+"&vvalue="+value)
defsendRequest(self,path):
try:
s=socket.socket()
s.connect((self.ip,self.port))
s.send(b"GET/json.htm?"+path+"HTTP/1.1\r\nHost:pycom.io\r\nAuthorizatio
n:Basic"+self.basic+"\r\n\r\n")
status=str(s.readline(),'utf8')
code=status.split("")[1]
s.close()
returncode
exceptException:
print("HTTPrequestfailed")
return0
4.2.13PIRSensor
184