Neal Singer
Created August 3, 2020 © GPL3+

Breathe Easy: Measuring Air Quality in Our Lives

Pandemic-related shutdowns mean fewer vehicles are on the road. Using IoT, we can measure the effect of cars on urban air-quality.

AdvancedShowcase (no instructions)10 hours44

Things used in this project

Hardware components

MCCI Catena 4610
This microcontroller devboard provides the logic and wireless connectivity.
×1
Amphenol U.FL to SMA Adapter
This adapter allows you to connect an SMA antenna to the Catena 4610.
×1
Sensirion SPS30
This is a particulate matter sensor.
×1
916 MHz SMA Antenna
This antenna is suitable for the Helium LPWAN network in North America.
×1
ZHR-5 Connector Housing
×1
Pre-crimped Wire Terminal for ZHR-5 Housing
×5
Plastic Food Container with Lid
×1
USB-A to Micro-USB Cable
USB-A to Micro-USB Cable
×1
Generic USB Charger (500 mA or Greater)
×1

Hand tools and fabrication machines

Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free
Drill / Driver, 20V
Drill / Driver, 20V
1/4 in. Drill Bit
Silicone Conformal Coating

Story

Read more

Schematics

Sensor Schematic

This is a schematic showing the connections between the Catena 4610 and the SPS30.

Please note that pins are not numbered on the Catena board, therefore signal names are used instead.

Helpful Connection Guide

This picture shows where wires were soldered on the Catena 4610, in order to easily connect to the SPS30.

Code

Catena and SPS30 Firmware

Arduino
This is an Arduino program designed to work with the MCCI Catena 4610 development board and Sensirion SPS30 particulate matter sensor.

In order to compile and run, you will need to insert your own Helium App EUI, Dev EUI, and App Key into their respective variables in this code listing.

This program reads data from the SPS30, connected to the I2C port of the Catena board. It formats the data as JSON and places it in a packet for transmission to the Helium Network.

For full details and help installing Arduino libraries, see: https://nealsinger.com/posts/Getting%20an%20SPS30%20working%20with%20the%20Catena%204610/post.html
/*******************************************************************************
 * Copyright (c) 2015 Thomas Telkamp and Matthijs Kooijman
 * Copyright (c) 2018 Terry Moore, MCCI
 * Copyright (c) 2020 Neal Singer

 * Permission is hereby granted, free of charge, to anyone
 * obtaining a copy of this document and accompanying files,
 * to do whatever they want with them without any restriction,
 * including, but not limited to, copying, modification and redistribution.
 * NO WARRANTY OF ANY KIND IS PROVIDED.
 *
 * This example sends a valid LoRaWAN packet with payload "Hello,
 * world!", using frequency and encryption settings matching those of
 * the The Things Network. It's pre-configured for the Adafruit
 * Feather M0 LoRa.
 *
 *******************************************************************************/

/*******************************************************************************
 *
 * For Helium developers, follow the Arduino Quickstart guide:
 * https://developer.helium.com/device/arduino-quickstart
 * TLDR: register your device on the console:
 * https://console.helium.com/devices
 *
 * The App EUI (as lsb) and App Key (as msb) get inserted below.
 *
 *******************************************************************************/

#include <SPI.h>
#include <arduino_lmic.h>
#include <arduino_lmic_hal_boards.h>
#include <arduino_lmic_hal_configuration.h>
#include <arduino_lmic_lorawan_compliance.h>
#include <arduino_lmic_user_configuration.h>
#include <hal/hal.h>
#include <lmic.h>

#include <sps30.h>

//String sensor_name = "{\"sensor_name\": \"sensor2\", ";
String sensor_tags = "{\"sensor_name\": \"sensor2\", \"location\": \"Home_interior\", ";

// Arduino sketch, based partly on 
// https://github.com/Sensirion/embedded-sps/blob/master/sps30-i2c/sps30_example_usage.c

bool enable_printing = true;

template<class T>
void toggleable_print(T param) {
  //https://forum.arduino.cc/index.php?topic=473031.15
  if(enable_printing) {
    //Serial.println(param);
  }
  return;
}


String print_float(float f, int num_digits) {
    //adapted from https://phanderson.com/arduino/arduino_display.html
    //takes a float and turns it into a string.
    //we use this because calling String() on a float truncates leading zeroes on the decimal part, e.g.
    //String(10.08) returns "10.8," and that's bad.
    
    //NOTE: This implementation appears to produce a "round-down" effect,
    //where e.g. a measurement of 8.08 will become a string value of 8.07.
    
    String parsed_float = String();

    int f_int;
    int pows_of_ten[4] = {1, 10, 100, 1000};
    int multiplier, whole, fract, d, n;

    multiplier = pows_of_ten[num_digits];
    if (f < 0.0)
    {
        f = -f;
        parsed_float += "-";
    }
    whole = (int) f;
    fract = (int) (multiplier * (f - (float)whole));

    parsed_float += whole;
    parsed_float += ".";

    for (n=num_digits-1; n>=0; n--) // print each digit with no leading zero suppression
    {
         d = fract / pows_of_ten[n];
         parsed_float += d;
         fract = fract % pows_of_ten[n];
    }
    return parsed_float;
}

void sps30_setup() {
  int16_t ret;
  uint8_t auto_clean_days = 1;

  delay(2000);

  sensirion_i2c_init();

  while (sps30_probe() != 0) {
    //Serial.print("SPS sensor probing failed\n");
    delay(500);
  }

  //Serial.println("SPS sensor probing successful");

  ret = sps30_set_fan_auto_cleaning_interval_days(auto_clean_days);
  if (ret) {
    //Serial.print("error setting the auto-clean interval: ");
    //Serial.println(ret);
  }

  ret = sps30_start_measurement();
  if (ret < 0) {
    //Serial.print("error starting measurement\n");
  }

  //Serial.print("measurements started\n");

#ifdef SPS30_LIMITED_I2C_BUFFER_SIZE
  //Serial.print("Your Arduino hardware has a limitation that only\n");
  //Serial.print("  allows reading the mass concentrations. For more\n");
  //Serial.print("  information, please check\n");
  //Serial.print("  https://github.com/Sensirion/arduino-sps#esp8266-partial-legacy-support\n");
  //Serial.print("\n");
  delay(2000);
#endif

  delay(1000);
}  

String measure(void) {
  struct sps30_measurement m;
  char serial[SPS30_MAX_SERIAL_LEN];
  uint16_t data_ready;
  int16_t ret;

  bool testing = false;

  String mc_json_data = String();
  String nc_json_data = String();
  String tps_json_data = String();
  String all_json_data = String();

  do {
    ret = sps30_read_data_ready(&data_ready);
    if (ret < 0) {
      //Serial.print("error reading data-ready flag: ");
      //Serial.println(ret);
    } else if (!data_ready) {
      //Serial.print("data not ready, no new measurement available\n");
      continue;
    } else {
      break;
    }
    delay(100); /* retry in 100ms */
  } while (1);

  ret = sps30_read_measurement(&m);
  if (ret < 0) {
    return String("error reading measurement\n");
  } else {
    if(testing) {
      //Serial.print("PM  1.0: ");
      //Serial.println(m.mc_1p0);
      //Serial.print("PM  2.5: ");
      //Serial.println(m.mc_2p5);
      //Serial.print("PM  4.0: ");
      //Serial.println(m.mc_4p0);
      //Serial.print("PM 10.0: ");
      //Serial.println(m.mc_10p0);
    }
    mc_json_data += "\"mc_1p0\":" + print_float(m.mc_1p0, 2) + ", \"mc_2p5\":" + print_float(m.mc_2p5, 2) +", \"mc_4p0\":" + print_float(m.mc_4p0, 2) + ", \"mc_10p0\":" + print_float(m.mc_10p0, 2) + ", ";

    if(testing) {
  
      //Serial.print("NC  0.5: ");
      //Serial.println(m.nc_0p5);
      //Serial.print("NC  1.0: ");
      //Serial.println(m.nc_1p0);
      //Serial.print("NC  2.5: ");
      //Serial.println(m.nc_2p5);
      //Serial.print("NC  4.0: ");
      //Serial.println(m.nc_4p0);
      //Serial.print("NC 10.0: ");
      //Serial.println(m.nc_10p0);
    }
    
    nc_json_data += "\"nc_0p5\":" + print_float(m.nc_0p5, 2) + ", \"nc_1p0\":" + print_float(m.nc_1p0, 2) + ", \"nc_2p5\":" + print_float(m.nc_2p5, 2) +", \"nc_4p0\":" + print_float(m.nc_4p0, 2) +", \"nc_10p0\":" + print_float(m.nc_10p0, 2) + ", "; //+"}";

    if(testing) {
      //Serial.print("Typical partical size: ");
      //Serial.println(m.typical_particle_size);
    }
    
    tps_json_data += "\"tps\":" + print_float(m.typical_particle_size, 2) + "}";
    
    all_json_data = sensor_tags + mc_json_data + nc_json_data + tps_json_data;

    if(testing) {
      //Serial.println(all_json_data);
      //Serial.println();
    }
    return all_json_data;
  }
}






// This is the "App EUI" in Helium. Make sure it is little-endian (lsb).
static const u1_t PROGMEM APPEUI[8] = { YOUR APP EUI HERE };
void os_getArtEui(u1_t *buf) { memcpy_P(buf, APPEUI, 8); }

// This should also be in little endian format
// These are user configurable values and Helium console permits anything
static const u1_t PROGMEM DEVEUI[8] = { YOUR DEV EUI HERE};
void os_getDevEui(u1_t *buf) { memcpy_P(buf, DEVEUI, 8); }

// This is the "App Key" in Helium. It is big-endian (msb).
static const u1_t PROGMEM APPKEY[16] = { YOUR APP KEY HERE };
void os_getDevKey(u1_t *buf) { memcpy_P(buf, APPKEY, 16); }

static uint8_t mydata[] = "Hello, world!";
static osjob_t sendjob;


// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 10;

// Pin mapping
//
// Adafruit BSPs are not consistent -- m0 express defs ARDUINO_SAMD_FEATHER_M0,
// m0 defs ADAFRUIT_FEATHER_M0
//
#if defined(ARDUINO_SAMD_FEATHER_M0) || defined(ADAFRUIT_FEATHER_M0)
// Pin mapping for Adafruit Feather M0 LoRa, etc.
const lmic_pinmap lmic_pins = {
    .nss = 8,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 4,
    .dio = {3, 6, LMIC_UNUSED_PIN},
    .rxtx_rx_active = 0,
    .rssi_cal = 8, // LBT cal for the Adafruit Feather M0 LoRa, in dB
    .spi_freq = 8000000,
};
#elif defined(ARDUINO_AVR_FEATHER32U4)
// Pin mapping for Adafruit Feather 32u4 LoRa, etc.
// Just like Feather M0 LoRa, but uses SPI at 1MHz; and that's only
// because MCCI doesn't have a test board; probably higher frequencies
// will work.
const lmic_pinmap lmic_pins = {
    .nss = 8,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 4,
    .dio = {7, 6, LMIC_UNUSED_PIN},
    .rxtx_rx_active = 0,
    .rssi_cal = 8, // LBT cal for the Adafruit Feather 32U4 LoRa, in dB
    .spi_freq = 1000000,
};
#elif defined(ARDUINO_CATENA_4551)
// Pin mapping for Murata module / Catena 4551
const lmic_pinmap lmic_pins = {
    .nss = 7,
    .rxtx = 29,
    .rst = 8,
    .dio =
        {
            25, // DIO0 (IRQ) is D25
            26, // DIO1 is D26
            27, // DIO2 is D27
        },
    .rxtx_rx_active = 1,
    .rssi_cal = 10,
    .spi_freq = 8000000 // 8MHz
};
#elif defined(MCCI_CATENA_4610)
#include "arduino_lmic_hal_boards.h"
const lmic_pinmap lmic_pins = *Arduino_LMIC::GetPinmap_Catena4610();
#elif defined(ARDUINO_DISCO_L072CZ_LRWAN1)
const lmic_pinmap lmic_pins = *Arduino_LMIC::GetPinmap_Disco_L072cz_Lrwan1();
#else
#error "Unknown target"
#endif

void onEvent(ev_t ev) {
  //Serial.print(os_getTime());
  //Serial.print(": ");
  switch (ev) {
  case EV_SCAN_TIMEOUT:
    //Serial.println(F("EV_SCAN_TIMEOUT"));
    break;
  case EV_BEACON_FOUND:
    //Serial.println(F("EV_BEACON_FOUND"));
    break;
  case EV_BEACON_MISSED:
    //Serial.println(F("EV_BEACON_MISSED"));
    break;
  case EV_BEACON_TRACKED:
    //Serial.println(F("EV_BEACON_TRACKED"));
    break;
  case EV_JOINING:
    //Serial.println(F("EV_JOINING"));
    break;
  case EV_JOIN_TXCOMPLETE:
    //Serial.println(F("EV_JOIN_TXCOMPLETE"));
    break;
  case EV_JOINED:
    //Serial.println(F("EV_JOINED"));
    {
      u4_t netid = 0;
      devaddr_t devaddr = 0;
      u1_t nwkKey[16];
      u1_t artKey[16];
      LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
      //Serial.print("netid: ");
      //Serial.println(netid, DEC);
      //Serial.print("devaddr: ");
      //Serial.println(devaddr, HEX);
      //Serial.print("artKey: ");
      for (size_t i = 0; i < sizeof(artKey); ++i) {
        if (i != 0) {
          //Serial.print("-");
        }
        //Serial.print(artKey[i], HEX);
      }
      //Serial.println("");
      //Serial.print("nwkKey: ");
      for (size_t i = 0; i < sizeof(nwkKey); ++i) {
        if (i != 0) {
          //Serial.print("-");
        }
        //Serial.print(nwkKey[i], HEX);
      }
      //Serial.println("");
    }
    // Disable link check validation (automatically enabled
    // during join, but because slow data rates change max TX
    // size, we don't use it in this example.
    LMIC_setLinkCheckMode(0);
    break;
  /*
  || This event is defined but not used in the code. No
  || point in wasting codespace on it.
  ||
  || case EV_RFU1:
  ||     //Serial.println(F("EV_RFU1"));
  ||     break;
  */
  case EV_JOIN_FAILED:
    //Serial.println(F("EV_JOIN_FAILED"));
    break;
  case EV_REJOIN_FAILED:
    //Serial.println(F("EV_REJOIN_FAILED"));
    break;
    break;
  case EV_TXCOMPLETE:
    //Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
    if (LMIC.txrxFlags & TXRX_ACK)
      //Serial.println(F("Received ack"));
    if (LMIC.dataLen) {
      //Serial.println(F("Received "));
      //Serial.println(LMIC.dataLen);
      //Serial.println(F(" bytes of payload"));
    }
    // Schedule next transmission
    os_setTimedCallback(&sendjob, os_getTime() + sec2osticks(TX_INTERVAL),
                        do_send);
    break;
  case EV_LOST_TSYNC:
    //Serial.println(F("EV_LOST_TSYNC"));
    break;
  case EV_RESET:
    //Serial.println(F("EV_RESET"));
    break;
  case EV_RXCOMPLETE:
    // data received in ping slot
    //Serial.println(F("EV_RXCOMPLETE"));
    break;
  case EV_LINK_DEAD:
    //Serial.println(F("EV_LINK_DEAD"));
    break;
  case EV_LINK_ALIVE:
    //Serial.println(F("EV_LINK_ALIVE"));
    break;
  /*
  || This event is defined but not used in the code. No
  || point in wasting codespace on it.
  ||
  || case EV_SCAN_FOUND:
  ||    (F("EV_SCAN_FOUND"));
  ||    break;
  */
  case EV_TXSTART:
    //Serial.println(F("EV_TXSTART"));
    break;
  default:
    //Serial.print(F("Unknown event: "));
    //Serial.println((unsigned)ev);
    break;
  }
}

void do_send(osjob_t *j) {
  // Check if there is not a current TX/RX job running
  if (LMIC.opmode & OP_TXRXPEND) {
    //Serial.println(F("OP_TXRXPEND, not sending"));
  } else {
    // Prepare upstream data transmission at the next possible time.
    //LMIC_setTxData2(1, mydata, sizeof(mydata) - 1, 0);
    String measurement = measure();
    char char_array[300]; //approx size of json data is 140 chars, this should be ample
    int len = measurement.length() + 1; //+ 1 for null terminator
    measurement.toCharArray(char_array, len);
    uint8_t buf[300];
    memcpy(buf, char_array, len); //avoids compiler complaining about casting between char and unsigned char
    //buf[len+1] = '\0';
    LMIC_setTxData2(1, buf, len, 0);
    //Serial.print("Contents of buf: ");
    //Serial.println((char*)buf);
    //Serial.println(F("Packet queued"));
  }
  // Next TX is scheduled after TX_COMPLETE event.
}

void setup() {
  delay(5000);
  //while (!Serial);
  //Serial.begin(9600);
  //Serial.println(F("Starting"));

#if defined(ARDUINO_DISCO_L072CZ_LRWAN1)
  SPI.setMOSI(RADIO_MOSI_PORT);
  SPI.setMISO(RADIO_MISO_PORT);
  SPI.setSCLK(RADIO_SCLK_PORT);
  SPI.setSSEL(RADIO_NSS_PORT);
// SPI.begin();
#endif

#ifdef VCC_ENABLE
  // For Pinoccio Scout boards
  pinMode(VCC_ENABLE, OUTPUT);
  digitalWrite(VCC_ENABLE, HIGH);
  delay(1000);
#endif

  // LMIC init
  os_init();
  // Reset the MAC state. Session and pending data transfers will be discarded.
  LMIC_reset();

  // allow much more clock error than the X/1000 default. See:
  // https://github.com/mcci-catena/arduino-lorawan/issues/74#issuecomment-462171974
  // https://github.com/mcci-catena/arduino-lmic/commit/42da75b56#diff-16d75524a9920f5d043fe731a27cf85aL633
  // the X/1000 means an error rate of 0.1%; the above issue discusses using
  // values up to 10%. so, values from 10 (10% error, the most lax) to 1000
  // (0.1% error, the most strict) can be used.
  LMIC_setClockError(1 * MAX_CLOCK_ERROR / 40);

  LMIC_setLinkCheckMode(0);
  LMIC_setDrTxpow(DR_SF8, 20);
  LMIC_selectSubBand(1);

  sps30_setup();
  //Serial.println(measure());

  // Start job (sending automatically starts OTAA too)
  do_send(&sendjob);
}

void loop() { os_runloop_once(); }

namespace Arduino_LMIC {

class HalConfiguration_Disco_L072cz_Lrwan1_t : public HalConfiguration_t {
public:
  enum DIGITAL_PINS : uint8_t {
    PIN_SX1276_NSS = 37,
    PIN_SX1276_NRESET = 33,
    PIN_SX1276_DIO0 = 38,
    PIN_SX1276_DIO1 = 39,
    PIN_SX1276_DIO2 = 40,
    PIN_SX1276_RXTX = 21,
  };

  virtual bool queryUsingTcxo(void) override { return false; };
};
// save some typing by bringing the pin numbers into scope
static HalConfiguration_Disco_L072cz_Lrwan1_t myConfig;

static const HalPinmap_t myPinmap = {
    .nss = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_NSS,
    .rxtx = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_RXTX,
    .rst = HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_NRESET,

    .dio =
        {
            HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO0,
            HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO1,
            HalConfiguration_Disco_L072cz_Lrwan1_t::PIN_SX1276_DIO2,
        },
    .rxtx_rx_active = 1,
    .rssi_cal = 10,
    .spi_freq = 8000000, /* 8MHz */
    .pConfig = &myConfig};

}; // end namespace Arduino_LMIC

Python Flask Server

Python
This is a simple Flask server.

When you expose this server as an Ngrok endpoint, you can direct a custom Helium API integration to send data to this server. This server will parse the data, and send it to an InfluxDB instance, so that the data can then be visualized.
import flask
import base64
import json
from influxdb import InfluxDBClient

influx_url = 'your url here'
client = InfluxDBClient(influx_url, 8086, 'your database name', 'your database password', 'your database name')

app = flask.Flask(__name__)
app.config["DEBUG"] = False

@app.route('/', methods=['GET', 'POST'])
def home():
    if flask.request.method == 'GET':
        return "<h1>Distance sunset on the Beach</h1>"
    if flask.request.method == 'POST':
        #data = flask.request.form
        #print(data)

        request_as_json = flask.request.get_json()
        print("name: " + request_as_json['name'])
        print("reported at: " + str(request_as_json['reported_at']))
        print("payload (base64): " + request_as_json['payload'])

        base64_decoded = base64.b64decode(request_as_json['payload'])
        without_last = base64_decoded.decode('utf8')[:-1] #remove trailing '\x00' null char
        json_obj = json.loads(without_last)
        print("payload (json object): " + str(json_obj))
        print(json_obj['mc_1p0'])

        json_values = {}

        for element in json_obj:
            if element != 'sensor_name':
                json_values[element] = json_obj[element]
        print(json_values)

        json_body = {}
        json_body['measurement'] = 'sensor_reading'
        json_body['tags'] = {'sensor': json_obj['sensor_name'], 'location': json_obj['location']}
        
        json_body['fields'] = json_values

        json_as_list = [json_body]

        print(json_as_list)

        #print(json_body)
        formatted_json = json.dumps(json_body)
        print(type(formatted_json))

        #test_db = True
        test_db = False
        if test_db:
            print("Now hitting InfluxDB...")
            #client.write_points(json_as_list)
            db_result = client.query('select * from sensor_reading;')

            print("Result: {0}".format(db_result))

        write_points = True
        #write_points = False
        if write_points:
            print("Writing to InfluxDB...")
            client.write_points(json_as_list)
            print("Done writing to InfluxDB")
        else:
            print("Writing to DB is disabled")
        print("Done handling request")
        return "<h1> OK </h1> \r\n"
    else:
        return("<h1>404'd<h1>")


app.run()

Credits

Neal Singer

Neal Singer

1 project • 0 followers

Comments