Digi MicroPython Programming Guide

Digi MicroPython
Programming Guide
Revision history—90002219
Revision Date Description
S February
2020
U August
2020
V December
2020
W February
2021
Added the iBeacon samples. Added sms_callback(), cellular.shutdown, signal(), ucryptolib, machine.WDT(), and relay.receive(my_callback).
Added xbee_connect(), updated Install the certificates.
Added modem_status, AT commands that do not work in
MicroPython, delete_bondings(), passkey_enter(), passkey_confirm (), secure(), io_callbacks(), and receive_callback(rx_callback). Added
the security argument to config(). Noted Digi modified slicing.
Added Idle device from MicroPython and apin.read_u16(). Updated Initiate sleep from MicroPython for the non-cellular devices. Updated Test the connection. Removed PyCharm section.
Added Recover an XBee device.
Trademarks and copyright
Digi, Digi International, and the Digi logo are trademarks or registered trademarks in the United States and other countries worldwide. All other trademarks mentioned in this document are the property of their respective owners.
© 2021 Digi International Inc. All rights reserved.
Disclaimers
Information in this document is subject to change without notice and does not represent a commitment on the part of Digi International. Digi provides this document “as is,” without warranty of any kind, expressed or implied, including, but not limited to, the implied warranties of fitness or merchantability for a particular purpose. Digi may make improvements and/or changes in this manual or in the product(s) and/or the program(s) described in this manual at any time.
Warranty
To view product warranty information, go to the following website:
www.digi.com/howtobuy/terms
Customer support
Gather support information: Before contacting Digi technical support for help, gather the following
information:
Product name and model
Product serial number (s)
Digi MicroPython Programming Guide
2
Firmware version
Operating system/browser (if applicable)
Logs (from time of reported issue)
Trace (if possible)
Description of issue
Steps to reproduce
Contact Digi technical support: Digi offers multiple technical support plans and service packages. Contact us at +1 952.912.3444 or visit us at www.digi.com/support.
Feedback
To provide feedback on this document, email your comments to
Include the document title and part number (Digi MicroPython Programming Guide, 90002219 U) in the subject line of your email.
techcomm@digi.com
Digi MicroPython Programming Guide
3
Contents
Digi MicroPython Programming Guide
Reference material 12
Which features apply to my device?
Use MicroPython
Access the MicroPython environment 15 Enter MicroPython code 15
Direct entry 15 Exit MicroPython 15 Display tools 15 Coding tips 15 Recover an XBee device 16
MicroPython syntax
Colons 18
After conditional statements and loop statements 18 Indentations 18
FORloop with one statement indented 18
FOR loop with two statements indented 19 Functions 19
Function with arguments 19
Errors and exceptions
Syntax error 22
Example 22 Name error 22
Referencing a name that was not created 22
Referencing a name from one function that was created in a different function 22 OSError 23 Socket errors 23
ENOTCONN: Time out error 23
ENFILE: No sockets are available 23
ENXIO: No such device or address 23
Digi MicroPython Programming Guide
4
Keyboard shortcuts
Keyboard shortcuts 25 Select a previously typed statement 25
Differences between MicroPython and other programming languages
Memory management 27 Variable types 27 Syntax 27
Curly braces and indentation 28
Semicolons 29
Increment operator 29
Logical operators 30
Develop applications on an XBee device
Space allocated to MicroPython 32 Code storage 32
Built-in modules embedded in XBee firmware (device flash) 32
Source code in .py files (file system) 32
Parsed and compiled code in .mpy files (file system) 32
Executable code on MicroPython heap (device RAM) 32
Compiled modules relocated from file system to device flash 33 How to organize your code 33 Run code at startup 33 Monitor memory usage 33
The gc module 33
The micropython module 34 Efficient coding 36 Application evolution 37
One-liners in the REPL 37
Short blocks in paste mode 37
Flash upload mode 37
Modules stored as .py files 37
Compiled modules stored as .mpy files 38
Compiled modules via Flash upload mode 38
Compiled modules embedded in device flash 39 Digi modified slicing for bytes and strings operations 39
Power management in MicroPython
Prevent sleep from MicroPython 41
XBee Cellular Modem: 41
XBee 3 Zigbee RF Module, XBee 3 802.15.4 RF Module, XBee 3 DigiMesh RF Module
description: 41 Initiate sleep from MicroPython 42
XBee Cellular Modem: 42
XBee 3 Zigbee RF Module, XBee 3 802.15.4 RF Module, XBee 3 DigiMesh RF Module: 42 Sleeping with AT commands 43 Idle a device from MicroPython 43
Enter and exit the idle state 43
Poll for data while the device is idle 44
Digi MicroPython Programming Guide
5
Access the primary UART
How to use the primary UART 47
sys.stdin limitations 47 Example: read bytes from the UART 47 Example: read the first 15 bytes from the UART 48
REPL (Read-Evaluate-Print Loop) examples
Ctrl+A: Enter raw REPLmode 50 Ctrl+B: Print the MicroPython banner 50
Print the banner 51
Print the banner and verify that the memory was not wiped 51 Ctrl+C: Regain control of the terminal 52 Ctrl+D: Reboot the MicroPython REPL 52 Ctrl+E: Enter paste mode 53
Paste one line of code 53
Paste a code segment 54 Ctrl+F: Upload code to flash 54
Load code to flash memory 55
Erase the code stored in flash memory 55 Flash memory and automatic code execution 56
Run stored code at start-up to flash LEDs 56
Disable code from running at start up 57
Ctrl+R: Run code in flash 58
Enable code to run at start-up 58 Perform a soft-reset or reboot 59
Access file system in MicroPython
Modify file system contents 61
uos.chdir(dir) 61
uos.getcwd() 61
uos.ilistdir([dir]) 61
uos.listdir([dir]) 61
uos.mkdir(dir) 61
uos.remove(file) 61
uos.rmdir(dir) 61
uos.rename(old_path, new_path) 61
uos.replace(old_path, new_path) 62
uos.sync() 62
uos.compile(source_file, mpy_file=None) 62
uos.format() 62
uos.hash([secure_file]) 62 Access data in files 63 File object methods 63
read(size=-1) 63
readinto(b) 64
readline(size=-1) 64
readlines() 64
write(b) 64
seek(offset, whence=0) 64
tell() 64
flush() 64
Digi MicroPython Programming Guide
6
close() 64 Import modules from file system 64 Reload a module 65 Compiled MicroPython files 65
Send and receive User Data Relay frames
Constants 67
Interfaces (always defined) 67
Limits 67 Methods 67
relay.receive() 67
relay.send(dest, data) 67
Exceptions 67
relay.callback(my_callback) 67 Examples 68
MicroPython libraries on GitHub
MicroPython modules
XBee-specific functions 71 Standard modules and functions 71 Discover available modules 72
Machine module
Reset-cause 74
Constants 74 Random numbers 74 Unique identifier 74 Class PWM (pulse width modulation) 74 Class ADC: analog to digital conversion 75
Constructors 75
Methods 76
Sample program 76 Class I2C: two-wire serial protocol 77
Constructors 77
General methods 78
Standard bus operations methods 78
Memory operations methods 78
Sample programs 79 Class Pin 82 Class UART 82
Test the UART interface 82
Use the UARTclass 83
Constructors 83
Methods 84
Constants 84 Class WDT: watchdog timer 85 Access the XBee device's I/O pins 85 Use the Pin() constructor 87 Use mode() to configure a pin 87
Digi MicroPython Programming Guide
7
Pin.DISABLED 87
Pin.IN 88
Pin.OUT 88
Pin.ALT 88
Pin.ANALOG 89
Pin.OPEN_DRAIN and Pin.ALT_OPEN_DRAIN 89 Use pull() to configure an internal pull up/down resistor 89
digi.ble module
Feature support 91 active() 91 config() 92
Query a value 92
Update configuration values 92 disconnect_code() 93 gap_connect() 93
<addr_type> 93
<address> 93
<timeout_ms> 94
<interval_us>, <window_us> 94
<onclose> 94
Return value 94 gap_connection methods 94
gattc_services() 94
gattc_characteristics() 95
gattc_descriptors() 96
gattc_read_characteristic() 96
gattc_configure() 96
gattc_read_descriptor() 97
gattc_write_characteristic() 97
gattc_write_descriptor() 98
addr() 98
close() 98
config() 98
isconnected() 100
secure() 100
io_callbacks() 100
delete_bondings() 101
passkey_enter() 101
passkey_confirm() 101 UUID() 101
<value> 101
Return value 101 gap_scan() 102
<duration_ms> 102
<interval_us>, <window_us> 102
<oldest> 102
Return value 102 gap_scan methods 102
get() 102
any() 103
stop() 103
stopped() 103 gap_scan advertisement format 103
Digi MicroPython Programming Guide
8
Use gap_scan as an iterator 103 Use gap_scan as a context manager 104 gap_advertise() 104
<interval_us> 104
<adv_data> 104
Return value 105 xbee_connect() 105
<gap_connection> 105
<receive> 105
<password> 106
<timeout> 106
Return value 106 xbee_connection methods 106 digi.ble samples 106
Generic gap advertising and gap scanning samples 106
Eddystone Beaconing samples 106
iBeacon samples 106 Troubleshooting 107
Fewer advertisements than expected when usinggap_scan 107
Cellular network configuration module
Configure a specific network interface 109 class Cellular 109
Constructors 110
Cellular power and airplane mode method 110
Verify cellular network connection method 110
Cellular connection configuration method 110
Send an SMS message method 110
Receive an SMS message method 111
Register an SMS Receive Callback method 111
Cellular shutdown method 111
RSRP/RSRQ reporting in MicroPython 112
XBee module
AT commands that do not work in MicroPython 114 class XBee on XBee Cellular Modem 114
Constructors 114
Methods 114 XBee MicroPython module on the XBee 3 RFModules 115
Functions 115
atcmd() 115
discover() 115
receive() 117
receive_callback(rx_callback) 118
transmit() 118
modem_status 119
digi.cloud module
Create and upload data points 122 class DataPoints 122
Digi MicroPython Programming Guide
9
Constructor 122
Optional parameter 122
Add a data point method 122
Upload data to Digi Remote Manager method 123
Check the status of a DataPoints object 124
The life-cycle of a DataPoints object 124
Delete a DataPoints object 124 Receive a Data Service Device Request 125 class device_request 125
Use the read(size=-1) method 126
Use the readinto(b) method 126
Use the write(b) method 126
Use the close() method 126 Use the API Explorer to send Device Requests 126
The ussl module
ussl on the XBee Cellular Modem 129 Syntax 129
Usage 129
Use AWS IoT from MicroPython
Add an XBee Cellular Modem as an AWS IoT device 131 Create a policy for access control 131 Create a Thing 132 Install the certificates 134 Test the connection 135 Publish to a topic 137 Confirm published data 138 Subscribe to updates from AWS 138
Time module example:get the current time
Retrieve the local time 141 Retrieve time with a loop 141 Delay and timing quick reference 142
Cellular network connection examples
Check the network connection 144 Check network connection with a loop 144 Check network connection and print connection parameters 145
Socket examples
Sockets 148 Basic socket operations: sending and receiving data, and closing the network connection 148
Basic data exchange code sample 148
Response header lines 149 Specialized receiving: send received data to a specific memory location 150 DNS lookup 151
Digi MicroPython Programming Guide
10
DNS lookup code output 152 Set the timeout value and blocking/non-blocking mode 152 Send an HTTPrequest and dump the response 154 Socket errors 154
ENOTCONN: Time out error 154
ENFILE: No sockets are available 155
ENXIO: No such device or address 155 Unsupported methods 155
I/O pin examples
Change I/O pins 157 Print a list of pins 157 Change output pin values:turn LEDs on and off 158 Poll input pin values 158 Check the configuration of a pin 159 Check the pull-up mode of a pin 160 Measure voltage on the pin (Analog to Digital Converter) 162
SMS examples
Send an SMS message 165 Send an SMS message to a valid phone number 165 Check network connection and send an SMS message 165 Send to an invalid phone number 166 Receive an SMS message 166
Sample code 167 Receive an SMS message using a callback 168
XBee device examples
Print the temperature of the XBee Cellular Modem 170 Print the temperature of the XBee 3 Zigbee RF Module 170 Print a list of AT commands 171 xbee.discover() examples 173
Handle responses as they are received 173
Gather all responses into a list 173 xbee.transmit() examples 174
xbee.transmit() using constants 174
xbee.transmit() using byte string 174
Digi MicroPython Programming Guide
11

Digi MicroPython Programming Guide

This guide introduces the MicroPython programming language by showing how to create and run a simple MicroPython program. It includes sample code to show how to use MicroPython to perform actions on a Digi device, particularly those devices with Digi-specific behavior. It also includes reference material that shows how MicroPython coding can be used with Digi devices.
You can code MicroPython to transform cryptic readings into useful data, filter out excess transmissions, directly employ modern sensors and actuators, and use operational logic to glue inputs and outputs together in an intelligent way.
The XBee Cellular Modem has MicroPython running on the device itself. You can access a MicroPython prompt from the XBee Cellular Modem when you install it in an appropriate development board (XBDB or XBIB), and connect it to a computer via a USB cable.

Reference material

MicroPython is an open-source programming language based on the Python 3 standard library. MicroPython is optimized to run on a microcontroller, cellular modem, or embedded system.
Refer to the Get started with MicroPython section of the appropriate user guide for information on how to enter the MicroPython environment and several simple examples to get you started:
n Digi XBee PyCharm IDE Plugin User Guide
n Digi XBee Cellular Embedded Modem User Guide
n Digi XBee Cellular 3G Global Embedded Modem User Guide
n Digi XBee 3 Cellular LTE Cat 1 Smart Modem User Guide
n Digi XBee 3 Cellular LTE-M Global Smart Modem User Guide
n XBee 3 802.15.4 RF Module User Guide
n XBee 3 DigiMesh RFModule User Guide
n XBee 3 Zigbee RF Module User Guide
This programming guide assumes basic programming knowledge. For help with programming knowledge, you can refer to the following sites for Python and MicroPython:
n MicroPython: micropython.org
n MicroPython documentation: docs.micropython.org
n MicroPython Wiki: wiki.micropython.org
n Python: python.org
Digi MicroPython Programming Guide
12

Which features apply to my device?

MicroPython features and errors differ depending on the device you use. Unless specified, information in this document applies to all devices. This table covers which features apply to specific products:
Feature XBee 3 Cellular XBee 3 Zigbee, DigiMesh, and 802.15.4
Digital I/O Yes Yes
I2C Yes Yes
Power management Yes Yes
Idle from MicroPython No Yes
Digi Remote Manager Yes
Secondary UART Yes No
Real-time clock Yes No
File system Yes Yes
File system - concurrent file writes Yes No
File system - rename Yes No
File system - Edit files after creation Yes No
1
No
File System - delete Yes No
File System - secure files Yes No
File System preserved across updates Yes No
1
Remote Manager features are only supported on XBee 3 Cellular devices, not XBee Cellular.
2
Files can be deleted, but doing so does not reclaim their space on the file system.
Digi MicroPython Programming Guide
2
13

Use MicroPython

Access the MicroPython environment 15 Enter MicroPython code 15 Exit MicroPython 15 Display tools 15 Coding tips 15 Recover an XBee device 16
Digi MicroPython Programming Guide
14
Use MicroPython Access the MicroPython environment

Access the MicroPython environment

To begin using MicroPython on the XBee device, open XCTU and enter MicroPython mode. See Use XCTU to enter the MicroPython environment in the appropriate user guide.

Enter MicroPython code

You can use different methods to enter MicroPython code into the MicroPython Terminal on the XBee device.
n Direct entry: Manually type code into the MicroPython Terminal.
n Paste mode: Use the REPL paste mode to paste copied code into the MicroPython Terminal for
immediate execution.
n Flash mode: Use the REPL flash mode to paste a block of code into the MicroPython Terminal
and store it in flash memory.
n Access file system in MicroPython: Upload code to the file system.

Direct entry

From a serial terminal, you can type code at the MicroPython REPL prompt. When you press Enter, the line of code runs and another MicroPython prompt appears. Manually typing in code is the simplest method.
Example
1. Access the MicroPython environment.
2. At the MicroPython >>> prompt, type print("This is a simple line of code") and then press
Enter. The phrase in quotes prints in the terminal: This is a simple line of code

Exit MicroPython

When you are done coding, exit MicroPython by closing the MicroPython terminal. Any code that has been executed will continue to run, even if the XBee device is set to Transparent or API mode.
For additional instructions, see the Exit MicroPython mode section in the appropriate user guide.

Display tools

MicroPython mode requires echo to be turned off in terminal emulation. Command mode does not echo your input back to you. In order to see what you are typing, use the appropriate display tool:
n MicroPython mode: For MicroPython coding, use the XCTU MicroPython Terminal or configure
your terminal emulator for "echo off."
n Command mode: For device configuration that is done in Command mode (initiated by sending
+++ to the device), use the XCTU Serial Console or configure your terminal emulator for "echo on."

Coding tips

For all XBee devices:
Digi MicroPython Programming Guide
15
Use MicroPython Recover an XBee device
n Use tabs instead of spaces when indenting lines of code to minimize source code byte count.
n Use the integer division operator (//) unless you need a floating point.
n MicroPython's struct_time does not include the tm_isdst element in the tuple.
For the XBee Cellular Modem:
n The XBee Cellular Modem supports the use of hostnames in socket.connect() calls, unlike
other MicroPython platforms that require an IP address obtained by doing a manual look-up using socket.getaddrinfo().
For the XBee 3 Zigbee RF Module:
n The Micropython time.time() function returns the number of seconds since the epoch. The
XBee 3 Zigbee RF Module does not have a realtime clock, so it does not support time.time(). To track elapsed time, use time.ticks_ms().
For XBee3 radio modules:
n The counter for the Micropython ticks_us() function will fall behind ticks_ms() by about 1 ms
every 10 seconds.
n If you need a high level of accuracy over a long period of time, use ticks_ms().

Recover an XBee device

If you are unable to communicate with an XBee device when a MicroPython script is running—for example, if your MicroPython code is changing settings such as ATBD to strange values—you can recover the XBee device by holding serial break—DIN line low—while the XBee is reset or powered up.
If serial break is held during reset/power-on, the XBee will enter Command mode at 9600 baud, and MicroPython will not execute until Command mode is exited.
While in Command mode you can then set ATPS to 0 to disable MicroPython autostart, for example. You can also query and set ATBD or other commands to assist in restoring communication with the XBee.
Note See Break control for related information.
Digi MicroPython Programming Guide
16

MicroPython syntax

Syntax refers to rules that must be followed when entering code into MicroPython. If you do not follow the syntax rules when coding, errors are generated, and the code may not run as expected or not run at all.
For information about coding errors, see Errors and exceptions.
The following sections describe coding syntax rules.
Colons 18 Indentations 18 Functions 19
Digi MicroPython Programming Guide
17
MicroPython syntax Colons

Colons

MicroPython requires a colon (:) after you entered the following statement types:
n Function name and the arguments that function accepts, if any
n Condition statement
n Loop statement
Defining a function
A function consists of the following:
n def keyword
n Function name
n Any arguments the function takes, inside a set of parentheses. The parentheses remain empty
if there are no passed arguments
n The function declaration must be followed by a colon
The code sample below is a basic function definition. Note that a colon is entered after the function name. This colon defines the following indented lines as part of the function. Indentation is equally important, and is discussed in Indentations.
def sample_function():

After conditional statements and loop statements

A colon is required after each conditional statement and loop statement. The code sample below shows how the colon is used for a conditional statement (if True:) and for a loop statement (for x in range(10):).
>if True:
for x in range(10):

Indentations

In MicroPython, an indentation tells the compiler which statements are members of a function, conditional execution block, or a loop. If a line is not indented, that line is not considered a part of the function, conditional execution block, or loop.
A function declaration, conditional execution block, or loop should be followed by a colon. All code after the colon that is meant to be part of that block must be indented. For more information about how colons are used in the code, see Colons.
print("I am a sample function!")
print("Condition is true!")
print("Current number: %d" % x)
FORloop with one statement indented
In this example, only one statement after the initial FORloop statement (which ends in a colon) is indented. When the loop is executed, only line 2 of the code is executed. When the loop completes, the code at line 3 executes.
Digi MicroPython Programming Guide
18
MicroPython syntax Functions
When this code executes, it prints "In the FORloop, iteration # <number>" 10 times, where <number> is 0 in the first loop of the code, and 9 at the last loop. Line 3 of the code runs one time, after the loop completes, printing the phrase "Current number: 9" one time.
for x in range(10):
print("In the FOR loop, iteration # %d" % x)
print("Current number: %d" % x)

FOR loop with two statements indented

In this example, both statements after the initial FORloop statement (which ends in a colon) are indented. When the loop is executed, both print statements are printed in each loop iteration.
As in the previous example, the code prints "In the FORloop, iteration # <number>", where <number> is 0 in the first loop of the code, and 9 at the last loop. This time, however, line 3 of the code is run in each loop iteration, and prints the phrase "Current number: number". Both phrases are printed 10 times, with the <number> starting at 0 and increasing by one on each loop.
for x in range(10):
print("In the FOR loop, iteration # %d" % x) print("Current number: %d" % x)

Functions

A function is an operation that performs an action and may return a value. A function consists of the following:
n def keyword. The def keyword is required, and is short for "define".
n Function name.
n Any arguments the function takes, defined by a set of parentheses. The parentheses remain
n The function statement must be followed by a colon. For more information, see Colons.
The code sample below is a basic function definition. Note that the colon is entered after the function name and parentheses. This colon defines that everything after that line that is indented is part of the function. Indentation is equally important, and is discussed in the Indentations section.

Function with arguments

This sample shows how to define a function and then how to call the function to perform an operation and return a value.
n Line 1: Define the function and define two arguments: x and y.
n Line 2: Define the variable that holds the sum of the arguments as sum_val.
n Line 3: Define a phrase that will be printed to the terminal including sum_val .
n Line 4: The function returns the value of its own variable sum_val. A returned value can be
n Line 6: Define the value of the variable global_sum to be the value returned by the function
empty if there are no passed arguments.
def example_function():
print("I am a function!")
used and stored outside of the function.
Digi MicroPython Programming Guide
19
MicroPython syntax Functions
defined in line 1: addition_function(3,4), which is equal to the returned variable sum_val.
n Line 7: Define that a phrase that includes global_sum is printed to the terminal.
def addition_function(x,y):
sum_val = x + y print("value of sum (x+y): %d" % sum_val) return sum_val
global_sum = addition_function(3,4) print("Value of global_sum: %d" % global_sum)
Note You can copy and paste code from the online version of the Digi MicroPython Programming Guide.
Use caution with the PDF version, as it may not maintain essential indentations.
Digi MicroPython Programming Guide
20

Errors and exceptions

If something goes wrong during compilation or during execution of code you have entered, you may get an error. The type of error that occurred and the line number that caused the error will print to the terminal. Errors can happen for many reasons, such as syntax errors, name errors (which generally means the variable or function you are referencing is not available), or other more specific errors.
Note Some exceptions have Error in their name and others have Exception.
Common types of errors include:
Syntax error 22 Name error 22 OSError 23 Socket errors 23
Digi MicroPython Programming Guide
21
Errors and exceptions Syntax error

Syntax error

A syntax error occurs when a MicroPython code statement has the wrong syntax.

Example

In this example, the syntax is incorrect. A colon is missing after the word "True".
if True print("Condition is true!")
When you press Enter to run the code it generates the following Exception describing the error (SyntaxError) and the execution path that led to it (line 1 of the code you entered).
Traceback (most recent call last):
File "<stdin>", line 1
SyntaxError: invalid syntax
The correct code syntax is:
if True: print("Condition is true!")

Name error

Aname error is generated when a name of an item, such as a variable or function, cannot be found. This can occur when:
n You typed the name into the code incorrectly.
n You are referencing a name that was never created.
n The name is defined, but is not in scope when you reference it. For example, if you defined the
name in function A, but are referencing the name in function B.

Referencing a name that was not created

In this example, the name deviation_factor was not created. If you reference this name in the code, a NameError occurs in line 4, as the code references the deviation_factor name, which was not created.
print("Assigning value to x...") x = 17 print("Adding deviation_factor to x...") x = x + deviation_factor

Referencing a name from one function that was created in a different function

In this example, a variable is created in the example_func. When you run the code, the NameError references line 8, where the code tries to print local_variable. The variable was created inside the function example_func, and the scope of that variable, meaning where it can be accessed, is in that function. The code references local_variable outside of that function.
def example_func():
print("Entering example function...") local_variable = "I'm a variable inside this function"
Digi MicroPython Programming Guide
22
Errors and exceptions OSError
print(local_variable)
example_func() print(local_variable)

OSError

MicroPython returns an OSError when a function returns a system-related error.
For example, if you try to send a message on a Zigbee network:
import xbee
xbee.transmit(xbee.ADDR_COORDINATOR, 'Hello!')
This code assumes that the device is associated to a network and able to send and receive data.
If the device is not associated with a network, it produces an OS error:
OSError: [Errno 7107] ENOTCONN.

Socket errors

Note This section only applies to the XBee Cellular Modem. See Which features apply to my device? for
a list of the supported features.
This following socket errors may occur.

ENOTCONN: Time out error

If a socket stays idle too long, it will time out and disconnect. Attempting to send data over a socket that has timed out produces the OSError ENOTCONN, meaning "Error, not connected." If this happens, perform another connect() call on the socket to be able to send data again.

ENFILE: No sockets are available

The socket.socket() or socket.connect() method returns an OSError (ENFILE) exception if no sockets are available. If you are already using all of the available sockets, this error may occur in the few seconds between calling socket.close() to close a socket, and when the socket is completely closed and returned to the socket pool.
You can use the following methods to close sockets and make more sockets available:
n Close abandoned sockets: Initiate garbage collection (gc.collect()) to close any abandoned
MicroPython sockets. For example, an abandoned socket could occur if a socket was created in a function but not returned. For information about the gc module, see the MicroPython
garbage collection documentation.
n Close all allocated sockets: Press Ctrl+D to perform a soft reset of the MicroPython REPL to
close all allocated sockets and return them to the socket pool.

ENXIO: No such device or address

OSError(ENXIO) is returned when DNS lookups fail from calling usocket.getaddrinfo().
Digi MicroPython Programming Guide
23

Keyboard shortcuts

This section includes keyboard shortcuts you can use to make coding with MicroPython easier.
Keyboard shortcuts 25 Select a previously typed statement 25
Digi MicroPython Programming Guide
24
Keyboard shortcuts Keyboard shortcuts

Keyboard shortcuts

XCTU version 6.3.6.2 and higher works when the REPL is enabled. The MicroPython Terminal tool allows you to communicate with the MicroPython stack of your device through the serial interface.
The MicroPython Terminal tool in XCTU supports the following control characters:
Ctrl+A: Enter raw REPLmode. This is like a permanent paste mode, except that characters are not
echoed back.
Ctrl+B: Print the MicroPython banner. Leave raw mode and return to the regular REPL (also known as
friendly REPL). Reprints the MicroPython banner followed by a REPLprompt.
Ctrl+C: Regain control of the terminal. Interrupt the currently running program.
Ctrl+D: Reboot the MicroPython REPL. Soft-reset MicroPython, clears the heap.
Ctrl+E: Enter paste mode. Does not auto-indent and compiles pasted code all at once before
execution. Uses a REPL prompt of ===. Use Ctrl-D to compile uploaded code, or Ctrl-C to abort.
Ctrl+F: Upload code to flash. Uses a REPL prompt of ^^^. Use Ctrl-D to compile uploaded code, or Ctrl-
C to abort.
Ctrl+R: Run code in flash. Run code compiled in flash.
Note If PS is set to 1, code in flash automatically runs once at startup. Use Ctrl-R to re-run it.

Select a previously typed statement

You can use the UP and DOWN arrows on the keyboard to display a previously typed statement at the current MicroPython prompt.
Note This shortcut does not work: (1) while in paste mode (Ctrl-E) or on any code entered while in
paste mode and (2) while in flash upload mode.
Arrow keys work to scroll back through previous commands, and to edit the current command. Some terminal emulators (like CoolTerm) might not work with scrollback.
1. Access the MicroPython environment.
2. At the MicroPython >>> prompt, type print("statement 1") and press Enter.
3. At the MicroPython >>> prompt, type print("statement 2") and press Enter.
4. At the MicroPython >>> prompt, type print("statement 3") and press Enter.
5. At the MicroPython >>> prompt, press the UParrow key on the keyboard. The most recently
typed statement displays at the prompt. In this example, the statement print("statement 3") displays.
6. You can press the UParrow key on the keyboard to display the next most recently type
statement, or press the DOWN arrow key on the keyboard to return the previously selected statement. Continue this process until the statement you want to use displays at the MicroPython >>> prompt. Use the Left and Right arrow keys and Backspace to make edits to the previous statement if desired.
7. Press Enter to execute the displayed statement.
Digi MicroPython Programming Guide
25

Differences between MicroPython and other programming languages

You may have experience coding in another language, such as C or Java. You should be aware of the coding differences between other languages and MicroPython.
Memory management 27 Variable types 27 Syntax 27
Digi MicroPython Programming Guide
26
Differences between MicroPython and other programming languages Memory management

Memory management

In C, memory has to be allocated by the user for a variable or object before it can be used.
For a variable in C, this is done by a declaration statement as shown in the code below. The first 2 lines create a floating-point (decimal-valued real number) type variable named salary and an integer named x. The last 2 lines assign values to each of those variables.
float salary; int x;
x = 9; salary = 3.0 + x;
In MicroPython, a variable does not need to be declared before it can be used. For example, the MicroPython code shown below does the same thing as the C code shown in the example above. Each line does multiple things: creates the variable (the name), assigns it a type based on the assigned value, determines the space it needs in memory and allocates that space, and then assigns the value to it.
Note You can copy and paste code from the online version of the Digi MicroPython Programming Guide.
Use caution with the PDF version, as it may not maintain essential indentations.
x = 9 salary = x + 3.0

Variable types

In C, variables are "statically typed", meaning they are a certain type when they are created, and the type does not change. This also means the variable can only hold data appropriate for the type.
In the C code sample shown below, an integer type variable named my_variable is created. An integer type variable can only hold integer values and the amount of memory allocated to this variable for storing its value is a fixed size- 4 bytes, limiting the range of values to -2,147,483,648 to 2,147,483,647 for a signed integer.
In MicroPython, variables are dynamically (or automatically) assigned a variable type when the user assigns a value to the variable. In the code shown below, the variable big_number is assigned an integer type, allocated the appropriate amount of memory, and the value stored after the user assigns a value to the variable.
big_number = 99999999999999999999
If a user changes the value of the variable to a text string, MicroPython stores the string and automatically changes the variable type to string.
int my_variable; my_variable = 32;
big_number = "This is a really big number!"

Syntax

Syntax refers to rules that you must follow when programming. The following sections explain the differences in syntax between MicroPython and other programming languages.
Digi MicroPython Programming Guide
27
Differences between MicroPython and other programming languages Syntax

Curly braces and indentation

In C, a function or conditional statement is enclosed by curly braces, as shown in the code sample below.
void action1(void) {
printf("Function action1\n");
}
void action2(void) {
printf("Function action2\n");
}
if condition {
action1(); } else {
action2(); }
In MicroPython, only a colon is required. Any statements that are part of the function must be indented. The C code sample shown above would be coded in MicroPython as shown below. After the function definitions and conditionals, the code to be executed is indented to make it a part of that block. Indentation is used in MicroPython to tell the compiler which lines are members of a certain structure.
def action1():
print("Function action1")
def action2():
print("Function action2")
if condition:
action1()
else:
action2()
In C, all of the instructions to be executed for the function some_function() are contained within the curly braces. Most programmers indent all the instructions within the function for readability, but this is not required for the code to work.
void some_function(void) {
int x;
x = 7;
x = x + 1;
printf("Incremented x!\n");
x = x + 2;
printf("Incremented x by 2!\n"); }
In MicroPython, indentation is required to tell the compiler what lines of code are to be executed for the function some_function(), as shown in the example below.
Digi MicroPython Programming Guide
28
Differences between MicroPython and other programming languages Syntax
def some_function():
x = 7 x = x + 1 print("Incremented x!") x = x + 2 print("Incremented x by 2!")
When nesting conditions and functions, C relies on curly braces, as shown in the example below. Each level of code is indented to make it more readable, but it is not required for the code to run.
void some_other_function(void) {
if (condition) {
do_something();
} }
In MicroPython, indentation is the only thing telling the compiler what instructions belong to what function or condition. The nested C code example shown above is coded in MicroPython in the example below:
def some_other_function():
if condition:
do_something()

Semicolons

Statements in C are followed by a semicolon, as shown in the example below.
int x; x = 7 + 3; action1();
In MicroPython, statements are ended by starting a new line. A special symbol or character is not needed.
x = 7 + 3 action1()

Increment operator

C and Java have an "increment" operator, which lets the user increase the value of a variable by 1. See the following excample:
int x; x = 1; x++; // x is now 2 x++; // x is now 3
MicroPython does not have an "increment" operator. To do the equivalent in MicroPython the variable would have to have 1 explicitly added to it, or use the += operator.
The += operator states that a variable equals itself plus a value. So, in the MicroPython code block below, line 3 is basically shorthand for line 2. They both do the same operation: set x equal to x plus 1.
x = 1 x = x + 1 # x is now 2 x += 1 # x is now 3
Digi MicroPython Programming Guide
29
Differences between MicroPython and other programming languages Syntax

Logical operators

In C, the logical operators AND, OR, and NOT are represented by &&, ||, and ! respectively. The C code block below shows the logical operators in use.
// if it's sunny out, AND NOT cold outside if (sunny_outside && !cold_outside) {
// if you have a towel AND an umbrella
if (have_towel && have_umbrella) {
// if you have a bike OR a car if (have_bike || have_car) {
// then you will go to the beach go_to_beach();
}
} }
In MicroPython, the operators for AND, OR, and NOT are simply and, or, and not, which is much more intuitive. The MicroPython code shown below has the same function as the C code shown above.
if sunny_outside and not cold_outside:
if have_towel and have_umbrella:
if have_bike or have_car:
go_to_beach()
Digi MicroPython Programming Guide
30
Loading...
+ 145 hidden pages