---
title: 'Host Firmware: C/C++ (Arduino) on Arduino Nano 33 BLE Sense'
description: Write host firmware in C/C++ (Arduino) for the Arduino Nano 33 BLE Sense that reads an external sensor and sends the readings to Notehub through Notecard.
source_url: https://dev.blues.io/guides-and-tutorials/writing-host-firmware/arduino-nano-33-ble-sense/c-cpp-arduino/
canonical_url: https://dev.blues.io/guides-and-tutorials/writing-host-firmware/arduino-nano-33-ble-sense/c-cpp-arduino/
markdown_url: https://dev.blues.io/guides-and-tutorials/writing-host-firmware/arduino-nano-33-ble-sense/c-cpp-arduino.md
---

# Writing Host Firmware C/C++ (Arduino) and Arduino Nano 33 BLE Sense

In previous tutorials, you used the In-Browser Terminal to communicate with your Notecard and sent hardcoded data to and from the Notehub.

In real-world applications, most connected products are driven by a host: a microcontroller (MCU) or single-board computer (SBC) that reads sensors, runs application logic, and controls the product’s behavior. In Notecard-based projects, the host communicates with Notecard over I2C or UART, typically using one of our official SDKs.

In this tutorial, you’ll learn how to write host firmware that communicates with Notecard, collects data, and sends that data to Notehub.

Versions of this guide are available for several popular languages and host platforms. Use the dropdowns below to explore the options. And if you want to communicate with Notecard using a language or environment not covered by this guide, see our [Firmware Libraries](https://dev.blues.io/tools-and-sdks/firmware-libraries.md) page for the official Notecard SDKs for Arduino, C, ESP-IDF, Go, Python, and Zephyr.

*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](https://discuss.blues.com/) and we can help you out.*

## Introduction {#introduction}

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

In this tutorial, you'll learn how to use **C/C++ (Arduino)** to write firmware that runs on a **Arduino Nano 33 BLE Sense**. Specifically, your firmware will collect temperature and humidity data at an interval, queue it on your Notecard, and synchronize it to Blues Notehub.

This tutorial uses a library that provides mock sensor readings for simplicity, but feel free to hook up a physical sensor of your choice and use that instead. The goal of this tutorial is to demonstrate reusable firmware techniques you can apply to your own Notecard-based projects.

AI Tip

Throughout this guide we’ll share tips for writing host firmware with AI, which we recommend. Look for these boxes for AI-specific guidance and prompts you can use with your LLM of choice.

## Setup {#setup}

Make sure you've met the following hardware and software requirements before continuing.

### Hardware {#hardware}

To complete this guide, you'll need the following hardware.

- Any Arduino-capable Microcontroller (MCU). *We will be using the [Arduino Nano 33 BLE Sense](https://store-usa.arduino.cc/products/arduino-nano-33-ble-sense?selectedStore=us), but any MCU that can be programmed with the Arduino IDE will do.*
- A Notecard wired to your Arduino Nano 33 BLE Sense. If you haven't done this yet, see the [Host Wiring Guide](https://dev.blues.io/guides-and-tutorials/host-wiring-guide.md).
- Micro USB to USB-A cable.

note

For this tutorial, you'll be powering the Notecard through the Micro USB connection of your Arduino Nano 33 BLE Sense. Some Arduino-compatible devices cannot handle 2 Amp pulses from the Notecard when connected to GSM, so if you experience resets or other power-related issues, we suggest powering your Notecard separately through the USB or LiPo connector on your Notecarrier.

If you need additional help finding the correct I2C, Power, GND, and Serial pins on your Arduino, be sure to visit the [Arduino Boards & Modules](https://store-usa.arduino.cc/collections/boards) page to find your board, along with its corresponding pinout diagram under the "Documentation" tab.

For example, here are the pinout diagrams for the [Arduino Nano 33 BLE Sense](https://content.arduino.cc/assets/Pinout-NANOsense_latest.png).

### Software {#software}

You'll also need the following software.

- **[Arduino IDE](https://www.arduino.cc/en/software) 2.0 or later.**

AI Tip

When writing host firmware with AI, we recommend installing [Blues Expert MCP](https://dev.blues.io/tools-and-sdks/generative-ai-tools/blues-expert-mcp.md). Blues Expert connects your AI coding assistant—Claude Code, GitHub Copilot, Cursor, etc—directly to our API docs, providing live request validation and firmware best practices for Arduino, C, Zephyr, and Python.

Prompt

Add a new HTTP MCP server named Blues Expert using `https://mcp.blues.io/expert/mcp`.

## Create a Notehub Project {#create-a-notehub-project}

Now that your hardware is ready, let's create a new Notehub project for this tutorial.

1. Navigate to [Notehub](https://notehub.io) and log in.

2. Click the **Create Project** button.

3. In the New Project dialog, give your project a name and ProductUID.

   ![How to create a new Notehub project](https://dev.blues.io/images/guides/notehub/create-project.png?v=bf29a47a)

   note

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

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

   ![Where to find your product UID](https://dev.blues.io/images/guides/notehub/product-uid.png?v=d829ab1d)

## Write Firmware {#write-firmware}

### Configure the Arduino IDE {#configure-the-arduino-ide}

For this portion of the guide, we'll be using the Arduino IDE, so be sure to [install version 2.0+](https://www.arduino.cc/en/software) if you haven't already.

Once installed, we'll need to add support for your Arduino Nano 33 BLE Sense Board.

### Configure the Arduino Boards Manager to use the Arduino Nano 33 BLE Sense {#configure-the-arduino-boards-manager-to-use-the-arduino-nano-33-ble-sense}

1. Start the Arduino IDE, then select the **Tools > Board: \[board name] > Boards Manager...** menu.

   ![Boards Manager menu option](https://dev.blues.io/images/guides/first-sensor/arduino/boards-manager.png?v=620ce782)

2. In the search box, type "nano 33 BLE" and press the **Enter** key. Select **Arduino Mbed OS Nano Boards** from the list, and press the **Install** button.

   ![Arduino Nano 33 BLE install](https://dev.blues.io/images/guides/first-sensor/arduino/nano-33-install.png?v=1229e8f4)

3. Once the installation completes, click **Close**.

4. Now select **Arduino Nano 33 BLE** from the **Tools > Board:** menu.

5. Finally, select your device from the **Tools > Port > Serial Ports** list.

### Communicating With Your Notecard {#communicating-with-your-notecard}

When communicating with the Notecard, the easiest approach is to use one of [Notecard's official SDKs](https://dev.blues.io/tools-and-sdks/firmware-libraries.md). Since this tutorial uses Arduino, let's install the Arduino SDK, [note-arduino](https://github.com/blues/note-arduino).

#### Install the Notecard Arduino Library {#install-the-notecard-arduino-library}

1. To use the [note-arduino library](https://github.com/blues/note-arduino), 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.](https://dev.blues.io/images/guides/first-sensor/arduino/install-library.png?v=ea1aec79)

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:

   ```cpp
   #include <Notecard.h>
   ```

#### Set Up Your Notecard {#communicating-with-your-notecard--set-up-your-notecard}

With the Notecard’s Arduino SDK installed, let’s start writing firmware. The steps below show you how to initialize a Notecard in an Arduino sketch, using AI or writing code manually.

AI Tip

Now that your project is set up and the necessary dependencies are installed, you’re ready to use an LLM to generate your host firmware.

To start, we recommend opening your AI coding assistant in the same folder as your firmware project. At a minimum, make sure your LLM knows where your code is located so it can make updates.

- Arduino IDE

  - Windows: `C:\Users\<username>\Documents\Arduino\project_name`
  - macOS: `~/Documents/Arduino/project_name`
  - Linux: `~/Arduino/project_name`

- PlatformIO

  - Windows: `C:\Users\<username>\Documents\PlatformIO\Projects\project_name`
  - macOS: `~/Documents/PlatformIO/Projects/project_name`
  - Linux: `~/Documents/PlatformIO/Projects/project_name`

Next, create an `AGENTS.md` file to provide the LLM context about the project you’re building. List all the hardware you’re using in this file, as well as a description of what your project does.

Prompt

Create an `AGENTS.md` file for this host firmware project. Record that I’m using a Notecard and a Arduino Nano 33 BLE Sense, and that I’m building a project that takes regular temperature and humidity readings.

Finally, we recommend using the tools in Blues Expert MCP to scaffold the initial version of your project.

Prompt

Use Blues Expert to scaffold this sketch as a Notecard project. Put my Notecard in continuous mode with a session duration of 15 minutes, and prompt me for my Notehub project’s ProductUID. Leave the loop empty for now; I want to make sure my Notecard initializes correctly first.

And if you’re not using AI (or you just want some background on how things work), the steps below show how to set up your Notecard in host firmware with manually written code.

If you’re unsure whether you’re using I2C or UART, see our [Host Wiring Guide](https://dev.blues.io/guides-and-tutorials/host-wiring-guide.md). Notecarrier CX and F boards connect the host to Notecard over I2C by default, so if you're using either of those, you're on I2C.

**I2C**

1. At the top of your sketch, define the Serial interface you'll use for logging.

   ```cpp
   #define usbSerial Serial
   ```

2. Add a definition for your ProductUID using the value you specified when creating your Notehub project.

   ```cpp
   #define productUID "com.your-company.your-name:your_product"
   ```

3. Above the `setup()` and `loop()` functions, declare a **global** object to represent the Notecard.

   ```cpp
   Notecard notecard;
   ```

4. In the `setup()` function, initialize the `usbSerial` object, then wait up to 3 seconds for it to connect. Boards with native USB need a moment to enumerate before the first log line is written, and the timeout keeps the sketch from hanging when no serial monitor is attached.

   ```cpp
   usbSerial.begin(115200);
   const size_t usb_timeout_ms = 3000;
   for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
     ;
   ```

5. Initialize the I2C connection to the Notecard using the `notecard.begin()` function. Then, use `setDebugOutputStream()` to link the debug output to `usbSerial` with the following code:

   ```cpp
   notecard.begin();
   notecard.setDebugOutputStream(usbSerial);
   ```

6. Next, configure the Notecard by adding the following `hub.set` request to the end of your `setup()` function, after the `setDebugOutputStream()` call. This request associates your Notecard with your project's ProductUID and sets it to operate in `continuous` mode, which tells the device to immediately connect to Notehub and keep that connection active.

   ```cpp
   {
     J *req = notecard.newRequest("hub.set");
     if (req != NULL) {
       JAddStringToObject(req, "product", productUID);
       JAddStringToObject(req, "mode", "continuous");
       JAddNumberToObject(req, "duration", 15);
       notecard.sendRequest(req);
     }
   }
   ```

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

   note

   The `duration` argument tells the Notecard to end its current [session](https://dev.blues.io/api-reference/glossary.md#session) and start a fresh one every 15 minutes, even though it stays connected the whole time. Each session includes [useful metadata](https://dev.blues.io/api-reference/system-notefiles.md#session-fields), such as signal strength, data usage, location, and more.

Your code should now look like this:

```cpp
#include <Arduino.h>
#include <Notecard.h>

#define usbSerial Serial
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin();
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      notecard.sendRequest(req);
    }
  }
}

void loop() {
}
```

**UART**

1. At the top of your sketch, define the Serial interfaces you'll use for logging and Notecard communication.

   ```cpp
   #define usbSerial Serial
   #define txRxPinsSerial Serial1
   ```

2. Add a definition for your ProductUID using the value you specified when creating your Notehub project.

   ```cpp
   #define productUID "com.your-company.your-name:your_product"
   ```

3. Above the `setup()` and `loop()` functions, declare a **global** object to represent the Notecard.

   ```cpp
   Notecard notecard;
   ```

4. In the `setup()` function, initialize the `usbSerial` object, then wait up to 3 seconds for it to connect. Boards with native USB need a moment to enumerate before the first log line is written, and the timeout keeps the sketch from hanging when no serial monitor is attached.

   ```cpp
   usbSerial.begin(115200);
   const size_t usb_timeout_ms = 3000;
   for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
     ;
   ```

5. Initialize the UART connection to the Notecard using the `begin()` function. Then, use `setDebugOutputStream()` to link the debug output to `usbSerial` with the following code:

   ```cpp
   notecard.begin(txRxPinsSerial, 9600);
   notecard.setDebugOutputStream(usbSerial);
   ```

6. Next, configure the Notecard by adding the following `hub.set` request to the end of your `setup()` function, after the `setDebugOutputStream()` call. This request associates your Notecard with your project's ProductUID and sets it to operate in `continuous` mode, which tells the device to immediately connect to Notehub and keep that connection active.

   ```cpp
   {
     J *req = notecard.newRequest("hub.set");
     if (req != NULL) {
       JAddStringToObject(req, "product", productUID);
       JAddStringToObject(req, "mode", "continuous");
       JAddNumberToObject(req, "duration", 15);
       notecard.sendRequest(req);
     }
   }
   ```

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

   note

   The `duration` argument tells the Notecard to end its current [session](https://dev.blues.io/api-reference/glossary.md#session) and start a fresh one every 15 minutes, even though it stays connected the whole time. Each session includes [useful metadata](https://dev.blues.io/api-reference/system-notefiles.md#session-fields), such as signal strength, data usage, location, and more.

Your code should now look like this:

```cpp
#include <Arduino.h>
#include <Notecard.h>

#define usbSerial Serial
#define txRxPinsSerial Serial1
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin(txRxPinsSerial, 9600);
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      notecard.sendRequest(req);
    }
  }
}

void loop() {
}
```

#### Flash Your Firmware {#flash-your-firmware}

1. Click the Upload button (right arrow icon) to flash firmware to your device.

   ![Arduino IDE Upload button](https://dev.blues.io/images/guides/first-sensor/feather/arduino-tutorial-upload.png?v=cc42f1f4)

#### View the Serial Log {#view-the-serial-log}

Now that your firmware is running on your device, you can use a Serial Monitor to view device output. If you are using an STLINK programmer, you will need to connect a second USB cable from your computer directly to your STM32-based host to view serial output.

Complete the instructions below in your preferred IDE.

1. 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 `{}`.

   ![Serial Monitor hub.set response](https://dev.blues.io/images/guides/first-sensor/feather/serial-configured.png?v=38df04b5)

### Read From the Sensor {#read-from-the-sensor}

Now that you've configured your host to communicate with your Notecard, let's next look at how to take some mock 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 {#install-the-notecardpseudosensor-library}

1. To generate mock sensor readings you'll use the [NotecardPseudoSensor library](https://github.com/blues/notecard-pseudo-sensor). 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.

   ![NotecardPseudoSensor library install](https://dev.blues.io/images/guides/first-sensor/arduino/pseudo-sensor-library.png?v=929defbe)

#### Gather Sensor Readings {#gather-sensor-readings}

Use the instructions below to take sensor readings in firmware using AI or writing code manually.

AI Tip

The prompt below can be used to generate firmware that uses the NotecardPseudoSensor library. If you’re using your own sensor, add it to your `AGENTS.md` file (ideally with a link to its datasheet!) before asking your LLM to generate firmware that uses it.

Prompt

Take a temperature and humidity reading using the NotecardPseudoSensor library every 30 seconds. Make 30 seconds a configurable interval. Log the values from the sensor to the serial log.

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

   ```cpp
   #include <NotecardPseudoSensor.h>
   ```

2. Next, include the following `namespace` under your includes.

   ```cpp
   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.

   ```cpp
   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 30 seconds before the loop runs again.

   ```cpp
   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(30000);
   ```

5. Upload this code to your Arduino Nano 33 BLE Sense. Open the Serial Monitor and you'll see temperature and humidity readings every 30 seconds.

   ![Serial monitor temperature and humidity](https://dev.blues.io/images/guides/first-sensor/arduino/arduino-tutorial-serial-monitor.png?v=09c9c2c5)

Your code should now look like this:

**I2C**

```cpp
#include <Arduino.h>
#include <Notecard.h>
#include <NotecardPseudoSensor.h>

using namespace blues;

#define usbSerial Serial
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;
NotecardPseudoSensor sensor(notecard);

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin();
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      notecard.sendRequest(req);
    }
  }
}

void 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(30000);
}
```

**UART**

```cpp
#include <Arduino.h>
#include <Notecard.h>
#include <NotecardPseudoSensor.h>

using namespace blues;

#define usbSerial Serial
#define txRxPinsSerial Serial1
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;
NotecardPseudoSensor sensor(notecard);

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin(txRxPinsSerial, 9600);
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      notecard.sendRequest(req);
    }
  }
}

void 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(30000);
}
```

### Queue Sensor Readings on Notecard {#queue-sensor-readings-on-notecard}

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

AI Tip

Prompt

Queue each temperature and humidity reading from the sensor library in a Note on my `sensors.qo` Notefile. Use `sync: true` on the `note.add` to trigger an immediate Notehub sync.

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.

   ```cpp
   {
     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);
     }
   }
   ```

2) 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.

   ![Serial Monitor note totals output](https://dev.blues.io/images/guides/first-sensor/feather/notes-mock-lib.png?v=5ec543e1)

Your code should now look like this:

**I2C**

```cpp
#include <Arduino.h>
#include <Notecard.h>
#include <NotecardPseudoSensor.h>

using namespace blues;

#define usbSerial Serial
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;
NotecardPseudoSensor sensor(notecard);

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin();
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      notecard.sendRequest(req);
    }
  }
}

void 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(" %");

  {
    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);
    }
  }

  delay(30000);
}
```

**UART**

```cpp
#include <Arduino.h>
#include <Notecard.h>
#include <NotecardPseudoSensor.h>

using namespace blues;

#define usbSerial Serial
#define txRxPinsSerial Serial1
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;
NotecardPseudoSensor sensor(notecard);

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin(txRxPinsSerial, 9600);
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      notecard.sendRequest(req);
    }
  }
}

void 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(" %");

  {
    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);
    }
  }

  delay(30000);
}
```

note

If you're using a Notecard for LoRa to complete this tutorial you have one additional step. Because the Notecard for LoRa requires a template for every Notefile you use, you must define a template for the `sensors.qo` Notefile in your `setup()` function. You can add the following code to the bottom of your `setup()` function to fix the problem.

```cpp
{
  J *req = notecard.newRequest("note.template");
  if (req != NULL) {
    JAddStringToObject(req, "file", "sensors.qo");
    JAddNumberToObject(req, "port", 1);
    JAddStringToObject(req, "format", "compact");
    J *body = JCreateObject();
    if (body != NULL) {
      JAddNumberToObject(body, "temp", 14.1);
      JAddNumberToObject(body, "humidity", 14.1);
      JAddItemToObject(req, "body", body);
      notecard.sendRequest(req);
    }
  }
}
```

Learn more about Notefile templates in [Working with Note Templates](https://dev.blues.io/notecard/notecard-walkthrough/low-bandwidth-design.md#working-with-note-templates).

note

Concerned about the size of `note-arduino`? You can [communicate with the Notecard without using the library](https://dev.blues.io/guides-and-tutorials/notecard-guides/notecard-communication-without-a-library.md).

## View Data in Notehub {#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](https://notehub.io) and open your project. You should see your Notecard in the Devices view.

   ![The new device in Notehub](https://dev.blues.io/images/guides/notehub/new-device.png?v=f506b425)

   note

   Each Notecard has a factory-assigned, globally unique identifier known as a [DeviceUID](https://dev.blues.io/api-reference/glossary.md#deviceuid). Notehub uses this identifier in the Devices view by default (for example, `dev:868531061604976` in the screenshot above).

   If you’d prefer to use your own identifier—such as a human-readable name or an internal ID—you can assign a [serial number](https://dev.blues.io/api-reference/glossary.md#product-sn) to your Notecard in one of the following ways:

   - **In Notehub:** Double-click your device in the Devices view to open its details, where you can edit the serial number.
   - **Via the Notehub API:** Set the reserved `_sn` environment variable using the [Set Device Environment Variables](https://dev.blues.io/api-reference/notehub-api/device-api.md#set-device-environment-variables) endpoint.
   - **Via the Notecard API**: Include an `sn` argument in the [hub.set request](https://dev.blues.io/api-reference/notecard-api/hub-requests/latest.md#hub-set) you used to configure your Notecard.

2. Now, click on the Events left menu item. Once your sensor Notes start syncing, they'll show up here. You may need to refresh the page to see newly synced Notes.

   ![The event list in Notehub](https://dev.blues.io/images/guides/notehub/events.png?v=76323245)

   Alongside your `sensors.qo` Notes you'll also see `_session.qo` events, which Notehub creates at the start and end of each session with details about your Notecard's connection.

## Use Environment Variables {#use-environment-variables}

[Environment variables](https://dev.blues.io/guides-and-tutorials/notecard-guides/understanding-environment-variables.md) are a Notehub state and settings management feature that allows 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.

### Using Environment Variables in Firmware {#using-environment-variables-in-firmware}

The Notecard provides [a set of requests for working with environment variables](https://dev.blues.io/api-reference/notecard-api/env-requests/latest.md). The most common of these requests is [`env.get`](https://dev.blues.io/api-reference/notecard-api/env-requests/latest.md#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_secs` environment variable.

AI Tip

Prompt

Set my Notecard to use an inbound interval of 5 minutes. Read a new environment variable named `reading_interval_secs`, and use that to determine how many seconds the firmware should wait between sensor readings.

1. In `setup()`, adjust your existing `hub.set` configuration to set the `inbound` argument to `5`. This tells your Notecard to look for inbound changes from Notehub every 5 minutes.

   ```c
   {
     J *req = notecard.newRequest("hub.set");
     if (req != NULL) {
       JAddStringToObject(req, "product", productUID);
       JAddStringToObject(req, "mode", "continuous");
       JAddNumberToObject(req, "duration", 15);
       JAddNumberToObject(req, "inbound", 5); // ADD THIS LINE
       notecard.sendRequest(req);
     }
   }
   ```

2. Next, place the following new function at the bottom of your sketch.

   ```c
   // This function assumes you’ll set the reading_interval_secs 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 intervalSeconds = 60;
     J *req = notecard.newRequest("env.get");
     if (req != NULL) {
       JAddStringToObject(req, "name", "reading_interval_secs");
       J* rsp = notecard.requestAndResponse(req);
       int readingIntervalEnvVar = atoi(JGetString(rsp, "text"));
       if (readingIntervalEnvVar > 0) {
         intervalSeconds = readingIntervalEnvVar;
       }
       notecard.deleteResponse(rsp);
     }
     return intervalSeconds;
   }
   ```

3. Then, add this line after the `#include` lines at the top of the file.

   ```c
   int getSensorInterval();
   ```

4. Next, rename your existing `loop()` function to `takeReading()`, and delete the `delay(30000)` line at the bottom of it. You'll call this function whenever it's time to take a new reading.

   ```c
   void takeReading() { // RENAMED FROM loop()
     float temperature = sensor.temp();
     float humidity = sensor.humidity();
     // ...the rest of your existing code, minus the delay(30000) line
   }
   ```

5. Add the following variables after the `NotecardPseudoSensor sensor(notecard);` line near the top of your sketch. These keep track of the current reading interval, and when your firmware last took a reading and last checked for a new `reading_interval_secs` value.

   ```c
   int sensorIntervalSeconds = 60;
   unsigned long lastReadingMs = 0;
   unsigned long lastEnvCheckMs = 0;
   ```

6. Finally, add a new `loop()` function below `takeReading()`.

   Rather than calling `delay()`, which would pause your firmware for the entire interval (and keep it from noticing a new `reading_interval_secs` until that pause ended), this `loop()` uses Arduino's [`millis()`](https://docs.arduino.cc/language-reference/en/functions/time/millis/) function to check how much time has passed, and only does work when it's needed. Your firmware checks for a new `reading_interval_secs` every 10 seconds, so changes you make in Notehub take effect as soon as they reach your Notecard.

   ```c
   void loop() {
     unsigned long currentMs = millis();

     // Check for a new reading_interval_secs value every 10 seconds.
     if (currentMs - lastEnvCheckMs >= 10000) {
       lastEnvCheckMs = currentMs;
       int newIntervalSeconds = getSensorInterval();
       if (newIntervalSeconds != sensorIntervalSeconds) {
         sensorIntervalSeconds = newIntervalSeconds;
         usbSerial.print("Reading interval changed to ");
         usbSerial.print(sensorIntervalSeconds);
         usbSerial.println(" seconds");
       }
     }

     // Take a reading on the first pass, and then whenever the interval has passed.
     if (lastReadingMs == 0 || currentMs - lastReadingMs >= sensorIntervalSeconds * 1000UL) {
       lastReadingMs = currentMs;
       takeReading();
     }
   }
   ```

   note

   Notecard for LoRa requires a template for each environment variable you use. If you're using a Notecard for LoRa to complete this tutorial, add the code below to your `setup()` to provide a template for the `reading_interval_secs` variable.

   ```c
   {
     J *req = notecard.newRequest("env.template");
     if (req != NULL) {
       J *body = JCreateObject();
       if (body != NULL) {
         JAddNumberToObject(body, "reading_interval_secs", 22);
         JAddItemToObject(req, "body", body);
         notecard.sendRequest(req);
       }
     }
   }
   ```

   Here `22` is the type hint for a 2-byte unsigned integer (`0`–`65535`).

Your code should now look like this:

**I2C**

```cpp
#include <Arduino.h>
#include <Notecard.h>
#include <NotecardPseudoSensor.h>

int getSensorInterval();

using namespace blues;

#define usbSerial Serial
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;
NotecardPseudoSensor sensor(notecard);

int sensorIntervalSeconds = 60;
unsigned long lastReadingMs = 0;
unsigned long lastEnvCheckMs = 0;

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin();
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      JAddNumberToObject(req, "inbound", 5);
      notecard.sendRequest(req);
    }
  }
}

void takeReading() {
  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(" %");

  {
    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);
    }
  }
}

void loop() {
  unsigned long currentMs = millis();

  // Check for a new reading_interval_secs value every 10 seconds.
  if (currentMs - lastEnvCheckMs >= 10000) {
    lastEnvCheckMs = currentMs;
    int newIntervalSeconds = getSensorInterval();
    if (newIntervalSeconds != sensorIntervalSeconds) {
      sensorIntervalSeconds = newIntervalSeconds;
      usbSerial.print("Reading interval changed to ");
      usbSerial.print(sensorIntervalSeconds);
      usbSerial.println(" seconds");
    }
  }

  // Take a reading on the first pass, and then whenever the interval has passed.
  if (lastReadingMs == 0 || currentMs - lastReadingMs >= sensorIntervalSeconds * 1000UL) {
    lastReadingMs = currentMs;
    takeReading();
  }
}

// This function assumes you’ll set the reading_interval_secs 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 intervalSeconds = 60;
  J *req = notecard.newRequest("env.get");
  if (req != NULL) {
    JAddStringToObject(req, "name", "reading_interval_secs");
    J* rsp = notecard.requestAndResponse(req);
    int readingIntervalEnvVar = atoi(JGetString(rsp, "text"));
    if (readingIntervalEnvVar > 0) {
      intervalSeconds = readingIntervalEnvVar;
    }
    notecard.deleteResponse(rsp);
  }
  return intervalSeconds;
}
```

**UART**

```cpp
#include <Arduino.h>
#include <Notecard.h>
#include <NotecardPseudoSensor.h>

int getSensorInterval();

using namespace blues;

#define usbSerial Serial
#define txRxPinsSerial Serial1
#define productUID "com.your-company.your-name:your_product"

Notecard notecard;
NotecardPseudoSensor sensor(notecard);

int sensorIntervalSeconds = 60;
unsigned long lastReadingMs = 0;
unsigned long lastEnvCheckMs = 0;

void setup() {
  usbSerial.begin(115200);
  const size_t usb_timeout_ms = 3000;
  for (const size_t start_ms = millis(); !usbSerial && (millis() - start_ms) < usb_timeout_ms;)
    ;

  notecard.begin(txRxPinsSerial, 9600);
  notecard.setDebugOutputStream(usbSerial);

  {
    J *req = notecard.newRequest("hub.set");
    if (req != NULL) {
      JAddStringToObject(req, "product", productUID);
      JAddStringToObject(req, "mode", "continuous");
      JAddNumberToObject(req, "duration", 15);
      JAddNumberToObject(req, "inbound", 5);
      notecard.sendRequest(req);
    }
  }
}

void takeReading() {
  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(" %");

  {
    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);
    }
  }
}

void loop() {
  unsigned long currentMs = millis();

  // Check for a new reading_interval_secs value every 10 seconds.
  if (currentMs - lastEnvCheckMs >= 10000) {
    lastEnvCheckMs = currentMs;
    int newIntervalSeconds = getSensorInterval();
    if (newIntervalSeconds != sensorIntervalSeconds) {
      sensorIntervalSeconds = newIntervalSeconds;
      usbSerial.print("Reading interval changed to ");
      usbSerial.print(sensorIntervalSeconds);
      usbSerial.println(" seconds");
    }
  }

  // Take a reading on the first pass, and then whenever the interval has passed.
  if (lastReadingMs == 0 || currentMs - lastReadingMs >= sensorIntervalSeconds * 1000UL) {
    lastReadingMs = currentMs;
    takeReading();
  }
}

// This function assumes you’ll set the reading_interval_secs 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 intervalSeconds = 60;
  J *req = notecard.newRequest("env.get");
  if (req != NULL) {
    JAddStringToObject(req, "name", "reading_interval_secs");
    J* rsp = notecard.requestAndResponse(req);
    int readingIntervalEnvVar = atoi(JGetString(rsp, "text"));
    if (readingIntervalEnvVar > 0) {
      intervalSeconds = readingIntervalEnvVar;
    }
    notecard.deleteResponse(rsp);
  }
  return intervalSeconds;
}
```

With this code in place, your firmware now uses the `reading_interval_secs` environment variable to determine how many seconds to wait between sensor readings. If you flash this updated code to your device and open your serial monitor, you'll see the device take a reading every 60 seconds, the default value for `reading_interval_secs`.

### Setting an Environment Variable {#setting-an-environment-variable}

Now that we have our device programmed to retrieve an environment variable from Notehub, we will create that 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, see the [Set Device Environment Variables](https://dev.blues.io/api-reference/notehub-api/device-api.md#set-device-environment-variables) endpoint.

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

   ![The Notehub device screen](https://dev.blues.io/images/guides/first-sensor/environment/device-screen.png?v=cdb91b6c)

2. Click the **Environment** tab.

3. In the **Device** section, define a new environment variable named `reading_interval_secs` and set its value to `30`.

   ![The environment screen with a new value set](https://dev.blues.io/images/guides/first-sensor/environment/setting-a-variable.png?v=ac552d2e)

Now that you have an environment variable set, you'll see it reflected on your device **after your configured `inbound` interval has passed**.

![The environment screen with a new value set](https://dev.blues.io/images/guides/first-sensor/environment/env-var-serial-log.png?v=f32fe5e6)

note

On cellular and WiFi-based Notecards you can use the [`hub.set` request](https://dev.blues.io/api-reference/notecard-api/hub-requests/latest.md#hub-set)'s `sync` argument to immediately receive inbound updates instead of relying on the `inbound` interval.

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_secs` with your serial monitor open.

tip

Checking `env.get` every few seconds works well for this tutorial, but it means your host has to stay awake and keep asking Notecard whether anything has changed. A more efficient approach is to have Notecard tell your host when a value changes.

If you connect Notecard's `ATTN` pin to a GPIO pin on your host, you can use the [`card.attn` request](https://dev.blues.io/api-reference/notecard-api/card-requests/latest.md#card-attn) with a `mode` of `"arm,env"`, and Notecard will fire `ATTN` whenever an environment variable changes. Your host can then sleep or do other work, and only call `env.get` when `ATTN` fires. See [Handling Notecard Interrupts](https://dev.blues.io/notecard/notecard-walkthrough/inbound-requests-and-shared-data.md#watching-for-environment-variable-changes) for details, and [Putting a Host to Sleep Between Sensor Readings](https://dev.blues.io/example-apps/samples/putting-a-host-to-sleep-between-sensor-readings.md) for a complete example of a host that sleeps between readings.

## Update Your `hub.set` Configuration {#update-your-hub-set-configuration}

Throughout this tutorial, you've used several configuration settings that are typically only appropriate for a Notecard running on mains power.

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

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

- Your firmware takes a new sensor reading every 30 seconds.

Because each of these settings causes the Notecard to use more power, you may wish to disable them if you plan to transition your project to battery power. Optionally complete the steps below to switch to a more typical setup for a battery-powered Notecard.

1. Update your existing `hub.set` request. Setting `mode` to `"periodic"` tells the Notecard to connect on a schedule rather than holding a connection open, and the `outbound` and `inbound` intervals control how many minutes it waits before syncing in each direction. Remove the `duration` argument, which only applies in `continuous` mode.

   ```cpp
   {
     J *req = notecard.newRequest("hub.set");
     if (req != NULL) {
       JAddStringToObject(req, "product", productUID);
       JAddStringToObject(req, "mode", "periodic");
       JAddNumberToObject(req, "outbound", 60);
       JAddNumberToObject(req, "inbound", 360);
       notecard.sendRequest(req);
     }
   }
   ```

2. In your `note.add` request, change `sync` from `true` to `false`, so each reading waits for the next scheduled sync instead of triggering one of its own.

   ```c
   JAddBoolToObject(req, "sync", false);
   ```

3. Save your changes and load the updated firmware onto your device.

4. Finally, slow down how often you take readings. A reading every 30 seconds is handy while you're learning, because new data shows up in Notehub almost right away, but it's far more often than most real products need.

   In Notehub, update your `reading_interval_secs` environment variable in Notehub to `1800` (30 minutes). Because your firmware reads its interval from Notehub, you don't need to reflash your device to make the change.

tip

- For a deeper look at how the `hub.set` request’s settings work together, watch [An In-Depth Guide to Notecard’s hub.set Request](https://www.youtube.com/watch?v=3D2p1t8UMHQ). The video steps through complete configuration scenarios that show how your choice of `mode`, `outbound`, `inbound`, and `sync` values determines exactly when your Notecard connects and syncs with Notehub.

- For other recommendations when building low-power friendly firmware, see [Low-Power Firmware Design](https://dev.blues.io/notecard/notecard-walkthrough/low-power-firmware-design.md).

AI Tip

LLMs can also help you get your configuration right.

Prompt

Review the Blues recommendations for the `hub.set` request at `https://dev.blues.io/notecard/notecard-walkthrough/essential-requests/#notehub-configuration-hub-set`. Then help me get my own `hub.set` configuration right in my firmware based on what you know about my project. Ask me questions to gather more information as necessary.

## Next Steps {#next-steps}

**Congratulations!** You've successfully connected your Arduino Nano 33 BLE Sense to your Notecard and built a basic IoT project.

tip

**Leave your device running.** The next tutorial uses the temperature, humidity, and session data your device is sending right now, and the more it has collected by the time you get there, the more interesting your questions can be. Keep your Notecard powered and connected until you've finished the final quickstart tutorial.

If you're following a Cell+WiFi Quickstart, next we recommend learning how to ask questions about the data your device is collecting:

1. ~~Use Notecard to Send Data~~

2) ~~Wire Notecard to Your Host~~

3. ~~Build Your First IoT App With Blues~~
4. [Explore Your Data With Notehub IQ](https://dev.blues.io/guides-and-tutorials/using-notehub-iq.md)

At any time, if you find yourself stuck, please reach out on the [community forum](https://discuss.blues.com/).

Can we improve this page? [Send us feedback](mailto:devrel@blues.com)
