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.
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 material12
Which features apply to my device?
Use MicroPython
Access the MicroPython environment15
Enter MicroPython code15
Direct entry15
Exit MicroPython15
Display tools15
Coding tips15
Recover an XBee device16
MicroPython syntax
Colons18
After conditional statements and loop statements18
Indentations18
FORloop with one statement indented18
FOR loop with two statements indented19
Functions19
Function with arguments19
Errors and exceptions
Syntax error22
Example22
Name error22
Referencing a name that was not created22
Referencing a name from one function that was created in a different function22
OSError23
Socket errors23
ENOTCONN: Time out error23
ENFILE: No sockets are available23
ENXIO: No such device or address23
Digi MicroPython Programming Guide
4
Keyboard shortcuts
Keyboard shortcuts25
Select a previously typed statement25
Differences between MicroPython and other programming languages
Memory management27
Variable types27
Syntax27
Curly braces and indentation28
Semicolons29
Increment operator29
Logical operators30
Develop applications on an XBee device
Space allocated to MicroPython32
Code storage32
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 flash33
How to organize your code33
Run code at startup33
Monitor memory usage33
The gc module33
The micropython module34
Efficient coding36
Application evolution37
One-liners in the REPL37
Short blocks in paste mode37
Flash upload mode37
Modules stored as .py files37
Compiled modules stored as .mpy files38
Compiled modules via Flash upload mode38
Compiled modules embedded in device flash39
Digi modified slicing for bytes and strings operations39
XBee 3 Zigbee RF Module, XBee 3 802.15.4 RF Module, XBee 3 DigiMesh RF Module:42
Sleeping with AT commands43
Idle a device from MicroPython43
Enter and exit the idle state43
Poll for data while the device is idle44
Digi MicroPython Programming Guide
5
Access the primary UART
How to use the primary UART47
sys.stdin limitations47
Example: read bytes from the UART47
Example: read the first 15 bytes from the UART48
REPL (Read-Evaluate-Print Loop) examples
Ctrl+A: Enter raw REPLmode50
Ctrl+B: Print the MicroPython banner50
Print the banner51
Print the banner and verify that the memory was not wiped51
Ctrl+C: Regain control of the terminal52
Ctrl+D: Reboot the MicroPython REPL52
Ctrl+E: Enter paste mode53
Paste one line of code53
Paste a code segment54
Ctrl+F: Upload code to flash54
Load code to flash memory55
Erase the code stored in flash memory55
Flash memory and automatic code execution56
Run stored code at start-up to flash LEDs56
Disable code from running at start up57
Ctrl+R: Run code in flash58
Enable code to run at start-up58
Perform a soft-reset or reboot59
Access file system in MicroPython
Modify file system contents61
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 files63
File object methods63
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 system64
Reload a module65
Compiled MicroPython files65
Send and receive User Data Relay frames
Constants67
Interfaces (always defined)67
Limits67
Methods67
relay.receive()67
relay.send(dest, data)67
Exceptions67
relay.callback(my_callback)67
Examples68
MicroPython libraries on GitHub
MicroPython modules
XBee-specific functions71
Standard modules and functions71
Discover available modules72
Machine module
Reset-cause74
Constants74
Random numbers74
Unique identifier74
Class PWM (pulse width modulation)74
Class ADC: analog to digital conversion75
Constructors75
Methods76
Sample program76
Class I2C: two-wire serial protocol77
Constructors77
General methods78
Standard bus operations methods78
Memory operations methods78
Sample programs79
Class Pin82
Class UART82
Test the UART interface82
Use the UARTclass83
Constructors83
Methods84
Constants84
Class WDT: watchdog timer85
Access the XBee device's I/O pins85
Use the Pin() constructor87
Use mode() to configure a pin87
Digi MicroPython Programming Guide
7
Pin.DISABLED87
Pin.IN88
Pin.OUT88
Pin.ALT88
Pin.ANALOG89
Pin.OPEN_DRAIN and Pin.ALT_OPEN_DRAIN89
Use pull() to configure an internal pull up/down resistor89
Generic gap advertising and gap scanning samples106
Eddystone Beaconing samples106
iBeacon samples106
Troubleshooting107
Fewer advertisements than expected when usinggap_scan107
Cellular network configuration module
Configure a specific network interface109
class Cellular109
Constructors110
Cellular power and airplane mode method110
Verify cellular network connection method110
Cellular connection configuration method110
Send an SMS message method110
Receive an SMS message method111
Register an SMS Receive Callback method111
Cellular shutdown method111
RSRP/RSRQ reporting in MicroPython112
XBee module
AT commands that do not work in MicroPython114
class XBee on XBee Cellular Modem114
Constructors114
Methods114
XBee MicroPython module on the XBee 3 RFModules115
Functions115
atcmd()115
discover()115
receive()117
receive_callback(rx_callback)118
transmit()118
modem_status119
digi.cloud module
Create and upload data points122
class DataPoints122
Digi MicroPython Programming Guide
9
Constructor122
Optional parameter122
Add a data point method122
Upload data to Digi Remote Manager method123
Check the status of a DataPoints object124
The life-cycle of a DataPoints object124
Delete a DataPoints object124
Receive a Data Service Device Request125
class device_request125
Use the read(size=-1) method126
Use the readinto(b) method126
Use the write(b) method126
Use the close() method126
Use the API Explorer to send Device Requests126
The ussl module
ussl on the XBee Cellular Modem129
Syntax129
Usage129
Use AWS IoT from MicroPython
Add an XBee Cellular Modem as an AWS IoT device131
Create a policy for access control131
Create a Thing132
Install the certificates134
Test the connection135
Publish to a topic137
Confirm published data138
Subscribe to updates from AWS138
Time module example:get the current time
Retrieve the local time141
Retrieve time with a loop141
Delay and timing quick reference142
Cellular network connection examples
Check the network connection144
Check network connection with a loop144
Check network connection and print connection parameters145
Socket examples
Sockets148
Basic socket operations: sending and receiving data, and closing the network connection148
Basic data exchange code sample148
Response header lines149
Specialized receiving: send received data to a specific memory location150
DNS lookup151
Digi MicroPython Programming Guide
10
DNS lookup code output152
Set the timeout value and blocking/non-blocking mode152
Send an HTTPrequest and dump the response154
Socket errors154
ENOTCONN: Time out error154
ENFILE: No sockets are available155
ENXIO: No such device or address155
Unsupported methods155
I/O pin examples
Change I/O pins157
Print a list of pins157
Change output pin values:turn LEDs on and off158
Poll input pin values158
Check the configuration of a pin159
Check the pull-up mode of a pin160
Measure voltage on the pin (Analog to Digital Converter)162
SMS examples
Send an SMS message165
Send an SMS message to a valid phone number165
Check network connection and send an SMS message165
Send to an invalid phone number166
Receive an SMS message166
Sample code167
Receive an SMS message using a callback168
XBee device examples
Print the temperature of the XBee Cellular Modem170
Print the temperature of the XBee 3 Zigbee RF Module170
Print a list of AT commands171
xbee.discover() examples173
Handle responses as they are received173
Gather all responses into a list173
xbee.transmit() examples174
xbee.transmit() using constants174
xbee.transmit() using byte string174
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 RFModule 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:
FeatureXBee 3 Cellular XBee 3 Zigbee, DigiMesh, and 802.15.4
Digital I/OYesYes
I2CYesYes
Power managementYesYes
Idle from MicroPythonNoYes
Digi Remote ManagerYes
Secondary UARTYesNo
Real-time clockYesNo
File systemYesYes
File system - concurrent file writesYesNo
File system - renameYesNo
File system - Edit files after creationYesNo
1
No
File System - deleteYesNo
File System - secure filesYesNo
File System preserved across updatesYesNo
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 environment15
Enter MicroPython code15
Exit MicroPython15
Display tools15
Coding tips15
Recover an XBee device16
Digi MicroPython Programming Guide
14
Use MicroPythonAccess 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 MicroPythonRecover 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.
Colons18
Indentations18
Functions19
Digi MicroPython Programming Guide
17
MicroPython syntaxColons
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 inrange(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)
FORloop with one statement indented
In this example, only one statement after the initial FORloop 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 syntaxFunctions
When this code executes, it prints "In the FORloop, 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 FORloop 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 FORloop, 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 syntaxFunctions
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 error22
Name error22
OSError23
Socket errors23
Digi MicroPython Programming Guide
21
Errors and exceptionsSyntax 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
Aname 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 exceptionsOSError
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 shortcuts25
Select a previously typed statement25
Digi MicroPython Programming Guide
24
Keyboard shortcutsKeyboard 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 REPLmode. 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 REPLprompt.
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 UParrow 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 UParrow 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 management27
Variable types27
Syntax27
Digi MicroPython Programming Guide
26
Differences between MicroPython and other programming languagesMemory 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 languagesSyntax
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 languagesSyntax
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 languagesSyntax
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
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.