Pycom FiPy Скачать руководство пользователя страница 35

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

Содержание FiPy

Страница 1: ...rted 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 ...

Страница 2: ...lugin 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 ...

Страница 3: ... 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 Pytra...

Страница 4: ...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...

Страница 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...

Страница 6: ...rds 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 ...

Страница 7: ...e 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 ...

Страница 8: ...ections 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 ...

Страница 9: ...Product Info API Documentation Pybytes Preface 9 ...

Страница 10: ...bles 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 ...

Страница 11: ...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 ...

Страница 12: ...ard 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 ...

Страница 13: ...Pyscan Modules OLED Module 2MP Camera Barcode Reader Fingerprint Scanner IR Image Sensor OEM Modules Pycom Products 13 ...

Страница 14: ...OEM Module L01 W01 Reference Board Universal Reference Board W01 L01 L04 G01 Pycom Products 14 ...

Страница 15: ...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 g...

Страница 16: ...ed 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 ...

Страница 17: ...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 ...

Страница 18: ...1 1 Hardware Setup 18 ...

Страница 19: ...1 1 Hardware Setup 19 ...

Страница 20: ...e 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 ...

Страница 21: ...ytrack 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...

Страница 22: ...lator 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 connectio...

Страница 23: ...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 ...

Страница 24: ...he 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 require...

Страница 25: ...sue 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 ...

Страница 26: ...e 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...

Страница 27: ...track 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...

Страница 28: ...o 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 ...

Страница 29: ...te 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 you...

Страница 30: ... 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 ...

Страница 31: ...onnector 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 ...

Страница 32: ...e 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 ...

Страница 33: ...ytrack 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...

Страница 34: ...lator 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 connectio...

Страница 35: ... 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 ...

Страница 36: ...l 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 softw...

Страница 37: ...umption 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 ...

Страница 38: ...he 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 ...

Страница 39: ...ytrack 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 ...

Страница 40: ... 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 ...

Страница 41: ...ess 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 y...

Страница 42: ...cluding 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 ...

Страница 43: ...ill 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 ...

Страница 44: ... 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 Expansio...

Страница 45: ... 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 ...

Страница 46: ... 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 use...

Страница 47: ...s 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 ...

Страница 48: ...ase 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...

Страница 49: ...g 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 ...

Страница 50: ...ll 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 ...

Страница 51: ...e 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 ...

Страница 52: ...ytrack 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...

Страница 53: ...lator 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 connectio...

Страница 54: ...ervers 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 b...

Страница 55: ...ins 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 f...

Страница 56: ... 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 mak...

Страница 57: ...S 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 F...

Страница 58: ...Right click the device and select Update Driver Software Select the option to Browse my computer for driver software 1 2 1 Drivers 58 ...

Страница 59: ...o 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 ...

Страница 60: ... 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 ...

Страница 61: ...irm 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 ...

Страница 62: ...alog 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 G...

Страница 63: ...nse 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 comput...

Страница 64: ...t 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 ...

Страница 65: ...kr 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 ...

Страница 66: ...1 2 3 Pymakr 66 ...

Страница 67: ...e 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 Eval...

Страница 68: ...from it 1 3 Programming the modules 68 ...

Страница 69: ...es 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 wri...

Страница 70: ...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 ...

Страница 71: ... 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 r...

Страница 72: ...nd adds them together outputting the result def add 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 def welcome 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 vari...

Страница 73: ... 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 be...

Страница 74: ...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 follow...

Страница 75: ...th 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...

Страница 76: ...makr 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 wi...

Страница 77: ...import os os mkfs flash 1 3 3 Your first Pymakr project 77 ...

Страница 78: ...ress 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 lik...

Страница 79: ... 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 AL...

Страница 80: ...d 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...

Страница 81: ...lnet 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 set...

Страница 82: ...e 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 ...

Страница 83: ...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 ...

Страница 84: ...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 ...

Страница 85: ...led 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 ...

Страница 86: ...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 r...

Страница 87: ...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 ...

Страница 88: ... 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 ...

Страница 89: ...twork 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 ...

Страница 90: ...ered 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 ...

Страница 91: ...ecific 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 netw...

Страница 92: ...oRa 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 ...

Страница 93: ...e 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 ...

Страница 94: ... 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 ...

Страница 95: ...ce 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 ...

Страница 96: ...egister 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...

Страница 97: ...tings 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 ...

Страница 98: ...n 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 t...

Страница 99: ...tings 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 ...

Страница 100: ...y 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 rando...

Страница 101: ... 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 obt...

Страница 102: ...1 4 3 2 Objenious 102 ...

Страница 103: ... 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 ...

Страница 104: ...2 1 Installation 104 ...

Страница 105: ...ext 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 ...

Страница 106: ...akr 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 ...

Страница 107: ...d 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 ser...

Страница 108: ...ettings 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 ...

Страница 109: ...ed 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 ...

Страница 110: ...2 1 1 Atom 110 ...

Страница 111: ...ill 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 ...

Страница 112: ...4 Within a few minutes a reload button should appear Press it to reload VSCode 2 1 2 Visual Studio Code 112 ...

Страница 113: ...5 That s it You ve installed the Pymakr Extension for VSCode 2 1 2 Visual Studio Code 113 ...

Страница 114: ...l 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 cli...

Страница 115: ...y 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...

Страница 116: ...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 ...

Страница 117: ...ut 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 time...

Страница 118: ...bserial 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 ...

Страница 119: ...ific 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 ...

Страница 120: ...ore 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 ...

Страница 121: ...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 improv...

Страница 122: ...d 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 ...

Страница 123: ...elow 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 p...

Страница 124: ...ry 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 ...

Страница 125: ...e 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 al...

Страница 126: ... 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 repe...

Страница 127: ... 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...

Страница 128: ...d 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 ...

Страница 129: ...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...

Страница 130: ...elow 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 Wi...

Страница 131: ...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 ...

Страница 132: ...cted 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 ...

Страница 133: ...hat 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 ...

Страница 134: ...3 2 2 Installing Drivers Windows 7 134 ...

Страница 135: ...d 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 pycopro...

Страница 136: ...from pysense import Pysense from LTR329ALS01 import LTR329ALS01 py Pysense lt LTR329ALS01 py print lt light 3 2 3 Installing Libraries 136 ...

Страница 137: ...ify 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 ...

Страница 138: ...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 thi...

Страница 139: ...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 ...

Страница 140: ...ully 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 wil...

Страница 141: ...ctor 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 humi...

Страница 142: ...ass 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 Re...

Страница 143: ...UDE 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 ...

Страница 144: ...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 ...

Страница 145: ...able 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 th...

Страница 146: ...ted 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 imp...

Страница 147: ...ds 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 ...

Страница 148: ...ins 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 fo...

Страница 149: ...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 ...

Страница 150: ...een 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 ...

Страница 151: ...p 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 ...

Страница 152: ... 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...

Страница 153: ...use 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 if not wlan isconnected change the line below to match your network ssid security and password wlan connect mywifi auth WLAN WPA2 mywifikey timeout 5000 while not wlan isconnected machine idle save power while waiting Notic...

Страница 154: ...wd net_properties pwd sec e sec for e in available_nets if e ssid net_to_use 0 if wlan_config in net_properties wl ifconfig config net_properties wlan_config wl connect net_to_use sec pwd timeout 10000 while not 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 in...

Страница 155: ...AP 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 c...

Страница 156: ...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 w...

Страница 157: ...one while True 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 ...

Страница 158: ...rvice 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 retr...

Страница 159: ...etooth 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 ...

Страница 160: ... 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 ...

Страница 161: ... same topic in order to show how to use the subscribe functionality from mqtt import MQTTClient from network import WLAN import machine import time def sub_cb topic msg print msg wlan WLAN mode WLAN STA wlan connect yourwifinetwork auth WLAN WPA2 wifipassword timeout 5000 while not wlan isconnected machine idle print Connected to WiFi n client MQTTClient device_id io adafruit com user your_usernam...

Страница 162: ...4 2 5 MQTT 162 ...

Страница 163: ...at 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 ...

Страница 164: ...ONN_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_TI...

Страница 165: ...eOfflinePublishQueueing 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 co...

Страница 166: ...SIoTMQTTShadowClient 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 ...

Страница 167: ...ient 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 createSh...

Страница 168: ... 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...

Страница 169: ...his sample code into a file named bh1750fvi py This can then be imported as a library Simple driver for the BH1750FVI digital light sensor class BH1750FVI 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 def read self self time se...

Страница 170: ...RA 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...

Страница 171: ...4 2 8 I2C 171 ...

Страница 172: ...neWire DS18B20 data line connected to pin P10 ow OneWire Pin P10 temp DS18X20 ow while True 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 class OneWire CMD_SEARCHROM const 0xf0 CMD_READROM const 0x33 CMD_MATCHROM const 0x55 CMD_SKIPROM const 0xcc def __init__ self pin self pin pin se...

Страница 173: ...ep_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 def read_byte self value 0 for i in range 8 value self read_bit i return value def read_bytes self count buf bytearray count for i in range count buf i self read_byte return...

Страница 174: ...elf write_byte CMD_MATCHROM self write_bytes rom def crc8 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 def scan 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 ...

Страница 175: ..._diff i self write_bit b if b r_b 1 bit i 1 rom byte r_b return rom next_diff class DS18X20 object def __init__ self onewire self ow onewire self roms rom for rom in self ow scan if rom 0 0x10 or rom 0 0x28 def isbusy self Checks wether one of the DS18x20 devices on the bus is busy performing a temperature conversion return not self ow read_bit def start_conversion self rom None Start the temp con...

Страница 176: ...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_r...

Страница 177: ...y number of parameters Below 3 threads are started each one perform a print at a different interval import _thread import time def th_func delay id while True 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 ...

Страница 178: ...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 t...

Страница 179: ...4 2 11 RGB LED 179 ...

Страница 180: ...ono 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 ...

Страница 181: ... 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 ...

Страница 182: ...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 while True 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...

Страница 183: ...nset 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 in net_properties wl ifconfig config net_properties wlan_config wl connect net_to_use sec pwd timeout 10000 while not wl isconnected machine idle save power while waiting ...

Страница 184: ...iable self name value return self sendRequest type command param updateuservariable vtype 0 vname name vvalue value def sendRequest 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 retu...

Страница 185: ... Write Single Coil 0x05 Write Single Register 0x06 Write Multiple Coils 0x0F Write Multiple Registers 0x10 For more information on the MODBUS RTU see the following PDF File Information on the MODBUS TCP can be found here Pycom Modbus Library Python libraries and sample code that support Modbus TCP and Modbus RTU are available at the following GitHub Repository To use this library connect to the ta...

Страница 186: ... join d format x for x in input_status Read Holding Registers This function code is used to read the contents of analogue output holding registers The slave address the starting register address the number of registers to read and the sign of the data must be specified Register addresses start at 0 and a maximum of 125 continuous registers can be read slave_addr 0x0A starting_address 0x00 register...

Страница 187: ...put_value 0xFF00 return_flag modbus_obj write_single_coil slave_addr output_address output_value output_flag Success if return_flag else Failure print Writing single coil status output_flag Write Single Register This command is used to write the contents of an analog output holding register on a remote device The slave address the register address the register value and the signature of the data m...

Страница 188: ...te Multiple Registers This command is used to write the contents of a continuous sequence of analogue registers on a remote device The slave address the starting register address the register values and the signature of the data must be specified The address of the first register is 0 and a maximum of 125 register values can be written The Python sample code is shown below slave_addr 0x0A register...

Страница 189: ...lar data via LoRa and when they receive a special command via a downlink message the devices will connect to a WiFi network It is unfeasible to ask customers to allow your device to connect to their home network so instead this network could be provided by a vehicle This vehicle will travel around a certain geographic area in which the devices have been sent the special downlink message to initiat...

Страница 190: ...e for the corresponding version number Firmware These files should be named in the format firmare_VERSION bin where VERSION is a a version number compatible with the python LooseVersion versioning scheme http epydoc sourceforge net stdlib distutils version LooseVersion class html This file should be in the format of the appimg bin created by the Pycom firmware build scripts How to use Once the dir...

Страница 191: ...8 1 144 8000 firmware_1 0 1b bin hash ccc6914a457eb4af8855ec02f6909316526bdd08 new URL http 192 168 1 144 8000 1 0 1b flash lib new_lib py dst_path flash lib new_lib py hash 1095df8213aac2983efd68dba9420c8efc9c7c4a update URL http 192 168 1 144 8000 1 0 1b flash changed_file py dst_path flash changed_file py hash 1095df8213aac2983efd68dba9420c8efc9c7c4a version 1 0 1b The manifest contains the fol...

Страница 192: ...the actual transport mechanism of how the device fetches the files and update manifest via WiFi as the class name suggests The reason for this split is so that the high level functionality can be reused regardless of what transport mechanism you end up using This could be implemented on top of Bluetooth for example or the sever changed from HTTP to FTP Although the above code is functional it is p...

Страница 193: ...868 app_eui ubinascii unhexlify 70B3D57ED0008CD6 app_key ubinascii unhexlify B57F36D88691CEC5EE8659320169A61C join a network using OTAA Over the Air Activation lora join activation LoRa OTAA auth app_eui app_key timeout 0 wait until the module has joined the network while not lora has_joined time sleep 2 5 print Not yet joined create a LoRa socket s socket socket socket AF_LORA socket SOCK_RAW set...

Страница 194: ...e s no data received it will block forever s setblocking False get any data received if any data s recv 64 Some sort of OTA trigger if data bytes 0x01 0x02 0x03 print Performing OTA Perform OTA ota connect ota update sleep 5 4 2 15 OTA update 194 ...

Страница 195: ...ins P13 P18 can only be used as inputs Channel Resolution Maximum Pulse Width 0 Used by on board LED 1 Used by pycom pulses_get 2 100nS 3 2768 ms 3 100nS 3 2768 ms 4 1000nS 32 768 ms 5 1000nS 32 768 ms 6 3125nS 102 4 ms 7 3125nS 102 4 ms Transmitting The following examples create an RMT object on channel 4 configure it for transmission and send some data in various forms The resolution of channel ...

Страница 196: ...ple of durations and what state the signal starts in from machine import RMT Map RMT channel 4 to P21 when the RMT is idle it will output LOW rmt RMT channel 4 gpio P21 tx_idle_level RMT LOW The list of durations for each pulse to be these are in units of the channels resolution duration Desired pulse length Channel Resolution duration 8000 11000 8000 11000 6000 13000 6000 3000 8000 start_level de...

Страница 197: ...level RMT LOW Produces the pattern shown in data where each bit lasts duration i channel resolution duration i 1000ns data 1 0 1 1 0 1 duration 400 200 100 300 200 400 rmt pulses_send duration data The following example creates an RMT object on channel 4 and configures it for transmission with carrier modulation from machine import RMT rmt RMT channel 4 gpio P21 tx_idle_level RMT LOW Carrier 100Hz...

Страница 198: ...defined number of pulses then waits maximum of 1000us for the first pulse from machine import RMT Sets RMT channel 2 to P21 and sets the maximum length of a valid pulse to 1000 channel resolution 1000 100ns 100us rmt machine RMT channel 2 gpio P21 rx_idle_threshold 1000 rmt init Get a undefined number of pulses waiting a maximum of 500us for the first pulse unlike other places where the absolute d...

Страница 199: ...ter out pulses shorter than 20 100ns 2us rx_filter_threshold 20 Receive 100 pulses pulses shorter than 2us or longer than 100us will be ignored That means if it receives 80 valid pulses but then the signal doesn t change for 10 hours and then 20 more pulses occur this function will wait for 10h data rmt pulses_get pulses 100 4 2 16 RMT 199 ...

Страница 200: ...e tail of the packet and this is removed before the received frame is passed on to the application This mode can be used to build any higher level protocol that can benefit from the long range features of the LoRa modulation Typical uses cases include LoPy to LoPy direct communication and a LoRa packet forwarder LoRaWAN mode implements the full LoRaWAN stack for a class A device It supports both O...

Страница 201: ...e word Hello being received on both sides from network import LoRa import socket import machine import time initialise LoRa in LORA mode Please pick the region that matches where you are using the device Asia LoRa AS923 Australia LoRa AU915 Europe LoRa EU868 United States LoRa US915 more params can also be given like frequency tx power and spreading factor lora LoRa mode LoRa LORA region LoRa EU86...

Страница 202: ...y is able to send and receive packets to from the Gateway If the keys are incorrect no response will be received and the has_joined method will always return False The example below attempts to get any data received after sending the frame Keep in mind that the Gateway might not be sending any data back therefore we make the socket non blocking before attempting to receive in order to prevent gett...

Страница 203: ...the Air Activation lora join activation LoRa OTAA auth app_eui app_key timeout 0 wait until the module has joined the network while not lora has_joined time sleep 2 5 print Not yet joined create a LoRa socket s socket socket socket AF_LORA socket SOCK_RAW set the LoRaWAN data rate s setsockopt socket SOL_LORA socket SO_DR 5 make the socket blocking waits for the data to be sent and for the 2 recei...

Страница 204: ...e procedure to exchange the keys such as the one performed during an OTAA join procedure The example below attempts to get any data received after sending the frame Keep in mind that the Gateway might not be sending any data back therefore we make the socket non blocking before attempting to receive in order to prevent getting stuck waiting for a packet that will never arrive 4 3 3 LoRaWAN with AB...

Страница 205: ...ey ubinascii unhexlify 2B7E151628AED2A6ABF7158809CF4F3C join a network using ABP Activation By Personalization lora join activation LoRa ABP auth dev_addr nwk_swkey app_swkey create a LoRa socket s socket socket socket AF_LORA socket SOCK_RAW set the LoRaWAN data rate s setsockopt socket SOL_LORA socket SO_DR 5 make the socket blocking waits for the data to be sent and for the 2 receive windows to...

Страница 206: ...et use rx_iq to avoid listening to our own messages Please pick the region that matches where you are using the device Asia LoRa AS923 Australia LoRa AU915 Europe LoRa EU868 United States LoRa US915 lora LoRa mode LoRa LORA rx_iq True region LoRa EU868 lora_sock socket socket socket AF_LORA socket SOCK_RAW lora_sock setblocking False while True recv_pkg lora_sock recv 512 if len recv_pkg 2 recv_pk...

Страница 207: ...RA_PKG_FORMAT is used as a method of identifying the different devices within a network The _LORA_PKG_ACK_FORMAT is a simple ack package as a response to the nodes package Node 4 3 4 LoRa MAC Nano Gateway 207 ...

Страница 208: ...g msg Device 1 Here pkg struct pack _LORA_PKG_FORMAT len msg DEVICE_ID len msg msg lora_sock send pkg Wait for the response from the gateway NOTE For this demo the device does an i nfinite loop for while waiting the response Introduce a max_time_waiting for you appl ication waiting_ack True while waiting_ack recv_ack lora_sock recv 256 if len recv_ack 0 device_id pkg_len ack struct unpack _LORA_PK...

Страница 209: ...send the package or mark it as invalid Increase the package size changing the _LORA_PKG_FORMAT to BH ds The H will allow the keeping of 2 bytes for size for more information about struct format Reduce the package size with bitwise manipulation Reduce the message size for this demo a string to something more useful for specific development 4 3 4 LoRa MAC Nano Gateway 209 ...

Страница 210: ...Ra mode LoRa LORA region LoRa EU868 s socket socket socket AF_LORA socket SOCK_RAW s setblocking False while True if s recv 64 b Ping s send Pong time sleep 5 Node B from network import LoRa import socket import time Please pick the region that matches where you are using the device Asia LoRa AS923 Australia LoRa AU915 Europe LoRa EU868 United States LoRa US915 lora LoRa mode LoRa LORA region LoRa...

Страница 211: ...4 3 5 LoPy to LoPy 211 ...

Страница 212: ...gateway will connect to a preferred network and how it can act as packet forwarder Gateway ID 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 ...

Страница 213: ...ERIOD_S nanogw start nanogw _log You may now press ENTER to enter the REPL input Configuration config py This file contains settings for the server and network it is connecting to Depending on the nano gateway region and provider TTN Loriot etc these will vary The provided example will work with The Things Network TTN in the European 868Mhz region The Gateway ID is generated in the script using th...

Страница 214: ...868100000 LORA_GW_DR SF7BW125 DR_5 LORA_NODE_DR 5 for US915 LORA_FREQUENCY 903900000 LORA_GW_DR SF7BW125 DR_3 LORA_NODE_DR 3 Library nanogateway py The nano gateway library controls all of the packet generation and forwarding for the LoRa data This does not require any user configuration and the latest version of this code should be downloaded from the Pycom GitHub Repository LoPy Nano Gateway cla...

Страница 215: ...ng 0 alti 0 rxnb 0 rxok 0 rxfw 0 ackr 100 0 dwnb 0 txnb 0 RX_PK rxpk time tmst 0 chan 0 rfch 0 freq 868 1 stat 1 modu LORA datr SF7BW125 codr 4 5 rssi 0 lsnr 0 size 0 data TX_ACK_PK txpk_ack error class NanoGateway def __init__ self id frequency datarate ssid password server port ntp poo l ntp org ntp_period 3600 self id id self frequency frequency self sf self _dr_to_sf datarate self ssid ssid se...

Страница 216: ... first time immediately self _push_data self _make_stat_packet Create the alarms self stat_alarm Timer Alarm handler lambda t self _push_data self _make_sta t_packet s 60 periodic True self pull_alarm Timer Alarm handler lambda u self _pull_data s 25 perio dic True Start the UDP receive thread _thread start_new_thread self _udp_thread Initialize LoRa in LORA mode self lora LoRa mode LoRa LORA freq...

Страница 217: ...K stat dwnb self dwnb STAT_PK stat txnb self txnb return json dumps STAT_PK def _make_node_packet self rx_data rx_time tmst sf rssi snr RX_PK rxpk 0 time d 02d 02dT 02d 02d 02d dZ rx_time 0 rx _time 1 rx_time 2 rx_time 3 rx_time 4 rx_time 5 rx_time 6 RX_PK rxpk 0 tmst tmst RX_PK rxpk 0 datr self _sf_to_dr sf RX_PK rxpk 0 rssi rssi RX_PK rxpk 0 lsnr float snr RX_PK rxpk 0 data ubinascii b2a_base64 ...

Страница 218: ...lora_sock recv 256 stats lora stats self _push_data self _make_node_packet rx_data self rtc now stats time stamp stats sf stats rssi stats snr self rxfw 1 if events LoRa TX_PACKET_EVENT self txnb 1 lora init mode LoRa LORA frequency self frequency bandwidth LoRa BW_125K HZ sf self sf preamble 8 coding_rate LoRa CODING_4_5 tx_iq True def _send_down_link self data tmst datarate frequency self lora i...

Страница 219: ..._us else ack_error TX_ERR_TOO_LATE print Downlink timestamp error t_us t_us self _ack_pull_rsp _token ack_error print Pull rsp except socket timeout pass except OSError as e if e errno errno EAGAIN pass else print UDP recv OSError Exception except Exception print UDP recv Exception Wait before trying to receive again time sleep 0 025 Registering with TTN To set up the gateway with The Things Netwo...

Страница 220: ...is navigate to the TTN Console web page Registering the Gateway 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 4 3 6 LoRaWAN Nano Gateway 220 ...

Страница 221: ...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 4 3 6 LoRaWAN Nano Gateway 221 ...

Страница 222: ...ribed near the top of this document to create your own unique Gateway ID 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 Next one or more nod...

Страница 223: ...vel OTAA Node example compatible with the LoPy Nano Gateway from network import LoRa import socket import ubinascii import struct import time Initialize LoRa in LORAWAN mode lora LoRa mode LoRa LORAWAN create an OTA authentication params dev_eui ubinascii unhexlify AABBCCDDEEFF7778 these settings can be found from T TN app_eui ubinascii unhexlify 70B3D57EF0003BFD these settings can be found from T...

Страница 224: ...e the socket non blocking s setblocking False time sleep 5 0 Your own code can be written below for i in range 200 s send b PKT bytes i time sleep 4 rx s recv 256 if rx print rx time sleep 6 ABP Activation By Personalisation Using ABP join mode requires the user to define the following values and input them into both the LoPy and the TTN Application Device Address Application Session Key Network S...

Страница 225: ...Activation By Personalisation lora join activation LoRa ABP auth dev_addr nwk_swkey app_swkey remove all the non default channels for i in range 3 16 lora remove_channel i set the 3 default channels to the same frequency lora add_channel 0 frequency 868100000 dr_min 0 dr_max 5 lora add_channel 1 frequency 868100000 dr_min 0 dr_max 5 lora add_channel 2 frequency 868100000 dr_min 0 dr_max 5 create a...

Страница 226: ...w will open Enter a unique Application ID as well as a Description Handler Registration Now the LoPy nodes must be registered to send data up to the new Application Registering Devices LoPy To connect nodes to the nano 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 p...

Страница 227: ...an be managed as to where data should be delivered to To do this use the Integrations tab within the new Application s settings Upon clicking add integration a screen with 4 different options will appear These have various functionality and more information about them can be found on the TTN website documentation For this example use the HTTP Integration to forward the LoRaWAN Packets to a remote ...

Страница 228: ... website called RequestBin may be used to receive the data that TTN forwards via POST Request To set this up navigate to RequestBin and click the Create a RequestBin Copy the URL that is generated and past this into the URL form under the Application Settings 4 3 6 LoRaWAN Nano Gateway 228 ...

Страница 229: ...s the address that TTN will forward data onto As soon as a LoPy starts sending messages TTN will forward these onto RequestBin and they will appear at the unique RequestBin URL 4 3 6 LoRaWAN Nano Gateway 229 ...

Страница 230: ...t sync 12 radio set prlen 8 Transmit via radio tx radio tx 48656c6C6F should send Hello LoPy from network import LoRa import socket lora LoRa mode LoRa LORA frequency 868000000 bandwidth LoRa BW_125KHZ sf 7 prea mble 8 coding_rate LoRa CODING_4_5 power_mode LoRa ALWAYS_ON tx_iq False rx_iq False public False s socket socket socket AF_LORA socket SOCK_RAW This keeps listening for data forever while...

Страница 231: ...torials demonstrate how to register and get started with the SiPy The SiPy can be configured for operation in various countries based upon specified RCZ zones see the Sigfox class for more info The SiPy supports both uplink and downlink Sigfox messages as well as device to device communication via its FSK Mode Sigfox 4 4 Sigfox Examples 231 ...

Страница 232: ...gfox 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 4 4 1 Register Device 232 ...

Страница 233: ...mport Sigfox import ubinascii initalise Sigfox for RCZ1 You may need a different RCZ Region sigfox Sigfox mode Sigfox SIGFOX rcz Sigfox RCZ1 print Sigfox Device ID print ubinascii hexlify sigfox id print Sigfox PAC number print ubinascii hexlify sigfox pac See Sigfox for more info about the Sigfox Class and which RCZ region to use 4 4 1 Register Device 233 ...

Страница 234: ...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 4 4 1 Register Device 234 ...

Страница 235: ...e device information or on the device type information page of the Sigfox backend to reset the number expected by the backend If the sequence number of your next message is different from the last trashed sequence number the message will be accepted Issues with the sequence number can occur when a lot of messages are sent when outside of Sigfox coverage for instance Firstly you will need to log in...

Страница 236: ...Finally on this page click on Disengage sequence number button in the upper right corner 4 4 2 Disengage Sequence Number 236 ...

Страница 237: ...T M1 and NB IoT these are new lower power long range cellular protocols These are not the same as the full version of 2G 3G LTE supported by cell phones and require your local carriers to support them At the time of writing CAT M1 and NB IoT connectivity is not widely available so be sure to check with local carriers if support is available where you are 4 5 LTE Examples 237 ...

Страница 238: ...e LTE instantiate the LTE object lte attach attach the cellular modem to a base station while not lte isattached time sleep 0 25 lte connect start a data session and obtain an IP address while not lte isconnected time sleep 0 25 s socket socket s ssl wrap_socket s s connect socket getaddrinfo www google com 443 0 1 s send b GET HTTP 1 0 r n r n print s recv 4096 s close lte disconnect lte dettach ...

Страница 239: ...he FiPy together the RTS CTS jumpers MUST be removed as those pins are being used by the LTE radio Keeping those jumpers in place will lead to erratic operation and higher current consumption specially while in deepsleep 4 5 1 CAT M1 239 ...

Страница 240: ...ted in a later release Support for Huawei base stations is also limited and only lab testing with Huawei eNodeB is recommended at the moment Full support for Huawei is planned for early Q2 2018 NB IoT usage Example with Vodafone from network import LTE lte LTE lte send_at_cmd AT CFUN 0 lte send_at_cmd AT clearscanconfig lte send_at_cmd AT addscanfreq band 20 dl earfcn 6300 lte send_at_cmd AT zsp0 ...

Страница 241: ...llowing use cases which require the system to be taken out from deepsleep by an event from the LTE network data or SMS received for instance When using the expansion board and the FiPy together the RTS CTS jumpers MUST be removed as those pins are being used by the LTE radio Keeping those jumpers in place will lead to erratic operation and higher current consumption specially while in deepsleep 4 ...

Страница 242: ... device via the interactive REPL import os os uname sysname GPy nodename GPy release 1 17 0 b1 version v1 8 6 849 d0dc708 on 20 18 02 27 machine GPy with ESP32 Once you have a compatible firmware you can run the following code to get your modules IMEI number from network import LTE lte LTE lte send_at_cmd AT CGSN 1 You ll get a return string like this r n CGSN 354347xxxxxxxxx r n r nOK The value b...

Страница 243: ...t 6MB of free space A Pycom Expansion Board or shield or a microSD card socket breakout board Usage If your module is running the factory LTE chip firmware you MUST first perform an update to the latest CAT M1 firmware before trying to upgrade to the NB IoT firmware Skipping this step will cause your radio to become unresponsive and it will require access to the test points in order to re flash th...

Страница 244: ...Session opened version 1 max transfer 8192 bytes Sending 4560505 bytes 100 Code download done returning to user mode Resetting DO NOT DISCONNECT POWER Deploying the upgrade DO NOT DISCONNECT POWER Resetting DO NOT DISCONNECT POWER Upgrade completed Here is the current firmware version UE6 0 0 0 ER7 LR6 0 0 0 35351 OK DO NOT disconnect power while the upgrade process is taking place wait for it to ...

Страница 245: ...Accelerometer Both the Pysense and Pytrack use the same accelerometer Please see the Pysense Examples to see how to use the accelerometer 4 6 Pytrack Examples 245 ...

Страница 246: ... CSV format over serial from LIS2HH12 import LIS2HH12 from pytrack import Pytrack py Pytrack acc LIS2HH12 while True pitch acc pitch roll acc roll print format pitch roll time sleep_ms 100 If you want to visualise the data output by this script a Processing sketch is available here that will show the board orientation in 3D 4 7 Pysense Examples 246 ...

Страница 247: ...4 7 Pysense Examples 247 ...

Страница 248: ...rable and each port to a particular board embedded system makes available only a subset of MicroPython libraries For officially supported ports there is an effort to either filter out non applicable items or mark individual descriptions with Availability clauses describing which ports provide a given feature With that in mind please still be warned that some functions classes in a module or even t...

Страница 249: ...the Pycom devices and may have slightly different implementations to other variations of MicroPython i e for Non Pycom devices Modules include those which support access to underlying hardware e g I2C SPI WLAN Bluetooth etc 5 2 Pycom Modules 249 ...

Страница 250: ...e Get the reset cause See constants for the possible return values Interrupt Functions machine disable_irq Disable interrupt requests Returns and integer representing the previous IRQ state This return value can be passed to enable_irq to restore the IRQ to its original state machine enable_irq state Enable interrupt requests The most common use of this function is to pass the value returned by di...

Страница 251: ...r instance machine pin_deepsleep_wakeup pins mode enable_pull Configure pins to wake up from deep sleep mode The pins which have this capability are P2 P3 P4 P6 P8 to P10 and P13 to P23 The arguments are pins a list or tuple containing the GPIO to setup for deepsleep wakeup mode selects the way the configure GPIO s can wake up the module The possible values are machine WAKEUP_ALL_LOW and machine W...

Страница 252: ... expect a short ID In some MicroPython ports ID corresponds to the network MAC address Use ubinascii hexlify to convert the byte string to hexadecimal form for ease of manipulation and use elsewhere machine info Returns the high water mark of the stack associated with various system tasks in words 1 word 4 bytes on the ESP32 If the value is zero then the task has likely overflowed its stack If the...

Страница 253: ...machine WAKEUP_ALL_LOW machine WAKEUP_ANY_HIGH 5 2 1 machine 253 ...

Страница 254: ...Enable the ADC block This method is automatically called on object creation Bits can take values between 9 and 12 and selects the number of bits of resolution of the ADC block adc deinit Disable the ADC block adc channel pin attn ADC ATTN_0DB Create an analog pin pin is a keyword only string argument Valid pins are P13 to P20 attn is the attenuation level The supported values are ADC ATTN_0DB ADC ...

Страница 255: ...nts ADC ATTN_0DB ADC ATTN_2_5DB ADC ATTN_6DB ADC ATTN_11DB ADC channel attenuation values class ADCChannel Read analog values from internal external sources ADC channels can be connected to internal points of the MCU or to GPIO pins ADC channels are created using the ADC channel method Methods adcchannel Fast method to read the channel value adcchannel value Read the channel value adcchannel init ...

Страница 256: ...value into a voltage in millivolts in the same way voltage does ADC pin input range is 0 1 1V This maximum value can be increased up to 3 3V using the highest attenuation of 11dB Do not exceed the maximum of 3 3V to avoid damaging the device 5 2 1 1 ADC 256 ...

Страница 257: ...in Create a DAC object that will let you associate a channel with a pin pin can be a string argument Methods dac init Enable the DAC block This method is automatically called on object creation dac deinit Disable the DAC block dac write value Set the DC level for a DAC pin value is a float argument with values between 0 and 1 dac tone frequency amplitude Sets up tone signal to the specified freque...

Страница 258: ...0 is 0dBV 3Vpp at 600 Ohm load 1 is 6dBV 1 5 Vpp 2 is 12dBV 0 8 Vpp 3 is 18dBV 0 4 Vpp The generated signal is a sine wave with an DC offset of VDD 2 5 2 1 2 DAC 258 ...

Страница 259: ...ate and use non default PIN assignments P10 SDA P11 SCL i2c init I2C MASTER baudrate 20000 init as a master i2c deinit turn off the peripheral Example using non default Pins from machine import I2C i2c I2C 0 pins P10 P11 create and use non default PIN assignments P10 SDA P11 SCL i2c init I2C MASTER baudrate 20000 init as a master i2c deinit turn off the peripheral Printing the i2c object gives you...

Страница 260: ...riteto_mem 0x42 0x10 xy write 2 bytes to slave 0x42 slave memory 0x10 Constructors class machine I2C bus Construct an I2C object on the given bus bus can only be 0 1 2 If the bus is not given the default one will be selected 0 Buses 0 and 1 use the ESP32 I2C hardware peripheral while bus 2 is implemented with a bit banged software driver General Methods i2c init mode baudrate 100000 pins SDA SCL I...

Страница 261: ...is the number of bytes written Memory Operations Some I2C devices act as a memory device or set of registers that can be read from and written to In this case there are two addresses associated with an I2C transaction the slave address and the memory address The following methods are convenience functions to communicate with such devices i2c readfrom_mem addr memaddr nbytes addrsize 8 Read nbytes ...

Страница 262: ...y memaddr The argument buf can also be an integer which will be treated as a single byte The addrsize argument is specified in bits and it can only take 8 or 16 The return value is the number of bytes written Constants I2C MASTER Used to initialise the bus to master mode 5 2 1 3 I2C 262 ...

Страница 263: ...n OUT p_out value 1 p_out value 0 p_out toggle p_out True make P10 an input with the pull up enabled p_in Pin P10 mode Pin IN pull Pin PULL_UP p_in get value 0 or 1 Constructors class machine Pin id Create a new Pin object associated with the string id If additional arguments are given they are used to initialise the pin See pin init from machine import Pin p Pin P10 mode Pin OUT pull None alt 1 M...

Страница 264: ...e given set the logic level of the pin value can be anything that converts to a boolean If it converts to True the pin is set high otherwise it is set low pin value Pin objects are callable The call method provides a fast shortcut to set and get the value of the pin Example from machine import Pin pin Pin P12 mode Pin IN pull Pin PULL_UP pin fast method to get the value See pin value for more deta...

Страница 265: ...RQ_FALLING interrupt on falling edge Pin IRQ_RISING interrupt on rising edge Pin IRQ_LOW_LEVEL interrupt on low level Pin IRQ_HIGH_LEVEL interrupt on high level The values can be OR ed together for instance trigger Pin IRQ_FALLING Pin IRQ_RISING handler is the function to be called when the event happens This function will receive one argument Set handler to None to disable it arg is an optional a...

Страница 266: ...dule Examples Pin module P9 led Pin Pin module P9 mode Pin OUT Pin module P9 id Constants The following constants are used to configure the pin objects Note that not all constants are available on all ports Pin IN Pin OUT Pin OPEN_DRAIN Selects the pin mode Pin PULL_UP Pin PULL_DOWN Enables the pull up or pull down resistor 5 2 1 4 Pin 266 ...

Страница 267: ...illate at the specified frequency timer is an integer from 0 to 3 frequency is an integer from 1 Hz to 78 KHz this values can change in future upgrades Methods pwm channel id pin duty_cycle 0 5 Connect a PWM channel to a pin setting the initial duty cycle id is an integer from 0 to 7 pin is a string argument duty_cycle is a keyword only float argument with values between 0 and 1 Returns an instanc...

Страница 268: ...Defaults to id 0 rtc RTC id 0 Methods rtc init datetime None source RTC INTERNAL_RC Initialise the RTC The arguments are datetime when passed it sets the current time It is a tuple of the form year month day hour minute second microsecond tzinfo source selects the oscillator that drives the RTC The options are RTC INTERNAL_RC and RTC XTAL_32KHZ For example for 2nd of February 2017 at 10 30am TZ 0 ...

Страница 269: ...None to disable the periodic updates update_period is the number of seconds between updates Shortest period is 15 seconds Can be used like rtc ntp_sync pool ntp org this is an example You can select a more specific serv er according to your geographical location rtc synced Returns True if the last ntp_sync has been completed False otherwise rtc synced Constants RTC INTERNAL_RC RTC XTAL_32KHZ Clock...

Страница 270: ...an be 0 or 1 and is the level the idle clock line sits at Phase can be 0 or 1 to sample data on the first or second clock edge respectively Quick Usage Example from machine import SPI configure the SPI master 2MHz this uses the SPI default pins for CLK MOSI and MISO P10 P11 and P14 spi SPI 0 mode SPI MASTER baudrate 2000000 polarity 0 phase 0 spi write bytes 0x01 0x02 0x03 0x04 0x05 send 5 bytes o...

Страница 271: ... extra arguments are given the bus is initialised See init for parameters of initialisation Methods spi init mode baudrate 1000000 polarity 0 phase 0 bits 8 firstbit SPI MSB pins CLK MOSI MISO Initialise the SPI bus with the given parameters mode must be SPI MASTER baudrate is the SCK clock rate polarity can be 0 or 1 and is the level the idle clock line sits at phase can be 0 or 1 to sample data ...

Страница 272: ...pecified by buf while writing the data specified by write Return the number of bytes read spi write_readinto write_buf read_buf Write from write_buf and read into read_buf Both buffers must have the same length Returns the number of bytes written Constants SPI MASTER For initialising the SPI bus to master SPI MSB Set the first bit to be the most significant bit SPI LSB Set the first bit to be the ...

Страница 273: ...UART EVEN or UART ODD Stop can be 1 1 5 or 2 A UART object acts like a stream object therefore reading and writing is done using the standard stream methods uart read 10 read 10 characters returns a bytes object uart readall read all available characters uart readline read a line uart readinto buf read and store into the given buffer uart write abc write the 3 characters To check if there is anyth...

Страница 274: ...can be 0 1 or 2 If the bus is not given the default one will be selected 0 or the selection will be made based on the given pins On the GPy FiPy UART2 is unavailable because it is used to communicate with the cellular radio Methods uart init baudrate 9600 bits 8 parity None stop 1 timeout_chars 2 pins TXD RXD RTS CTS Initialise the UART bus with the given parameters baudrate is the clock rate bits...

Страница 275: ...many bytes Return value a bytes object containing the bytes read in Returns None on timeout uart readall Read as much data as possible Return value a bytes object or None on timeout uart readinto buf nbytes Read bytes into the buf If nbytes is specified then read at most that many bytes Otherwise read at most len buf bytes Return value number of bytes read and stored into buf or None on timeout ua...

Страница 276: ...e uart wait_tx_done timeout_ms Waits at most timeout_ms for the last Tx transaction to complete Returns True if all data has been sent and the TX buffer has no data in it otherwise returns False Constants UART EVEN UART ODD Parity types along with None UART RX_ANY IRQ trigger sources 5 2 1 8 UART 276 ...

Страница 277: ...tors class machine WDT id 0 timeout Create a WDT object and start it The id can only be 0 See the init method for the parameters of initialisation Methods wdt init timeout Initialises the watchdog timer The timeout must be given in milliseconds Once it is running the WDT cannot be stopped but the timeout can be re configured at any point in time wdt feed Feed the WDT to prevent it from resetting t...

Страница 278: ...rg an optional argument can be passed to the callback handler function If None is specified the function will receive the object that triggered the alarm s ms us the interval can be specified in seconds float miliseconds integer or microseconds integer Only one at a time can be specified periodic an alarm can be set to trigger repeatedly by setting this parameter to True Methods Timer sleep_us Del...

Страница 279: ... Start the chronometer chrono stop Stop the chronometer chrono reset Reset the time count to 0 chrono read Get the elapsed time in seconds chrono read_ms Get the elapsed time in milliseconds chrono read_us Get the elapsed time in microseconds Example 5 2 1 10 Timer 279 ...

Страница 280: ... alarm callback handler arg None Specify a callback handler for the alarm If set to None the alarm will be disabled An optional argument arg can be passed to the callback handler function If None is specified the function will receive the object that triggered the alarm alarm cancel Disables the alarm Example from machine import Timer class Clock def __init__ self self seconds 0 self __alarm Timer...

Страница 281: ...For more information on how Pycom s products handle interrupts see notes 5 2 1 10 Timer 281 ...

Страница 282: ...al pull up resistors are needed If you have one of the Pycom expansion boards then simply insert the card into the micro SD socket and run your script Make sure your SD card is formatted either as FAT16 or FAT32 Quick Example Usage from machine import SD import os sd SD os mount sd sd check the content os listdir sd try some standard file operations f open sd test txt w f write Testing SD card wri...

Страница 283: ...rd sd deinit Disable the SD card Please note that the SD card library currently supports FAT16 32 formatted SD cards up to 32 GB Future firmware updates will increase compatibility with additional formats and sizes 5 2 1 11 SD 283 ...

Страница 284: ...AN peripheral is available so the bus must always be 0 can CAN 0 mode CAN NORMAL baudrate 500000 pins P22 P23 pin order is Tx Rx Methods can init mode CAN NORMAL baudrate 500000 frame_format CAN FORMAT_STD rx_queue_len 128 pins P22 P23 Initialize the CAN controller The arguments are mode can take either CAN NORMAL or CAN SILENT Silent mode is useful for sniffing the bus baudrate sets up the bus sp...

Страница 285: ...ed specifies if the message identifier width should be 11bit standard or 29bit extended Can be used like can send id 0x0020 data bytes 0x01 0x02 0x03 0x04 0x05 extended True sen ds 5 bytes with an extended identifier can send id 0x010 data bytes 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 sen ds 8 bytes with an standard identifier can send id 0x012 rtr True sends a remote request for message id 0x12 c...

Страница 286: ...only accept identifiers from 0x001 to 0x010 from 0x020 to 0x030 and from 0x040 to 0x 050 can soft_filter CAN FILTER_MASK 0x100 0x7FF 0x200 0x7FC more of the class ic Filter and Mask method can soft_filter None disable soft filters all messages are accepted can callback trigger handler None arg None Set a callback to be triggered when any of this 3 events are present trigger is the type of event th...

Страница 287: ...ts if any indicating the events that have occurred in the bus Please note that by calling this function the internal events registry is cleared automatically therefore calling it immediately for a second time will most likely return a value of 0 Constants CAN NORMAL CAN SILENT CAN FORMAT_STD CAN FORMAT_EXT CAN FORMAT_BOTH CAN RX_FRAME CAN RX_FIFO_NOT_EMPTY CAN RX_FIFO_OVERRUN CAN FILTER_LIST CAN F...

Страница 288: ...uration 10000 send the signal rmt send_pulses duration data Quick Usage Example receiving import machine create a RMT object rmt machine RMT channel 3 Configure RTM for receiving rmt init gpio P20 rx_idle_threshold 12000 wait for any number of pulses until one longer than rx_idle_threshold data rmt recv_pulses Constructors class machine RMT channel Construct an RMT object on the given channel chan...

Страница 289: ...31 tx_idle_level is the output signal s level after the transmission is finished can be RMT HIGH or RMT LOW tx_carrier is the modulation of the pulses to send Either rx_idle_threshold or tx_idle_level must be defined both cannot be given at the same time because a channel can be configured in RX or TX mode only rx_filter_threshold is not mandatory parameter If not given then all pulses are accepte...

Страница 290: ...ived in a row without receiving idle signal If the incoming pulse sequence contains more than 128 pulses the rest is dropped and the receiver waits for another sequence of pulses The pulses_get function can be called to receive more than 128 pulses however the above mentioned limitation should be kept in mind when evaluating the received data rmt pulses_send duration data start_level Generates pul...

Страница 291: ...qual length as set by duration If data and duration are provided as tuples they must be of the same number of elements with each pulse lasting its matching duration Constants RMT LOW RMT HIGH Defines the level of the pulse 5 2 1 13 RMT 291 ...

Страница 292: ... module provides access to network drivers and routing configuration Network drivers for specific hardware are available within this module and are used to configure specific hardware network interfaces 5 2 2 network 292 ...

Страница 293: ...S wlan ifconfig config 192 168 0 107 255 255 255 0 192 168 0 1 192 168 0 1 wlan scan scan for available networks wlan connect ssid mynetwork auth WLAN WPA2 my_network_key while not wlan isconnected pass print wlan ifconfig Constructors class network WLAN id 0 Create a WLAN object and optionally configure it See init for params of configuration The WLAN constructor is special in the sense that if n...

Страница 294: ... external antenna Can be either WLAN INT_ANT WLAN EXT_ANT With our development boards it defaults to using the internal antenna but in the case of an OEM module the antenna pin P12 is not used so it s free to be used for other things power_save enables or disables power save functions in STA mode hidden only valid in WLAN AP mode to create an access point with a hidden SSID when set to True For ex...

Страница 295: ...rname and password are not part of the auth tuple identity is only used in case of WLAN WPA2_ENT security wlan scan Performs a network scan and returns a list of named tuples with ssid bssid sec channel rssi Note that channel is always None since this info is not provided by the WiPy wlan disconnect Disconnect from the WiFi access point wlan isconnected In case of STA mode returns True if connecte...

Страница 296: ...nnel channel Get or set the channel only applicable in AP mode wlan antenna antenna Get or set the antenna type external or internal wlan mac Get a 6 byte long bytes object with the WiFI MAC address Constants WLAN STA WLAN AP WLAN STA_AP WLAN mode WLAN WEP WLAN WPA WLAN WPA2 WLAN WPA2_ENT WLAN network security WLAN INT_ANT WLAN EXT_ANT Antenna type 5 2 2 1 WLAN 296 ...

Страница 297: ... network import Server init with new user password and seconds timeout server Server login user password timeout 60 server timeout 300 change the timeout server timeout get the timeout server isrunning check whether the server is running or not Constructors class network Server id Create a server instance see init for parameters of initialisation Methods server init login micro python timeout 300 ...

Страница 298: ...Get or set the server timeout server isrunning Returns True if the server is running connected or accepting connections False otherwise 5 2 2 2 Server 298 ...

Страница 299: ...rint 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 print Error while connecting or reading from the BLE device break else time sleep 0 050 Bluetooth Low Energy BLE Bluetooth low energy B...

Страница 300: ...ntenna selects between the internal and the external antenna Can be either Bluetooth INT_ANT Bluetooth EXT_ANT With our development boards it defaults to using the internal antenna but in the case of an OEM module the antenna pin P12 is not used so it s free to be used for other things Initialises and enables the Bluetooth radio in BLE mode bluetooth deinit Disables the Bluetooth radio bluetooth s...

Страница 301: ...ructure mac addr_type adv_type rssi data mac is the 6 byte ling mac address of the device that sent the advertisement addr_type is the address type See the constants section below for more details adv_type is the advertisement type received See the constants section below fro more details rssi is signed integer with the signal strength of the advertisement data contains the complete 31 bytes of th...

Страница 302: ...ooth 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 bluetooth connect mac_addr Opens a BLE connection with the device specified by the mac_addr argument This function blocks until the connection succeeds or fails If the connections succeeds it returns a object of type GATTCCo...

Страница 303: ...ENT_CONNECTED print Client connected elif events Bluetooth CLIENT_DISCONNECTED print Client disconnected bluetooth callback trigger Bluetooth CLIENT_CONNECTED Bluetooth CLIENT_DISCONNECTED handler conn_cb bluetooth advertise True bluetooth set_advertisement name None manufacturer_data None service_data None service_uuid None Configure the data to be sent while advertising If left with the default ...

Страница 304: ... the number of characteristics that the service will contain start if True the service is started immediately bluetooth service abc123 bluetooth disconnect_client Closes the BLE connection with the client Constants Bluetooth mode Bluetooth BLE Advertisement type Bluetooth CONN_ADV Bluetooth CONN_DIR_ADV Bluetooth DISC_ADV Bluetooth NON_CONN_ADV Bluetooth SCAN_RSP Address type Bluetooth PUBLIC_ADDR...

Страница 305: ...rties bit values that can be combined Bluetooth PROP_BROADCAST Bluetooth PROP_READ Bluetooth PROP_WRITE_NR Bluetooth PROP_WRITE Bluetooth PROP_NOTIFY Bluetooth PROP_INDICATE Bluetooth PROP_AUTH Bluetooth PROP_EXT_PROP Characteristic callback events Bluetooth CHAR_READ_EVENT Bluetooth CHAR_WRITE_EVENT Bluetooth NEW_ADV_EVENT Bluetooth CLIENT_CONNECTED Bluetooth CLIENT_DISCONNECTED Bluetooth CHAR_NO...

Страница 306: ...ction is established between two devices meaning that the device will have already gone through the advertising process managed by GAP It s important to remember that this connection is exclusive i e that only one client is connected to one server at a time This means that the client will stop advertising once a connection has been made This remains the case until the connection is broken or disco...

Страница 307: ...n False otherwise Example from network import Bluetooth import ubinascii bluetooth Bluetooth scan until we can connect to any BLE device around bluetooth start_scan 1 adv None while True 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 connection services...

Страница 308: ... assuming that a BLE connection is already open services connection services print services for service in services print service uuid 5 2 2 3 Bluetooth 308 ...

Страница 309: ... if the service is a primary one False otherwise service uuid Returns the UUID of the service In the case of 16 bit or 32 bit long UUIDs the value returned is an integer but for 128 bit long UUIDs the value returned is a bytes object service instance Returns the instance ID of the service service characteristics Performs a get characteristics request on the connected BLE peripheral a returns a lis...

Страница 310: ...rties of the characteristic Properties are represented by bit values that can be OR ed together See the constants section for more details characteristic read Read the value of the characteristic sending a request to the GATT server Returns a bytes object representing the characteristic value characteristic value Returns the locally stored value of the characteristic without sending a read request...

Страница 311: ...Y_EVENT handler is the function that will be executed when the callback is triggered arg is the argument that gets passed to the callback If nothing is given the characteristic object that owns the callback will be used 5 2 2 3 Bluetooth 311 ...

Страница 312: ...arts the service if not already started service stop Stops the service if previously started service characteristic uuid permissions properties value Creates a new characteristic on the service Returns an object of the class GATTSCharacteristic The arguments are uuid is the UUID of the service Can take an integer or a 16 byte long string or bytes object permissions configures the permissions of th...

Страница 313: ...acteristic callback trigger None handler None arg None Creates a callback that will be executed when any of the triggers occurs The arguments are trigger can be either Bluetooth CHAR_READ_EVENT or Bluetooth CHAR_WRITE_EVENT handler is the function that will be executed when the callback is triggered arg is the argument that gets passed to the callback If nothing is given the characteristic object ...

Страница 314: ...har1_read_counter 0 def char1_cb_handler chr global char1_read_counter char1_read_counter 1 events chr events if events Bluetooth CHAR_WRITE_EVENT print Write request with value format chr value else if char1_read_counter 3 print Read request on char 1 else return ABC DEF char1_cb chr1 callback trigger Bluetooth CHAR_WRITE_EVENT Bluetooth CHAR_READ_EVEN T handler char1_cb_handler srv2 bluetooth se...

Страница 315: ...5 2 2 3 Bluetooth 315 ...

Страница 316: ...unpack l binascii unhexlify 00000005 0 nwk_swkey ubinascii unhexlify 2B7E151628AED2A6ABF7158809CF4F3C app_swkey ubinascii unhexlify 2B7E151628AED2A6ABF7158809CF4F3C join a network using ABP Activation By Personalisation lora join activation LoRa ABP auth dev_addr nwk_swkey app_swkey create a LoRa socket s socket socket socket AF_LORA socket SOCK_RAW set the LoRaWAN data rate s setsockopt socket SO...

Страница 317: ...868 or LoRa US915 If not provided this will default to LoRaEU868 If they are not specified this will also set appropriate defaults for frequency and tx_power frequency accepts values between 863000000 and 870000000 in the 868 band or between 902000000 and 928000000 in the 915 band tx_power is the transmit power in dBm It accepts between 2 and 14 for the 868 band and between 5 and 20 in the 915 ban...

Страница 318: ...aWAN stack directly On the other hand in LoRa LORA mode from those 4 arguments only the public one is important in order to program the sync word In LoRa LORA mode adr tx_retries and device_class are ignored since they are only relevant to the LoRaWAN stack For example you can do initialize in raw LoRa mode lora init mode LoRa LORA tx_power 14 sf 12 or initialize in LoRaWAN mode lora init mode LoR...

Страница 319: ...twork import LoRa import socket import time import ubinascii Initialise LoRa in LORAWAN mode Please pick the region that matches where you are using the device Asia LoRa AS923 Australia LoRa AU915 Europe LoRa EU868 United States LoRa US915 lora LoRa mode LoRa LORAWAN region LoRa EU868 create an OTAA authentication parameters app_eui ubinascii unhexlify ADA4DAE3AC12676B app_key ubinascii unhexlify ...

Страница 320: ...join a network using ABP Activation By Personalisation lora join activation LoRa ABP auth dev_addr nwk_swkey app_swkey lora bandwidth bandwidth Get or set the bandwidth in raw LoRa mode LoRa LORA Can be either LoRa BW_125KHZ 0 LoRa BW_250KHZ 1 or LoRa BW_500KHZ 2 get raw LoRa Bandwidth lora bandwidth set raw LoRa Bandwidth lora bandwidth LoRa BW_125KHZ lora frequency frequency Get or set the frequ...

Страница 321: ...amble LoRa CODING_4_5 lora sf sf Get or set the spreading factor value in raw LoRa mode LoRa LORA The minimum value is 7 and the maximum is 12 get raw LoRa spread factor value lora sf set raw LoRa spread factor value lora sf 7 lora power_mode power_mode Get or set the power mode in raw LoRa mode LoRa LORA The accepted values are LoRa ALWAYS_ON LoRa TX_ONLY and LoRa SLEEP lora stats Return a named ...

Страница 322: ...the last transmission in dBm tx_time_on_air is the time on air of the last transmitted packet in ms tx_counter is the number of packets transmitted tx_frequency is the frequency used for the last transmission lora has_joined Returns True if a LoRaWAN network has been joined False otherwise lora add_channel index frequency dr_min dr_max Add a LoRaWAN channel on the specified index If there s alread...

Страница 323: ...even if a downlink is received the LoRa TX_PACKET_EVENT will come last In the case of non confirmed transmissions this will occur at the end of the receive windows but in the case of confirmed transmissions this event will only be raised if the ack is received If the ack is not received LoRa TX_FAILED_EVENT will be raised after the number of tx_retries configured have been performed An example of ...

Страница 324: ...print Lora packet received if events LoRa TX_PACKET_EVENT print Lora packet sent lora callback trigger LoRa RX_PACKET_EVENT LoRa TX_PACKET_EVENT handler lora_cb lora nvram_save Save the LoRaWAN state joined status network keys packet counters etc in non volatile memory in order to be able to restore the state when coming out of deepsleep or a power cycle lora nvram_save lora nvram_restore Restore ...

Страница 325: ...4_8 Raw LoRa coding rate LoRa RX_PACKET_EVENT LoRa TX_PACKET_EVENT LoRa TX_FAILED_EVENT Callback trigger types may be ORed LoRa CLASS_A LoRa CLASS_C LoRaWAN device class LoRa AS923 LoRa AU915 LoRa EU868 LoRa US915 LoRaWAN regions Working with LoRa and LoRaWAN Sockets LoRa sockets are created in the following way import socket s socket socket socket AF_LORA socket SOCK_RAW And they must be created ...

Страница 326: ...socket recvfrom bufsize This method is useful to know the destination port number of the message received Returns a tuple of the form data port Usage s recvfrom 128 socket setsockopt level optname value Set the value of the given socket option The needed symbolic constants are defined in the socket module SO_ etc In the case of LoRa the values are always integers Examples 5 2 2 4 LoRa 326 ...

Страница 327: ... socket SO_CONFIRMED True Socket options are only applicable when the LoRa radio is used in LoRa LORAWAN mode When using the radio in LoRa LORA mode use the class methods to change the spreading factor bandwidth and coding rate to the desired values socket settimeout value Sets the socket timeout value in seconds Accepts floating point values Usage s settimeout 5 5 socket setblocking flag Usage s ...

Страница 328: ... transmissions However due to FCC duty cycle limitations there must a minimum of a 20s delay after resetting to the default macro channel Our API takes care of this and in real life applications you should not be in the need to send Sigfox messages that often so it will wait for the necessary amount of time to make sure that the duty cycle restrictions are fulfilled This means that if you run a pi...

Страница 329: ...se e g without an antenna may damage the device Constructors class network Sigfox id 0 Create and configure a Sigfox object See init for params of configuration Examples configure radio for the Sigfox network using RCZ1 868 MHz sigfox Sigfox mode Sigfox SIGFOX rcz Sigfox RCZ1 configure radio for FSK device to device across 912 MHz sigfox Sigfox mode Sigfox FSK frequency 912000000 Methods sigfox in...

Страница 330: ...turns a byte object with the 4 Byte bytes object with the Sigfox ID sigfox rssi Returns a signed integer with indicating the signal strength value of the last received packet sigfox pac Returns a byte object with the 8 Byte bytes object with the Sigfox PAC To return human readable values you should import ubinascii and convert binary values to hexidecimal representation For example print ubinascii...

Страница 331: ...ealand Singapore Taiwan Hong Kong Colombia Argentina Working with Sigfox Sockets Sigfox sockets are created in the following way import socket s socket socket socket AF_SIGFOX socket SOCK_RAW And they must be created after initialising the Sigfox network card Sigfox sockets support the following standard methods from the socket module socket close Use it to close an existing socket socket send byt...

Страница 332: ...s setsockopt socket SOL_SIGFOX socket SO_OOB True disable Out Of Band to use the socket normally s setsockopt socket SOL_SIGFOX socket SO_OOB False select the bit value when sending bit only packets s setsockopt socket SOL_SIGFOX socket SO_BIT False Sending a Sigfox packet with a single bit is achieved by sending an empty string i e import socket s socket socket socket AF_SIGFOX socket SOCK_RAW se...

Страница 333: ...ocket socket socket AF_SIGFOX socket SOCK_RAW make the socket blocking s setblocking True configure it as DOWNLINK specified by True s setsockopt socket SOL_SIGFOX socket SO_RX True send some bytes and request DOWNLINK s send bytes 1 2 3 await DOWNLINK message s recv 32 Sigfox FSK Device to Device To communicate between two Sigfox capable devices it may be used in FSK mode Two devices are required...

Страница 334: ...8000000 s socket socket socket AF_SIGFOX socket SOCK_RAW s setblocking True while True s send Device 2 time sleep 1 print s recv 64 Remember to use the correct frequency for your region 868 MHz for Europe 912 MHz for USA etc 5 2 2 5 Sigfox 334 ...

Страница 335: ...cifically designed for IoT devices with a very long battery life NB IoT shares some features with LTE such as operating in licensed spectrum but it s a very different protocol It should be noted that NB IoT has many restrictions as does not offer full IP connectivity and does not support mobility When moving between cells you will need to reconnect Please note The GPy and FiPy only support the two...

Страница 336: ...functionality and attach to the LTE Cat M1 network authorised by the inserted SIM card Optionally specify the band to scan for networks If no band or None is specified all 6 bands will be scanned The possible values for the band are 3 4 12 13 20 and 28 lte isattached Returns True if the cellular mode is attached to the network False otherwise lte dettach Detach the modem from the LTE Cat M1 and di...

Страница 337: ...o the modem Returns the raw response from the modem as a string object IMPORTANT If a data session is active i e the modem is connected sending the AT commands requires to pause and then resume the data session This is all done automatically but makes the whole request take around 2 5 seconds Example lte send_at_cmd AT CEREG check for network registration manually sames as lt e isattached Optional...

Страница 338: ... the LTE modem lte iccid Returns a string object with the ICCID number of the SIM card lte reset Perform a hardware reset on the cellular modem This function can take up to 5 seconds to return as it waits for the modem to shutdown and reboot 5 2 2 6 LTE 338 ...

Страница 339: ...properly sent the encrypted message somewhere cipher AES key AES MODE_CFB msg 16 on the decryption side original cipher decrypt msg 16 print original Constructors class ucrypto AES key mode IV counter segment_size Create an AES object that will let you encrypt and decrypt messages The arguments are key byte string is the secret key to use It must be 16 AES 128 24 AES 192 or 32 AES 256 bytes long m...

Страница 340: ...for more info AES MODE_CBC Cipher Block Chaining An Initialisation Vector IV is required AES MODE_CFB Cipher feedback plaintext and ciphertext are processed in segments of segment_size bits Works a stream cipher AES MODE_CTR Counter mode Each message block is associated to a counter which must be unique across all messages that get encrypted with the same key AES SEGMENT_8 AES SEGMENT_128 Length o...

Страница 341: ...t enable Allows you permanently disable or enable the heartbeat LED Once this setting is set it will persist between reboots Note this only comes into effect on the next boot it does not stop the already running heartbeat pycom rgbled color Set the colour of the RGB LED The colour is specified as 24 bit value representing red green and blue where the red colour is represented by the 8 most signifi...

Страница 342: ...the AP with the default SSID lopy wlan xxx for example will be enabled as part of the boot process If the flag is set to False the module will boot with WiFi disabled until it s enabled by the script via the WLAN class This setting is stored in non volatile memory which preserves it across resets and power cycles Example import pycom pycom wifi_on_boot True enable WiFi on boot pycom wifi_on_boot g...

Страница 343: ...tion in microseconds of that value pin is a pin object which must have set to INP or OPEN_DRAIN mode The scan stops if not transitions occurs within timeout milliseconds Example get the raw data from a DHT11 DHT22 AM2302 sensor from machine import Pin from pycom import pulses_get from time import sleep_ms pin Pin G7 mode Pin OPEN_DRAIN pin 0 sleep_ms 20 pin 1 data pulses_get pin 100 pycom ota_star...

Страница 344: ...OCKSIZE const 4096 APPIMG sd appimg bin sd SD mount sd sd with open APPIMG rb as f buffer bytearray BLOCKSIZE mv memoryview buffer size 0 ota_start while True chunk f readinto buffer if chunk 0 ota_write mv chunk size chunk print r 7d size end else break ota_finish Instead of reading the data to be written from a file it can obviously also be received from a server using any suitable protocol with...

Страница 345: ...ovide the core functionality of that module and are intended to be a drop in replacement for the standard Python library Some modules are available by an u name and also by their non u name The non u name can be overridden by a file of that name in your package path For example import json will first search for a file json py or directory json and load that package if it s found If nothing is foun...

Страница 346: ...he use of this function should be as follows from micropython import const CONST_X const 123 CONST_Y const 2 CONST_X 1 Constants declared this way are still accessible as global variables from outside the module they are declared in On the other hand if a constant begins with an underscore then it is hidden it is not available as a global variable and does not take up any memory during execution T...

Страница 347: ...used The absolute value of this is not particularly useful rather it should be used to compute differences in stack usage at different points micropython heap_lock micropython heap_unlock Lock or unlock the heap When locked no memory allocation can occur and a MemoryError will be raised if any heap allocation is attempted These functions can be nested i e heap_lock can be called multiple times in ...

Страница 348: ...re layout is defined by a descriptor a Python dictionary which encodes field names as keys and other properties required to access them as associated values Currently uctypes requires explicit specification of offsets for each field Offset are given in bytes from a structure start Following are encoding examples for various field types Scalar types field_name uctypes UINT32 0 In other words value ...

Страница 349: ...econd is descriptor of type pointed to Bitfields bitf0 uctypes BFUINT16 0 0 uctypes BF_POS 8 uctypes BF_LEN I e value is type of scalar value containing given bitfield typenames are similar to scalar types but prefixes with BF OR ed with offset for scalar value containing the bitfield and further OR ed with values for bit offset and bit length of the bitfield within scalar value shifted by BF_POS ...

Страница 350: ...ructure Packed means that every field occupies exactly as many bytes as defined in the descriptor i e the alignment is 1 uctypes BIG_ENDIAN Layout type for a big endian packed structure uctypes NATIVE Layout type for a native structure with data endianness and alignment conforming to the ABI of the system on which MicroPython runs uctypes sizeof struct Return size of data structure in bytes Argume...

Страница 351: ...network socket Structure objects Structure objects allow accessing individual fields using standard dot notation my_struct substruct1 field1 If a field is of scalar type getting it will produce a primitive value Python integer or float corresponding to the value contained in a field A scalar field can also be assigned to If a field is an array its individual elements can be accessed with the stand...

Страница 352: ...For example instead of peripheral_a register 0 use peripheral_a register0 Note that these recommendations will lead to decreased readability and conciseness of layouts so they should be used only if the need to access structure fields without allocation is anticipated it s even possible to define 2 parallel layouts one for normal usage and a restricted one to use when memory allocation is prohibit...

Страница 353: ...ion value instead of exception type exception value and traceback object file argument should be positional further arguments are not supported CPython compatible traceback module can be found in micropython lib Constants sys argv A mutable list of arguments the current program was started with sys byteorder The byte order of the system little or big sys implementation Object with information abou...

Страница 354: ...rm else 32 bit or less platform Note that on 32 bit platform value of bits may be less than 32 e g 31 due to peculiarities described above so use 16 32 64 style of comparisons sys modules Dictionary of loaded modules On some ports it may not include builtin modules sys path A mutable list of directories to search for imported modules sys platform The platform that MicroPython is running on For OS ...

Страница 355: ...ndard output stream sys version Python language version that this implementation conforms to as a string sys version_info Python language version that this implementation conforms to as a tuple of ints 5 3 3 sys 355 ...

Страница 356: ...internal flash filesystem sd the SD card if it exists Functions uos uname Return information about the system firmware release version and MicroPython interpreter version uos chdir path Change current directory uos getcwd Get the current directory uos listdir dir With no argument list the current directory Otherwise list the given directory uos mkdir path Create a new directory uos remove path Rem...

Страница 357: ...ed returns 0 st_size size of file in bytes st_atime time of most recent access st_mtime time of most recent content modification st_ctime time of most recent metadata change uos getfree path Returns the free space in KiB in the drive specified by path uos sync Sync all filesystems uos urandom n Return a bytes object with n random bytes uos unlink path Alias for the remove method uos mount block_de...

Страница 358: ...k device can also be passed like an SD object before being mounted uos dupterm stream_object Duplicate the terminal the REPL on the passed stream like object The given object must at least implement the read and write methods Constants uos sep Separation character used in paths 5 3 4 uos 358 ...

Страница 359: ...lasses class array array typecode iterable Create array with elements of given type Initial contents of the array are given by an iterable If it is not provided an empty array is created array append val Append new element to the end of array growing it array extend iterable Append new elements as contained in an iterable to the end of array growing it 5 3 5 array 359 ...

Страница 360: ... z cmath log z Return the natural logarithm of z The branch cut is along the negative real axis cmath log10 z Return the base 10 logarithm of z The branch cut is along the negative real axis cmath phase z Returns the phase of the number z in the range pi pi cmath polar z Returns as a tuple the polar form of z cmath rect r phi Returns the complex number with modulus r and phase phi cmath sin z Retu...

Страница 361: ...Constants cmath e Base of the natural logarithm cmath pi The ratio of a circle s circumference to its diameter 5 3 6 cmath 361 ...

Страница 362: ...rn the inverse hyperbolic cosine of x math asin x Return the inverse sine of x math asinh x Return the inverse hyperbolic sine of x math atan x Return the inverse tangent of x math atan2 y x Return the principal value of the inverse tangent of y x math atanh x Return the inverse hyperbolic tangent of x math ceil x Return an integer being x rounded towards positive infinity math copysign x y Return...

Страница 363: ...th expm1 x Return exp x 1 math fabs x Return the absolute value of x math floor x Return an integer being x rounded towards negative infinity math fmod x y Return the remainder of x y math frexp x Decomposes a floating point number into its mantissa and exponent The returned value is the tuple m e such that x m 2 e exactly If x 0 then the function returns 0 0 0 otherwise the relation 0 5 abs m 1 h...

Страница 364: ...function of x math log x Return the natural logarithm of x math log10 x Return the base 10 logarithm of x math log2 x Return the base 2 logarithm of x math modf x Return a tuple of two floats being the fractional and integral parts of x Both return values have the same sign as x math pow x y Returns x to the power of y math radians x Return degrees x converted to radians math sin x Return the sine...

Страница 365: ...e root of x math tan x Return the tangent of x math tanh x Return the hyperbolic tangent of x math trunc x Return an integer being x rounded towards 0 Constants math e Base of the natural logarithm math pi The ratio of a circle s circumference to its diameter 5 3 7 math 365 ...

Страница 366: ... garbage collection Heap memory can still be allocated and garbage collection can still be initiated manually using gc collect gc collect Run a garbage collection gc mem_alloc Return the number of bytes of heap RAM that are allocated gc mem_free Return the number of bytes of available heap RAM 5 3 8 gc 366 ...

Страница 367: ...ns bytes string Difference to CPython If additional argument sep is supplied it is used as a separator between hexadecimal values ubinascii unhexlify data Convert hexadecimal data to binary representation Returns bytes string i e inverse of hexlify ubinascii a2b_base64 data Convert Base64 encoded data to binary representation Returns bytes string ubinascii b2a_base64 data Encode binary data in Bas...

Страница 368: ...umps obj Return obj represented as a JSON string ujson loads str Parse the JSON str and return an object Raises ValueError if the string is not correctly formed ujson load fp Parse contents of fp a read supporting file like object containing a JSON document Raises ValueError if the content is not correctly formed 5 3 10 ujson 368 ...

Страница 369: ...ted repetitions m n more advanced assertions named groups etc are not supported Functions ure compile regex Compile regular expression return regex object ure match regex string Match regex against string Match always happens from starting position in a string ure search regex string Search regex in a string Unlike match this will search string for first position which matches regex which still ma...

Страница 370: ...his class are created using ure compile regex match string regex search string regex split string max_split 1 Match objects Match objects as returned by match and search methods match group index Only numeric groups are supported 5 3 11 ure 370 ...

Страница 371: ...t getaddrinfo Functions socket socket socket AF_INET socket SOCK_STREAM socket IPPROTO_TCP Create a new socket using the given address family socket type and protocol number socket getaddrinfo host port Translate the host port argument into a sequence of 5 tuples that contain all the necessary arguments for creating a socket connected to that service The list of 5 tuples has following structure fa...

Страница 372: ...rk the socket closed Once that happens all future operations on the socket object will fail The remote end will receive no more data after queued data is flushed Sockets are automatically closed when they are garbage collected but it is recommended to close them explicitly or to use a with statement around them socket bind address Bind the socket to address The socket must not already be bound The...

Страница 373: ...ocket connect address Connect to a remote socket at address socket send bytes Send data to the socket The socket must be connected to a remote socket socket sendall bytes Alias of socket send bytes socket recv bufsize Receive data from the socket The return value is a bytes object representing the data received The maximum amount of data to be received at once is specified by bufsize socket sendto...

Страница 374: ...hod is a shorthand for certain settimeout calls sock setblocking True is equivalent to sock settimeout None sock setblocking False is equivalent to sock settimeout 0 0 socket makefile mode rb Return a file object associated with the socket The exact returned type depends on the arguments given to makefile The support is limited to binary modes only rb and wb CPython s arguments encoding errors and...

Страница 375: ...many bytes Otherwise read at most len buf bytes Return value number of bytes read and stored into buf socket readline Read a line ending in a newline character Return value the line read socket write buf Write the buffer of bytes to the socket Return value number of bytes written 5 3 12 usocket 375 ...

Страница 376: ...ss select select rlist wlist xlist timeout Wait for activity on a set of objects This function is provided for compatibility and is not efficient Usage of Poll is recommended instead class Poll Methods poll register obj eventmask Register obj for polling eventmask is logical OR of select POLLIN data available for reading select POLLOUT more data can be written select POLLERR error occurred select ...

Страница 377: ... list of obj event tuples event element specifies which events happened with a stream and is a combination of select POLL constants described above There may be other elements in tuple depending on a platform and version so don t assume that its size is 2 In case of timeout an empty list is returned Timeout is in milliseconds 5 3 13 select 377 ...

Страница 378: ...ed by following means By a backup battery which may be an additional optional component for a particular board Using networked time protocol requires setup by a port user Set manually by a user on each power up many boards then maintain RTC time across hard resets though some may require setting it again in such case If actual calendar time is not maintained with a system MicroPython RTC functions...

Страница 379: ...nt for compatibility with them use sleep_ms and sleep_us functions utime sleep_ms ms Delay for given number of milliseconds should be positive or 0 utime sleep_us us Delay for given number of microseconds should be positive or 0 utime ticks_ms Returns uptime in milliseconds utime ticks_us Just like ticks_ms above but in microseconds utime ticks_cpu Same as ticks_us but faster utime ticks_diff old ...

Страница 380: ... not set this function returns number of seconds since power up or reset If you want to develop portable MicroPython application you should not rely on this function to provide higher than second precision If you need higher precision use ticks_ms and ticks_us functions if you need calendar time localtime without an argument is a better choice utime timezone secs Set or get the timezone offset in ...

Страница 381: ...lib sha224 data Create a SHA 224 hasher object and optionally feed data into it class uhashlib sha256 data Create a SHA 256 hasher object and optionally feed data into it class uhashlib sha384 data Create a SHA 384 hasher object and optionally feed data into it class uhashlib sha512 data Create a SHA 512 hasher object and optionally feed data into it Methods hash update data Feed more binary data ...

Страница 382: ...This method is NOT implemented Use ubinascii hexlify hash digest to achieve a similar effect 5 3 15 uhashlib 382 ...

Страница 383: ...ocket getaddrinfo www google com 443 0 1 Certificates must be used in order to validate the other side of the connection and also to authenticate ourselves with the other end Such certificates must be stored as files using the FTP server and they must be placed in specific paths with specific names For instance to connect to the Blynk servers using certificates take the file ca pem located in the ...

Страница 384: ...ssl CERT_NONE ssl CERT_OPTIONAL ssl CERT_REQUIRED Supported values in cert_reqs 5 3 16 ussl 384 ...

Страница 385: ...ts can be used as the basis for cryptographical operations These true random numbers are generated based on the noise in the Wi Fi BT RF system When Wi Fi and BT are disabled the random number generator will give out pseudo random numbers The parameter bits is rounded upwards to the nearest multiple of 32 bits Cryptography is not a trivial business Doing things the wrong way could quickly result i...

Страница 386: ...n value is a bytes object encoding the values ustruct pack_into fmt buffer offset v1 v2 Pack the values v1 v2 according to the format string fmt into a buffer starting at offset offset may be negative to count from the end of buffer ustruct unpack fmt data Unpack from the data according to the format string fmt The return value is a tuple of the unpacked values ustruct unpack_from fmt data offset ...

Страница 387: ...thread th_func i 1 i Functions _thread start_new_thread function args kwargs Start a new thread and return its identifier The thread executes the function with the argument list args which must be a tuple The optional kwargs argument specifies a dictionary of keyword arguments When the function returns the thread silently exits When the function terminates with an unhandled exception a stack trace...

Страница 388: ...ion between threads Methods Lock objects have the following methods lock acquire waitflag 1 timeout 1 Without any optional argument this method acquires the lock unconditionally if necessary waiting until it is released by another thread only one thread at a time can acquire a lock that s their reason for existence If the integer waitflag argument is present the action depends on its value if it i...

Страница 389: ...it has been acquired by some thread False if not In addition to these methods lock objects can also be used via the with statement e g import _thread a_lock _thread allocate_lock with a_lock print a_lock is locked while this executes 5 3 19 _thread 389 ...

Страница 390: ...tin Functions All builtin functions are described here They are also available via builtins module abs all any bin class bool class bytearray class bytes callable chr class method compile 5 3 20 Builtin 390 ...

Страница 391: ...class complex class dict dir divmod enumerate eval exec filter class float class frozenset getattr globals 5 3 20 Builtin 391 ...

Страница 392: ...hasattr hash hex id input class int isinstance issubclass iter len class list locals map 5 3 20 Builtin 392 ...

Страница 393: ...max class memoryview min next class object oct open ord pow print property range 5 3 20 Builtin 393 ...

Страница 394: ...repr reversed round class set setattr sorted staticmethod class str sum super class tuple type zip 5 3 20 Builtin 394 ...

Страница 395: ...5 3 20 Builtin 395 ...

Страница 396: ...les pinouts spec sheets relevant examples and notes Development Modules WiPy 2 0 WiPy 3 0 SiPy LoPy LoPy4 GPy FiPy OEM modules W01 L01 L04 G01 L01 W01 Reference Board Universal Reference Board Shields and Expansion boards Expansion Board 2 0 Pysense Pytrack Deep Sleep Shield 6 0 Introduction 396 ...

Страница 397: ...Development Devices This section contains all of the datasheets for the Pycom Development Devices This includes the WiPy 2 0 and 3 0 LoPy LoPy 4 SiPy GPy and FiPy 6 1 Development Modules 397 ...

Страница 398: ...ting Started Click Here Pinout The pinout of the WiPy2 is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Datasheet 6 1 1 WiPy 2 0 398 ...

Страница 399: ...ulator is put into ECO mode the quiescent current goes down to 10uA Unfortunately the pin used to control this mode is out of the RTC domain and therefore not usable during deep sleep This causes the regulator to always stay in PWM mode keeping its quiescent current at 10mA Alongside this the flash chip doesn t enter power down mode because the CS pin is floating during deep sleep This causes the ...

Страница 400: ...6 1 1 WiPy 2 0 400 ...

Страница 401: ...ng Started Click Here Pinout The pinout of the WiPy3 is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software 6 1 2 WiPy 3 0 401 ...

Страница 402: ... io The RF switch that selects between the on board and external antenna is connected to P12 for this reason using P12 should be avoided unless WiFi is disabled in your application Power The Vin pin on the WiPy3 can be supplied with a voltage ranging from 3 5v to 5 5v The 3 3v pin on the other hand is output only and must not be used to feed power into the WiPy3 otherwise the on board regulator wi...

Страница 403: ...arted Click Here Pinout The pinout of the LoPy is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Datasheet 6 1 3 LoPy 403 ...

Страница 404: ...or is put into ECO mode the quiescent current goes down to 10uA Unfortunately the pin used to control this mode is out of the RTC domain and therefore not usable during deep sleep This causes the regulator to always stay in PWM mode keeping its quiescent current at 10mA Alongside this the flash chip doesn t enter power down mode because the CS pin is floating during deep sleep This causes the flas...

Страница 405: ...LoRaWAN nano gateway BLE 6 1 3 LoPy 405 ...

Страница 406: ...g Started Click Here Pinout The pinout of the LoPy4 is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software 6 1 4 LoPy 4 406 ...

Страница 407: ...12 should be avoided unless WiFi is disabled in your application Power The Vin pin on the LoPy4 can be supplied with a voltage ranging from 3 5v to 5 5v The 3 3v pin on the other hand is output only and must not be used to feed power into the LoPy4 otherwise the on board regulator will be damaged Tutorials Tutorials on how to the LoPy4 module can be found in the examples section of this documentat...

Страница 408: ...arted Click Here Pinout The pinout of the SiPy is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Datasheet 6 1 5 SiPy 408 ...

Страница 409: ...lator is put into ECO mode the quiescent current goes down to 10uA Unfortunately the pin used to control this mode is out of the RTC domain and therefore not usable during deep sleep This causes the regulator to always stay in PWM mode keeping its quiescent current at 10mA Alongside this the flash chip doesn t enter power down mode because the CS pin is floating during deep sleep This causes the f...

Страница 410: ...BLE 6 1 5 SiPy 410 ...

Страница 411: ...tarted Click Here Pinout The pinout of the GPy is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Datasheet 6 1 6 GPy 411 ...

Страница 412: ...abled in your application Power The Vin pin on the GPy can be supplied with a voltage ranging from 3 5v to 5 5v The 3 3v pin on the other hand is output only and must not be used to feed power into the GPy otherwise the on board regulator will be damaged AT Commands The AT commands for the Sequans Monarch modem on the GPy are available in a PDF file Tutorials Tutorials on how to the GPy module can...

Страница 413: ...arted Click Here Pinout The pinout of the FiPy is available as a PDF File Please note that the PIN assignments for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Datasheet 6 1 7 FiPy 413 ...

Страница 414: ...ion Power The Vin pin on the FiPy can be supplied with a voltage ranging from 3 5v to 5 5v The 3 3v pin on the other hand is output only and must not be used to feed power into the FiPy otherwise the on board regulator will be damaged AT Commands The AT commands for the Sequans Monarch modem on the FiPy are available in a PDF file Tutorials Tutorials on how to the FiPy module can be found in the e...

Страница 415: ...6 1 7 FiPy 415 ...

Страница 416: ...OEM Devices This section contains all of the datasheets for the Pycom OEM Devices This includes the W01 L01 L04 and G01 6 2 OEM Modules 416 ...

Страница 417: ...W01 Pinout The pinout of the W01 is available as a PDF File Specsheets The specsheet of the W01 is available as a PDF File 6 2 1 W01 417 ...

Страница 418: ...for UART1 TX1 RX1 SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Tutorials Tutorials on how to the W01 module can be found in the examples section of this documentation The following tutorials might be of specific interest for the W01 WiFi connection BLE 6 2 1 W01 418 ...

Страница 419: ...L01 Pinout The pinout of the L01 is available as a PDF File Specsheets The specsheet of the L01 is available as a PDF File 6 2 2 L01 419 ...

Страница 420: ... SPI CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Tutorials Tutorials on how to the L01 module can be found in the examples section of this documentation The following tutorials might be of specific interest for the L01 WiFi connection LoRaWAN node LoRaWAN nano gateway BLE 6 2 2 L01 420 ...

Страница 421: ...L04 Pinout The pinout of the L04 is available as a PDF File Specsheets The specsheet of the L04 is available as a PDF File 6 2 3 L04 421 ...

Страница 422: ...I CLK MOSI MISO and I2C SDA SCL are defaults and can be changed in Software Tutorials Tutorials on how to the L04 module can be found in the examples section of this documentation The following tutorials might be of specific interest for the L04 WiFi connection LoRaWAN node LoRaWAN nano gateway Sigfox BLE 6 2 3 L04 422 ...

Страница 423: ...G01 Pinout The pinout of the G01 is available as a PDF File Specsheets The specsheet of the G01 is available as a PDF File 6 2 4 G01 423 ...

Страница 424: ...efaults and can be changed in Software AT Commands The AT commands for the Sequans Monarch modem on the G01 are available in a PDF file Tutorials Tutorials on how to the G01 module can be found in the examples section of this documentation The following tutorials might be of specific interest for the G01 WiFi connection LTE CAT M1 NB IoT BLE 6 2 4 G01 424 ...

Страница 425: ... antenna connection For the G01 or L04 please use the Universal OEM Baseboard Reference Features Suits both L01 or W01 OEM Modules U FL connector for the L01 s LoRa output On board 2 4GHz antenna for WiFi and Bluetooth with the ability to switch to a external antenna via a U FL connector WS2812B RGB LED 3 5 5 5 Input switch mode DC DC regulator with low current draw during deep sleep Reset button ...

Страница 426: ... The schematic of the L01 baseboard reference is available as a PDF File Altium Project and Gerber Files The Altium Project and Gerber files are also available as a ZIP File 6 2 5 L01 OEM Baseboard Reference 426 ...

Страница 427: ...6 2 5 L01 OEM Baseboard Reference 427 ...

Страница 428: ...nce board does not contain the necessary SIM slot Features Suits all OEM modules L01 L04 W01 G01 On board 2 4GHz antenna for WiFi and Bluetooth with the ability to switch to a external antenna via a U FL connector 3 U FL connectors for all the outputs available on the OEM modules WS2812B RGB LED 3 5 5 5 Input switch mode DC DC regulator with low current draw during deep sleep Reset button Layout T...

Страница 429: ...e schematic of the OEM baseboard reference is available as a PDF File Altium Project and Gerber Files The Altium Project and Gerber files are also available as a ZIP File 6 2 6 Universal OEM Baseboard Reference 429 ...

Страница 430: ...6 2 6 Universal OEM Baseboard Reference 430 ...

Страница 431: ...oards and Shields This section contains all of the datasheets for the Pycom Expansion Boards and Shields This includes the Expansion Board Pytrack Pysense and Deep Sleep Shield 6 3 Expansion Boards and Shields 431 ...

Страница 432: ...sion Board is available as a PDF File Be gentle when plugging unplugging from the USB connector Whilst the USB connector is soldered and is relatively strong if it breaks off it can be very difficult to fix Battery Charger 6 3 1 Expansion Board 3 0 432 ...

Страница 433: ...rrent to 100mA Specsheets The specsheet of the Expansion Board is available as a PDF File Differences between v2 0 and v3 0 The FTDI chip as been replaced with a custom programmed PIC like on the Pysense Pytrack Pyscan boards This allows our firmware update tool to automatically put the module into bootloader mode Added a Safe boot button to enter safe boot easier This button connects P12 to 3 3v ...

Страница 434: ... Pytrack is available as a PDF File Battery Charger The board features a single cell Li Ion Li Po charger When the board is being powered via the micro USB connector it will charge the battery if connected Specsheets 6 3 2 Pytrack 434 ...

Страница 435: ...The specsheet of the Pytrack is available as a PDF File 6 3 2 Pytrack 435 ...

Страница 436: ... Pysense is available as a PDF File Battery Charger The board features a single cell Li Ion Li Po charger When the board is being powered via the micro USB connector it will charge the battery if connected Specsheets 6 3 3 Pysense 436 ...

Страница 437: ...The specsheet of the Pysense is available as a PDF File 6 3 3 Pysense 437 ...

Страница 438: ...file via FTP due to current limitations of Pymakr that will be fixed shortly Libraries for the rest of the components will be added soon Pyscan components Accelerometer ST LIS2HH12 Ambient light sensor Lite on LTR 329ALS 01 RFID NFC reader NXP MFRC63002HN 151 Driver The Windows 7 driver for Pyscan is located in https docs pycom io chapter pytrackpysense installation drivers html For other Operatin...

Страница 439: ... features a single cell Li Ion Li Po charger When the board is being powered via the micro USB connector it will charge the battery if connected Specsheets The specsheet of the Pyscan is available as a PDF File 6 3 4 Pyscan 439 ...

Страница 440: ...Expansion Board 2 0 Pinout The pinout of the Expansion Board is available as a PDF File 6 3 5 Expansion Board 2 0 440 ...

Страница 441: ...gle cell Li Ion Li Po charger When the board is being powered via the micro USB connector the Expansion Board will charge the battery if connected When the CHG jumper is present the battery will be charged at 450mA If this value is too high for your application removing the jumper lowers the charge current to 100mA Specsheets The specsheet of the Expansion Board is available as a PDF File 6 3 5 Ex...

Страница 442: ...leep Shield is available as a PDF File To correctly connect a WiPy 2 0 LoPy or SiPy to the Deep Sleep Shield align the white triangle on the Shield with the LED of the Pycom Device Once the Pycom Device is seated onto the Deep Sleep Shield this can then be connected to the Expansion Board 6 3 6 Deep Sleep Shield 442 ...

Страница 443: ...6 3 6 Deep Sleep Shield 443 ...

Страница 444: ...ke_status print wake_s if wake_s wake deepsleep PIN_WAKE print Pin wake up elif wake_s wake deepsleep TIMER_WAKE print Timer wake up else deepsleep POWER_ON_WAKE print Power ON reset ds enable_pullups P17 can also do ds enable_pullups P17 P18 ds enable_wake_on_fall P17 can also do ds enable_wake_on_fall P17 P18 ds go_to_sleep 60 go to sleep for 60 seconds DeepSleep The Deep Sleep Shield allows for...

Страница 445: ... trigger on a rising voltage For example if an external rising voltage triggers occurs wake the Pycom device from Deep Sleep pins may be passed into the method as a list i e P17 P18 deepsleep disable_wake_on_raise pins This method allows for disabling pull up pins that trigger on a rising voltage pins may be passed into the method as a list i e P17 P18 deepsleep enable_wake_on_fall pins This metho...

Страница 446: ... for a period of seconds or until an external interrupt has triggered see set_pullups deepsleep hw_reset This method resets the PIC controller and resets it to the state previous to the pins min voltage being set 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 Pycom Libraries GitH...

Страница 447: ...rnal battery should use a female adapter in order to connect and power the expansion board The polarity of the battery should be checked before being plugged into the expansion board the cables may require swapping The GPIO pins of the modules are NOT 5V tolerant connecting them to voltages higher than 3 3V might cause irreparable damage to the device Static electricity can damage components on th...

Страница 448: ...Development Modules Datasheets 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 1 Development Modules 448 ...

Страница 449: ...OEM Module Datasheets 7 2 1 W01 7 2 2 L01 7 2 3 L04 7 2 4 G01 7 2 OEM Modules 449 ...

Страница 450: ...Expansion Board and Shield Datasheets 7 3 1 Expansion Board 3 0 7 3 2 Pytrack 7 3 3 Pysense 7 3 4 Expansion Board 2 0 7 3 Expansion Boards and Shields 450 ...

Страница 451: ... you Data Visualisation Pybytes dashboard is customisable allowing you to freely set up key performance indicators and time series data from all your sensors Intelligent notifications Keep track of your device s status battery level data streaming and measurements with pre defined alarms Receive notifications via email or SMS Terminal Execute commands to gather accurate information from your devic...

Страница 452: ...Visualise data from your device 8 1 Introduction 452 ...

Страница 453: ... this link 2 Enter your full name email address and a password to your account 3 Confirm the verification message sent to your email address 4 Click on the link and complete your login Go Invent Now it s time to explore Pybytes You can start by connecting your Pycom board to Pybytes Check here 8 2 Getting Started 453 ...

Страница 454: ...s In this section we will explain to you how to add a device to Pybytes Step 1 Add device wizard In Pybytes go to Devices Page 1 Click on Add Device 2 Select your device e g WiPy LoPy SiPy etc 8 3 Add a device to Pybytes 454 ...

Страница 455: ...3 Select your shield e g PySense PyTrack PyScan or other 4 Select your network option 8 3 Add a device to Pybytes 455 ...

Страница 456: ...twork credentials SSID and password for your device Step 2 Connect your device to Pybytes At the end of the Add Device wizard Pybytes will give you two options for you to connect your device to Pybytes 8 3 Add a device to Pybytes 456 ...

Страница 457: ...NNECT YOUR DEVICE BY FLASHING PYBYTES LIBRARY From firmware 1 16 x onwards all Pycom devices come with Pybytes library build in frozen folder That means that you can choose between adding your device quickly with the firmware updater or you can flash Pybytes library manually 8 3 Add a device to Pybytes 457 ...

Страница 458: ... Pybytes quickly using the Firmware Updater In case you want to extend Pybytes library you can flash Pybytes library manually Click here for more information Step 1 Download the firmware updater At the last step of the Add Device process 1 Download the firmware updater for your operating system 8 3 1 Connect to Pybytes Quick Add 458 ...

Страница 459: ...2 Copy the device token Step 2 Firmware updater Install the Firmware updater on your computer 1 Start the Firmware updater 8 3 1 Connect to Pybytes Quick Add 459 ...

Страница 460: ...serial port Make sure your device is connected to your computer 3 Mark the options Erase flash file system and Force update Pybytes registration 4 Paste your device token from Pybytes 8 3 1 Connect to Pybytes Quick Add 460 ...

Страница 461: ...5 The firmware updater will update the device s firmware 8 3 1 Connect to Pybytes Quick Add 461 ...

Страница 462: ...Next step Set up your device s dashboard Now it s time to display data from your device into Pybytes dashboard You can check more about it here 8 3 1 Connect to Pybytes Quick Add 462 ...

Страница 463: ...re 1 16 x onwards all Pycom devices come with Pybytes library build in frozen folder That means that you can add your device quickly without the need of flashing Pybytes library manually Click here for more information Step 1 Download your Pybytes Library At the last step of the Add Device process 1 Click on download Pybytes library 8 3 2 Connect to Pybytes Flash Pybytes library manually 463 ...

Страница 464: ...sh your device with Pymakr In case you haven t installed Pymakr plugin follow these instructions 1 Connect your device to your computer with USB cable 2 Extract download Pybytes library and open extracted folder with Atom 3 Get your device serial port in Pymakr plugin click on More get serial ports 4 Paste your device s serial port to pymakr conf file 8 3 2 Connect to Pybytes Flash Pybytes library...

Страница 465: ...ot mode 7 Upload code to your device by clicking on Upload button in Pymakr After all Pybytes library files are uploaded to device device will restart and will connect to Pybytes Pybytes library is written to flash folder and will take precedence over build in firmware libraries in frozen folder Next step Set up your device s dashboard Now it s time to display data from your device into Pybytes da...

Страница 466: ...tes In case you haven t check how to add your device here After your done with that you can proceed to the next example Step 1 Set up your application main py The first step is to have an application running on your device The application in this example sends data from a vector every 10 seconds to Pybytes 1 Open the main py file on Pymakr 2 Insert the following code on your main py 8 4 Visualise ...

Страница 467: ...x inc idx sensors_data sleep 10 Start your thread _thread start_new_thread send_env_data 1 Upload the code into your device Now your device is sending data to Pybytes In this code we re calling the function pybytes send_virtual_pin_value persistent pin value to communicate with Pybytes This function is part of the Pybytes library and it has three arguments persistent pin and value persistent denot...

Страница 468: ...2 On your device s page click on Data tab 3 Click on the Define New Signal button 8 4 Visualise data from your device 468 ...

Страница 469: ...4 Define the new signal by entering a number a name a data type and a unit Finally click on the button Define 5 Your signal was added 8 4 Visualise data from your device 469 ...

Страница 470: ...pybytes send_virtual_pin_value function call inside your main py code In this example we defined pin 1 The datatype also has to match the variable used as argument on pybytes send_virtual_pin_value function call inside your main py code In this example our variable is a floating number therefore we defined as a Float32 Step 3 Add a widget for the signal 1 Click on the signal card 8 4 Visualise dat...

Страница 471: ...2 Click on the button Create a new display 3 Select the type of visualisation e g Bar chart or Line chart 8 4 Visualise data from your device 471 ...

Страница 472: ...parameters of your widget at Settings After click on the button Create 5 Your widget was created Now add your widget to your device s dashboard Click on the button Edit on your widget 8 4 Visualise data from your device 472 ...

Страница 473: ...6 Mark the checkbox Display on Dashboard at Settings Finally click on the button Save 7 Click on the tab Dashboard Your widget was successfully added there 8 4 Visualise data from your device 473 ...

Страница 474: ...ll enter the edit mode and allow you to resize and reposition its widgets 2 Resize a widget by clicking on the triangle icon at the bottom right corner of the widget and drag the cursor over the grid After click on the button Save to save this action 8 4 Visualise data from your device 474 ...

Страница 475: ...ping it over the grid After click on the button Save to save this action Done Now you ve learned how to set up your device s dashboard to display data Also you can add more widgets to other pins of your device 8 4 Visualise data from your device 475 ...

Страница 476: ...8 4 Visualise data from your device 476 ...

Страница 477: ...of understanding However there may be some unusual features for those not used to Python documentation or that are new to the MicroPython Language This section of the documentation aims to provide clarity for any of the design specifics that might be confusing for those new to Python and this style of documentation 9 1 Introduction 477 ...

Страница 478: ...the arguments as seen in the examples docs refer to the default values that are passed into the constructor if nothing is provided i2c init mode baudrate 100000 pins SDA SCL An example of how this method might be called i2c init I2C MASTER pins P12 P11 It can be seen that a value for baudrate was not passed into the method and thus MicroPython will assume a default value of 100000 Also the first a...

Страница 479: ...in pin P12 Value The documentation may refer to a method that takes an argument listed by name but does allow for a keyword to be passed For example the pycom class contains a method rgbled This lists that the method accepts a value for color however this may not be specified by keyword only value This is intentional as the value being passed is the only argument valid for this method pycom rgbled...

Страница 480: ...specific values from that library s class These might be used when constructing an object from that class or when utilising a method from within that class These are generally listed by the library name followed by the specific value See the example below I2C MASTER Be aware that you can only reference these constants upon importing and constructing a object from a library 9 2 Syntax 480 ...

Страница 481: ...t might display this behaviour Basic Arithmetic 1 1 REPL will print out 2 to console 1 1 Script will not return anything the console print 1 1 Both the REPL and a script will return 2 to the console Calling Methods import ubinascii ubinascii hexlify b 12345 REPL will print out b 3132333435 to the console ubinascii hexlify b 12345 Script will not return any the console In order to use these functio...

Страница 482: ... reset button before beginning You can obtain previous firmware versions here WiPy LoPy SiPy GPy FiPy LoPy4 Note Prior to version 1 16 0 b1 the firmware for modules with LoRa functionality was frequency specific From 1 16 0 b1 and onward the firmware is region agnostic and this can either be set programatically or via the config block see here GUI As of version 1 12 0 b0 of the firmware update too...

Страница 483: ...ll behave just like a regular update but using the local file instead of downloading the latest Command line You can also use the CLI version of the update tool to downgrade your device Will need to get a tar or tar gz archive of the firmware you wish to upload to the board Then run the following commands pycom fwtool cli v p PORT flash t path to firmware archive tar gz 10 1 Firmware Downgrade 483...

Страница 484: ...ware Update macOS In order to get access to the CLI tool on macOS you will need to right click on the Mac version of the updater tool and click Show Package Contents then navigate to Contents Resources here you will find the pycom fwtool cli Linux In the Ubuntu 14 04 LTS and newer version of the updater tool pycom fwtool cli is installed in usr local bin In the Generic Linux package the tool is ex...

Страница 485: ...lash memory wifi Get Set default WIFI parameters pybytes Read Write pybytes configuration cb Read Write config block nvs Read Write non volatile storage ota Read Write ota block lpwan Get Set LPWAN parameters EU868 US915 AS923 AU915 erase_fs Erase flash file system area erase_all Erase entire flash optional arguments h help show this help message and exit v verbose show verbose output from esptool...

Страница 486: ... environ ment variable ESPPORT s speed specifies the serial speed to be used Can also be set via enviro nment variable ESPBAUD c continuation continue previous connection in FTDI mode This allows running multiple commands sequentially without having to reset the module This option is ign ored in PIC mode as the module can be reset via the serial connection x noexit This will prevent the PIC from l...

Страница 487: ...essary Special note for Expansion Board 2 0 You will need to have a jumper wire connected between G23 and GND to use any of the commands below You will also need to press the reset button either before running each command or at least before running the first command To avoid having to press the reset button again after each command you can use the c continuation option The first command connectin...

Страница 488: ...etails usage pycom fwtool cli p PORT sigfox h optional arguments h help show this help message and exit exit If a Pysense Pytrack Expansion 3 has previously been left in firmware update mode by using the x option this command can be used to exit the firmware update mode usage pycom fwtool cli p PORT exit h optional arguments h help show this help message and exit flash Writes firmware image to fla...

Страница 489: ... file FILE name of the binary file default wmac part bin r restore restore partition from binary file b backup backup partition to binary file default write Write to a specific location in flash memory usage pycom fwtool cli p PORT write h a ADDRESS contents CONTENTS optional arguments h help show this help message and exit a ADDRESS address ADDRESS address to write to contents CONTENTS contents o...

Страница 490: ...s Pybytes firmware 1 17 5 b6 or higher and Firmware updater 1 14 3 cb Read Write config block LPMAC Sigfox PAC ID etc You can find the structure of this block here usage pycom fwtool cli p PORT cb h f FILE b r optional arguments h help show this help message and exit f FILE file FILE name of the backup file b backup backup cb partition to file r restore restore cb partition from file If neither b ...

Страница 491: ...te ota block this contains data relating to OTA updates such as the hash of the OTA firmware usage pycom fwtool cli ota h f FILE b r optional arguments h help show this help message and exit f FILE file FILE name of the backup file b backup backup cb partition to file r restore restore cb partition from file If neither b nor r is provided the command will default to backup If no file name is provi...

Страница 492: ... system area This is useful if some code running on the device is preventing access to the REPL usage pycom fwtool cli p PORT erase_fs h optional arguments h help show this help message and exit erase_all Erase entire flash only use this if you are sure you know what you are doing This will remove your devices lpwan mac addresses etc usage pycom fwtool cli erase_all h optional arguments h help sho...

Страница 493: ... here Once you have complete this you will need to open a terminal in the esp32 folder of the firmware source code repo Next you will need keys for Flash Encryption and Secure Boot they can be generated randomly with the following commands python IDF_PATH components esptool_py esptool espsecure py generate_flash_encrypt ion_key flash_encryption_key bin python IDF_PATH components esptool_py esptool...

Страница 494: ...rt dev ttyUSB0 bur n_efuse FLASH_CRYPT_CONFIG 0x0F Enabling Secure Boot mechanism python IDF_PATH components esptool_py esptool espefuse py port dev ttyUSB0 bur n_efuse ABS_DONE_0 If the keys are not written in efuse before flashing the bootloader then random keys will be generated by the ESP32 they can never be read nor re written so bootloader can never be updated Even more the application can b...

Страница 495: ...h_freq 80m flash_size detect 0x0 build GPY release bootloader bootloader r eflash digest bin_enc 0x8000 build GPY release lib partitions bin_enc 0x10000 build GP Y release gpy bin_enc_0x10000 OTA update The OTA should be done using the pre encrypted application image Because the encryption is done based on the physical flash address there are 2 application binaries generated gpy bin_enc_0x10000 wh...

Страница 496: ... all copies or substantial portions of the Software THE SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND EXPRESS OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM DAMAGES OR OTHER LIABILITY WHETHER IN AN ACTION OF CONTRACT TORT OR OTHERWISE ...

Отзывы: