Sensor21: Earn bitcoin by collecting environmental data

Posted by Tyler Pate

Sensor21: Earn bitcoin by collecting environmental data


In this tutorial we are going to show you how to use bitcoin and the 21 software to buy and sell data from a distributed grid of sensors. The diagram below shows how this application (which we call sensor21) uses micropayments to gather data from a distributed sensor network to measure barometric pressure and temperature from multiple locations:

alt text

To buy sensor readings, all you need is the 21 client and some bitcoin. To sell sensor readings, however, you will need to set up physical hardware capable of collecting sensor data.

We demonstrate both steps in this tutorial, beginning by installing 21 and then buying readings from the sensor21 endpoint at We will then walk through setting up your own sensor21 endpoint on a 21 Bitcoin Computer or a DIY 21 Bitcoin Computer to sell your data for bitcoin. Finally, we'll go through some troubleshooting steps to help debug your hardware.

Buy sensor data for bitcoin

After installing 21, you can buy readings from the sensor21 aggregator using the 21 buy command. In this example, we pay five machines in San Francisco for their most recent barometric pressure readings. We pay 20 satoshis per request per sensor, for a total of 100 satoshis.

$ 21 buy --data '{"n": 5, "sensor": "barometricpressure", "city": "San Francisco"}'

## Output
## {
##  "sensor_type": "barometricpressure", 
##  "city": "San Francisco", 
##  "readings": [
##    {"timestamp": "2016-05-17T19:55:52.429Z", "sensor_id": "<hash>", "reading": 101434.0}, 
##    {"timestamp": "2016-05-17T19:55:52.478Z", "sensor_id": "<hash>", "reading": 100737.5},
##    ...
##  ]
## }

As shown, the command takes in the service you want to purchase (sensor21) and the POST data specifies the type of sensor you want to gather data from, as well as the number of sensors and the city you want data about. The buy command then hits an endpoint in the 21 marketplace and returns a JSON array of sensor data from active Sensor21 servers.

Note that you can also use the following shortcut command, which omits the prefix:

$ 21 buy 21dotco/sensor21_aggregator/sensor21 --data '{"n": 5, "sensor": "barometricpressure", "city": "San Francisco"}'

You can also see which cities have active sensors by querying the 21dotco/sensor21_aggregator/sensor21/info endpoint (for free), as shown:

$ 21 buy 21dotco/sensor21_aggregator/sensor21/info

## Output:
## {
##   "info": [
##     {
##        "sensors": {
##            "TEMPERATURE": {"num_active_endpoints": 1, "price_to_buy_active_endpoints": 20}, 
##            "BAROMETRICPRESSURE": {"num_active_endpoints": 1, "price_to_buy_active_endpoints": 20}
##        }, 
##        "city": "London"
##     }, 
##     {
##        "sensors": {
##            "TEMPERATURE": {"num_active_endpoints": 3, "price_to_buy_active_endpoints": 60}, 
##            "BAROMETRICPRESSURE": {"num_active_endpoints": 3, "price_to_buy_active_endpoints": 60}
##        }, 
##        "city": "Chicago"
##     }, 
##     {
##        "sensors": {
##            "TEMPERATURE": {"num_active_endpoints": 2, "price_to_buy_active_endpoints": 40}, 
##            "BAROMETRICPRESSURE": {"num_active_endpoints": 2, "price_to_buy_active_endpoints": 40}
##        }, 
##        "city": "Tokyo"
##     },
##     ...
##   ]
## }

Sell sensor data for bitcoin


To sell sensor data for bitcoin you will need the following:

You can click the links above to order each item. The materials will take a few days to ship to your location.

Set up your sensor

Once you've got the materials, let's go through the process of setting up a sensor and connecting it to your Bitcoin Computer. The MPL3115A2 breakout board and jumper wires will be used to add a hardware temperature and pressure sensor to your 21 Bitcoin Computer or DIY 21 Bitcoin Computer.

Connecting the sensor to a 21 Bitcoin Computer

If you have bought a 21 Bitcoin Computer, use the female to female jumper wires to connect the breakout board to the 21 Bitcoin Computer's expansion header. See the pin associations and connection diagram below.

  • VCC_3V3 -> Vin
  • GND -> GND
  • SDA -> GPIO6
  • SCL -> GPIO13

21 Bitcoin Computer + MPL3115A2 Connection Diagram

Connecting the sensor to a DIY 21 Bitcoin Computer If you have

If you have instead set up a DIY 21 Bitcoin Computer on a Raspberry Pi, we will use the female to female jumper wires to connect the MPL3115A2 breakout board to the Raspberry Pi expansion header. See the pin associations and connection diagram below.

  • VCC_3V3 -> 3V3 (Pin 01)
  • GND -> GND (Pin 06)
  • SDA -> SDA (Pin 03)
  • SCL -> SCL (Pin 05)

Raspberry Pi + MPL3115A2 Connection Diagram

Setting up the protective enclosure

After you have connected the MPL3115A2 board to your Bitcoin Computer or DIY Bitcoin Computer, you can put the entire thing inside a protective enclosure as shown:

MPL3115A2 3D Case Rendering

As noted above, you can print this enclosure at Shapeways or use this STL file to 3D print your own.

Step 1: Set up your sensor21 endpoint

Next, let's set up the sensor21 endpoint.

As a first step, if you are using a DIY 21 Bitcoin Computer, you must have the I2C kernel module enabled. Follow the directions in the code below to enable it:

# Enable I2C Kernel Module for DIY 21 Bitcoin Computer Users
sudo raspi-config

# Navigate to Advanced Options
# Navigate to I2C
# Enable I2C & Force I2C Module loading on startup
# Choose to reboot your machine now

Next, we are going to clone the sensor21 repository and run the install script. Do this by running the following commands:

cd ~/

# Install git to clone the Sensor21 code
sudo apt-get install git

# git clone the code
git clone

# run the setup script
cd sensor21

The setup script will install required software packages: unzip, PIGPIO, SQLite3, python3-pip, python-periphery, and flask. Then it runs, which creates a database and initializes it. Finally, it sets up a cron job (in cron.txt) to query the sensor every minute. The measured data is inserted into a database table called Barometer.

Here's the output from a successful install on a DIY 21 Bitcoin Computer.

Setup script successful install

Step 2: Start selling your sensor21 readings

At this point you have the hardware sensor set up and the software to read and store recordings. We can now start the sensor21 server and publish our endpoint, so that others can buy sensor readings from us in aggregate. Start the server by running the following command:

cd ~/sensor21
python3 -d

Now publish your endpoint to the marketplace using the manifest you created when you ran earlier. Substitute your own name and email in the publish command. For more information about publishing new endpoints in the marketplace, please read the 21 marketplace documentation.

21 publish submit manifest.yaml -p 'name="Joe Smith" email="" price="5" host="AUTO" port="5002"'

You can verify that your Sensor21 endpoint is part of the aggregator pool by testing the /verify endpoint:

# grab your ZeroTier IP address and save it to shell variable ZT_IP
ZT_IP=$(ifconfig | grep -A2 zt | grep inet | sed 's|[^0-9. ]||g' | sed 's|[^ \t]*||' | awk 'NR==1{print $1}')

# verify your endpoint is part of the pool

Note that if you shut down your 21 Bitcoin Computer or turn off the flask server, the server will no longer be accessible. To re-start the server, navigate to the sensor21 directory, and re-run python3 -d in the terminal.

How the sensor works

The sensor21 example uses temperature and pressure sensors from the MPL3115A2 board. However, there are a number of other sensor types you might want to use to generate machine-buyable data. While there are many similarities in approach, each sensor manufacturer approaches communication, data capture, and data transmission differently. We will describe how sensor21 works so that you can apply the same concepts to another device.

System administration (

The bash script (view it here) helps manage the processes related to sensor21. Run with the function you want to execute as the argument.

cd ~/sensor21
source <function>

## function list
# Note: pigpiod is only used for software I2C (used on 21 Bitcoin Computer)
# start_pigpiod, stop_pigpiod, restart_pigpiod
# start_server, stop_server, restart_server
# start_cron_job, stop_cron_job

# Example
source stop_server

As an example, before you can use python to directly access the sensor board, you will need to stop the cron job that is making sensor measurements. The script contains multiple functions to help with managing this sensor21 setup.

source stop_cron_job

When you are done, you can reinstate the cron job as follows:

source start_cron_job

Software and hardware I2C (, python-periphery, pigpio)

The file ( view it here) implements hardware and software I2C and contains a driver to enable, configure, and measure data from the barometric pressure sensor. I2C can be implemented either by using metal-level features of a processor, or by using GPIO pins and internal timers to replicate the metal-level implementation in software. For DIY Bitcoin Computer users, we use python-periphery to access hardware I2C through python. For 21 Bitcoin Computer users, we use software I2C to set up 2 GPIO pins as I2C Clock and Data lines. Software I2C is also referred to as ‘bit banging’.

Python-periphery, a python module for the Raspberry Pi, enables hardware I2C access in userspace Linux. Learn more about python-periphery here.

PIGPIO, a C library for the Raspberry Pi, gives us a python interface to access software I2C. It provides access to both hardware and software communication protocols (Serial, SPI, and I2C). Learn more about PIGPIO here and here.

You can programmatically access the sensor using commands like the following:

import mpl3115a2
pressure = mpl3115a2.PressureAPI()

Datastore (

The file (view it here) is a helper script which provides python functions for interacting with a SQLite database. This script helps set up the database tables, append a new sensor reading to the next row, and read data from the tables.

Because the I2C bus is not equipped to handle multiple users attempting simultaneous access, it is important to separate the low-level I2C process from server requests with a database and cron job. If each server request instead resulted in an I2C operation, there would be issues when multiple users made overlapping calls. By storing the readings in a database, we eliminate this problem, and we allow a client to request one or more readings in a single request. contains the python script needed to update the database, and cron.txt is a cron file used to run the script every minute.

Web service (

The script (view it here) starts a flask server that provides a sensor21 endpoint. When queried, the server requests a payment and then provides the requested sensor readings. It also implements a server_status route which checks to see whether a sensor reading has been written to the database within the last five minutes.


If you're relatively new to hardware hacking, it can be a little confusing at first to learn how to debug issues. If you can't read data from the sensor board, there are a few things to try.

If you are getting I2C related errors on a DIY 21 Bitcoin Computer, ensure that I2C is enabled on your Raspberry Pi:

sudo raspi-config

# Navigate to Advanced Options
# Navigate to I2C
# Enable I2C & Force I2C Module loading on startup
# Choose to reboot your machine now

If you are getting PIGPIO related errors on a 21 Bitcoin Computer, restart the pigpio daemon:

cd ~/sensor21
source restart_pigpiod

And if you are getting error codes or do not see sensor output during the setup script, try these steps in the following order:

  • Make sure that the pins are connected according to the connection diagram you used during setup.
  • Power cycle the MPL3115A2 by removing the Vcc jumper wire and then re-connect.
  • Perform a system reboot: sudo reboot now.
  • Then perform a MPL3115A2 software reset as shown:
// Software Reset
import mpl3115a2 as mpl
p = mpl.PressureAPI()

If you encounter other issues, please join our public Slack group at and we will try to help!

Next Steps

In this tutorial you learned how to buy and sell bitcoin-incentivized distributed data sets through sensor21. We hope this tutorial will inspire and help guide you to develop your own bitcoin-payable hardware applications. Come discuss your hardware ideas with other developers in our #iot channel on Slack!

How to send your Bitcoin to the Blockchain

Just as a reminder, you can send bitcoin mined or earned in your balance to the blockchain at any time by running 21 flush . A transaction will be created within 10 minutes, and you can view the transaction id with 21 log. Once the transaction has been confirmed, you can check the balance in your bitcoin wallet from the command line with wallet balance, and you can send bitcoin from your wallet to another address with wallet sendto $BITCOIN_ADDRESS --satoshis $SATOSHI_AMOUNT --use-unconfirmed. The --satoshis flag allows you to specify the amount in satoshis; without it the sendto amount is in BTC, but this behavior is deprecated and will be removed soon. The --use-unconfirmed flag ensures that you can send even if you have unconfirmed transactions in your wallet.

Ready to sell your endpoint? Go to

Ready to try out your bitcoin-payable server in the wild? Or simply want to browse and purchase from other bitcoin-enabled servers? Head over to the 21 Developer Community at to join the bitcoin machine-payable marketplace hosted on the 21 peer-to-peer network.