Get Started with the Notecard and Cellular IoT on June 8th !

Blues Developers
Search
Documentation Results
End of results
Community Results
End of results
What’s New
Blues.io
Notehub.io
Shop
Sign In
What’s New
Blues.io
Notehub.io
Shop
×
HomeGuides & Tutorials
Welcome
Collecting Sensor DataIntroductionSet up HardwareCreate a Notehub ProjectWrite FirmwareView Data in NotehubUse Environment VariablesNext Steps
Routing Data to Cloud
Building Edge ML Applications
Twilio SMS Guide
Fleet Admin Guide
Using the Notehub API
Notecard Guides
Guide Listing
Asset Tracking
Attention Pin Guide
Connecting to a Wi-Fi Access Point
Debugging with the FTDI Debug Cable
Diagnosing Cellular Connectivity Issues
Encrypting Data With the Notecard
Minimizing Latency
Notecard Communication Without a Library
Notecard Outboard Firmware Update
Remote Command and Control
Serial-Over-I2C Protocol
Understanding Environment Variables
Understanding Notecard Penalty Boxes
Updating ESP32 Host Firmware
Using External SIM Cards
Using JSONata to Transform JSON

Collecting Sensor Data

Get started with:
C/C++ (Arduino/Wiring)CircuitPythonC/C++ (STM32Cube)Python
and
Adafruit Feather M4 ExpressAdafruit HUZZAH32Blues SwanArduino Nano 33 BLE SenseArtemis Thing PlusRaspberry PiSparkFun MicroMod STM32 ProcessorSTM32 DiscoverySTM32 Nucleo
and
Notecarrier-FNotecarrier-ANotecarrier-PiSparkFun MicroMod Cellular Function BoardSparkfun Qwiic Cellular

Don't see your favorite hardware here? Rest assured the Notecard works with virtually every MCU and SBC available. If you can't figure out how to complete this tutorial let us know in our forum and we can help you out.

Introduction

This tutorial should take approximately 40-50 minutes to complete.

In this tutorial, you'll learn how to take sensor readings from a Device and send readings to your Notecard and the Blues Notehub. You'll use C/C++ (Arduino/Wiring) running on a Blues Swan wired up to Notecarrier-F hardware. If you would like to use a different language, board, or Notecarrier, modify the dropdowns at the top of this guide.

The tutorial uses mock sensor readings for simplicity, but feel free to hook up a physical sensor of your choice and use that instead.

note

If you get stuck at any point during this tutorial, the full source for each example is available on GitHub:

  • View this example's source code on GitHub .

Set up Hardware

First, you'll need to get all of your hardware connected. Follow the instructions below to connect your Blues Swan and Notecard mounted on a Notecarrier-F.

In order to complete this guide, you'll need the following:

  • A Notecard mounted to a Notecarrier-F
  • A Blues Swan
  • A Micro USB to USB-A cable

Connect the MCU to the Notecarrier

  1. Plug your Swan into the Feather headers on the Notecarrier-F.

  2. Attach the Swan to your computer with a Micro USB to USB-A cable, using the Micro USB port on the Swan.

    The Swan connected to a Notecarrier-F

Create a Notehub Project

Now that your hardware is all connected, let's create a new Notehub project to receive sensor readings from your Notecard.

  1. Navigate to notehub.io and log-in, or create a new account.

  2. Using the New Project card, give your project a name and ProductUID.

    How to create a new Notehub project

NOTE: The ProductUID must be globally unique, so we recommend a namespaced name like "com.your-company.your-name:your_product".

  1. Take note of your ProductUID. This identifier is used by Notehub to associate your Notecard to your project.

    Where to find your product UID

Write Firmware

For this portion of the guide you'll be writing firmware on your Blues Swan that will communicate with the Notecard. You can write the firmware using either PlatformIO (recommended) or Arduino IDE.

Configure your IDE to use the Blues Swan

If you haven't already, make sure you've completed the Swan quickstart for either PlatformIO or Arduino IDE using the links below.

  • Option #1: Swan quickstart for PlatformIO (recommended)
  • Option #2: Swan quickstart for Arduino IDE

Great job, now you're ready to write some firmware!

Communicating With Your Notecard

When communicating with the Notecard over I2C, you'll want to use the note-arduino library . The code snippets below provide everything you need to talk to the Notecard over I2C in Arduino.

warning

The Notecarrier-F provides only an I2C connection between a Feather MCU host and the Notecard; it does not facilitate Serial communication between devices.

Install the Notecard Arduino Library

    1. Open PlatformIO within Visual Studio Code, and click the Libraries menu.

    2. Type "Blues" in the search input.

    3. Click the blue search button.

    4. Click the "Blues Wireless Notecard" result.

      Searching for note-arduino in PlatformIO

    5. Click the Add to Project button, which adds note-arduino to the lib_deps section of your project's platformio.ini file.

      Installing note-arduino in PlatformIO

    1. To use the note-arduino library , you'll need to add it to the Arduino IDE.

    2. Click on Tools > Manage Libraries...

    3. Search for "Blues" in the input box and click the "Install" button next to the "Blues Wireless Notecard" result.

      Installing the Blues Wireless Notecard library.

    4. Create a new sketch and select the Sketch > Include Library > Contributed Libraries > Blues Wireless Notecard menu option, to add the following include to your sketch:

      #include <Notecard.h>

    Set Up Your Notecard

    1. Now, configure a Serial interface. Serial will be used to log information to the Serial terminal of the Arduino IDE.

      #define usbSerial Serial
    2. Next, add a definition for your ProductUID using the value you specified when creating your Notehub project.

      #define productUID "com.your-company.your-name:your_product"
    3. Above the setup() and loop() functions, declare a global object to represent the Notecard.

      Notecard notecard;
    4. In the setup() function, initialize the usbSerial object and tell the Notecard library to use this serial object for sending debug output.

      delay(2500);
      usbSerial.begin(115200);
    5. Initialize an instance of the Notecard class and initialize an I2C connection to the Notecard using the notecard.begin() function. Then, use setDebugOutputStream() to link the debug output to usbSerial with the following code:

      notecard.begin();
      notecard.setDebugOutputStream(usbSerial);
    6. Now, we'll configure the Notecard. Using the hub.set request, we associate this Notecard with the ProductUID of your project and set the Notecard to operate in continuous mode, which indicates that the device should immediately make a connection to Notehub and keep it active.

      J *req = notecard.newRequest("hub.set");
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      notecard.sendRequest(req);

      The lines above build-up a JSON object by adding two string values for product and mode, and then fires the request off to the Notecard with the sendRequest() function.

    Flash Your Firmware

    1. Enter bootloader mode on your Swan by pressing and holding the BOOT button, pressing RESET, then releasing both buttons.

        If you're using PlatformIO, click the Upload button (right arrow icon) at the bottom of the VS Code interface to flash the firmware to your device.

        Uploading firmware from PlatformIO

        If you're using Arduino IDE, click the Upload button (right arrow icon) to flash the firmware to your device.

        Uploading firmware from Arduino IDE

      note

      If you're using an STLink-V3Mini debugger you can use these instructions for uploading code to your Swan.

      View the Serial Log

      Now that your firmware is running on your device, you can use a Serial Monitor to view device output. Complete the instructions below in your preferred IDE.

        1. If you're using PlatformIO, open the Serial Monitor by clicking the plug icon in the bottom of VS Code.

          You should see a few debug messages, including the JSON object you sent, as well as the response from the Notecard {}. (Note: You might need to upload your code a second time to see the result of the hub.set request, as the Serial Monitor only captures output when it's actively running.)

        1. If you're using Arduino IDE, open the Arduino Serial Monitor. If everything has been connected and configured properly, you'll see a few debug messages, including the JSON object you sent, as well as the response from the Notecard {}.

        Read from the sensor

        Now that you've configured your Arduino to communicate with the Notecard, let's grab some pseudo sensor readings.

        note

        If you have your own sensor, feel free to hook it up and use your own values instead of this tutorial's mocked ones.

        Install the NotecardPseudoSensor Library

        To generate mock sensor readings you'll use the NotecardPseudoSensor library . Complete the instructions below for your preferred IDE.

          1. Click the Libraries menu within PlatformIO.

          2. Search for "Notecard" and scroll a bit to find the NotecardPseudoSensor library.

            Finding the pseudo sensor library in PlatformIO

          3. Click the "Add to Project" button, which adds the library to the lib_deps section of your project's platformio.ini file.

            Adding the pseudo sensor library in PlatformIO

          1. To add the library to Arduino IDE start by clicking on Tools > Manage Libraries...

          2. Search for “NotecardPseudoSensor” in the input box and click the Install button next to the “Blues Wireless Notecard Pseudo Sensor” result.

          Gather Sensor Readings

          1. Add the following include to the top of your sketch:

            #include <NotecardPseudoSensor.h>
          2. Next, include the following namespace under your includes.

            using namespace blues;
          3. After that, create an instance of NotecardPseudoSensor with the line of code below. Place this directly under your existing Notecard notecard statement.

            NotecardPseudoSensor sensor(notecard);
          4. Finally, place the following code in your loop function, which generates mock temperature and humidity readings, prints them to the console, and then waits 15 seconds before exiting the loop.

            float temperature = sensor.temp();
            float humidity = sensor.humidity();
            
            usbSerial.print("Temperature = ");
            usbSerial.print(temperature);
            usbSerial.println(" *C");
            usbSerial.print("Humidity = ");
            usbSerial.print(humidity);
            usbSerial.println(" %");
            
            delay(15000);
          5. Upload this code to your Blues Swan. Open the Serial Monitor and you'll see temperature and humidity readings every 15 seconds.

          Send Sensor Readings to the Notecard

          Now that we're getting sensor readings, let's send these to our Notecard.

          1. To send a sensor reading to the Notecard, we'll need to construct a new JSON request to the note.add API that includes a new Notefile name (sensors.qo), sets the sync field to true to instruct the Notecard to sync to Notehub immediately, and finally, sets the body to the sensor temperature and humidity. Add the following in loop right after the usbSerial commands to print out readings.

            J *req = notecard.newRequest("note.add");
            if (req != NULL)
            {
              JAddStringToObject(req, "file", "sensors.qo");
              JAddBoolToObject(req, "sync", true);
              J *body = JAddObjectToObject(req, "body");
              if (body)
              {
                JAddNumberToObject(body, "temp", temperature);
                JAddNumberToObject(body, "humidity", humidity);
              }
              notecard.sendRequest(req);
            }
          1. Enter bootloader mode again and upload this code to your device. After reboot, the Serial monitor will update to display the response from the note.add request (the total number of Notes in the notefile) each time you add a new reading.

          note

          Concerned about the size of note-arduino? You can communicate with the Notecard without using the library.

          View Data in Notehub

          Once you start capturing readings, your Notecard will initiate a connection to Notehub and will start transferring Notes. Depending on signal strength and coverage in your area, it may take a few minutes for your Notecard to connect to Notehub and transfer data.

          1. Return to notehub.io and open your project. You should see your notecard in the Devices view.

            The new device in Notehub

          2. Now, click on the Events left menu item. Once your sensor Notes start syncing, they'll show up here.

            The event list in Notehub

          Use Environment Variables

          Environment variables are a Notehub state and settings management feature that allow you to set variables in key-value pairs, and intelligently synchronize those values across devices and fleets of devices.

          In this section you'll learn how environment variables work by creating a variable that determines how often your firmware should take sensor readings.

          Setting an Environment Variable

          Environment variables can be set in the Notehub UI or through the Notehub API. In this tutorial you'll learn how to set the values through the Notehub UI. If you'd like to instead set environment variables through the Notehub API, refer to the Environment Variable API.

          1. Return to your Notehub project, go the the Devices page, and double click your device. You should see a screen that looks like this.

            The Notehub device screen

          2. Click the Environment tab.

          3. Under the Device environment variables header, define a new environment variable named reading_interval and set its value to 30.

            The environment screen with a new value set

          Now that you have an environment variable set you're ready to use it in your app. Let's look at how that works.

          Using Environment Variables in Firmware

          The Notecard provides a set of requests for working with environment variables. The most common of these requests is env.get, which allows you to retrieve the value of an environment variable.

          Complete the steps below to use the env.get request to retrieve and use the reading_interval environment variable you set in Notehub.

          1. Place the following new function at the bottom of your sketch.

            // This function assumes you’ll set the reading_interval environment variable to
            // a positive integer. If the variable is not set, set to 0, or set to an invalid
            // type, this function returns a default value of 60.
            int getSensorInterval() {
              int sensorIntervalSeconds = 60;
              J *req = notecard.newRequest("env.get");
              if (req != NULL) {
                  JAddStringToObject(req, "name", "reading_interval");
                  J* rsp = notecard.requestAndResponse(req);
                  int readingIntervalEnvVar = atoi(JGetString(rsp, "text"));
                  if (readingIntervalEnvVar > 0) {
                    sensorIntervalSeconds = readingIntervalEnvVar;
                  }
                  notecard.deleteResponse(rsp);
              }
              return sensorIntervalSeconds;
            }
          2. Next, find the delay(15000) line at the bottom of your loop() function, and replace it with the code below.

            int sensorIntervalSeconds = getSensorInterval();
            serialDebug.print("Delaying ");
            serialDebug.print(sensorIntervalSeconds);
            serialDebug.println(" seconds");
            delay(sensorIntervalSeconds * 1000);
          3. Finally, back in setup(), adjust your existing hub.set configuration to set the sync argument to true. When sync is true, the Notecard synchronizes inbound environment variable changes as soon as they're made in Notehub.

            J *req = notecard.newRequest("hub.set");
            JAddStringToObject(req, "product", productUID);
            JAddStringToObject(req, "mode", "continuous");
            JAddBoolToObject(req, "sync", true); // ADD THIS LINE
            notecard.sendRequest(req);

          With this code in place, your firmware now uses the reading_interval environment variable to determine how many seconds to delay in between sensor readings. If you flash this updated code to your device and open your serial monitor, you can see the device retrieving and using the reading_interval: 30 value you set in Notehub.

          The environment screen with a new value set

          And with that, you've used your first environment variable on your Notecard! To see the real power of environment variables in action, try returning to Notehub and updating your device's reading_interval with your serial monitor open. Your firmware will retrieve the updated value and start using it immediately.

          note

          This tutorial had you use several configuration settings are best used when you have your Notecard connected to mains power.

          • In the hub.set request, setting mode to "continuous" tells the Notecard to maintain an active network connection.

          • In the hub.set request, setting sync to true tells the Notecard to immediately synchronize inbound Notes and environment variables from Notehub.

          • In the note.add request, setting sync to true tells the Notecard to immediately synchronize all outbound Notes to Notehub.

          Because each of these settings cause the Notecard to use more power, you may wish to disable them if you plan to transition your project to battery power. You can run the command below to put your Notecard into periodic mode with the sync argument turned off.

          {
           "req": "hub.set",
           "mode": "periodic",
           "sync": false,
           "outbound": 60,
           "inbound": 120
          }

          Learn more about optimizing the Notecard for low-power scenarios in Low Power Design.

          Next Steps

          Congratulations! You've successfully connected your Blues Swan to your Notecard and built a basic IoT project.

          If you're following the Blues Quickstart, next we recommend learning how to send (and visualize) your data in a cloud application:

          1. Use the Notecard to Send Data
          2. Set Up Your Microcontroller
          3. Build Your First IoT App With Blues
          4. Send Data to Your Cloud

          At any time, if you find yourself stuck, please reach out on the community forum .

          Can we improve this page? Send us feedback
          © 2023 Blues Inc.Terms & ConditionsPrivacy
          blues.ioTwitterLinkedInGitHubHackster.io
          Disconnected
          Notecard Disconnected
          Having trouble connecting?

          Try changing your Micro USB cable as some cables do not support transferring data. If that does not solve your problem, contact us at support@blues.com and we will get you set up with another tool to communicate with the Notecard.

          Advanced Usage

          The help command gives more info.

          Connect a Notecard
          Use USB to connect and start issuing requests from the browser.
          Try Notecard Simulator
          Experiment with Notecard's latest firmware on a Simulator assigned to your free Notehub account.

          Don't have an account? Sign up