Home/ Blog/Examples & Guides

Examples & Guides’ Category

Hands-on MicroPython Programming Examples for Edge Computing: Part 2

Posted on:

In our first post in the MicroPython programming for the edge series, we talked about how to collect sensor readings and make sense of them using the Digi XBee3 Cellular LTE-M Kit, as well as Digi’s free configuration software, XCTU, and some simple MicroPython code. Welcome to Part 2 of this series.

The edge intelligence provided in Digi’s XBee3 line of embedded RF modules makes sending data to the cloud a snap. For our second project in this hands-on series, we show how to upload temperature readings measured from a Digi XBee3 Cellular LTE-M module to “data streams” on Digi Remote Manager (DRM). Developers can use this data and device management platform for free. The Digi XBee3 Cellular line supports open communications standards, so it can also share data with Amazon’s IoT Platform, Microsoft Azure, Adafruit.io, Google Cloud IoT, ThingSpeak, IBM Watson and many others. Look for hands-on tutorials or several of those in future projects. Readers of our first project will recall that MicroPython is an open-source programming language based on Python 3, modified to fit on small devices and optimized for microcontrollers. By using MicroPython you can rapidly create connections to cloud services right from the edges of your network.

Send Data to Digi Remote Manager

Many IoT systems feed data to online cloud platforms on the Internet. They typically sample some value locally, like temperature, then send the readings to any one of a dizzying number of online application for logging, processing and data visualization. In this project, we will take some temperature measurements using a simple sensor, then send them to Digi Remote Manager® as a “data stream” that can be visualized in different ways, accessed via an open API or stored for later use.

We begin with the exact same hardware setup used in the “Sense, Transform and Send a Value” project, including the TMP36 temperature sensor.

Set up the Hardware

If you missed our first post, please work through the following items to prepare for this second project:

  1. Getting Started: Demonstrates how to set up the hardware and software you’ll need.
  2. Hello World Example: Teaches how to upload code to Digi XBee3.
  3. Sense, Transform and Send a Value – shows how to take a temperature reading and send it as a text message.

Once you have set up the Digi XBee3 hardware, hooked up the TMP36 temperature sensor, connected it to the configuration software, and opened the MicroPython terminal in XCTU, you are ready to begin. Your setup should look similar to this one:

XBee3 XCTU TMP36
TMP36, Digi XBee3 Cellular, XBIB connected to MicroPython Terminal in XCTU

About Digi Remote Manager

Remote Manager enables you to configure and manage dynamic device networks. A free developer account lets you explore Remote Manager’s application development and device management tools, with a limited number of devices and transactions, for as long as you need to.

To create your free developer account:

  1. Navigate to http://myacct.digi.com.
  2. Follow the steps for creating your account.

Developer account setup

If you need help setting up or using your account, see the Remote Manager User Guide.

Your Remote Manager account username and password will let your Digi XBee3 Cellular upload data streams, in this case temperature measurements. It provides a layer of security that’s appropriate to this simple example. Many additional layers of security and authentication are available to provide increased protection for production applications, though we won’t look at those right now so we can focus on the basics.

Library Uploads

To make our code simpler and more readable, we rely on two libraries uploaded to the file system inside the Digi XBee3 Cellular module. These libraries are collections of pre-written code. They provide simple ways to call complex routines without the routines themselves cluttering up your program. For this example we will use the remotemanager library, and the urequests library that remotemanager requires.

  1. Locate the remotemanager.py and urequests.py libraries on this GitHub page: https://github.com/digidotcom/xbee-micropython/tree/master/lib.
  2. Right-click on each filename and select Download to create a local copy of each on your computer. (GitHub users could also Clone or Download the entire repository here: https://github.com/digidotcom/xbee-micropython).
  3. With your Digi XBee3 and XBIB board added to XCTU, open the Tools menu and select File System Manager.
  4. Click Open to connect the File System Manager to your Digi XBee3’s file system.
  5. Navigate the “Local Path” folders in the left-hand column to find the remotemanager.py and urequests.py files you just downloaded.
  6. Use the “Remote Path” folders in the right-hand column to open the “lib” directory (“/flash/lib”).
  7. Drag the remotemanager.py and urequests.py files from your local directory and drop them in the remote “lib” directory to store them on the XBee3.
  8. When you are done, close the File System Manager window.
Currently the MicroPython program pasted at the Ctrl-F prompt in the REPL is the only way to run a program at startup. Once this pasted program is executing, it can import modules from the file system as well as writing files out to it. Launching from a filesystem file is on Digi’s development roadmap so look for this feature in future firmware.

Configure the XBee

The module is configured identically to our first Sense, Transform and Send a Value project. If anything might have changed, mount the Digi XBee3 Cellular on the XBIB board and connected to your computer over USB, launch the XCTU program.

  • Add a radio module, then click on that device in the list to configure it.
  • BD Baud Rate should be set to 115200 [7]  and AP API Enable set to MicroPython REPL [4].
  • Write these settings to the module, using the pencil icon at the top.

Load the Code

Copy the below code to a text editor like Notepad. Be sure to enter your own username and password, replacing “your_username_here” and “your_password_here” before uploading the code. By default, this program sends a temperature reading to Digi Remote Manager data stream once per minute, over 24 hours (1440 samples).  You can customize that by changing the wait_time or cycles variables as desired.

Remember, this sample code must be edited before you upload it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Digi XBee3 Cellular DRM Example
# uses a TMP36 to measure temperature and post it to Digi Remote Manager
# by default repeating once per minute, 1440 times total, stopping after a day
# ENTER YOUR DRM username and password, REPLACING "your_username_here" etc. BEFORE UPLOADING THIS CODE!
from remotemanager import RemoteManagerConnection
from machine import ADC
from time import sleep
from xbee import atcmd
cycles = 1440 # number of repeats
wait_time = 60 # seconds between measurements
username = 'your_username_here' #enter your username!
password = 'your_password_here' #enter your password!
# Device Cloud connection info
stream_id = 'temperature'
stream_type = 'FLOAT'
stream_units = 'degrees F'
description = "temperature example"
# prepare for connection
credentials = {'username': username, 'password': password}
stream_info = {"description": description,
                   "id": stream_id,
                   "type": stream_type,
                   "units": stream_units}
ai_desc = {
    0x00: 'CONNECTED',
    0x22: 'REGISTERING_TO_NETWORK',
    0x23: 'CONNECTING_TO_INTERNET',
    0x24: 'RECOVERY_NEEDED',
    0x25: 'NETWORK_REG_FAILURE',
    0x2A: 'AIRPLANE_MODE',
    0x2B: 'USB_DIRECT',
    0x2C: 'PSM_DORMANT',
    0x2F: 'BYPASS_MODE_ACTIVE',
    0xFF: 'MODEM_INITIALIZING',
}
def watch_ai():
    old_ai = -1
    while old_ai != 0x00:
        new_ai = atcmd('AI')
        if new_ai != old_ai:
            print("ATAI=0x%02X (%s)" % (new_ai, ai_desc.get(new_ai, 'UNKNOWN')))
            old_ai = new_ai
        else:
            sleep(0.01)
# Main Program
# create a connection
rm = RemoteManagerConnection(credentials=credentials)
# update data feed info
print("updating stream info...", end ="")
try:
    rm.update_datastream(stream_id, stream_info)
    print("done")
except Exception as e:
    status = type(e).__name__ + ': ' + str(e)
    print('\r\nexception:', e)
    
while True:
    print("checking connection...")
    watch_ai()
    print("connected")
    for x in range(cycles):
        # read temperature value & print to debug
        temp_pin = ADC("D0")
        temp_raw = temp_pin.read()
        print("raw pin reading: %d" % temp_raw)
    
        # convert temperature to proper units
        temperatureC = (int((temp_raw * (2500/4096)) - 500) / 10)
        print("temperature: %d Celsius" % temperatureC)
        temperatureF = (int(temperatureC * 9.0 / 5.0) + 32.0);
        print("temperature: %d Fahrenheit" % temperatureF)
    
        # send data points to DRM
        print("posting data...", end ="")
        try:
            status = rm.add_datapoint(stream_id, temperatureF) # post data to Device Cloud
            print("done")
            print('posted to stream:', stream_id, '| data:', round(temperatureF), '| status:', status.status_code)
        except Exception as e:
            print('\r\nexception:', e)
        # wait between cycles
        sleep(wait_time)

Use It

With the Data to Digi Remote Manager example running, a new temperature measurement will be uploaded to a DRM data stream each minute. If you left the settings at their default, you will receive 1440 uploads, one minute apart, or 24 hours worth. To monitor the data stream:

  1. Log in to Digi Remote Manager and select the Data Services tab.

    Remote Manager Data Services
    Digi Remote Manager Data Services
  2. Click on the Stream named “temperature” to select it.
  3. Locate the Charts and Raw Data area below. It may be helpful to drag the separator line upwards to enlarge this area.
  4. Click on Raw Data to see the data points that have been uploaded

    Raw Data
    Digi Remote Manager Raw Data
  5. Click on Charts to see line graphs of the temperature data. Daily, weekly, monthly and yearly summary graphs can be generated.

    Remote Manager Charts
    Digi Remote Manager Charts

Related white paper: 5 Reasons You Should Consider Embedded Cellular Connectivity.


 

Digi Remote Manager has a complete API for sharing your data with other online systems. Thanks to its RESTful interface, it can accept standard requests (using HTTP GET) from a web browser. Use this link to see your temperature data. You’ll  be prompted to enter your username and password:

http://remotemanager.digi.com/ws/DataPoint/temperature

The output will be in XML format, and will look like this:

Digi Remote Manager XML Response
Digi Remote Manager XML Response
Digi Remote Manager API Explorer
Digi Remote Manager API Explorer

Summary

This Digi Remote Manager example demonstrates one way to centralize your IoT system’s data uploads. You can now create multiple sensors that all transfer data to a central location online. You created your first DRM account, located your data and visualized it. We also covered uploading libraries to Digi XBee3 Cellular using the File System Manager in XCTU. The File System Manager can also manage key files and security certificates that are required by many online IoT platforms. In future posts, we will look at uploading data to other cloud applications, triggering alerts, improving battery life, reducing bandwidth costs and much more.

Your feedback about this series is welcome. Please post any questions or suggestions in the comments below.

>>> Learn more about the Digi XBee Ecosystem of wireless modules, or contact us to discuss your needs.

Hands-on MicroPython Programming Examples for Edge Computing: Part 1

Posted on:

The new Digi XBee3® line of embedded RF modules feature edge intelligence to help execute business rules and a whole lot more. By running simple Python-based scripts on Digi XBee3, you can save money, extend battery life, improve responsiveness and enhance system reliability.

The best way to understand the power of edge intelligence is hands-on. In this series we’ll take you through some simple examples that you can use directly, then customize and extend to bring the power of programming to everyone’s favorite line of radio modules.

MicroPython is an open-source programming language based on Python 3, modified to fit on small devices and optimized for microcontrollers. Using MicroPython, an easy-to-learn scripting and programming language, you can rapidly prototype intelligent behaviors at the edges of your network. Cryptic sensor readings can be transformed into useful data, excess transmissions can be intelligently filtered out, and modern sensors and actuators can be employed directly, with complex procedures carried out locally when needed.

Getting Started

XCTU v6.3.8 and later feature a new MicroPython terminal, allowing the user to interact with MicroPython on the Digi XBee3 modules. Through the serial interface in the terminal, users can write, test, load, and run MicroPython code using the familiar REPL interactive prompt.

It’s simple to get started. We’ll begin with the Digi XBee3 Cellular LTE-M Kit. (Other Digi XBee3 Cellular Kits are similar.)

MicroPython Terminal

  1. Assemble the hardware and connect it to the XCTU configuration software. Complete instructions, if needed, can be found in the Getting Started Guide.
  2. Open the XCTU program.
  3. Add a device (help).
  4. The XBee Cellular Modem appears as a box in the Radio Modules information panel. Click this box to select the device and load its current settings.
  5. Set the device’s baud rate to 115200 bps for the best experience. In the BD field, select 115200 [7] and click the Write button.
  6. To put the XBee Cellular Modem into MicroPython mode, in the AP field select MicroPython REPL [4] and click the Write button.
  7. Note what COM port(s) the XBee Cellular Modem is using, because you will need this information when you use terminal communication. The Radio Modules information panel lists the COM port in use.

To use the MicroPython Terminal in XCTU:

  1. Click the Tools drop-down menu and select MicroPython Terminal.
  2. Click Open. If you have not already added devices to XCTU:
    1. In the Select the Serial/USB port area, click the COM port that the device uses.
    2. Verify that the baud rate and other settings are correct.
  3. Click OK. (The Open icon changes to Close, indicating that the device is properly connected.)
  4. Press Ctrl+B to get the MicroPython version banner and prompt.

Related white paper: 5 Reasons You Should Consider Embedded Cellular Connectivity.


Hello World Example

Let’s upload some simple “Hello World” code to confirm everything is working. Using a text editor, such as Notepad in Windows or TextEdit on MacOS, type in this short script:

1
2
3
4
from time import sleep
while True:
    print("Hello World!")
    sleep(2)
    1. In XCTU at the MicroPython Terminal, press Ctrl+F at the >>> prompt to put MicroPython into Flash Compile mode.
    2. Copy the script from your text editor and paste it into the MicroPython Terminal, then press Ctrl+D to finish.
    3. You won’t need to run this code at startup, so answer N when you’re asked.
    4. Finally press Ctrl+R to run your code. It will begin printing Hello World to the screen every two seconds. You can stop execution by pressing Ctrl-C. Here’s how your entire session should look:
MicroPython v1.9.4-797-g4361c12 on 2018-09-20; XBC LTE-M/NB-IoT Global with EFR32MG
Type "help()" for more information.
>>> 
flash compile mode; Ctrl-C to cancel, Ctrl-D to finish
   1^^^ from time import sleep
   2^^^ while True:
   3^^^         print("Hello World!")
   4^^^         sleep(2)
   5^^^ 
Compiling 67 bytes of code...
Used 10/371 QSTR entries.
stack: 424 out of 3584
GC: total: 32000, used: 224, free: 31776
 No. of 1-blocks: 6, 2-blocks: 2, max blk sz: 4, max free sz: 1933
Compiled 67 bytes of code to 108/31232 bytes of flash.
Automatically run this code at startup [y/N]? N
Stored code will not run at startup.
Press CTRL-R in the REPL to run the code at any time.


MicroPython v1.9.4-797-g4361c12 on 2018-09-20; XBC LTE-M/NB-IoT Global with EFR32MG
Type "help()" for more information.
>>> 
Running 108 bytes of stored bytecode...
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!


Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
KeyboardInterrupt: 


>>>

Hello World Summary

By completing this Hello World example you now have all the skills needed to start using edge intelligence. You have set up the Digi XBee3 hardware, connected it to the configuration software, opened MicroPython, loaded working code, and run it yourself. You are ready to run your first real application.

Sense, Transform and Send a Value

Now that we know how to create MicroPython code on the Digi XBee3 platform, let’s do something useful with it. Many IoT systems are fundamentally sensor networks. They sample some value locally, such as temperature, water pressure or human presence, then send that information for logging, processing and decision-making by online applications. For our next project, we’re going to take a temperature measurement using a simple sensor, then send it to your phone as an SMS text message. This measurement cycle repeats every minute, stopping after 10 rounds to protect your sanity.

Many sensors produce a simple varying voltage that needs to be transformed into the proper units. For example, at 25º Celsius a temperature sensor might output 750 mV. While it’s possible to send the meaningless number 750 to the cloud application, it would be much clearer to send 25ºC instead—that’s the actual temperature. This is easily accomplished in MicroPython, and these transformations will be increasingly helpful as we build more intelligent systems.

First, let’s attach a sensor to our Digi XBee3 Cellular modem. To make things easy, we will use a the TMP36 temperature sensor, which is self-calibrating and communicates over a single wire.

Parts to Order

Prepare the Board to Connect Components

20-pin headerThe easiest way to connect additional components to the XBIB development board is to solder one of these headers to the 20-pin socket on the XBIB labeled P1. Now you can use jumper wires to attach peripherals like sensors or motors.

Note: If you don’t have jumper wires or a header, soldering wires or sensors directly to the XBIB board will also work.

Assemble the Hardware

Use jumper wires to connect the TMP36 temperature sensor to the XBIB board.

  1. With the flat side of the TMP36 facing you, the leftmost lead gets connected to pin 1, VCC on the XBIB board.
  2. The middle lead connects to pin 20 (right next to it) DIO0.
  3. The rightmost lead goes to pin 10, GND.

TMP36 temperature layout

Configure the XBee

With the Digi XBee3 Cellular on the XBIB board and connected to your computer over USB, launch the XCTU program.

  1. Add a radio module, then click on that device in the list to configure it.
  2. BD Baud Rate should already be set to 115200 [7]  and AP API Enable set to MicroPython REPL [4].
  3. With these two confirmed, locate the P# Destination Phone Number field and enter the mobile phone number you want to receive the temperature texts.
  4. Write these settings to the module, using the pencil icon at the top.

Load the Code

Copy the below code to a text editor like Notepad. Be sure to enter your own phone number, replacing “your_mobile_number_here” before uploading the code. Enter it just as you would dial it on a cell phone, including the + symbol if needed. By default, this program sends a temperature reading once per minute, 10 times total. You can customize that by changing the wait_time or cycles variables as desired.

Remember, this sample code must be edited before you upload it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Digi XBee3 Cellular Basic Example
# uses a TMP36 to measure temperature and send it as an SMS message
# by default repeating once per minute, 10 times total
# ENTER YOUR PHONE NUMBER, REPLACING "your_mobile_number_here" BEFORE UPLOADING THIS CODE!

import network
from machine import ADC
from time import sleep
wait_time = 60 # seconds between measurements
cycles = 10 # number of repeats
number = "your_mobile_number_here" # this phone number receives the text notifications
 
# while True: 
for x in range(cycles):
    # read temperature value & print to debug 
    temp_pin = ADC("D0")
    temp_raw = temp_pin.read()
    print("Raw pin reading: %d" % temp_raw)

    # convert temperature to proper units
    temperatureC = (int((temp_raw * (2500/4096)) - 500) / 10)
    print("Temperature: %d Celsius" % temperatureC)
    temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
    print("Temperature: %d Fahrenheit" % temperatureF)

    # send as text to phone number 
    message = ("Temperature: %d'F  (%d of %d)" % (temperatureF, x+1, cycles))  # message
    c = network.Cellular() 
    while not c.isconnected():
        print("waiting for cell network...") 
        sleep(1.5)  # Pause 1.5 seconds between checking connection 
    print("connected to cell network.")
    try:
        c.sms_send(number, message)
        print("message sent successfully to " + number)
    except Exception as e:
        print("Send failure: " +  str(e))

    #wait between cycles
    sleep(wait_time)

 

Once the code has been edited by adding your mobile phone number, it can be uploaded in XCTU at the MicroPython Terminal in the usual way:

  1. Press Ctrl+F at the >>> prompt to put MicroPython into Flash Compile mode.
  2. Copy the script from your text editor and paste it into the MicroPython Terminal.
  3. Press Ctrl+D to finish and answer N when you’re asked.
  4. Finally press Ctrl+R to run your code. You can stop execution by pressing Ctrl-C.

Use It

With the temperature SMS example running, you should begin receiving text messages. If you left the settings at their default, you will receive ten messages, one minute apart. The results on your phone should look like this:

SMS Temperature Example

Summary

By completing this SMS example you have created real, if basic, edge intelligence. Now you have experience hooking up a sensor, recording its values, transforming them into useful units and sending them to a mobile phone. In future posts, we will look at uploading data to cloud applications, triggering alerts, improving battery life, reducing bandwidth costs and much more.

Your feedback about this series is welcome. Please post any questions or suggestions in the comments below.

>>> Learn more about the Digi XBee Ecosystem of wireless modules, or contact us to discuss your needs.

Seven Segment Display with Digi XBee

Posted on:

Number communicate clearly. With a simple 7-segment numeric display you can show how many, how much, which one or when with precision. It’s a snap to display numbers wirelessly with an Digi XBee radio.

Controlling a Lamp from the Internet with Digi Remote Manager

Posted on:

In this example, we’ll walk you through the steps for setting up the Digi XBee Internet Gateway and Digi Remote Manager (DRM) to control a lamp over the internet! Of course, you don’t have to use a lamp for this; you can use XIG and Digi Remote Manager to control many kinds of devices and even read wireless sensors.

LCD Text Display with Digi XBee Radios

Posted on:

Words are how humans communicate. An inexpensive LCD text display can be the most economical way to make your project talk to people, and it’s easy to make a wireless one with a Digi XBee radio.

Simple Garage Door Sensor

Posted on:

Whether you’re pulling into work after a busy morning, driving to the family cabin, or just laying in bed after a long day, the last thing you want to worry about is your car garage door. This example will show you how to install a simple garage door monitor so you never have to worry if your garage door is left open. Using the Digi XBee LTE Cat1 Development Kit and a magnetic reed switch, an SMS can be sent to your phone notifying you if your garage door is opened or closed.

Communicate with Therapist Bot Using Digi XBee Cellular and XCTU

Posted on:

XCTU is a free multi-platform application designed to enable developers to interact with Digi RF modules through a simple-to-use graphical interface. By using XCTU and the Digi XBee cellular, you can connect to many servers such as the ELIZA Therapist Bot, Echo, and Daytime.

Prototype Digi XBee and Other Wireless Projects with Tinylab

Posted on:

You might remember our post about the XBee product turned Indiegogo superstar last year–Plexidrone. Well, there’s another XBee related Indiegogo campaign making headlines. Tinylab is a prototyping platform, developed by Bosphorus Mechatronics, simplifying IoT development with an all-in-one Arduino-based solution.

Tinylab reduces the need to stack multiple Arduino shields, pull out the breadboard and jumper wires, or hunt down that spare LTH sensor in your drawer. This flexible and extensive development board supports Arduino and other development environments, hosts 20 Digital I/O, and additional sensors come pre-attached. And, perhaps most exciting, is the support for a number of wireless technologies like XBee, Bluetooth, or Wi-Fi with the ESP8266 chip as seen in the graphic below.

 

tinylab-schematic
 

The Indiegogo campaign got off to a great start and Bosphorus Mechatronics quickly exceeded their goal of $25,000. The crew is shipping development kits to their campaign supporters in May and one level of support will even earn contributors a development kit that includes XBee RF modules.

Also, to demonstrate the board’s capabilities, the team at Tinylab created an wireless lighting demo. The video is showing wireless control of a lightbulb with commands sent over XBee. Check out the video below.

If you are interested in learning more about the Tinylab prototyping platform, click here to visit the Indiegogo campaign and support! You can follow their updates on Twitter or visit the Bosphorus Mechatronics website here.

Contact a Digi expert and get started today! Contact Us
Have a Question?