CircuitPython Cellular Usage

Cellular Data Setup

This page assumes you've set up and connected your CircuitPython board to a cellular data connection.

Connect FONA

Make sure you have attached a LiPoly battery, GSM antenna, GPS antenna to your FONA. 

You must also have a SIM card inserted in the FONA to use the module with cellular data. 

Code Usage

Copy the following code to a file on your computer. Name the file code.py. With your operating system file explorer/finder, copy this file to the CIRCUITPY drive which appears when your microcontroller board is plugged in via USB.

import time
import board
import busio
import digitalio
from adafruit_fona.adafruit_fona import FONA
import adafruit_fona.adafruit_fona_network as network
import adafruit_fona.adafruit_fona_socket as socket

import adafruit_minimqtt.adafruit_minimqtt as MQTT

# Get Adafruit IO details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("GPRS secrets are kept in secrets.py, please add them there!")
    raise

### Cellular ###

# Create a serial connection for the FONA connection
uart = busio.UART(board.TX, board.RX)
rst = digitalio.DigitalInOut(board.D4)
# Initialize FONA
fona = FONA(uart, rst)

### Feeds ###

# Setup a feed named 'photocell' for publishing to a feed
photocell_feed = secrets["aio_username"] + "/feeds/photocell"

# Setup a feed named 'onoff' for subscribing to changes
onoff_feed = secrets["aio_username"] + "/feeds/onoff"

### Code ###

# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connected(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed)
    # Subscribe to all changes on the onoff_feed.
    client.subscribe(onoff_feed)


def disconnected(client, userdata, rc):
    # This method is called when the client is disconnected
    print("Disconnected from Adafruit IO!")


def message(client, topic, message):
    # This method is called when a topic the client is subscribed to
    # has a new message.
    print("New message on topic {0}: {1}".format(topic, message))


# Initialize cellular data network
network = network.CELLULAR(
    fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"])
)

while not network.is_attached:
    print("Attaching to network...")
    time.sleep(0.5)
print("Attached!")

while not network.is_connected:
    print("Connecting to network...")
    network.connect()
    time.sleep(0.5)
print("Network Connected!")

# Initialize MQTT interface with the cellular interface
MQTT.set_socket(socket, fona)

# Set up a MiniMQTT Client
# NOTE: We'll need to connect insecurely for ethernet configurations.
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    is_ssl=False,
)

# Setup the callback methods above
mqtt_client.on_connect = connected
mqtt_client.on_disconnect = disconnected
mqtt_client.on_message = message


# Connect the client to the MQTT broker.
print("Connecting to Adafruit IO...")
mqtt_client.connect()

photocell_val = 0
while True:
    # Poll the message queue
    mqtt_client.loop()

    # Send a new message
    print("Sending photocell value: %d..." % photocell_val)
    mqtt_client.publish(photocell_feed, photocell_val)
    print("Sent!")
    photocell_val += 1
    time.sleep(5)

Feed Publishing Example

Directly after saving the code.py file, open a serial monitor/REPL to see the output. It should look something like the following:

Download: file
Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Attaching to network...
Attached to network!
Connecting to network...
Connected to network!
Connecting to Adafruit IO...
Connected to Adafruit IO! Listening for topic changes on brubell/feeds/onoff
Sending photocell value: 0...
Sent!
Sending photocell value: 1...
Sent!
Sending photocell value: 2...
Sent!
Sending photocell value: 3...
Sent!

Navigate to the dashboard you created earlier. You should see the photocell gauge increasing its value as your CircuitPython device publishes the increasing photocell value to Adafruit IO.

If you navigate to the page for the photocell feed, you'll see the values increasing there along with metadata about when the data was received by the Adafruit IO broker.

Feed Subscription Example

While we're publishing the increasing photocell value to Adafruit IO - our code also subscribes to changes on the onoff feed.

The example code.py subscribes to the onoff feed when the client successfully connects to Adafruit IO. You don't need to make any changes to your code!

With the code still running on your CircuitPython device - click the toggle switch to send a value to the onoff feed. You should see the value appear on your serial monitor/REPL.

If you really want to see the speed of MQTT - remove the one second delay in the while True loop.

Change the following code (within while True) from:

print('Sent!')
photocell_val += 1
time.sleep(1)

to

print('Sent!')
photocell_val += 1
time.sleep(0.5)

Be warned - if you do this you will not be able to run the code for very long. This is because Adafruit IO's MQTT server imposes a rate limit to prevent excessive load on the service.

The current Adafruit IO Data Rate is at most 1 request per second (or 60 requests within 60 seconds), without an Adafruit IO+ Boost applied to your account.

Going Further - the Adafruit IO CircuitPython Module

While you can use this code to communicate with Adafruit IO, the recommended method of using CircuitPython with Adafruit IO is with the Adafruit IO CircuitPython module

This module has methods to simplify using the Adafruit IO MQTT API. It also includes helper features to make your experience using Adafruit IO better.

If you want to use Adafruit IO and CircuitPython, check out Adafruit IO CircuitPython and the code example for Ethernet on GitHub!

This guide was first published on Jul 23, 2019. It was last updated on Jul 23, 2019.
This page (CircuitPython Cellular Usage) was last updated on Aug 07, 2020.