Super SIM can empower a wide range of IoT devices. This guide focuses on just one of them: Sixfab’s Cellular IoT Hat, a development board which equips a low-cost Raspberry Pi computer with a Quectel BG96 cellular modem. The BG96 is a particularly good modem with which to try out Super SIM: it supports the key IoT-oriented cellular standard, Cat-M. The European version also provides 2G for back-up where that is still available.
This guide requires a configured Super SIM. If you haven’t set up your Super SIM in the Console, please do so now.
In addition to your configured Super SIM, to proceed with this guide, you will need:
- A Sixfab Cellular IoT Hat. It’s available in Worldwide and Verizon USA-certified forms; select the one that’s right for your location.
- A Raspberry Pi. This guide was written using the Pi 3 Model B+, but there are other versions of this inexpensive computer available too, including the more recent Pi 4 Model B. The Cellular IoT Hat works with all of these but the very first Pi, ie. from the Pi 2 onwards. To run the Pi, you will also need:
- A Micro SD card of 8GB or above.
- A monitor, keyboard and mouse.
- A 5V, 3A (15W) USB AC adaptor.
The Raspberry Pi has its own setup procedure which involves downloading and installing its Linux operating system, called Raspbian, onto the Micro SD card. The Raspberry Pi Foundation has a very good walkthrough of its own that covers this process — you should use this to get your Pi ready before proceeding to the next stage of this guide.
If you prefer to work on your main computer, you can access the Pi remotely using SSH. You will need to enable SSH on the Pi first: run
sudo raspi-config then cursor down to option 5, hit Return then select option P2 and hit Return again. Make sure you select Yes then hit Return. At the main menu, navigate to Finish, hit Return and, if the Pi asks you to, select Reboot now. Later you can fire up a Terminal on your main machine and enter
ssh firstname.lastname@example.org to access the Pi over your local network.
The Cellular IoT Hat ships with all you need to fit it onto the Pi. Just follow these steps to set everything up:
- If it’s powered up, turn off the Pi.
- If you’re at the command line, enter
sudo shutdown -hnow.
- If you’re at the desktop, select Shutdown... from the Raspberry menu and then click Shutdown.
- Remove the power cable when the Pi’s activity LED has flashed yellow ten times.
- If you’re at the command line, enter
- Fit either of the two headers supplied with the Hat to the Pi’s paired row of GPIO pins:
- Slot the Cellular IoT Hat onto the header:
- Fit the Super SIM into the Cellular IoT Hat’s SIM slot. The slot takes a 3FF Micro SIM, so take care removing your Super SIM from its mount, or use an adaptor if you have removed the Super SIM as a 4FF Nano SIM:
- Connect the bundled cellular antenna to the Cellular IoT Hat. You need only connect the cable marked LTE to the similarly marked connector on the Hat; this guide doesn’t use the GPS antenna. However, we recommend fitting both antennas to reduce the strain on a single connector:
- Connect the small USB adaptor to the micro USB port on the Cellular IoT Hat and a full USB port on the Pi:
- Finally, power up the Pi by re-inserting the power cable.
You need to ensure the Pi is configured so that it doesn’t make use of the Serial connection over which the Cellular IoT Hat expects to be accessed. You do this as follows:
- At the command line run
- Select 5 Interfacing Options.
- Select P5 I2C.
- Select Yes.
- Select 5 Interfacing Options.
- Select P6 Serial.
- For Would you like a login shell to be accessible over serial? select No.
- For Would you like the serial port hardware to be enabled? Select Yes.
- Select Finish.
- Reboot the Pi. The raspi-config utility will offer to do this for you; if it does not enter
sudo shutdown -r now.
The Cellular IoT Hat can be controlled using a software library written in Python. We’ll use this library to set up the Hat and get it connected, so let’s install it now. Enter the following at the command line (or in Terminal if your Pi boots to the desktop):
cd ~ wget https://www.twilio.com/docs/documents/218/cellulariot.py
To make use of the Super SIM, you need to apply a couple of essential settings to the BG96:
- Set the Access Point Name (APN).
- Turn roaming on (required whatever country you are using Super SIM in).
Let’s do this now.
In order for the Super SIM to transfer data to and from the cellular network, it needs to connect to what’s known as an ‘Access Point’. This is identified by its APN. At the Raspberry Pi command line, fire up the Python command prompt:
At the Python prompt (
>>>) enter the following lines, one after the other:
from cellulariot import * modem = CellularIoT()
You’ll now see the response
CellularIoT class instantiated. You’re ready to continue entering setup commands:
You’ll use all of these commands in your own Python programs that make use of the Cellular IoT Hat.
We’ll now use the Cellular IoT Hat library’s send_command() function to send the AT commands that are used to control the cellular modem. There are many, many AT commands that your code can employ — see our separate guide Introduction to AT Commands to learn more — but we’ll focus on just a few here. First, we use the command
+GCDCONT to set the modem’s APN, which must be set to super. Enter the following:
The argument passed into the function is the AT command. We need to escape quote marks that need to be included in the string.
You should then see the following output — the APN has been set:
Next, tell the BG96 to activate roaming which is required for Super SIM usage, whatever country you are in:
This should yield the following output:
Let’s check the network stats. Enter the following:
You’ll receive something like:
AT+CREG: 0,2 OK
The key value is the second one; a
2 indicates that the BG96 is looking for a cellular operator’s network to connect to (called ‘Registration’). If you issue the above command repeatedly, you should eventually see the second value become
5 — the modem has registered with a network and is roaming on it:
modem.send_command("AT+CREG?") AT+CREG: 0,5 OK
To see which network it is enter:
which will show the connected network between the quotes:
+COPS: 0,0,"vodafone UK Twilio",0 OK
Your network may be different, of course, but whatever it is, your IoT development device is now ready to use.
You can use Super SIM Commands to exchange machine-to-machine SMS with your devices. Commands are transmitted to and from the special phone number 000. Let’s send one to the Raspberry Pi now:
- On your computer, login to the Console and go to Internet of Things > Super SIM > SIMs.
- Note down your Super SIM’s unique name, or its SID if you have not yet given it a name.
- Go to the Console Dashboard.
- Note down your Account SID and your Auth Token.
- In a Terminal, enter the following command. The items bracketed with
>should be replaced with your own values, which you just obtained. After each
\, hit the Return key on your keyboard to start a new line:
curl -X POST https://supersim.twilio.com/v1/Commands \ --data-urlencode "Sim=<YOUR_SIM_NAME>" \ --data-urlencode "Command=Hello, Super SIM!" \ -u <YOUR_ACCOUNT_SID>:<YOUR_AUTH_TOKEN>
- The API will return and print a block of JSON; if you get an error, hit the up arrow key on your keyboard to view the command you just entered and look for errors.
- At the Raspberry Pi Python prompt, tell the modem you want to view the command in text format:
- Enter the AT command to read the command you’ve just sent:
This should yield something like:
+CMGR=0: "REC UNREAD","000",,"20/04/09,12:39:06+00" Hello, Super SIM! OK
The first line shows that the message’s status is UNREAD (the modem will change that to READ now, as you’ll see if you issue the command in step 8 a second time) and provides the date and time the SMS message was received. The second line is, of course, the command you sent via the Super SIM Commands API in step 5.
Received SMS messages are stored sequentially and are accessed by an index value (the
=0 in the command above). If you send some more Commands, you will need to change the index value when you read them. If you want to delete all your messages, just issue:
You can turn these commands into a control script which continually checks incoming messages and performs tasks according to commands issued as messages.
Exit from the Python prompt by typing
exit(), copy the lines below into a new file, save it as
commands.py and then run it using
from cellulariot import * import time import sys # Set up the modem modem = CellularIoT() modem.boot() modem.set_debug(False) modem.send_command("AT+CMGF=1") while True: try: # Is there a message? msg = modem.send_command("AT+CMGR=0") if msg == "OK" and len(msg) > 0: # Extract the command from the message parts = msg.split("\r\n") command = parts if len(command) > 0: # Delete the message (all messages, in fact) modem.send_command("AT+CMGD=0,4") # Process the command if command.upper() == "EXIT": print("Quitting...") sys.exit() if command.upper() == "INFO": # Display modem info result = modem.send_command("AT+QNWINFO") result = result.split("\r\n") print(result) if command.upper()[:2] == "AT": # Run supplied AT command print("AT Command Received:", command[2:]) result = modem.send_command(command) result = result.split("\r\n") print("Response: ", result) # Wait 15 seconds before checking again time.sleep(15) except KeyboardInterrupt: print("Ctrl-c hit... quitting...") sys.exit()
This code sets up the modem then loops every 15 seconds. The loop checks for a message; if there is one, it is decoded and its command is extracted. If it’s command that the code understands —
at... — it acts upon it.
For example, send the command
AT+COPS? (as per step 5, above) and the script will print:
AT Command Received: +COPS? Response: +COPS: 0,0,"Vodafone UK Twilio",0,0
info and you will see something like:
+QNWINFO: "EDGE","23415","GSM 900",31
We’ll leave it as an exercise for later to decode the response!
Super SIM can also be used to reach out to the Internet via the cellular network and request data from or upload it to a remote server via an API hosted by that server. You do this using the standard HTTP verbs: GET, POST, PUT, etc.
The following code demonstrates how the first of those operations — requesting data — can be achieved. It accesses a public API which provides location data for the International Space Station (ISS), relative to the surface of the Earth. The API returns a bunch of data, from which the program extracts the ISS’ co-ordinates. The code gets the ISS location every ten seconds, until you hit Ctrl-C to break out of the program.
Paste the program into a new file — call it
iss.py — then run it using
from cellulariot import * import time import sys import json # Process the ISS data: lat and long def process_iss_data(modem_response): # 'modem_response' is a string, eg. "+QHTTPGET: 0,200,22323" # Check for HTTP error code, the response = modem_response.split(": ") response = response.split(",") if response == "0": # Got a good response from the server, # so read it back from the modem result = modem.send_command("AT+QHTTPREAD", "OK") if result == "OK": received_data = result.split("\r\n") iss_data = json.loads(received_data) if iss_data["message"] == "success": print("ISS is at",iss_data["iss_position"]["longitude"],",",iss_data["iss_position"]["latitude"]) return # Display error message print("ISS location not retrieved") # Set up the modem modem = CellularIoT() modem.boot() modem.set_debug(False) # Turn off echoing (easier to parse responses) modem.send_command("ATE0") # URL of the data source source_url = "http://api.open-notify.org/iss-now.json" conn_open = False while True: try: # Open a data connection modem.activate_context() conn_open = True # Assemble the HTTP request # 1. Set the PDP Context ID modem.send_command("AT+QHTTPCFG=\"contextid\",1") # 2. Choose no custom headers modem.send_command("AT+QHTTPCFG=\"requestheader\",0") # 3. Set the URL parameters: length and timeout modem.send_command("AT+QHTTPURL=" + str(len(source_url)) + ",80", "CONNECT", 30) # 4. Set the URL as data modem.send_data(source_url) # Make the GET request and parse the result result = modem.send_command("AT+QHTTPGET", "+QHTTPGET", 120) if result == "OK": process_iss_data(result) # Close the data connection modem.deactivate_context() conn_open = False # Pause 1 minute time.sleep(60) except KeyboardInterrupt: if conn_open: modem.deactivate_context() sys.exit()
Run the code and you should see the usual debugging messages plus something like:
ISS is at 158.4735 , -47.8412
It will be repeated every ten seconds to give you the latest ISS location. Just hit Ctrl-C to exit the program.
How does it work? The code establishes a data connection, called a ‘context’, and then uses AT commands (
AT+QHTTPGET) to assemble an HTTP GET request to the target API. These commands are specific to the Cellular IoT Hat’s BG96 modem; other devices have equivalent but different commands for this task. The modem stores the API’s response internally; the code retrieves the response with another AT command (
AT+QHTTPREAD), checks that it is valid and, if so, extracts and prints the ISS coordinates.
With all the commands and data you have been transferring in and out of your IoT device in this guide, we’ll end by showing you how to keep an eye on your device’s cellular data usage. You can do so by visiting the Console:
- Go to Internet of Things > Super SIM > SIMs.
- Click on the unique name or SID of the Super SIM fitted to the device.
- Click on the Usage tab to view the Super SIM’s activity and thus that of the device it’s fitted into.
Your Raspberry Pi and Sixfab Cellular IoT Hub are now able to access the cellular network. Over to you: what are you going to build? We can’t wait to find out.
In the meantime, here are some suggestions for things to try:
- Expand the range of commands your Pi will accept and action.
- Try contacting other APIs via cellular and retrieve data from them. There’s a good selection of public APIs you can try here.
- Use the Console or Super SIM API to monitor your Super SIM’s data usage.
- Check out our guide Introduction to AT Commands and try sending to your modem some of the more useful commands it lists.
- You may prefer to use a different language than Python, which is the basis for the control library we use earlier in this guide. No problem — the Cellular IoT Hat can be controlled by any code in any language capable of accessing the Pi GPIO pins that allow the two boards to communicate. You can check out the Pi pins used by the Hat here.