Soracom Cellular IoT Starter Kit

Welcome!

Cellular connectivity opens up a world of possibilities for IoT development, letting you build devices that can connect to the cloud from almost anywhere — and we’re excited to help you get started!
This Starter Kit includes everything you need to quickly get up and running. We’ll guide you through building a simple application that records data from an ultrasonic range finder (distance) sensor, and sends it to the cloud for real-time visualization.

Afterwards, we’ll give you some tips and ideas on how you can start customizing your application, and introduce additional Soracom services, like Soracom Beam for encrypting and forwarding data, and Soracom Lagoon for building powerful IoT dashboards, to help you leverage the power of the cloud.

Starter Kit Contents

Starter Kit Contents

    • Soracom Global SIM Card
      The Soracom Global SIM provides cellular data connectivity and SMS functionality on 2G, 3G, and 4G/LTE networks in over 120 countries around the world, fully managed right from your browser on the Soracom User Console.
    • Raspberry Pi Zero W and Official Case
      Super-small and easy-to-use, this tiny Linux computer supports a wide variety of programming environments to make developing your project a breeze, with a case to keep everything protected.
      For more information, visit: raspberrypi.org/products/raspberry-pi-zero
    • Huawei 3G USB Modem (MS2131i) and USB OTG Adapter Cable
      A great modem that provides 2G and 3G cellular connectivity, designed especially for IoT projects, plus a USB OTG cable to hook it up to the Raspberry Pi.
    • Ultrasonic Range Finder (HC-SR04)
      This simple yet reliable sensor measures distance using ultrasonic vibrations, and accurate up to 10 feet. We love this sensor because we can quickly capture data for easy visualization, just by waving our hand in front of it!
    • 16GB Micro-SD Card and Micro-SD Card Reader
      Storage for your Raspberry Pi, plus a card reader so you can edit its contents on your computer.
    • Perma-Proto Breadboard and Color-coded Wires
      For connecting the Ultrasonic Range Finder to your Raspberry Pi, without soldering anything.
    • USB-A to Micro-USB Cable
      To power your Raspberry Pi from your computer or another power source.
    • $10 Starter Kit Coupon
      Coupon to cover Soracom service fees (such as data usage) as you build your project.

 

Ultrasonic Range Finder Project

Project Overview

In this project, we will use our Raspberry Pi to capture data from our Ultrasonic Range Finder sensor, and send the data to Soracom Harvest using a cellular connection with the Huawei 3G USB modem and the Soracom Global SIM card. Soracom Harvest will take care of saving the data, and also automatically generate graphs so we can visualize the data in real-time.

The first half of this project—creating a Soracom account, setting up the Raspberry Pi, and configuring the 3G USB modem—we only need to perform one time.

Once completed, we can easily build our project by:

  • Connecting our sensor to the Raspberry Pi,
  • Using a Python script to read the sensor data and send it to Soracom Harvest, and
  • Accessing Soracom Harvest to see our data.

 

After completing the project, we can easily begin modifying it to add more functionality. Since we have full control over each step of the project, we can add or change sensors and control interfaces, write additional code for more interactivity, and extend cloud integration with other Soracom services, such as Soracom Beam for sending data to custom servers, and Soracom Lagoon for building powerful dashboards.

Before we get ahead of ourselves, let’s start the initial setup!

Setup your Soracom Account

In order use the Soracom Global SIM card, we need to register and activate it. The Soracom User Console lets you fully manage your Soracom SIM cards, as well as enable additional Soracom services. Let’s create an account and register our SIM card.

1. Create a Soracom Account

  • Access the Soracom User Console by visiting: https://console.soracom.io
  • Click Sign up.
  • On the sign up screen, select Coverage Type Global.
  • Enter your email address, password, and contact information, and click Create account.

Signup

You should see the following screen:

Verify your email address

  • A confirmation email will be sent to your email address. Click the link in the email to complete your account creation. If you haven’t received the confirmation email, check your Spam folder, and ensure that you can receive emails from no-reply@soracom.jp.

2. Register your Payment Information

As Soracom services are post-paid, a credit card is required in order to begin using services. While any fees from Soracom services will be billed to your credit card, your Starter Kit also includes $10.00, enough to cover service fees for this project for approximately 3 months. First, let’s get our payment information set up.

  • Click your email address at the top right corner, and select Payment settings:

  • Click New payment method, and enter your credit card information.

New payment method

Tip! If you have trouble adding your credit card, please try another card, or refer to the Additional Resources and Support section at the end of this guide in order to contact Soracom Support.

Your account is now set up! For reference, the following fees apply for this project:

  • Basic maintenance fee of $0.06 per day for the Soracom Global SIM card
  • Data usage fee of $0.073 per 1MB of cellular data used (upload and download)
  • Soracom Harvest fee of $0.05 per SIM card per day (first 30 days free)

 

You can suspend or terminate your Soracom SIM card, and disable Soracom Harvest at any time to stop fees associated with this project.

3. Apply your Soracom IoT Starter Kit Coupon

Next, let’s add the coupon that was included in the Starter Kit.

  • Click your email address at the top right corner, and select Manage coupons:

  • Then click Register coupon.

Register coupon

  • In the popup, enter the coupon code you received, and click Apply.

In the popup, enter the coupon code you received, and click Apply

We should now see our coupon balance reflected in our account. At the end of each month, any usage charges will be deducted from our coupon balance (once the balance is used up, charges will be billed to our credit card normally). Now we can continue with building our project—and also try other ideas—without having to worry about initial usage charges.

Your account is now set up! For reference, the following fees apply for this project:

  • Basic maintenance fee of $0.06 per day for the Soracom Global SIM card
  • Data usage fee of $0.073 per 1MB of cellular data used (upload and download)
  • Soracom Harvest fee of $0.05 per SIM card per day (first 30 days free)

 

You can suspend or terminate your Soracom SIM card, and disable Soracom Harvest at any time to stop fees associated with this project.

4. Register your Soracom Global SIM Card

Now that your Soracom account is set up, let’s register the Soracom Global SIM card that was included in this Starter Kit.

  • Click the Menu button at the top left corner, and select SIM Management.
  • Click Register SIM.

Register SIM

  • A dialog will appear asking for the ICCID and PUK of the SIM card. Enter the numbers printed on the back of the SIM card, leaving the Name and Group fields blank for now. Then click Register:

Register ICCID and PUK

  • Your SIM card will now appear in the list, and you can confirm it is Ready for cellular connections and currently Offline:

Your SIM card will now appear in the list

Tip! If you have trouble registering your SIM card, please refer to the Additional Resources and Support section at the end of this guide in order to contact Soracom Support.

Your SIM card is now ready for use! In addition to registering and managing Soracom SIM cards, the Soracom User Console gives you access to additional Soracom services, such as Soracom Beam and Soracom Lagoon.

Later, we will return to the User Console to configure Soracom Harvest for this project.

For more information on using the User Console, refer to the Additional Resources and Support section.

Setup your Raspberry Pi

Although the Raspberry Pi Zero includes a lot of powerful functionality, we need to set up basic connectivity so we can interact with it. While we can connect a monitor and keyboard to our Pi just like a normal computer, let’s get it connected to our Wifi network so we can connect to it and control it from our Mac or PC using SSH (Secure Shell).

1. Enable SSH and Configure your Wifi Network Settings

Raspberry Pi makes it easy to enable SSH and join a Wifi network without even using a monitor or keyboard. All we need to do is create a couple of files on the micro-SD card.

    • Carefully remove the micro-SD card that is installed in the Raspberry Pi Zero.

Carefully remove the micro-SD card

  • Insert the micro-SD card into the micro-SD card reader, then plug the card reader into your computer.

Insert the micro-SD card

Important! In some cases, your computer may ask if you want to format the micro-SD card. The micro-SD card is preloaded with Raspberry Pi software, so make sure that you do not format it.

  • Using your computer’s file explorer, open the micro-SD card drive (labelled BOOT).
  • Create an empty text file named ssh in the root directory.
  • Create another text file named wpa_supplicant.conf in the root directory, with the following text:

 

country=US
ctrl_interface=DIR=/var/run/wpa_supplicant
update_config=1

network={
ssid=”your_wifi_name”
psk=”your_wifi_password”
key_mgmt=WPA-PSK
scan_ssid=1
}

 

Make sure to edit the ssid= and psk= lines with the name and password of your Wifi network, making sure that you keep the double quotes ” “ surrounding the Wifi name and password

  • Eject the micro-SD card drive from your computer, and re-insert the card into the Raspberry Pi.

Eject the micro-SD card
By creating these two files, the Raspberry Pi will detect them when it boots up, and automatically connect to our Wifi network and enable SSH access.

2. Assemble the Raspberry Pi Case and Power On

  • Place the Raspberry Pi in the case, making sure the connectors line up with the precut holes. Press firmly until the Raspberry Pi clicks into the case.

Place the Raspberry Pi in the case

  • Place the cover on top, making sure the cut-out lines up with the Raspberry Pi’s GPIO pins, and press the two halves together until you hear and feel a light click.

Place the cover on top

  • Connect the Raspberry Pi to your computer or other USB power source using the included USB-A to Micro-USB cable. The Raspberry Pi will automatically turn on as soon as the cable is connected.

Attach USB cables

Setup the 3G USB Modem

Now that our Raspberry Pi is all set up, let’s get it connected to a cellular network using the 3G USB modem. We need to insert the Soracom Global SIM card into the USB modem, then configure the connection settings on the Raspberry Pi.

1. Insert the Soracom Global SIM Card

  • Gently detach the SIM card from the card package as shown below. Note that the card package allows you to detach the SIM card into three different sizes, to fit a variety of devices. As our USB modem uses the largest size, make sure to detach the largest size accordingly.

Gently detach the SIM card from the card package

  • Next, gently press and slide the cover on the USB modem to open the SIM card slot.

 

  • Insert your SIM card into the slot as shown below, making sure the angled corner of the SIM card is oriented correctly. When fully inserted, the Soracom logo should still be visible.

 

Insert your SIM card

  • Slide the cover back into place.
  • Connect the 3G USB modem to your Raspberry Pi using the USB OTG adapter cable.

 


Once the 3G USB modem is connected to our Raspberry Pi, its status light will blink green or blue as it searches for a cellular signal. Since we haven’t configured the cellular connection yet, it will continue to blink, so let’s set that up next.

2. Install and Configure the 3G USB Modem

In order to configure the cellular connection, we need to connect to the Raspberry Pi. As we mentioned before, we’re going to connect using SSH (Secure Shell).

SSH is a command line application. That means rather than using a graphical interface, we will enter some text commands to connect to and then control our Raspberry Pi.

In order to run SSH, we need to open a command line or terminal application. Each operating system’s command line is different, so let’s first check which one we will use:

  • For Mac users, search Spotlight for the Terminal app, then click to open it.
  • For Linux users, open your application drawer and open the Terminal app.
  • For Windows 10 users, click the Start Menu and search for Windows PowerShell, then click to open it.

 

For Windows 7 (and earlier) users, the default command line application does not support SSH. Please refer to the Additional Resources and Support section for more information.

With the command line application open, we just need to find our Raspberry Pi’s network address. Luckily, most modern operating systems allow us to use mDNS (multicast DNS) in order to automatically detect devices connected to our local network. Since we set up our Raspberry Pi to connected to our Wifi network, we can use raspberrypi.local as the network address, and our computer will automatically search for devices that match that address.

mDNS is built into Mac OS, many Linux distributions, and recent versions of Windows 10. Additionally, the raspberrypi.local address may not work if you have more than one Raspberry Pi device connected to your Wifi network. If you are using an older operating system without mDNS, or are unable to connect to your Raspberry Pi using the raspberrypi.local network address, please refer to the Additional Resources and Support section for alternative methods.

Now, let’s connect to our Raspberry Pi!

  • In your command line window, type the following command and press Enter:

ssh pi@raspberrypi.local

  • A message should appear asking for the Raspberry Pi’s password. Login using password: raspberry

pi@raspberrypi.local’s password: _

Note: As you type the password, no characters will be displayed. However, the password will still be entered, so just press Enter after you finish typing the password.

If everything went well, you should see a welcome message, with the following line at the bottom of your command window:

pi@raspberrypi:~ $ _

This is the Raspberry Pi’s command line input, and it means that you can now run commands directly on the Pi!

If you receive an error, or don’t see the command line input, please refer to the Additional Resources and Support section and contact Soracom Support for help connecting to your Raspberry Pi.

Tip! Any time you restart your Raspberry Pi or disconnect its power, the SSH connection will be lost. Once your Raspberry Pi is powered on again, simply follow the steps above again to reconnect.

Now that we’re connected to our Raspberry Pi, let’s configure the 3G USB modem.

  • Download and install the Soracom Starter Kit modem setup script:

pi@raspberrypi:~ $ sudo curl -O https://soracom-files.s3.amazonaws.com/starterkit/setup.sh

  • Next, modify the file properties so that we can run it:

pi@raspberrypi:~ $ sudo chmod +x setup.sh

  • Then all we have to do is run it, and the script will take care of everything else:

pi@raspberrypi:~ $ sudo ./setup.sh

The setup.sh script will first install some required packages and get our Raspberry Pi prepared. Once it’s ready, it will ask us to plug in our modem:

So, let’s plug it in!

Now, the script will finish configuring the modem, adding the Soracom cellular connection profile, and setting up a custom routing rule. We can check the progress of the script in our terminal window:

Since our modem (and Raspberry Pi!) is now connected to a cellular network, you might be wondering about data usage fees. Not to worry! The setup script has gone ahead and added a custom route, so that only data sent to the Soracom platform (such as to Soracom Harvest or Soracom Beam) will be sent using the cellular connection. As long as our Pi is also connected to Wifi, all other data will be sent using the Wifi connection.

If you would like to learn more about what the setup.sh script does, refer to Appendix section. This may be helpful if you want to modify the connection configuration, such as changing routing rule or customizing connection behavior.

If everything went well, congratulations—you’ve successfully completed the hard part! Now would be a great time to grab a cup of coffee and have a quick break!

Setup the Ultrasonic Range Finder

The HC-SR04 Ultrasonic Range Finder sensor uses sonar to determine distance to an object, much like a bat or dolphin. It offers excellent non-contact range detection with high accuracy and stable readings in an easy-to-use package.

These types of sensors are often used to measure the level of liquid in a tank, in smart trash cans that detect the level of trash, or even to check the presence of a car in a parking spot or car wash.

For this project, we’ll use it just to detect the distance of our hand from the sensor, and capture that data using Soracom Harvest.

Important! When connecting sensors and other devices to the Raspberry Pi, there is a risk of creating a short-circuit that may permanently damage your Raspberry Pi. Before continuing, disconnect your Raspberry Pi from its power source by unplugging the USB-A to Micro-USB cable.

  • Give the Pi a minute or so to complete its boot up procedure. Then, open your command line application and connect to the Pi using SSH just as before:

1. Connect the Sensor using the Breadboard

  • The Ultrasonic Range Finder has four pins. Carefully insert these pins into the included breadboard, making sure to follow the breadboard orientation indicated below:

Note that the exact location where the pins are inserted is not important. However, the sensor must be oriented correctly relative to the breadboard.

  • Next, insert the color-coded wires into the breadboard, sothat each wire is directly adjacent to one of the sensor pins. Use the following colors for the corresponding pin:


Note that each color-coded wires has a male end and a female end. Use the male end to connect to the breadboard.

  • Last, connect each of the wires to the Raspberry Pi GPIO pins, using the corresponding wire color:

Pin name - wire color

Graph
Note that pins 1 and 2 will be open (unconnected).

Because the Raspberry Pi is disconnected, there is no danger of creating a short-circuit. However, in general, it’s always good practice to connect the RED (power) wire last, so that you have a chance to check all wiring before turning your device on.


Note that pins 1 and 2 will be open (unconnected).

Because the Raspberry Pi is disconnected, there is no danger of creating a short-circuit. However, in general, it’s always good practice to connect the RED (power) wire last, so that you have a chance to check all wiring before turning your device on.

Now that we have everything wired up, let’s give it a test!
Now that we have everything wired up, let’s give it a test!

2. Test the Sensor

Let’s run a quick script to test that the sensor is connected properly, and that we can read data from it.

  • Plug the USB-A to Micro-USB cable back in to your computer or other USB power source to power on your Raspberry Pi again.

 

Important! Keep a close eye on your Raspberry Pi! If the ultrasonic sensor or Raspberry Pi feels hot, or if you smell smoke, disconnect the Raspberry Pi from the power source immediately. Then double-check your wiring before trying again.

  • Give the Pi a minute or so to complete its boot up procedure. Then, open your command line application and connect to the Pi using SSH just as before:

ssh pi@raspberrypi.local

  • Once we’re logged in, let’s download the following Python script:

pi@raspberrypi:~ $ curl -O https://soracom-files.s3.amazonaws.com/starterkit/hcsr04.py

  • And then let’s run the script using Python:

pi@raspberrypi:~ $ python hcsr04.py

  • If everything goes well, we should see some output similar to this:

 

Distance: 46.0 cm
Distance: 46.4 cm
Distance: 46.0 cm
Distance: 47.2 cm

We can wave our hand in front of the sensor to see the value change. Cool!

All that’s left is to modify this script to send the distance data to Soracom Harvest.

For now, let’s press Ctrl+C to stop the script.

Send Sensor Data to Soracom Harvest

While seeing the live sensor data with the test script is fun, it requires us to connect to our Raspberry Pi using SSH and manually running the script in order to see the data.

We can modify our script so that rather than outputting the distance data directly on the command line output, the data is sent to a server online. That way we can view the data, the same way we would view a typical website.

To accomplish this, we would normally have to set up our own server and configure it both to accept our data, and display the results on a webpage. While not uncommon, this is a relatively complicated process, involving services, firewalls, authentication, and more!

Fear not—Soracom Harvest to the rescue!

SORACOM Harvest
Soracom Harvest is a simple service that lets you capture data from your device and quickly visualize the data directly from the Soracom User Console, all without needing to set up any servers!

Harvest accepts data using a variety of common protocols (HTTP, TCP, UDP, and more!), which allows developers to quickly build proof-of-concepts in order to capture device data right away and confirm that their projects are working as intended.

Let’s enable Harvest for our project, then update our script to start sending data!

1. Enable Soracom Harvest

We’ll head back to the Soracom User Console in order to enable Soracom Harvest.

Many services, including Harvest, are linked to groups. Groups let us manage multiple SIM cards together. When we enable Harvest for a particular group, all of the devices (SIM cards) that belong to that group will automatically be able to use Harvest. That way we can easily add more devices to the group without having to enable Harvest for each individual device. Neat!

Let’s first create a group for our SIM card:

  • If you’re not already logged in, open https://console.soracom.io again and login using your email address and password.
  • From the list of SIM cards in your account, click the checkbox next to your SIM card.
  • Then click the Actions menu, and select Change group.

Click the Actions menu, and select Change group

    • We don’t have any groups yet, so let’s create one. Click the dropdown menu, and select Create….

Create a group

    • In the popup, give the group a name, such as Harvest Group, then click Create.

Create group

  • Our group has been created. Now let’s click Update to set our new group for our SIM card.

Update Group
Next, let’s enable Soracom Harvest for our new group:

  • Click the name of the group underneath the Group column. This will open the group configuration page.

  • Click the SORACOM Harvest panel to expand Harvest settings.

Group Settings

  • Click the toggle switch to turn Harvest ON, then click Save.

Harvest settings
All done!

2. Send Test Data to Soracom Harvest

Before we start sending our sensor data, let’s quickly check that Harvest will receive data from our Raspberry Pi.

  • Back in our command line window (connected to our Raspberry Pi using SSH), run:

pi@raspberrypi:~ $ curl -v -d “Hello Harvest!” http://harvest.soracom.io

When we run the command, we should see some output that looks like this:

* Hostname was NOT found in DNS cache
* Trying 100.127.111.111…
* Connected to harvest.soracom.io (100.127.111.111) port 80 (#0)
> POST / HTTP/1.1
> User-Agent: curl/7.38.0
> Host: harvest.soracom.io
> Accept: */*
> Content-Length: 14
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 14 out of 14 bytes
< HTTP/1.1 201 Created
< Date: Tue, 09 May 2017 15:55:55 GMT
< Server: nginx/1.6.2
< Content-Length: 0
< Connection: Close
<
* Closing connection 0

What we want to check is the line < HTTP/1.1 201 Created. The 201 code is sent back from Soracom Harvest, and tells us that our data was successfully sent!

Let’s head back to the User Console and open up Harvest to see our data:

    • Click the Menu button, and select SIM Management.

 

  • Click the checkbox next to your SIM card. Then click the Actions menu, and select Harvest data.

Harvesta data

  • Scroll down to the bottom of the page to see the raw data. Our test message should be there!

 

Harvest test data

3. Send Sensor Data to Soracom Harvest

Now that we’ve confirmed that we can send data from our Raspberry Pi to Soracom Harvest, we can update our script to send data to the cloud.

In the last step, we used the curl command, which sent our test message to Harvest in the form of an HTTP request directly from the command line. We want to keep the HTTP request format (just replacing the test message with sensor data), but since our script is a Python script, we need to install a package that lets us make HTTP requests from within Python.

  • Run the following command to install the python-requests package:

pi@raspberrypi:~ $ sudo apt-get install python-requests

Then, let’s download a modified version of our sensor script, which also sends the sensor data to Harvest.

  • Run the following command to download the modified sensor script:

 

pi@raspberrypi:~ $ curl -O
https://soracom-files.s3.amazonaws.com/starterkit/ultrasonic_harvest.py

 

  • Start the script:

pi@raspberrypi:~ $ python ultrasonic_harvest.py

While the script runs, we should see some output that looks like this:

Distance: 45.8 cm
Sending data {“distance”:45.8} to Harvest…
Response 201: Success!

Distance: 46.2 cm
distance: 46.2 cm
Sending data {“distance”:46.2} to Harvest…
Response 201: Success!

From the output, we can see that the sensor is functioning correctly, and that our data is being sent to Harvest successfully!

4. Visualize Sensor Data from the User Console

Our modified script is sending the numerical sensor data to Harvest using a simple format that allows Harvest to generate real-time graphs. As soon as Harvest sees the numerical data, it will automatically generate a graph for us!

Let’s turn on the Auto refresh option, which will tell Harvest to check for new data every 5 seconds and update the graph.

Auto refresh
Now we can wave our hand in front of the sensor to generate new data points, and our Harvest chart will automatically update with the latest data! Awesome!

Now that you’ve made it here, congratulations! You’ve completed the Ultrasonic Range Finder project!

Since our Raspberry Pi is sending data to Soracom Harvest using the 3G USB modem, we can now set up our distance-detecting device just about anywhere (as long as there’s a USB power source and a cellular signal), and see the data from the comfort of the Soracom User Console.

With a few tweaks and some clever modifications, we can easily start expanding our device’s capabilities to build another project!

Extra Project Recipes

 

Editing Scripts on the Raspberry Pi

If you haven’t edited scripts on a command line interface before, not to worry! After learning a few commands and shortcuts, you’ll be on your way to coding in no time.

Since we can easily connect to the Raspberry Pi using SSH, we can use a command line text editor to edit files directly on the Raspberry Pi without having to disconnect and remove the micro-SD card each time.

There are lots of command line text editors available for the Raspberry Pi, but for beginners, one of the most popular is nano, which comes pre-installed. Here are a few quick tips:

  • To open a file, simply type nano path/to/myfile.py .
  • If you are in the same directory as the file, you can just type nano myfile.py .
  • After you’re done editing your file, save it by pressing Ctrl+X to exit nano, Y to save changes to your file, and Enter to keep the same filename.
  • Some files are protected by the operating system, and require root privileges to edit, such as files within the /etc directory. To edit them, simply add sudo when opening the file.

 

There are plenty of great tutorials and articles on how to use nano, be sure to search online for additional tips and tricks.

 

Running a Script when the Raspberry Pi boots up

Since the Raspberry Pi operating system is based on Linux, we get access to many different ways to configure the device behavior. One of the easiest ways to start a script is to edit the /etc/rc.local file to include our script file. For our ultrasonic_harvest.py script, the process looks like this:

Open /etc/rc.local. Since it’s a protected file, we need to use sudo:

pi@raspberrypi:~ $ sudo nano /etc/rc.local

Add the following line to the file:

python /home/pi/ultrasonic_harvest.py &

Previously, we could just run our script with python ultrasonic_harvest.py because we were already in the same directory as our script file. Since the Raspberry Pi won’t be in any folder when it boots up, we need to specify the /home/pi/ path here. Additionally, the & tells the Pi to run the script in its own process, since the script will loop continuously. That way, the script can continue to run without blocking anything else.

Then, just Ctrl+X , Y , and Enter to save the file and close nano.

If you want to run a shell script, or a script using another language besides Python, you’ll need to modify the line appropriately. Be sure to check online for examples of how to configure /etc/rc.local for other scripts.

 

Running a Script at regular intervals

Sometimes, we might want an extended interval in between telling our Raspberry Pi to do something. We could always add a delay to our script to have it pause for an hour (or any other interval) before looping again, but this would cause our script to idle in the background, and in some cases might use more power.

Instead, it would be more efficient to run the script only once. Then later, after a given duration, run the script again.

In Linux, this type of behavior is easily handled using cronjobs. With cronjobs, we can tell the Raspberry Pi to run a script at specific intervals, which can be defined by minute or hour intervals, on specific days of the week or days of the month, and on specific months.

For information on configuring a cronjob, take a look at the official Raspberry Pi example: https://www.raspberrypi.org/documentation/linux/usage/cron.md

If we had a Python script that we wanted to run once every 30 minutes, we would create a cronjob that looked something like this:

*/30 * * * * python /home/pi/my_30min_script.py

Just as with rc.local, be sure to check online for additional examples if you want to schedule other types of scripts using cronjobs.

Also, be sure to check www.crontab.guru to check how your cronjob should be written for other intervals.

 

Running Scripts when the 3G USB Modem connects/disconnects

In some cases, we only want our scripts to run when our cellular connection is connected (or disconnected). For example, we might want to set up our device to collect data while it’s offline using one script, and then run a second script to send the collected data once the modem has connected to a cellular network.

When we initially configured our 3G USB modem using the setup.sh script, the script installed a program called NetworkManager which helps us manage our cellular connection. NetworkManager comes with the ability to perform actions whenever a connection status changes (and in fact, many Linux programs offer similar event-driven functionality), so we can hook into it to run an upload script when the 3G USB modem is connected.

In fact, the setup.sh script we used earlier uses this feature to create and remove a custom data routing rule whenever the 3G USB modem connects/disconnects, to ensure that data sent to the Soracom platform is sent using the 3G USB modem.

Have a look at the custom routing script in nano:

pi@raspberrypi:~ $ nano /etc/NetworkManager/dispatcher.d/90.soracom_route

Our script simply checks which connection changed (ppp0 for the 3G USB modem), and whether the new status is up or down. Then it creates/removes our custom routing rule.

With some simple modifications, we can create another rule in the same folder to run a script whenever the ppp0 connection is connected. First, Ctrl+X to close the custom route rule script. Then, let’s start a new script in the same folder:

pi@raspberrypi:~ $ sudo nano /etc/NetworkManager/dispatcher.d/99.my_custom_rule

#!/bin/bash

if [ “$1” == “ppp0” ]
then
case “$2” in
up)
python /home/pi/upload.py
;;
*)
;;
esac
fi

Then Ctrl+X, Y, and Enter to save the file, and then run this command to make it executable:

pi@raspberrypi:~ $ sudo chmod +x /etc/NetworkManager/dispatcher.d/99.my_custom_rule

Our script is now set up. The next time the ppp0 connection changes, NetworkManager will run our rule, and if the ppp0 connection is connected (up), it will in turn run our upload.py script.

Combining this with cronjobs above, we could create a third script that enables our cellular connection at regular intervals, which would in turn run our upload.py script. Then we can also add some extra code to our upload.py script to disconnect the cellular connection once the upload is complete. That way our cellular connection is enabled only at the intervals we want. Scripts running scripts!

 

Run a Script by sending an SMS to the Raspberry Pi

When our Raspberry Pi is deployed in a remote area, we won’t have a Wifi connection to use in order to connect to it using SSH. While auto-starting scripts on boot with rc.local or running scripts at regular intervals with cronjobs work for certain actions, sometimes we just want an easy way to run a script on-demand.

Because our Soracom Global SIM supports SMS, we can take advantage of the functionality to control the Raspberry Pi by simply sending text messages right from the User Console.

NetworkManager, the program that we’re using to manage our cellular connection, includes another program called ModemManager, which gives us some commands to send and receive SMS. All we need to do is run the appropriate command to check for new messages.

Since we probably want ModemManager to automatically check for us, we can either run this command in a loop, or combine it with a cronjob so that the command runs automatically at regular intervals.

We’ve put together a sample script that you can use to quickly test receiving an SMS:

  • Download the following script:

 

pi@raspberrypi:~$ curl -O https://soracom-files.s3.amazonaws.com/starterkit/checksms.sh

  • Make it executable:

 

pi@raspberrypi:~$ chmod +x checksms.sh

  • Then add a new cronjob:

 

pi@raspberrypi:~$ sudo crontab -e

 

***** /home/pi/checksms.sh

 

We’ll set up this cronjob to run once every minute. Save and exit.

  • Last, reload the cron service:

 

pi@raspberrypi:~ $ sudo service cron reload

 

Each time this script runs, it does a few things. First, it gets the ID number of our modem, and uses it to check if there are any messages. If it finds a message, it extracts the text message content and logs it to a  soracom_status.log  file in our home directory.

We can monitor this log file by running the command  tail -f soracom_status.log . To send the actual text message, we just need to open the User Console, select the SIM card of our device, and click Actions > Send SMS. Make sure to change the Encoding to GSM7 (plain text). Then type the message, and send! Once the SMS arrives on our device, the message will show up in our log file.

Last, the script checks the text message content. If it matches some sample values, our script will run some additional commands:

  • Texting  up  will connect our modem
  • Texting  down  will disconnect our modem
  • Texting  shutdown  will turn off our Raspberry Pi

Now we can customize the checksms.sh script to add more commands which we can then execute just by sending an SMS to our device!

 

Want more ideas?

We’ve only touched the tip of the iceberg with these quick recipes. Be sure to check out the Soracom developer community for more project ideas and sample code. And remember, the Raspberry Pi is quite a powerful little device, so be sure to look around online for all the different things you can do in Linux!

Additional Soracom Services

General Services

Soracom Beam
Soracom Funnel
Soracom Harvest
Soracom Lagoon

Intermediate/Advanced Security Services

Soracom Endorse
Soracom Krypton

Intermediate/Advanced Networking Services

Soracom Canal, Door, and Direct
Soracom Gate
Soracom Junction

Also the right section to e.g. link to the PubNub smart parking blog as an example of what you might do with an ultrasonic sensor

Appendix

 

I can’t connect using raspberrypi.local. What should I do?

The raspberrypi.local network address uses mDNS (multicast DNS) feature found on most modern operating systems, and works by scanning your local network for devices that match the raspberrypi hostname. If your computer has trouble detecting your Raspberry Pi, SSH will give you an error saying that it was unable to resolve the hostname.

This typically occurs because mDNS has not been installed or enabled on your computer. On Mac OS, modern Linux distributions, and the latest versions of Windows 10, mDNS should be pre-installed on your computer. However, if you are using an older operating system, you can install mDNS to allow your computer to detect your Raspbery Pi:

  • On Mac: mDNS is included by default.
  • On Linux: Use your package manager to search for and install the avahi package, then restart your computer.
  • On Windows: There are several mDNS installation options available. The easiest is to install the Apple Print Services, which includes mDNS: https://support.apple.com/kb/DL999

 

In some cases, your computer may not be able to detect your Raspberry Pi due to certain network configurations. You can use your Raspberry Pi’s IP address instead, however finding the IP address takes a few extra steps.

Usually, the most straightforward way to find the IP address is to use your Wifi router’s management page. The management page is typically access by opening http://192.168.1.1 or a similar address in your browser, and logging in using the Wifi router’s login information. From there, you should be able to view a list of connected devices, one of which will be the Raspberry Pi. Make a note of the IP address.

If you are unable to find the IP address using your Wifi router’s management page, you can also connect your Raspberry Pi to an external monitor by using a mini-HDMI to HDMI adapter or cable. As the Raspberry Pi boots, it will display information about the startup process. Once it completes booting, it should display a message saying, My IP address is: … .

Once you have found your Raspberry Pi’s IP address, you can connect using SSH by using the IP address (replacing the numbers below with the IP address of your Raspberry Pi):

ssh pi@192.168.1.123

Once connected, you can continue your project as normal.

Keep in mind, while most Wifi routers will try to use the same IP address each time your Raspberry Pi is restarted, there may be times when the IP address changes. If you are unable to connect, repeat the steps above to check if your Raspberry Pi’s IP address has changed.

 

My computer doesn’t have SSH. What should I do?

While Mac OS and Linux include the SSH command line tool, certain versions of Windows do not include SSH.

There are many great (and free!) SSH tools, and one of the most widely used is PuTTY, which you can find at: www.putty.org. Click the download link, and download the putty.exe file (in most cases, the 32-bit version works just fine). Then just run the putty.exe application.

When using PuTTY, the initial connection step is a little different. Unlike running the ssh pi@raspberrypi.local command from your command line program, you will need to enter the following connection settings:

  • Hostname or IP address: raspberrypi.local or your Raspberry Pi’s IP address
  • Port: 22
  • Connection type: SSH

When you click Open, a new window will open. Once PuTTY connects to your Raspberry Pi, you will be asked to enter your username. Use pi as your username. Then continue logging in using the password raspberry from the instructions in this guide.

 

How do I restore/reset my Raspberry Pi?

If you want to give your Raspberry Pi a fresh start, or if you want to use an extra micro-SD card to test various projects, you can format and reinstall the Raspberry Pi operating system.

First, head over to the Raspberry Pi official website, and download the latest version of Raspbian Stretch Lite: www.raspberrypi.org/downloads/raspbian

You can also download the Desktop version, if you would like to have a traditional desktop interface when working on the Pi. As our Raspberry Pi projects will be headless when deployed (no monitor or keyboard), we generally opt for the lighter Lite version.

Once the file finishes downloading, unzip it. You should have a .img file which is approximately 1.7GB in size.

To install Raspbian to your micro-SD card, you will need to use an image flashing program. There are multiple programs available, and the program we recommend is Etcher. Download and install the latest version from here: www.balena.io/etcher

Then, insert your micro-SD card into your computer using the included micro-SD card reader, start the Etcher application, and select the Raspbian .img file. Make sure that you have selected the drive that that corresponds to the micro-SD card, as the flashing process will delete all data on the drive. Then click Flash.

After a few minutes, your micro-SD card will have a fresh copy of Raspbian.

Because this new copy will not have any software installed, you will also need to add the ssh and wpa_supplicant.conf files to get connected, and re-download and re-run the setup.sh script to get your modem set up.

 

What does the setup.sh script do?

In order to simplify the 3G USB modem setup process, we’ve create a simple Linux script that automatically installs the required packages and configures the modem, cellular connection, and routing to Soracom platform services.

When you run the setup.sh script, it performs the following actions:

1. Install required packages:

  • network-manager – This program helps with managing various network connections, including the cellular connection to Soracom.
  • usb-modeswitch – In some cases, Linux will treat the 3G USB modem as a storage device rather than as a modem. This program switches the mode back to modem mode.

To install these packages manually, simply run:

pi@raspberrypi:~ $ sudo apt-get update
pi@raspberrypi:~ $ sudo apt-get install usb-modeswitch network-manager

2. Configure the modem:
The script will check if the modem was attached in storage mode, and if so it will run the following command:

pi@raspberrypi:~ $ sudo usb_modeswitch -v 12d1 -p 14fe -J

The -v 12d1 parameter will match Huawei devices, and the -p 14fe parameter matches Huawei devices that were attached in storage mode. Last, setting the -J parameter will tell Linux to reattach the modem in modem mode.

Additional Resources and Support

Let’s use this section to consolidate relevant Community, GitHub, and Dev Site links and provide Support info as last resort.