# Getting Started

Welcome to **Consentium IoT**! We empower developers, researchers, and innovators to build the next generation of intelligent products with **Edge AI** and **IoT**. Whether you're a beginner or an expert, our platform provides all the tools you need to bring your ideas to life. Explore our comprehensive user guides, tutorials, and API documentation to get started.

Consentium IoT offers tailored experiences based on your background and expertise, ensuring a smooth development process. Whether you're a **beginner**, an **advanced embedded engineer**, an **ML engineer**, or a **data scientist**, we've crafted the following getting-started guides just for you:

* **Beginners**: Learn the fundamentals of IoT and get started with your first device.
* **Advanced Embedded Engineers**: Dive into hardware integration and low-level programming for optimizing performance.
* **ML Engineers**: Harness the power of Edge AI with our easy-to-use machine learning frameworks.
* **Data Scientists**: Explore how to collect, analyze, and utilize data effectively with Consentium IoT.

Get ready to innovate with **Consentium IoT**—your partner in intelligent edge solutions!

### Jump right in

<table data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Getting Started</strong></td><td>Using the site and Sensor data API documentation</td><td><a href="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2F5rwivWfMiYlozcd66Pwr%2Fhero-img.png?alt=media&amp;token=053bc52a-4015-420c-956e-da3e9cb09d1a">hero-img.png</a></td><td></td><td><a href="/readme/consentium-iot-platform-usage">Consentium IoT Platform usage</a></td></tr><tr><td><strong>Uploading sensor data</strong></td><td>Tutorial on uploading sensor data to Consentium IoT cloud</td><td><a href="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FFfbhVd417qtIaGgUvkSC%2Ffeatures-3.png?alt=media&amp;token=93ceb4ff-dc3b-4b87-8184-cbba0a44eb85">features-3.png</a></td><td></td><td><a href="/code-usage">Code usage</a></td></tr><tr><td><strong>Tutorials</strong></td><td>Detailed tutorial with various sensors </td><td><a href="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FqCyybaP6fkStsCImayts%2Ffeatures-2.png?alt=media&amp;token=ef2f971d-52c1-4e2d-a5da-598b091d4912">features-2.png</a></td><td></td><td><a href="/tutorials/receiving-sensor-data">Tutorials</a></td></tr></tbody></table>


# Consentium IoT Platform usage

## Steps to Set Up Your Board and Send Sensor Data

### 1. Sign Up

* Visit the [Consentium IoT](https://consentiumiot.com/) website and create an account.
* After completing the sign-up process, verify your email to activate your account.

### 2. Log In

* Once verified, log into your Consentium IoT account using your credentials.

### 3. Create a New Board

* Navigate to the dashboard.
* Click on the "Create Board" option. You’ll see a pop-up to input board details.

### 4. Add Board Details

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2Fb3SPRQvq7rDlGW7R7Z5t%2FCapture.PNG?alt=media&amp;token=54f9b56d-63b8-4a91-99d2-331ecc22b476" alt=""><figcaption></figcaption></figure>

* Provide the following details:
  * **Board Name**: The name of your board (e.g., Temperature Sensor).
  * **Board Description**: A short description of what the board will do (e.g., This board will monitor room temperature).
  * **Send API Key**: A unique API key will be generated for the board.

### 5. Access API Documentation

* After saving the board, click on the "API Documentation" button.
* This will provide detailed instructions on integrating with the platform.

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FfqMHrlrZZwOrg4LNzyF4%2F4.%20API%20documentation.png?alt=media&amp;token=8a873269-530c-43ad-be34-1bdc3b78208d" alt="" width="280"><figcaption></figcaption></figure>

### 6. Copy the Send API Key

* From the "Authentication API Key" section, copy the **Send API Key**.
* This key will be used to authenticate sensor data transmission.

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2F6Y7Dgld3e9fti2I0CeQN%2F5.%20copy_send_key.png?alt=media&amp;token=babb793f-9b63-4c5f-97f4-f5cfc3686c3a" alt=""><figcaption></figcaption></figure>

### 7. Use in ConsentiumThings Code

* Paste the **Send API Key** into the appropriate field in the ConsentiumThings send sensor data code.
* Similarly, copy the **Board Key** (also generated) and paste it into the code where required.

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FlXE9XYtkhQE6MvZD1W7K%2F6.%20copy_board_key.png?alt=media&amp;token=8366f062-a401-4391-a5e2-a85a3d4d783c" alt=""><figcaption></figcaption></figure>

Following these steps will allow you to successfully create a board and begin sending sensor data to the Consentium IoT platform.

## 8. Install the Consentium IoT library&#x20;

To install the Arduino library for Consentium IoT services on ESP32,  ESP 8266 or Raspberry Pi Pico W microcontrollers, move over to **Arduino's Library Manager** and search for **ConsentiumThings.**

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2F1JCQsMoMFo6krf1FTrhL%2FScreenshot%202024-09-04%20at%2011.22.02%E2%80%AFAM.png?alt=media&amp;token=1f8debe1-dcd0-4d63-82a5-96ddf93c1914" alt="" width="283"><figcaption></figcaption></figure>


# Consentium IoT Sensor Data API — Developer Documentation v2

The Consentium IoT API enables **IoT devices** to send telemetry (sensor readings, firmware/device status) to the cloud and allows **applications** to retrieve historical and real-time data for monitoring, analytics, or automation.

***

### **Base URL**

```url

https://api.consentiumiot.com

```

***

### **Authentication & Access Control**

Every request requires **authentication keys** provided at board registration:

* **`sendKey`** → Used for **write operations** (sending or updating sensor data).
* **`receiveKey`** → Used for **read operations** (retrieving sensor data).
* **`boardKey`** → Unique identifier for a virtual board.

⚠️ **Important:**

* Keep your keys secret. Treat them like passwords.
* Use HTTPS at all times to avoid exposing credentials.

***

### **Quickstart Guide**

#### **1. Submit Data (POST)**

**cURL Example**

```bash
curl -X POST "https://api.consentiumiot.com/v2/updateData?sendKey=<YOUR-SEND-KEY>&boardKey=<YOUR-BOARD-KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "sensors": {
      "sensorData": [
        { "info": "Temperature/C", "data": "40.00" },
        { "info": "Humidity/%", "data": "90.00" }
      ]
    },
    "boardInfo": {
      "firmwareVersion": "0.0",
      "architecture": "ESP32",
      "statusOTA": false,
      "deviceMAC": "DD:DA:0C:20:E1:41",
      "signalStrength": -30
    }
  }'
```

**Postman Example**

* **Method**: `POST`
* **URL**:

  ```
  https://api.consentiumiot.com/v2/updateData?sendKey=<YOUR-SEND-KEY>&boardKey=<YOUR-BOARD-KEY>
  ```
* **Headers**: `Content-Type: application/json`
* **Body (raw JSON)**:

  ```json
  {
    "sensors": {
      "sensorData": [
        { "info": "Temperature/C", "data": "40.00" },
        { "info": "Humidity/%", "data": "90.00" }
      ]
    },
    "boardInfo": {
      "firmwareVersion": "0.0",
      "architecture": "ESP32",
      "statusOTA": false,
      "deviceMAC": "DD:DA:0C:20:E1:41",
      "signalStrength": -30
    }
  }
  ```

***

#### **2. Get Historical Data (GET)**

**cURL Example**

```bash
curl "https://api.consentiumiot.com/getData?receiveKey=<YOUR-RECEIVE-KEY>&boardKey=<YOUR-BOARD-KEY>"
```

**Postman Example**

* **Method**: `GET`
* **URL**:

  ```
  https://api.consentiumiot.com/getData?receiveKey=<YOUR-RECEIVE-KEY>&boardKey=<YOUR-BOARD-KEY>
  ```

***

#### **3. Get Most Recent Data (GET)**

**cURL Example**

```bash
curl "https://api.consentiumiot.com/getData?recents=true&receiveKey=<YOUR-RECEIVE-KEY>&boardKey=<YOUR-BOARD-KEY>"
```

**Postman Example**

* **Method**: `GET`
* **URL**:

  ```
  https://api.consentiumiot.com/getData?recents=true&receiveKey=<YOUR-RECEIVE-KEY>&boardKey=<YOUR-BOARD-KEY>
  ```

***

### **Endpoints Overview**

| HTTP Method | Endpoint                | Purpose                                         |
| ----------- | ----------------------- | ----------------------------------------------- |
| **POST**    | `/v2/updateData`        | Submit or update telemetry data for a board.    |
| **GET**     | `/getData`              | Retrieve all historical data feeds for a board. |
| **GET**     | `/getData?recents=true` | Retrieve only the most recent feed(s).          |

***

### **1. Submit / Update Sensor Data**

#### **Endpoint**

```http
POST /v2/updateData?sendKey=<YOUR-SEND-KEY>&boardKey=<YOUR-BOARD-KEY>
```

#### **Description**

Used by IoT boards or edge devices to **push telemetry data** to the Consentium IoT platform.

Each update includes:

1. **Sensor readings** → flexible key-value structure.
2. **Board metadata (`boardInfo`)** → mandatory information about the device’s state and identity.

***

#### **Request Body**

```json
{
  "sensors": {
    "sensorData": [
      {
        "info": "Temperature/C",
        "data": "40.00"
      },
      {
        "info": "Humidity/%",
        "data": "90.00"
      }
    ]
  },
  "boardInfo": {
    "firmwareVersion": "0.0",
    "architecture": "ESP32",
    "statusOTA": false,
    "deviceMAC": "DD:DA:0C:20:E1:41",
    "signalStrength": -30
  }
}
```

#### **Response**

* **200 OK**

```json
{
  "status": "success",
  "message": "Sensor data updated successfully"
}
```

#### **Error Codes**

* **422 Unprocessable Entity** → Missing required `boardInfo` fields.
* **429 Too Many Requests** → MAC address mismatch (board vs. physical device).
* **400 Bad Request** → Malformed JSON or missing parameters.
* **401 Unauthorized** → Invalid `sendKey`.

***

### **2. Get Historical Data**

#### **Endpoint**

```http
GET /getData?receiveKey=<YOUR-RECEIVE-KEY>&boardKey=<YOUR-BOARD-KEY>
```

#### **Description**

Fetch all stored feeds for a board. Each feed entry maps `infoN` (sensor name) to `valueN` (sensor reading).

***

#### **Response**

```json
{
  "board": {
    "info1": "Temperature",
    "info2": "Humidity",
    "name": "Test board2"
  },
  "feeds": [
    {
      "updated_at": "2025-09-05T14:20:56.914801Z",
      "value1": 40.0,
      "value2": 90.0
    },
    {
      "updated_at": "2025-09-05T13:59:22.101432Z",
      "value1": 39.5,
      "value2": 88.0
    }
  ]
}
```

***

### **3. Get Most Recent Data**

#### **Endpoint**

```http
GET /getData?recents=true&receiveKey=<YOUR-RECEIVE-KEY>&boardKey=<YOUR-BOARD-KEY>
```

#### **Description**

Returns only the most recent feed entry for a board.

***

#### **Response**

```json
{
  "board": {
    "info1": "Temperature",
    "info2": "Humidity",
    "name": "Test board2"
  },
  "feeds": [
    {
      "updated_at": "2025-09-05T14:20:56.914801Z",
      "value1": 40.0,
      "value2": 90.0
    }
  ]
}
```

***

**Base Endpoint**

```
GET /getData?receiveKey=<RECEIVE_KEY>&boardKey=<BOARD_KEY>
```

***

***

### 5. Time-Range Slicing (Grafana Compatible)

Consentium API supports proper ISO-8601 UTC format:

```
YYYY-MM-DDTHH:mm:ss.SSSZ
```

#### **Example**

```hurl
https://api.consentiumiot.com/getData?recents=false&receiveKey=<KEY>&boardKey=<KEY>&from=2025-11-18T08:30:21.000 00:00&to=2025-11-18T10:00:21.000 00:00
```

***

## Grafana Integration Guide

*Using the Infinity Plugin*

***

### 1. Install Infinity Plugin

1. Go to **Connections → Plugins**
2. Search "Infinity"
3. Install & enable

***

### 2. Add Data Source

* Data Sources → **Add New**
* Select **Infinity**
* Set:
  * **Access:** Server
  * **Method:** GET

***

### 3. Use Time-Range Query URL

```hurl
https://api.consentiumiot.com/getData?recents=false&receiveKey=<YOUR_RECEIVE_KEY>&boardKey=<YOUR_BOARD_KEY>&from=${__from:date:YYYY-MM-DDTHH:mm:ss.SSSZ}&to=${__to:date:YYYY-MM-DDTHH:mm:ss.SSSZ}
```

> **Why `Z`?** This ensures Grafana formats timestamps in **pure UTC**, avoiding timezone issues.

***

### 4. Recommended Infinity Settings

| Setting    | Value               |
| ---------- | ------------------- |
| Query Type | URL                 |
| Parse As   | JSON                |
| Format     | Table / Time Series |
| Method     | GET                 |

***

### 5. Field Mapping in Grafana

| Column  | JSON Path                 |
| ------- | ------------------------- |
| Time    | `feeds[].updated_at`      |
| Value 1 | `feeds[].value1`          |
| Value 2 | `feeds[].value2`          |
| …       | Additional sensor indexes |

Suggested transforms:

* **Extract Fields**
* **Organize Fields**
* **Convert to Time Series (Wide)**
* **Rename Fields** to match sensor names

***

## Timestamp Specification

All timestamps returned by the Consentium API are:

* **UTC**
* **ISO-8601 format**
* **Always end with Z**

Examples:

```
2025-09-05T14:20:56.914801Z
2025-10-01T06:12:30.000Z
```

***

### **Error Handling**

The API uses standard HTTP status codes:

| Status Code                  | Meaning             | Example Scenario                                |
| ---------------------------- | ------------------- | ----------------------------------------------- |
| **200 OK**                   | Success             | Data retrieved or updated successfully.         |
| **400 Bad Request**          | Invalid request     | Malformed JSON, missing params.                 |
| **401 Unauthorized**         | Invalid/missing key | Wrong `sendKey` or `receiveKey`.                |
| **404 Not Found**            | Board not found     | Invalid `boardKey`.                             |
| **422 Unprocessable Entity** | Validation error    | Missing required `boardInfo` field.             |
| **429 Too Many Requests**    | MAC mismatch        | Board’s virtual key doesn’t match reported MAC. |

***

### **Best Practices**

* **Rate limiting:** Avoid excessive calls. Implement exponential backoff for retries.
* **Secure your keys:** Never expose `sendKey` or `receiveKey` in client-side code.
* **Validate data locally:** Ensure correct sensor units, numeric ranges, and field consistency.
* **Use device MAC correctly:** Each virtual board is **tagged with its physical MAC**. Mismatches will be rejected.
* **Timestamp awareness:** All timestamps are returned in **UTC (ISO 8601 format)**.

***

### **Changelog**

* **v2 (Current)**
  * Introduced `boardInfo` block (mandatory).
  * MAC address validation enforced.
  * Unified `getData` responses into `board + feeds` structure.
* **v1 (Deprecated)**
  * Sensor data posted without `boardInfo`.
  * Simple array responses instead of structured board metadata.

***


# Using the Consentium IoT Public MQTT Broker

This guide provides developers with the necessary information to connect to the Consentium IoT public MQTT broker. Our broker is designed to facilitate lightweight, real-time data exchange for your IoT projects, including those utilizing our proprietary hardware such as the Edge Dalton board.

### Connection Details

* Broker Address: `broker.consentiumiot.com`
* Port: `1883` (Non-secure TCP)
* Protocol: MQTT (Message Queuing Telemetry Transport)

### Python Implementation

To interact with the broker in Python, we recommend using the `paho-mqtt` library.

#### Prerequisites

Install the library via terminal:

Bash

```
pip install paho-mqtt
```

#### Example Code

Python

```python
import paho.mqtt.client as mqtt
import time

# Broker settings
BROKER = "broker.consentiumiot.com"
PORT = 1883
TOPIC = "consentium/test/topic"

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to Consentium Broker")
        client.subscribe(TOPIC)
    else:
        print(f"Failed to connect, return code {rc}")

def on_message(client, userdata, msg):
    print(f"Message received on {msg.topic}: {msg.payload.decode()}")

# Setup client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

# Connect and loop
client.connect(BROKER, PORT, 60)
client.loop_start()

# Publish a test message
client.publish(TOPIC, "Hello from Consentium IoT!")

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    client.loop_stop()
```

### ESP32 Implementation

For ESP32 development, the `PubSubClient` library is the standard choice for handling MQTT communication.

#### Prerequisites

1. Ensure the ESP32 Board Support is installed in your Arduino IDE.
2. Install the PubSubClient library via the Library Manager.

#### Example Code

C++

```cpp
#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
const char* mqtt_server = "broker.consentiumiot.com";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  
  client.setServer(mqtt_server, 1883);
}

void loop() {
  if (!client.connected()) {
    // Unique ID based on MAC address
    String clientId = "ESP32Client-" + String(WiFi.macAddress());
    if (client.connect(clientId.c_str())) {
      Serial.println("Connected to Broker");
    }
  }
  
  client.loop();
  
  // Publish example data
  client.publish("consentium/edge/dalton", "{\"status\": true, \"value\": 42}");
  delay(5000);
}
```

### Best Practices

* Client IDs: Always use unique Client IDs for each device. Using `WiFi.macAddress()` is a reliable way to ensure uniqueness for ESP32 devices.
* Payloads: While our broker supports raw strings, we recommend using JSON format for structured data, ensuring you follow schema requirements (e.g., using `true`/`false` for boolean feature states).
* QoS: Use QoS 0 for telemetry data to maintain low latency, and QoS 1 if message delivery guarantees are critical for your application.
* Non-blocking: Keep your `loop()` functions non-blocking to ensure the MQTT client can maintain its connection heartbeats.


# Consentium IoT Sensor Data API — Developer Documentation v1 (depricated)

This API allows the creation, update, retrieval, and management of sensor data associated with various boards. Each board can have multiple sensors with unique data points.

### Base URL

```url
https://consentiumiot.com/api/board/
```

***

## **Authentication**

All API requests require authentication via `sendkey` or `receivekey`, depending on the type of operation (e.g., sending or receiving data). The keys should be included as URL parameters.

### **Request Authentication Parameters:**

* **`sendkey`**: A key used for authenticated operations such as creating or deleting data.
* **`receivekey`**: A key used to retrieve or read data from the board.

***

## **Endpoints Overview**

| HTTP Method | Endpoint          | Description                                                |
| ----------- | ----------------- | ---------------------------------------------------------- |
| **POST**    | `/updatedata`     | Create or update sensor data on a board.                   |
| **GET**     | `/getdata`        | Retrieve all sensor data for a specific board.             |
| **GET**     | `/getdata/recent` | Retrieve the most recent sensor data for a specific board. |

***

## **1. Create or Update Sensor Data (POST)**

### **Endpoint**

```url
POST /updatedata?key=YOUR_SEND_KEY&boardkey=YOUR_BOARD_KEY
```

### **Description**

This API endpoint is used to create new sensor data or update existing sensor data for a specific board. Up to seven sensors can be updated simultaneously for a board. Each sensor has an `info` field (which provides a label or description) and a `data` field (which stores the value for that sensor).

### **URL Parameters**

* `key=YOUR_SEND_KEY` (required): The authentication key used to authorize the creation or update of sensor data.
* `boardkey=YOUR_BOARD_KEY` (required): The unique identifier for the board to which the sensor data will be added.

### **Request Body Format**

The body must include a JSON object with an array of sensors. Each sensor entry contains:

* `info`: A string describing the sensor (e.g., "Temperature", "Humidity").
* `data`: A numeric value representing the data for that sensor.
* `firmwarefirmwareVersion`: A numeric value representing the firmware version for that board.
* `architecture`: A string value representing the board type (e.g. ESP32, ESP8266, GenericPython)

#### **Example Request Body**

```json
{
    "sensors": {
        "sensorData": [
            {
                "info": "Temperature",
                "data": "34.00"
            },
            {
                "info": "Humidity",
                "data": "90.00"
            }
        ]
    },
    "boardInfo": {
        "firmwareVersion": "0.0",
        "architecture": "ESP32"
    }
}
```

### **Response**

* **200 OK**: The sensor data was successfully created or updated.
* **400 Bad Request**: There was an issue with the request (e.g., malformed body, missing parameters).

#### **Example Response**

```json
{
  "message": "Sensor data updated successfully"
}
```

***

## **2. Get All Sensors for a Board (GET)**

### **Endpoint**

```
GET /getdata?receivekey=YOUR_RECEIVE_KEY&boardkey=YOUR_BOARD_KEY
```

### **Description**

This API retrieves all the sensor data associated with a specific board. It returns an array of sensor data, each containing information such as the sensor type (`info`) and its recorded value (`data`).

### **URL Parameters**

* `receivekey=YOUR_RECEIVE_KEY` (required): The authentication key used to retrieve sensor data.
* `boardkey=YOUR_BOARD_KEY` (required): The unique identifier for the board from which the sensor data will be retrieved.

### **Response**

* **200 OK**: A JSON array of sensor data is returned.
* **400 Bad Request**: The request is invalid (e.g., missing or incorrect parameters).

#### **Example Response**

```json
{
  "sensors": [
    {
      "info": "Humidity",
      "data": "230"
    },
    {
      "info": "Temperature",
      "data": "24"
    }
  ]
}
```

***

## **3. Get the Most Recent Sensor Data (GET)**

### **Endpoint**

```
GET /getdata/recent?receivekey=YOUR_RECEIVE_KEY&boardkey=YOUR_BOARD_KEY
```

### **Description**

This API fetches the most recent sensor data entry for a specified board. It is particularly useful for monitoring real-time updates or viewing the latest data points for a board.

### **URL Parameters**

* `receivekey=YOUR_RECEIVE_KEY` (required): The authentication key used to retrieve the most recent sensor data.
* `boardkey=YOUR_BOARD_KEY` (required): The unique identifier for the board from which the most recent sensor data will be retrieved.

### **Response**

* **200 OK**: The most recent sensor data is returned in JSON format.
* **400 Bad Request**: The request is invalid (e.g., missing or incorrect parameters).

#### **Example Response**

```json
{
  "info": "Temperature",
  "data": "24",
  "timestamp": "2024-09-03T12:34:56Z"
}
```

***

## **Error Handling**

The API uses standard HTTP status codes to indicate the success or failure of an API request. Here's a summary of the potential errors:

| Status Code          | Error Message              | Description                                                                                                                                |
| -------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| **200 OK**           | Success                    | The request was successful, and the response contains the data requested.                                                                  |
| **400 Bad Request**  | Invalid request            | There was a problem with the request. This could be due to missing required parameters or an invalid request format.                       |
| **401 Unauthorized** | Invalid or missing API key | The provided `sendkey` or `receivekey` is either missing or invalid. Please ensure the key is correct and has the appropriate permissions. |
| **404 Not Found**    | Board not found            | The `boardkey` provided does not match any existing boards. Ensure the board key is correct.                                               |

***

## **Best Practices**

* **Rate Limiting**: Avoid sending too many requests in a short period. Implement proper rate-limiting mechanisms in your application to prevent being throttled.
* **Error Handling**: Always check for non-200 status codes and handle them appropriately in your application (e.g., retry logic, user-friendly error messages).
* **Data Validation**: Ensure that the `info` field in sensor data accurately describes the sensor and that the `data` field contains appropriate numeric values. This ensures consistency and readability when retrieving sensor data later.


# Steps for Using Consentium IoT's OTA Service

## Step 1: Prepare the OTA-Capable Sketch

1. **Create an OTA-Capable Sketch**: Write an Arduino sketch for your **ESP32**, **ESP8266**, or **Raspberry Pi Pico W** that includes OTA functionality.
2. **Set Firmware Version**: Ensure the `FIRMWARE_VERSION` variable is set to `"0.0"`. This indicates the initial firmware version. You can update this to any version number as needed, but `0.0` is used here for demonstration.

   ```cpp
   #define FIRMWARE_VERSION "0.0"  // Initial firmware version
   ```

## Step 2: Upload the Sketch to the IoT Board

1. **Connect the Board**: Connect your IoT board to your development machine using a USB cable.
2. **Upload the Sketch**: Upload the OTA-capable sketch to the board using the Arduino IDE.

## Step 3: Access the Consentium IoT Cloud

1. **Log In**: Log into the **Consentium IoT Cloud**.
2. **Navigate to Device OTA**: Go to the **Device OTA** page. You should see the OTA-capable device listed with its current firmware version displayed.

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2F0TiaapjPJmTh1s6RZ2k0%2FScreenshot%202024-09-04%20at%201.49.29%E2%80%AFPM.png?alt=media&amp;token=74765818-28a8-42c3-8f2a-b0f1ac31569c" alt=""><figcaption></figcaption></figure>

## Step 4: Prepare the Updated Firmware

1. **Disconnect the Board**: Ensure the IoT board is no longer physically connected to the development machine.
2. **Update the Sketch**: Make any desired changes to your code and update the `FIRMWARE_VERSION` variable to `"0.1"` (or any new version number).

   ```cpp
   #define FIRMWARE_VERSION "0.1"  // Updated firmware version
   ```
3. **Export the Compiled Binary**: In the Arduino IDE, go to the **Sketch** menu and click on **Export Compiled Binary**. This action generates a **.bin** file for the updated firmware, which will be saved in a folder under your project directory.

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2F4uPuJHgwUKKJrHHFyoM9%2FScreenshot%202024-09-04%20at%201.50.24%E2%80%AFPM.png?alt=media&amp;token=3ec287d6-a63b-41dc-9645-f08d5b327d19" alt="" width="259"><figcaption></figcaption></figure>

## Step 5: Upload the New Firmware

1. **Upload the .bin File**: Return to the **Device OTA** page in the Consentium IoT Cloud.
2. **Select and Upload**: Choose the generated **.bin** file and upload it to the appropriate board.

## Step 6: Verify the Update

1. **Check Firmware Versions**: After the update is pushed, verify that the **Current** and **Board Firmware Versions** are the same to confirm the update was successful.


# Consentium Edge Machine Learning

Overview

**EdgeNeuron** is an Arduino-style wrapper for TensorFlow Lite Micro, making it easier to deploy machine learning models on microcontrollers. It abstracts TensorFlow Lite Micro functionalities into intuitive functions that resemble standard Arduino API usage. This library aims to simplify the process of setting up and running machine learning inferences on embedded devices such as the ESP32, Nano 33 BLE, and Portenta, without requiring deep knowledge of TensorFlow Lite's internal workings.

#### Features

* Easy integration with TensorFlow Lite Micro models.
* Simple function-based interface for model initialization, input handling, and inference execution.
* Avoids advanced C++ structures (e.g., pointers) commonly not recommended in Arduino sketches.
* Efficient memory management using a user-defined tensor arena buffer.
* Supports a variety of microcontroller architectures such as **mbed\_nano**, **esp32**, **mbed\_nicla**, **mbed\_portenta**, and **mbed\_giga**.

#### Architecture

EdgeNeuron is built on top of the `TensorFlowLite Micro` library and offers a simplified interface to interact with TensorFlow Lite models. The core components of the library include:

* **Model Initialization**: Handles loading the TensorFlow Lite model into memory and allocating the required tensors.
* **Input Data Handling**: Provides an interface to set input data to the model's input tensor.
* **Inference Execution**: Executes the inference cycle and retrieves the output predictions.
* **Tensor Memory Management**: Defines a user-controlled memory area for storing tensors and running inferences efficiently.

#### Supported Platforms

EdgeNeuron supports the following microcontroller architectures:

* **mbed\_nano**
* **esp33**
* **esp8266**

### Installation

#### Using Arduino Library Manager

1. Open the Arduino IDE.
2. Go to **Sketch** -> **Include Library** -> **Manage Libraries**.
3. Search for **EdgeNeuron**.
4. Click **Install** to add the library to your project.

#### Manual Installation

1. Download the latest release from the [GitHub repository](https://github.com/ConsentiumInc/EdgeNeuron).
2. Extract the contents into the `libraries` folder inside your Arduino project directory.

### Getting Started

This section provides a step-by-step guide to using the EdgeNeuron library for running machine learning models on an Arduino-compatible board.

#### 1. Model Conversion

Before using EdgeNeuron, you must convert your TensorFlow model into a TensorFlow Lite Micro format (`.tflite`). This can be done using TensorFlow's Python API by following these steps:

```python
import tensorflow as tf

# Load your trained model
model = tf.keras.models.load_model('your_model.h5')

# Convert the model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()

# Save the model in TFLite format
with open('model.tflite', 'wb') as f:
    f.write(tflite_model)
```

Once you have your `model.tflite` file, you can convert it to a static byte array for embedding into the Arduino project using [xxd](https://linux.die.net/man/1/xxd) or an online tool.

```bash
xxd -i model.tflite > model.h
```

#### 2. Basic Example

Below is a simple example that uses EdgeNeuron to perform inference with a TensorFlow Lite Micro model that predicts sine wave values:

```cpp
#include <EdgeNeuron.h>
#include "model.h"

// Tensor arena for TensorFlow Lite to store tensors
constexpr int kTensorArenaSize = 2000;
alignas(16) uint8_t tensor_arena[kTensorArenaSize];

// Define the range for x (between 0 and 2π)
float x = 0.0;
float step = 0.1;

void setup() {
  Serial.begin(9600);
  while (!Serial);

  Serial.println("Initializing TensorFlow Lite Micro Interpreter...");

  // Initialize the model with the tensor arena
  if (!initializeModel(model, tensor_arena, kTensorArenaSize)) {
    Serial.println("Model initialization failed!");
    while (true);
  }

  Serial.println("Model initialization done.");
}

void loop() {
  if (x > 6.28) {
    x = 0.0;
  }

  // Set the input value in the input tensor
  setModelInput(x, 0);

  // Run inference
  if (!runModelInference()) {
    Serial.println("Inference failed!");
    return;
  }

  // Get predicted output
  float y_predicted = getModelOutput(0);
  float y_actual = sin(x);

  // Print results
  Serial.print("Input x: ");
  Serial.print(x, 2);
  Serial.print(" | Predicted sin(x): ");
  Serial.print(y_predicted, 2);
  Serial.print(" | Actual sin(x): ");
  Serial.println(y_actual, 2);

  // Increment x for the next loop iteration
  x += step;

  delay(500);
}
```

### API Reference

#### 1. `bool initializeModel(const unsigned char* model, byte* tensorArena, int tensorArenaSize)`

This function initializes the TensorFlow Lite model and prepares the interpreter for inference.

**Parameters:**

* `model`: Pointer to the model data in memory (typically a `const unsigned char*`).
* `tensorArena`: Pointer to the memory buffer that will be used to store tensors.
* `tensorArenaSize`: The size of the tensor memory buffer.

**Returns:**

* `true` if the initialization was successful, otherwise `false`.

#### 2. `bool setModelInput(float inputValue, int index)`

Sets the input value at the specified index in the input tensor.

**Parameters:**

* `inputValue`: The value to set in the input tensor.
* `index`: The index of the input tensor where the value should be placed.

**Returns:**

* `true` if the input was successfully set, otherwise `false`.

#### 3. `bool runModelInference()`

Runs the inference cycle of the model.

**Returns:**

* `true` if the inference was successful, otherwise `false`.

#### 4. `float getModelOutput(int index)`

Retrieves the output value from the specified index of the output tensor.

**Parameters:**

* `index`: The index of the output tensor to retrieve the value from.

**Returns:**

* The output value, or `-1` if an error occurred.

#### 5. `void cleanupModel()`

Optionally cleans up the interpreter to free up memory after inference.

### Example Use Cases

#### 1. Gesture Recognition

Using an IMU sensor like MPU6050 to recognize hand gestures. The sensor data (acceleration and gyroscope) is fed into a pre-trained model to classify gestures such as "punch" or "flex."

#### 2. Voice Command Recognition

You can run a simple audio classification model on the microcontroller to recognize voice commands, such as "yes" or "no," by converting raw audio signals into features that are input into the model.

### Known Limitations

* **Limited Memory**: EdgeNeuron operates on devices with limited RAM, which restricts the complexity of models you can deploy.
* **Inference Speed**: The performance of the model inference can be slow depending on the complexity of the model and the microcontroller's processing power.
* **Limited Model Support**: Only TensorFlow Lite Micro models are supported. Complex models like RNNs and CNNs with many layers may require optimization or pruning to fit within microcontroller memory constraints.

### Conclusion

**EdgeNeuron** is a powerful, easy-to-use library for integrating TensorFlow Lite Micro models into Arduino-based projects. It simplifies running machine learning inferences on microcontrollers, making it suitable for applications such as gesture recognition, speech recognition, and simple sensor-based predictions.

For advanced use cases, users may need to delve into TensorFlow Lite Micro documentation to understand the limitations of running deep learning models on constrained devices.

For more examples and detailed guides, visit the [GitHub repository](https://github.com/ConsentiumInc/EdgeNeuron/).


# ConsentiumNow Library Documentation

### Overview

The **ConsentiumNow** library provides seamless ESP-NOW communication between ESP32-compatible devices. It is a powerful tool designed to facilitate real-time, reliable data exchange for IoT applications using custom user-defined data structures. Built with simplicity and flexibility in mind, the library is lightweight yet robust, supporting a wide range of IoT use cases.

#### Key Features

* Lightweight and flexible ESP-NOW integration.
* Customizable data structures for specific applications.
* Supports one-to-one and one-to-many communication.
* Easy-to-use API for sending and receiving data.
* Highly efficient for low-latency IoT communication.

***

### Getting Started

#### Prerequisites

Before you begin, ensure you have the following:

* **Hardware**: ESP32-compatible boards (minimum two for testing).
* **Software**: Arduino IDE (or PlatformIO) configured for ESP32 development.
* **Basic Knowledge**: Familiarity with the ESP-NOW protocol and Arduino programming basics.

***

### Installation

1. Clone this repository or download it as a ZIP.
2. Open the Arduino IDE and navigate to **Sketch > Include Library > Add .ZIP Library**.
3. Select the `ConsentiumNow` library ZIP file.

Alternatively, extract the ZIP into your Arduino `libraries` folder:\
`<Arduino Sketchbook Folder>/libraries/ConsentiumNow`

***

### Usage Examples

#### 1. Basic Sender

```cpp
#include <ConsentiumNow.h>

// Define the data structure
struct SensorData {
    float temperature;  // Temperature in °C
    float humidity;     // Humidity in %
};

// Create an instance of ConsentiumNow for sending
ConsentiumNow<SensorData> consentiumSender;

// Replace with the receiver's MAC address
uint8_t receiverMac[] = {0x7C, 0x9E, 0xBD, 0x66, 0x7A, 0x0C};

void setup() {
    Serial.begin(115200);
    consentiumSender.sendBegin(receiverMac);  // Initialize sender
    Serial.println("Sender initialized.");
}

void loop() {
    SensorData data;
    data.temperature = random(200, 300) / 10.0; // Random temperature (20.0 - 30.0)
    data.humidity = random(400, 600) / 10.0;    // Random humidity (40.0 - 60.0)
    
    consentiumSender.sendData(data);
    Serial.printf("Sent Data - Temperature: %.2f, Humidity: %.2f\n", 
                  data.temperature, data.humidity);
    delay(2000); // Send every 2 seconds
}
```

***

#### 2. Basic Receiver

```cpp
#include <ConsentiumNow.h>

// Define the data structure
struct SensorData {
    float temperature;  // Temperature in °C
    float humidity;     // Humidity in %
};

// Create an instance of ConsentiumNow for receiving
ConsentiumNow<SensorData> consentiumReceiver;

void setup() {
    Serial.begin(115200);
    consentiumReceiver.receiveBegin();  // Initialize receiver
    Serial.println("Receiver ready to receive data.");
}

void loop() {
    if (consentiumReceiver.isDataAvailable()) {
        SensorData data = consentiumReceiver.getReceivedData();
        Serial.printf("Received Data - Temperature: %.2f, Humidity: %.2f\n", 
                      data.temperature, data.humidity);
    }
    delay(500); // Check every 500ms
}
```

***

#### Multi-Sender to One Receiver

1. Configure the receiver to recognize multiple senders.
2. Use `addPeer()` to add the MAC addresses of each sender.

```cpp
void setup() {
    consentiumReceiver.receiveBegin();
    uint8_t sender1Mac[] = {0x7C, 0x9E, 0xBD, 0x66, 0x7A, 0x0C};
    uint8_t sender2Mac[] = {0x24, 0x6F, 0x28, 0x18, 0x2B, 0x4A};
    consentiumReceiver.addPeer(sender1Mac);
    consentiumReceiver.addPeer(sender2Mac);
    Serial.println("Ready to receive data from multiple senders.");
}
```

***

#### Custom Data Structures

Modify the `struct` to include additional fields based on your use case.

```cpp
struct ExtendedSensorData {
    float temperature;
    float humidity;
    int deviceID;   // Device identifier
    long timestamp; // Timestamp in ms
};
```

Use the custom structure in both sender and receiver implementations.

***

### Troubleshooting Guide

#### Common Issues and Fixes

| Issue                          | Possible Cause                  | Solution                                   |
| ------------------------------ | ------------------------------- | ------------------------------------------ |
| **No Data Received**           | Incorrect MAC address           | Verify sender and receiver MAC addresses.  |
| **Inconsistent Data Transfer** | ESP-NOW interference or timeout | Ensure devices are within range.           |
| **Compilation Errors**         | Library not included correctly  | Reinstall the library and check IDE paths. |

#### Debugging Tips

* Use `Serial.print` statements to log important steps.
* Verify MAC addresses using `WiFi.macAddress()` on each device.

***

### FAQs

#### 1. How many devices can communicate simultaneously using ESP-NOW?

ESP-NOW supports up to 10 peers (devices) in station mode.

#### 2. Can I encrypt the data sent using this library?

Currently, the library does not support encryption. Use HTTPS or secure layers for sensitive data.

#### 3. How reliable is ESP-NOW for IoT applications?

ESP-NOW is highly reliable for short-range, low-latency communication, making it ideal for IoT.

***

### Support

For detailed tutorials, visit [Consentium IoT Docs](https://docs.consentiumiot.com/).\
For further assistance, contact: <official@consentiumiot.com>.

***

### License

This project is licensed under the MIT License. Redistribution must include the original license header. See the `LICENSE` file for details.

***

### Feedback and Contributions

We welcome contributions!

* Submit pull requests for improvements.
* Report bugs or suggest features through GitLab Issues.

Together, let's build robust IoT solutions with ConsentiumNow! 🚀


# EdgeModelKit: Sensor Data Acquisition and Logging Library

EdgeModelKit is a Python library developed by **EdgeNeuron**, designed to simplify sensor data acquisition, logging, and real-time processing for IoT devices. It works seamlessly with the **DataLogger script** from the [EdgeNeuron Arduino library](https://github.com/ConsentiumIoT/EdgeNeuron), and now supports **HTTP-based acquisition** for devices that expose REST APIs.

***

## **Features**

* **Serial Communication**: Supports data acquisition over serial ports with robust error handling.
* **Flexible Data Fetching**: Retrieve sensor data as Python lists or NumPy arrays.
* **Customizable Logging**: Log sensor data into CSV files with optional timestamps and counters.
* **Class-Based Organization**: Log data with class labels to prepare datasets for machine learning tasks.
* **Error Handling**: Gracefully handles data decoding errors and missing keys in sensor data packets.

***

## **Usage Prerequisites**

This library is designed to work with the **DataLogger script** available in the [EdgeNeuron Arduino library](https://github.com/ConsentiumIoT/EdgeNeuron). The DataLogger script configures your Arduino-based IoT device to send structured JSON sensor data over a serial connection.

Before using EdgeModelKit, ensure:

1. Your Arduino device is programmed with the **DataLogger script** from the [EdgeNeuron Arduino library](https://github.com/ConsentiumIoT/EdgeNeuron).
2. The device is connected to your system via a serial interface.

***

## **Installation**

Install EdgeModelKit using pip:

```bash
pip install edgemodelkit  
```

***

## **Quick Start**

### **1. Initialize the DataFetcher**

```python
from edgemodelkit import DataFetcher  

# Initialize the DataFetcher with the desired serial port and baud rate  
fetcher = DataFetcher(serial_port="COM3", baud_rate=9600)  
```

### **2. Fetch Sensor Data**

```python
# Fetch data as a Python list  
sensor_data = fetcher.fetch_data(return_as_numpy=False)  
print("Sensor Data:", sensor_data)  

# Fetch data as a NumPy array  
sensor_data_numpy = fetcher.fetch_data(return_as_numpy=True)  
print("Sensor Data (NumPy):", sensor_data_numpy)  
```

### **3. Log Sensor Data**

```python
# Log 10 samples to a CSV file with timestamp and count columns  
fetcher.log_sensor_data(class_label="ClassA", num_samples=10, add_timestamp=True, add_count=True)  
```

***

## **CSV Logging Details**

The CSV file is generated automatically based on the sensor name (e.g., `TemperatureSensor_data_log.csv`) and contains the following:

* **Timestamp**: (Optional) Records the time when the data was logged.
* **Sample Count**: (Optional) A sequential counter for each data sample.
* **Data Columns**: Each element in the sensor data array is stored in separate columns (e.g., `data_value_1`, `data_value_2`, ...).

The data is saved under a folder named `Dataset`, with subfolders organized by `class_label` (if specified).

***

## **Real-Time Data Processing Example**

```python
from edgemodelkit import DataFetcher  

fetcher = DataFetcher(serial_port="COM3", baud_rate=9600)  

try:  
    while True:  
        # Fetch data as NumPy array  
        sensor_data = fetcher.fetch_data(return_as_numpy=True)  
        print("Received Data:", sensor_data)  

        # Perform custom processing (e.g., feed to a TensorFlow model)  
        # prediction = model.predict(sensor_data)  
        # print("Prediction:", prediction)  
finally:  
    fetcher.close_connection()  
```

***

## **Dependencies**

EdgeModelKit requires the following Python packages:

* `numpy`
* `pandas`
* `pyserial`
* `json`

Install dependencies with:

```bash
pip install numpy pandas pyserial json  
```

***

## **Contributing**

We welcome contributions to EdgeModelKit! Feel free to submit bug reports, feature requests, or pull requests on our [GitHub repository](https://github.com/ConsentiumIoT/edgemodelkit).

***

## **License**

EdgeModelKit is licensed under the MIT License. See the LICENSE file for details.

***

## **Support**

For support and inquiries, contact us at **<support@edgeneuronai.com>** or visit our [GitHub repository](https://github.com/ConsentiumIoT/edgemodelkit).

***

## **About EdgeNeuron**

EdgeNeuron is a pioneer in edge computing solutions, enabling developers to build intelligent IoT applications with state-of-the-art tools and libraries. Learn more at [edgeneuronai.com](https://edgeneuronai.com).

***


# Code usage

## Code Usage Overview

Welcome to the Consentium IoT code usage guide! This section provides an overview of how to implement various APIs and development environments for Consentium IoT-enabled devices.

### Available APIs

#### 1. **ConsentiumThings Python API**

Learn how to use the ConsentiumThings Python API for interacting with Consentium IoT devices, including sensor data handling and device management.

#### 2. **ConsentiumThings Arduino API**

Get started with the ConsentiumThings Arduino API for seamless integration with Arduino-based hardware. This section also covers how to perform over-the-air (OTA) updates for Consentium IoT devices.

#### 3. **Arduino Data Receiver API**

Understand how to implement the data receiver API for ConsentiumThings to manage and handle incoming data from your IoT devices.

### Tutorials and Setup

#### - Adding NodeMCU Support to Arduino IDE

Step-by-step instructions to add support for NodeMCU devices within the Arduino IDE.

#### - Adding ESP32 Support to Arduino IDE

Learn how to set up the ESP32 board support in your Arduino IDE to start programming Consentium IoT devices based on this platform.

***

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Consentium Python API</strong> </td><td>Find support for Consentium's Python API. </td><td></td><td><a href="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FEL0fB7f2ymDleHltdzoB%2Fcurie-2.jpg?alt=media&amp;token=9e84cdfe-6f60-49b1-94d1-301b44b13868">curie-2.jpg</a></td><td><a href="/code-usage/consentiumthings-python-api">ConsentiumThings Python API</a></td></tr><tr><td><strong>Consentium Arduino sending API</strong> </td><td>Find support for Consentium's Arduino API to send sensor data to cloud.</td><td></td><td><a href="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FuoETKI1LsJu8OJVWaAhh%2Fcurie-3.jpg?alt=media&amp;token=ec9cabeb-70f8-47e7-a8ba-60ea61be98a6">curie-3.jpg</a></td><td><a href="/code-usage/consentiumthings-arduino-api">ConsentiumThings Arduino API</a></td></tr><tr><td><strong>Consentium Arduino receiving API</strong> </td><td>Find support for Consentium's Arduino API to receive sensor data from cloud.</td><td></td><td><a href="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2FNG9SYNv4Czc2YQj9pPVz%2Fcurie-1.jpg?alt=media&amp;token=d5c1c022-bd27-46b1-8c81-1fe5534721d9">curie-1.jpg</a></td><td><a href="/code-usage/consentiumthings-arduino-data-receiver-api">ConsentiumThings Arduino Data Receiver API</a></td></tr></tbody></table>


# ConsentiumThings Python API

## Overview

**ConsentiumThings** is a user-friendly Python API that simplifies sending and receiving data between your devices and **Consentium Cloud**. It provides an intuitive interface, making it easy for developers to connect their IoT devices to Consentium Cloud for seamless data communication.

***

## Installation

First, install the **ConsentiumThings** API using `pip`:

```bash
pip install consentiumthings
```

***

## Getting Started

### 1. Import the ConsentiumThings Library

You’ll need to import the library before using it in your Python script:

```python
from consentiumthings import consentiumthings
```

### 2. Initialize ConsentiumThings

To get started, initialize the API with your **board key**. This key is provided by Consentium Cloud to identify your specific IoT device.

```python
ct = consentiumthings("your_board_key")
```

***

## Sending Data

### Steps to Send Data:

1. **Begin a Send Operation**: Use your **send key** to initialize the sending process.
2. **Send Data**: Pass the data and related information using the `send_data()` method.

```python
# Initialize the send operation with your send key
ct.begin_send("your_send_key")

# Send data along with information about the data
data = [1, 2, 3, 4]  # Example: sensor readings
info = ['temp', 'humidity', 'pressure', 'light']  # Labels for the data
ct.send_data(data, info)
```

***

## Receiving Data

### Steps to Receive Data:

1. **Begin a Receive Operation**: Initialize the receive operation with your **receive key**.
2. **Receive Data**: Call `receive_data()` to retrieve the information sent to your board.

```python
# Initialize the receive operation with your receive key
ct.begin_receive("your_receive_key")

# Retrieve the data from Consentium Cloud
received_data = ct.receive_data()
print(received_data)
```

* To receive only the **most recent** data, add the `recent=True` flag:

```python
ct.begin_receive("your_receive_key", recent=True)
```

***

## API Methods

Here’s a quick breakdown of all available methods:

### 1. `consentiumthings(board_key)`

This initializes the **ConsentiumThings** instance.

* **Parameter**:
  * `board_key` (str): The unique key that identifies your board.

### 2. `begin_send(send_key)`

This sets up the **send operation**.

* **Parameter**:
  * `send_key` (str): The unique key that allows your board to send data to Consentium Cloud.

### 3. `send_data(data, info_list)`

This sends data and its corresponding labels to Consentium Cloud.

* **Parameters**:
  * `data` (list): A list of data values (e.g., sensor readings).
  * `info_list` (list): A list of labels or information for the data (e.g., type of sensor).

### 4. `begin_receive(receive_key, recent=False)`

This sets up the **receive operation**.

* **Parameters**:
  * `receive_key` (str): The unique key that allows your board to receive data from Consentium Cloud.
  * `recent` (bool, optional): If `True`, fetches only the most recent data. Default is `False`.

### 5. `receive_data()`

This retrieves the data from Consentium Cloud after calling `begin_receive()`.

* **Returns**:
  * A list of data values received from the cloud.

***

## Complete Example

Here’s a full example to showcase how easy it is to send and receive data using **ConsentiumThings**:

```python
from consentiumthings import consentiumthings

# Initialize the API with your board key
ct = consentiumthings("your_board_key")

# ---- Sending Data ----
ct.begin_send("your_send_key")

# Example: Sending sensor data
data = [25.5, 60, 1013, 300]  # Temp, Humidity, Pressure, Light Intensity
info = ['temperature', 'humidity', 'pressure', 'light']
ct.send_data(data, info)

# ---- Receiving Data ----
ct.begin_receive("your_receive_key")

# Get the data and print it
received_data = ct.receive_data()
print("Received Data:", received_data)
```

***


# ConsentiumThings Arduino API

## Overview

This code is designed to interface with the **ConsentiumThings Dalton** IoT board, which connects to a Wi-Fi network and transmits sensor data over the internet using a RESTful API. The board reads data from connected sensors and sends it to a designated endpoint at regular intervals.

## Dependencies

The code depends on the following library:

* **ConsentiumThings.h**: This is a library specific to the ConsentiumThings IoT board, enabling functions such as Wi-Fi connectivity, sensor reading, and data transmission via RESTful APIs.

## Components

### 1. **Wi-Fi Configuration**

* `const char *ssid = "YOUR_WIFI_SSID";`: Defines the name of the Wi-Fi network that the IoT board will connect to.
* `const char *pass = "YOUR_WIFI_PASSWORD";`: Defines the password for the specified Wi-Fi network.

### 2. **API Keys**

* `const char *SendApiKey = "YOUR_API_KEY";`: API key used for sending data via the REST API.
* `const char *BoardApiKey = "YOUR_BOARD_API_KEY";`: API key specific to the board for authentication purposes.

### 3. **Data Transmission Interval**

* `constexpr int interval = 7000;`: Sets the delay interval between data transmissions in milliseconds. In this case, the system waits for 7 seconds (7000 ms) between data sends.

### 4. **Board Initialization**

* `ConsentiumThingsDalton board;`: Creates an instance of the **ConsentiumThingsDalton** object, which represents the IoT board.

## Functions

### `void setup()`

* This function is called once when the board is powered on or reset.
* **Wi-Fi Initialization**:
  * `board.initWiFi(ssid, pass);`: Connects the board to the specified Wi-Fi network using the SSID and password provided.
* **Board API Initialization**:
  * `board.beginSend(SendApiKey, BoardApiKey);`: Authenticates the board with the necessary API keys to enable data transmission.

### `void loop()`

* This function runs repeatedly after the setup is complete.
* **Sensor Data Reading**:
  * `double data_0 = board.busRead(0);`: Reads the voltage data from the sensor connected to port 0 of the board.
* **Sensor Data Array**:
  * `double sensorValues[] = {data_0};`: Stores the sensor data (in this case, only one sensor) in an array.
* **Sensor Information Array**:
  * `const char* sensorInfo[] = {"Temperature"};`: Describes the type of data being read from the sensor.
* **Sensor Count**:
  * `int sensorCount = sizeof(sensorValues)/sizeof(sensorValues[0]);`: Calculates the number of sensors connected by determining the size of the sensor data array.
* **Data Transmission**:
  * `board.sendData(sensorValues, sensorInfo, sensorCount, LOW_PRE);`: Sends the sensor data, along with the sensor information, to the server using REST with low precision.
* **Delay**:
  * `delay(interval);`: Waits for 7 seconds before running the loop again, creating a periodic data transmission schedule.

## Customization

### Wi-Fi Configuration

Replace `"YOUR_WIFI_SSID"` and `"YOUR_WIFI_PASSWORD"` with your actual Wi-Fi network credentials:

```cpp
const char *ssid = "MyWiFiNetwork";
const char *pass = "MyWiFiPassword";
```

### API Keys

You must replace `"YOUR_API_KEY"` and `"YOUR_BOARD_API_KEY"` with the actual API keys provided by the ConsentiumThings service. These keys authenticate the board and allow it to send data to the designated API endpoint.

### Interval

The data transmission interval is set to 7 seconds by default. You can modify this by changing the value of the `interval` constant.

```cpp
constexpr int interval = 5000; // Waits for 5 seconds between data transmissions
```

### Adding More Sensors

If you have more than one sensor, you can expand the `sensorValues` and `sensorInfo` arrays. For example, to add a second sensor:

```cpp
double data_1 = board.busRead(1); // Read voltage data from sensor on port 1
double sensorValues[] = {data_0, data_1}; // Add both sensor data to array
const char* sensorInfo[] = {"Temperature", "Humidity"}; // Add sensor info for both
```

Then adjust the sensor count:

```cpp
int sensorCount = sizeof(sensorValues)/sizeof(sensorValues[0]); // Update sensor count
```


# ConsentiumThings Arduino API with OTA Updates

## Overview

This code demonstrates how to set up the **ConsentiumThings Dalton IoT board** to collect sensor data, send it via REST API, and check for Over-The-Air (OTA) firmware updates periodically. The code is designed to work with **ESP8266**, **ESP32**, and **Raspberry Pi Pico W** boards and includes provisions for connecting analog sensors and using GPIO pins for REST event indication.

## Dependencies

The code depends on the **ConsentiumThings.h** library, which provides functionality for:

* Wi-Fi connection
* Sending and receiving data via RESTful APIs
* Over-The-Air (OTA) firmware updates

## Components

### 1. **Wi-Fi Configuration**

* `const char *ssid = "YOUR_WIFI_SSID";`: Specifies the Wi-Fi network to which the IoT board will connect.
* `const char *pass = "YOUR_WIFI_PASSWORD";`: Defines the password for the specified Wi-Fi network.

### 2. **API Keys**

* `const char *SendApiKey = "YOUR_API_KEY";`: API key for sending data via the REST API.
* `const char *ReceiveApiKey = "YOUR_API_KEY";`: API key used for OTA updates.
* `const char *BoardApiKey = "YOUR_BOARD_API_KEY";`: API key specific to the board for authentication.

### 3. **Firmware Version**

* `#define FIRMWARE_VERSION "0.0";`: Specifies the current version of the firmware running on the IoT board.

### 4. **Data Transmission Interval**

* `constexpr int interval = 7000;`: Defines the delay interval between each data transmission in milliseconds (7 seconds).

### 5. **Update Interval**

* `const int updateInterval = 100;`: The board checks for OTA firmware updates after every 100 cycles of the main loop.

### 6. **Board Initialization**

* `ConsentiumThingsDalton board(FIRMWARE_VERSION);`: Creates an instance of the **ConsentiumThingsDalton** object, specifying the firmware version.

## Functions

### `void setup()`

* This function runs once when the board is powered on or reset.
* **Wi-Fi Initialization**:
  * `board.initWiFi(ssid, pass);`: Connects the board to the specified Wi-Fi network using the provided credentials.
* **Data Transmission Initialization**:
  * `board.beginSend(SendApiKey, BoardApiKey);`: Authenticates the board and prepares it for sending sensor data over REST.
* **OTA Initialization**:
  * `board.beginOTA(ReceiveApiKey, BoardApiKey);`: Enables Over-The-Air updates, allowing the firmware to be updated remotely.

### `void loop()`

* This function runs repeatedly after `setup()` and handles the following operations:
* **Sensor Data Reading**:
  * `double data_0 = board.busRead(0);`: Reads analog sensor data from the specified pin (GPIO 34 for ESP32, A0 for ESP8266, and GPIO 26 for Raspberry Pi Pico W).
* **Sensor Data Array**:
  * `double sensorValues[] = {data_0};`: Stores the sensor data (in this case, only one sensor) in an array.
* **Sensor Information Array**:
  * `const char* sensorInfo[] = {"Temperature"};`: Describes the type of sensor data being read.
* **Sensor Count**:
  * `int sensorCount = sizeof(sensorValues)/sizeof(sensorValues[0]);`: Calculates the number of connected sensors based on the size of the data array.
* **Data Transmission**:
  * `board.sendData(sensorValues, sensorInfo, sensorCount, LOW_PRE);`: Sends the sensor data to the server using the REST API with low precision.
* **OTA Firmware Update Check**:
  * `loopCounter++`: Increments the loop counter with each cycle.
  * `if (loopCounter >= updateInterval)`: Checks if the loop counter has reached the update interval (100 cycles).
  * `board.checkAndPerformUpdate();`: Checks for available OTA firmware updates and performs an update if one is found.
  * `loopCounter = 0;`: Resets the counter after checking for updates.
* **Delay**:
  * `delay(interval);`: Pauses execution for 7 seconds before running the loop again.

## Customization

### Wi-Fi Configuration

Replace `"YOUR_WIFI_SSID"` and `"YOUR_WIFI_PASSWORD"` with your actual Wi-Fi network credentials:

```cpp
const char *ssid = "MyWiFiNetwork";
const char *pass = "MyWiFiPassword";
```

### API Keys

You must replace the placeholders `"YOUR_API_KEY"` and `"YOUR_BOARD_API_KEY"` with the actual API keys provided by the ConsentiumThings platform. These keys are used for data transmission and OTA updates.

### Data Transmission Interval

To modify the delay between data transmissions, adjust the value of the `interval` constant (in milliseconds):

```cpp
constexpr int interval = 5000; // Wait for 5 seconds between data transmissions
```

### Firmware Version

If you update your firmware, change the `FIRMWARE_VERSION` definition:

```cpp
#define FIRMWARE_VERSION "0.1"; // Updated firmware version
```

### Update Interval

The board checks for firmware updates after every 100 cycles by default. You can change the frequency by adjusting `updateInterval`:

```cpp
const int updateInterval = 50; // Check for updates after 50 cycles
```

### LED Indication (Optional)

You can connect an LED to specific GPIO pins to visually indicate REST events as specified in the comment header:

* GPIO 16 for ESP8266
* GPIO 23 for ESP32
* GPIO 25 for Raspberry Pi Pico W

### Adding More Sensors

If additional sensors are connected, expand the `sensorValues` and `sensorInfo` arrays:

```cpp
double data_1 = board.busRead(1); // Read from another analog sensor
double sensorValues[] = {data_0, data_1}; // Add both sensor data to array
const char* sensorInfo[] = {"Temperature", "Humidity"}; // Add sensor descriptions
```


# WiFi auto connect API

## **Function Prototype**

```cpp
void initWiFiAutoConnect();
```

## **Description**

The `initWiFiAutoConnect()` function is designed to provide **seamless and intelligent WiFi connectivity** for Consentium IoT edge devices, such as the ESP8266, ESP32, and Raspberry Pi Pico W. It eliminates the need for manually entering WiFi credentials in the code, making the deployment process more **user-friendly, scalable, and secure**.

This function first attempts to connect to a **previously stored WiFi network**. If the device cannot establish a connection, it **automatically switches to Access Point (AP) mode**, allowing users to configure the network settings via a **web-based interface**. Once configured, the credentials are saved for future use, ensuring the device connects automatically in subsequent reboots.

This approach makes it ideal for **remote deployments**, **dynamic environments**, and **non-technical users** who need to set up IoT devices without accessing or modifying the firmware.

***

## **Key Features**

**Zero Hardcoded Credentials** – Eliminates security risks by not storing SSID and passwords in firmware.\
**Automatic WiFi Connection** – Connects to known networks without user intervention.\
**Fallback AP Mode** – Creates a temporary WiFi network if no saved network is available.\
**Web-Based Setup Portal** – Users can configure WiFi settings using a simple browser interface.\
**Persistent Network Configuration** – Credentials are stored and automatically used for future connections.\
**Auto-Restart on Failure** – If the connection fails, the device restarts and retries until successful.

***

## **How to Use**

### **1. Integrate the API in Your Code**

Call `initWiFiAutoConnect()` in the `setup()` function to ensure the device establishes a network connection before proceeding with other tasks.

#### **Example Usage**

```cpp
#include <ConsentiumThings.h>

ConsentiumThingsDalton board;

void setup() {
    Serial.begin(115200);

    // Establish WiFi connection automatically
    board.initWiFiAutoConnect();

    Serial.println("WiFi connected. Device is online!");
}

void loop() {
    // Your application logic goes here
}
```

***

## **Behavior of the API**

### **1. Connection to a Saved Network**

* The device first attempts to **connect to a previously stored WiFi network**.
* If successful, it prints the assigned **IP address** to the Serial Monitor.

### **2. Automatic Access Point (AP) Mode**

* If no known WiFi network is found, the device creates a temporary **WiFi Access Point** (e.g., `ConsentiumIoT_AP_ABC`).
* A randomly generated password is displayed in the Serial Monitor.
* Users can **connect to this AP using a smartphone or computer** and configure WiFi settings via a **web interface**.

### **3. Web-Based Setup Interface**

* After connecting to the AP, users can **open a browser** and navigate to the **configuration page** (typically at `192.168.4.1`).
* The interface allows users to select a network and enter a password.

### **4. Persistent WiFi Credentials**

* Once a WiFi network is selected, the credentials are **stored in the device’s memory**.
* The device **reboots and connects automatically** in future sessions.

### **5. Auto-Restart on Connection Failure**

* If the connection attempt fails, the device waits for a few seconds and **automatically restarts** to retry the process.

***

## **Best Practices**

**Call this function in `setup()`** before executing any WiFi-dependent tasks.\
**Monitor the Serial Output** during the first setup to obtain AP credentials if needed.\
**Ensure the device has access to a stable WiFi network** to minimize reconnection delays.\
**Use this feature for remote deployments** where manual reconfiguration is not feasible.

***

## **Conclusion**

The `initWiFiAutoConnect()` API is an **essential tool for Consentium IoT edge devices**, making network setup effortless and reliable. By combining **automatic WiFi connection, fallback AP mode, and a web-based configuration interface**, this API ensures a **smooth, scalable, and secure** networking experience for IoT applications. Whether used in **smart homes, industrial IoT, or edge computing**, it provides a **robust and fail-proof mechanism** to keep devices connected with minimal user intervention.


# ConsentiumThings Arduino Data Receiver API

## Overview

This code interfaces with the **ConsentiumThings board** to receive sensor data from a server via Wi-Fi and print it to the Serial Monitor. It is intended for use with **ESP8266**, **ESP32**, and **Raspberry Pi Pico W** boards and operates by connecting to Wi-Fi and receiving data at regular intervals using the ConsentiumThings REST API.

## Dependencies

The code depends on the **ConsentiumThings.h** library, which provides functions for Wi-Fi connection, data reception, and RESTful API communication with the Consentium IoT platform.

## Components

### 1. **Wi-Fi Configuration**

* `const char *ssid = "YOUR_WIFI_SSID";`: This is the Wi-Fi network SSID to which the IoT board will connect.
* `const char *pass = "YOUR_WIFI_PASSWORD";`: The password for the specified Wi-Fi network.

### 2. **API Keys**

* `const char *ReceiveApiKey = "YOUR_API_KEY";`: API key for receiving data from the server.
* `const char *BoardApiKey = "YOUR_BOARD_API_KEY";`: API key specific to the board, used for authentication purposes.

### 3. **Data Reception Interval**

* `constexpr int interval = 7000;`: Defines the time interval between each data reception in milliseconds. In this case, the system will wait for 7 seconds (7000 ms) between receiving data from the server.

### 4. **Board Initialization**

* `ConsentiumThings board;`: Creates an instance of the **ConsentiumThings** object, representing the IoT board that will receive data from the server.

## Functions

### `void setup()`

* This function runs once when the board is powered on or reset.
* **Wi-Fi Initialization**:
  * `board.initWiFi(ssid, pass);`: Connects the board to the Wi-Fi network using the provided SSID and password.
* **Board API Initialization**:
  * `board.beginReceive(ReceiveApiKey, BoardApiKey);`: Authenticates the board and initiates the process to receive data from the server using the ConsentiumThings platform.

### `void loop()`

* This function runs repeatedly after `setup()` and handles the continuous reception and printing of sensor data.
* **Data Reception**:
  * `auto dataPairs = board.receiveData();`: Retrieves the sensor data from the server, storing it as key-value pairs, where each pair contains a sensor reading and its corresponding label.
* **Data Printing**:
  * A `for` loop iterates through the received `dataPairs` to print both the sensor data and its corresponding label (`info`) to the Serial Monitor.
  * `Serial.print("Data: ");` and `Serial.print("Info: ");`: These lines are used to display the data and information for each sensor.
* **Delay**:
  * `delay(interval);`: Pauses execution for 7 seconds before receiving and printing new data again.

## Example Output

The code prints the received sensor data in the following format on the Serial Monitor:

```
Data: 24.5          	Info: Temperature
Data: 55.0          	Info: Humidity
```

This output shows the sensor values along with the description of what each value represents.

## Customization

### Wi-Fi Configuration

You must replace `"YOUR_WIFI_SSID"` and `"YOUR_WIFI_PASSWORD"` with your actual Wi-Fi network credentials:

```cpp
const char *ssid = "MyWiFiNetwork";
const char *pass = "MyWiFiPassword";
```

### API Keys

The placeholders `"YOUR_API_KEY"` and `"YOUR_BOARD_API_KEY"` should be replaced with the actual API keys provided by the ConsentiumThings service. These keys authenticate the board and allow it to receive data.

### Interval

To change the interval between receiving data from the server, adjust the value of the `interval` constant (in milliseconds):

```cpp
constexpr int interval = 5000; // Wait for 5 seconds between data receptions
```

### LED Indication (Optional)

You can connect an LED to a specific GPIO pin to visually indicate REST events as mentioned in the comment header. The GPIO pin depends on the board:

* GPIO 16 for ESP8266
* GPIO 23 for ESP32
* GPIO 25 for Raspberry Pi Pico W


# ConsentiumNow Library API

The `ConsentiumNow` library simplifies the implementation of ESP-NOW communication for ESP32 devices. It provides a templated, type-safe interface for transmitting and receiving structured data between devices.

***

### **Class: ConsentiumNow**

The `ConsentiumNow` class is a templated class designed to handle communication using ESP-NOW. `DataType` is a user-defined struct or class representing the data to be exchanged.

#### **Template Parameter**

* `DataType`: A user-defined data structure (e.g., a `struct`) that represents the data to be sent/received. Must be serializable (e.g., no pointers or virtual members).

***

### **Public Methods**

#### **Constructor**

```cpp
ConsentiumNow();
```

Initializes the `ConsentiumNow` object. Does not perform any hardware initialization.

***

#### **void receiveBegin()**

Initializes ESP-NOW in receive mode.

* **Purpose**: Sets up the ESP32 to receive data over ESP-NOW and register a callback function to handle incoming messages.
* **Usage**:

  ```cpp
  consentiumNowInstance.receiveBegin();
  ```
* **Output**: Prints initialization status to `Serial`.

***

#### \**void sendBegin(const uint8\_t peerMac)*

Initializes ESP-NOW in send mode and sets the receiver’s MAC address.

* **Parameters**:
  * `peerMac`: A 6-byte array representing the receiver's MAC address.
* **Usage**:

  ```cpp
  uint8_t receiverMac[] = {0x24, 0x6F, 0x28, 0x11, 0x22, 0x33};
  consentiumNowInstance.sendBegin(receiverMac);
  ```
* **Output**: Prints initialization status to `Serial`.

***

#### \**bool addPeer(const uint8\_t peerMac)*

Adds a peer (sender or receiver) to the ESP-NOW network.

* **Parameters**:
  * `peerMac`: A 6-byte array representing the MAC address of the peer to be added.
* **Returns**:
  * `true` if the peer is added successfully.
  * `false` if the operation fails.
* **Usage**:

  ```cpp
  uint8_t senderMac[] = {0x24, 0x6F, 0x28, 0xAA, 0xBB, 0xCC};
  bool success = consentiumNowInstance.addPeer(senderMac);
  ```
* **Output**: Prints success/failure status to `Serial`.

***

#### **void sendData(const DataType \&data)**

Sends data to the predefined receiver.

* **Parameters**:
  * `data`: A reference to the `DataType` object containing the data to be sent.
* **Usage**:

  ```cpp
  SensorData sensorData = {25.5, 60.0};
  consentiumNowInstance.sendData(sensorData);
  ```
* **Output**:
  * Prints success/failure status to `Serial`.

***

#### **bool isDataAvailable()**

Checks if new data has been received.

* **Returns**:
  * `true` if new data is available.
  * `false` if no data is available.
* **Usage**:

  ```cpp
  if (consentiumNowInstance.isDataAvailable()) {
      // Handle received data
  }
  ```

***

#### **DataType getReceivedData()**

Retrieves the most recently received data.

* **Returns**:
  * The received data of type `DataType`.
* **Usage**:

  ```cpp
  SensorData receivedData = consentiumNowInstance.getReceivedData();
  Serial.printf("Temperature: %.2f, Humidity: %.2f\n", 
                receivedData.temperature, receivedData.humidity);
  ```
* **Note**: Resets the data availability flag.

***

#### **void readMacAddress()**

Prints the MAC address of the ESP32 to the `Serial` monitor.

* **Purpose**: Useful for identifying devices in an ESP-NOW network.
* **Usage**:

  ```cpp
  consentiumNowInstance.readMacAddress();
  ```

***

### **Static Callback Methods**

#### void onDataReceive(const esp\_now\_recv\_info\_t *info, const uint8\_t incoming, int len)*

Handles incoming ESP-NOW messages. Automatically called when data is received.

* **Parameters**:
  * `info`: Information about the sender (e.g., MAC address).
  * `incoming`: Pointer to the incoming data.
  * `len`: Length of the received data.
* **Purpose**: Parses and stores incoming data in the `incomingData` buffer and sets the `dataAvailable` flag.
* **Usage**: Registered automatically by `receiveBegin()`.

***

### **Static Variables**

#### **DataType incomingData**

Holds the latest received data.

* **Scope**: Private (access via `getReceivedData()`).

***

#### **bool dataAvailable**

Indicates whether new data has been received.

* **Scope**: Private (access via `isDataAvailable()`).

***

### **Example: Using ConsentiumNow**

#### **Receiver Code**

```cpp
#include "ConsentiumNow.h"

struct SensorData {
    float temperature;
    float humidity;
};

ConsentiumNow<SensorData> receiver;

void setup() {
    Serial.begin(115200);
    receiver.receiveBegin();
}

void loop() {
    if (receiver.isDataAvailable()) {
        SensorData data = receiver.getReceivedData();
        Serial.printf("Temperature: %.2f, Humidity: %.2f\n", 
                      data.temperature, data.humidity);
    }
}
```

#### **Sender Code**

```cpp
#include "ConsentiumNow.h"

struct SensorData {
    float temperature;
    float humidity;
};

ConsentiumNow<SensorData> sender;

uint8_t receiverMac[] = {0x24, 0x6F, 0x28, 0x11, 0x22, 0x33};

void setup() {
    Serial.begin(115200);
    sender.sendBegin(receiverMac);
}

void loop() {
    SensorData data = {random(200, 300) / 10.0, random(400, 600) / 10.0};
    sender.sendData(data);
    delay(2000);
}
```

***

### **Features**

* **Templated Design**: Flexibility to handle any structured data.
* **Static Methods**: Callback management for receiving data.
* **Ease of Use**: Abstracts ESP-NOW complexity, focusing on data exchange.

***

#### **Known Limitations**

1. **Peer Management**: Must manually add peers to the network using `addPeer()`.
2. **Static Data Buffer**: Only one instance of incoming data can be stored.


# Edge boards


# Consentium Edge Dalton board

The **Edge Dalton IoT Board** is a powerful, ESP32-C3-based development board designed for seamless integration with **Consentium IoT**. It is optimized for **industrial IoT applications**, featuring multiple sensor interfaces, voltage and current monitoring capabilities, and robust connectivity options.

<figure><img src="https://1722507258-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2tTe7YNQtbpNi3ve2r6s%2Fuploads%2F9zWXD5eeIqMqVjp5STKR%2FGemini_Generated_Image_crxnb4crxnb4crxn.png?alt=media&amp;token=a8bc3c65-2a72-4b34-9236-21c41b8f1de6" alt="" width="375"><figcaption><p>Back view</p></figcaption></figure>

## Features

### **Core Processor**

* **ESP32-C3-MINI** with **Wi-Fi and Bluetooth LE** for wireless connectivity
* **RISC-V 32-bit single-core** processor for low-power edge computing
* **FreeRTOS support** for real-time applications

### **Power Options**

* **USB-C Port** for easy connectivity and power
* **DC Barrel Jack** for external power supply
* **Onboard AMS1117 voltage regulator** for stable power management

### **Connectivity & Expansion**

* **I2C, UART, and I2S interfaces** for sensor and peripheral integration
* **Dedicated GPIO headers** for expansion
* **3.3V logic level support** for interfacing with various devices

### **Sensor Integration & Monitoring**

* **Voltage Terminal (J3):** Four input channels for voltage monitoring
* **Current Terminal (J5):** Four input channels for current sensing
* **Dedicated ADCs for precision measurements**

### **Additional Features**

* **Boot and Reset buttons** for easy development and debugging
* **LED indicators** for power and status
* **Compact and robust PCB design** for industrial environments

## Applications

* **Industrial Sensor Monitoring** – Capture and transmit real-time voltage and current data
* **Edge AI & TinyML** – Deploy ML models on the ESP32-C3 for predictive maintenance and anomaly detection
* **IoT Data Logging** – Send sensor data to **Consentium IoT Cloud** for analytics and visualization
* **Wireless Automation** – Utilize Wi-Fi and BLE for remote monitoring and control

## Getting Started

1. **Power Up:** Connect via USB-C or DC barrel jack.
2. **Firmware Setup:** Flash your ConsentiumThings firmware or EdgeNeuron using Arduino IDE.
3. **Sensor Integration:** Connect voltage/current sensors to respective terminals.
4. **Cloud Connectivity:** Send data to Consentium IoT Cloud for real-time analytics.


# Receiving sensor data


# Receiving Sensor Data from Consentium IoT Cloud and Controlling LED

This documentation provides the steps and code required to receive data from the **Consentium IoT cloud** using the **ConsentiumThings** library. The code checks whether the first data pair (assumed to be temperature data) exceeds a threshold of 30°C and turns on an LED if the condition is met. This is intended for ESP8266, ESP32, or Raspberry Pi Pico W compatible boards.

### Dependencies

The code utilizes the `ConsentiumThings.h` library to handle communication with the Consentium IoT platform. Additionally, it uses GPIO pins to control an LED.

### Features

* Connect to a WiFi network for cloud communication.
* Receive sensor data from the Consentium IoT platform.
* Parse and display the received data on the serial monitor.
* Control an LED connected to a specific GPIO pin based on sensor data (temperature in this case).

### Hardware Setup

* **LED**: Connect the anode (positive leg) of an LED to **GPIO 16** on an ESP8266, **GPIO 23** on an ESP32, or **GPIO 25** on a Raspberry Pi Pico W.
* **Resistor**: Use a 220Ω resistor in series with the LED to limit current.

#### GPIO Pin Mapping for LED:

* **ESP8266**: GPIO 16
* **ESP32**: GPIO 23
* **Raspberry Pi Pico W**: GPIO 25

### Constants

* **WiFi Credentials**: Set your WiFi SSID and password.
* **Receive Interval**: The loop runs every 7 seconds (7000 ms) to retrieve data from the server.
* **API Keys**: Required to authenticate the connection to the Consentium IoT cloud.

### Code Overview

#### 1. Initialization

A `ConsentiumThings` the object is created to manage communication with the Consentium IoT platform.

```cpp
ConsentiumThings board; // Create ConsentiumThings object
```

WiFi credentials and API keys are declared:

```cpp
const char *ssid = "YOUR_WIFI_SSID"; // Add WiFi SSID
const char *pass = "YOUR_WIFI_PASSWORD"; // Add WiFi password
```

An LED is connected to the designated GPIO pin (D15 in the example) to indicate whether the temperature exceeds the threshold.

```cpp
#define LED_PIN 15  // Set the pin to which the LED is connected
```

#### 2. Setup

The `setup()` function establishes a WiFi connection, configures the IoT board to receive data, and initializes the LED pin as an output.

```cpp
void setup() {
  pinMode(LED_PIN, OUTPUT);  // Set the LED pin as an output
  digitalWrite(LED_PIN, LOW);  // Turn off the LED initially

  board.initWiFi(ssid, pass);  // Begin WiFi connection
  board.beginReceive(ReceiveApiKey, BoardApiKey);  // Initialize board to receive data from Consentium IoT cloud
}
```

#### 3. Main Loop

The `loop()` function receives sensor data from the cloud, displays it on the serial monitor, and checks if the 0th data pair (assumed to be temperature) exceeds 30°C. If so, it turns on the LED connected to D15; otherwise, the LED remains off.

**a. Receiving Data**

The sensor data is fetched from the Consentium IoT platform using the `receiveData()` function.

```cpp
auto dataPairs = board.receiveData();  // Receive sensor data from server
```

**b. Parsing Data**

The received data is stored in pairs (value and info), which are iterated through and printed on the serial monitor.

```cpp
for(size_t i = 0; i < dataPairs.size(); i++){
    double data = dataPairs[i].first; 
    String info = dataPairs[i].second.c_str();

    Serial.print("Data: ");
    Serial.print(data);
    Serial.print("          \t");
    Serial.print("Info: ");
    Serial.println(info);
}
```

**c. Testing Temperature and Controlling LED**

If the temperature (0th data pair) exceeds 30°C, the LED connected to **GPIO D15** is turned on.

```cpp
// Test the 0th data pair (temperature) against 30°C
if (dataPairs.size() > 0) {
  double temperature = dataPairs[0].first;  // Assume 0th data pair is temperature

  if (temperature > 30) {
    digitalWrite(LED_PIN, HIGH);  // Turn on LED if temperature > 30°C
  } else {
    digitalWrite(LED_PIN, LOW);   // Turn off LED if temperature <= 30°C
  }
}
```

#### 4. Loop Control

The loop repeats every 7000 milliseconds (7 seconds), allowing for periodic data retrieval.

```cpp
delay(interval);
```

### Full Code

```cpp
/***************************************************
  This is Consentium's IoT library
  ----> https://consentiuminc.online/
  Check out the links above for our tutorials and product diagrams.

  This Consentium's IoT library works only for ESP8266/ESP32/Raspberry Pi Pico W compatible Edge boards. 
  
  Connect a LED to GPIO 16 for ESP 8266, GPIO 23 for ESP 32 and GPIO 25 for Raspberry Pi Pico W to indicate the REST events. 
  
  Written by Debjyoti Chowdhury for Consentium.
  MIT license, all text above must be included in any redistribution
 ****************************************************/

#include <ConsentiumThings.h>

ConsentiumThings board; // Create ConsentiumThings object

const char *ssid = "YOUR_WIFI_SSID"; // Add WiFi SSID
const char *pass = "YOUR_WIFI_PASSWORD"; // Add WiFi password
constexpr int interval = 7000; // Wait for 7 seconds
const char *ReceiveApiKey = "YOUR_API_KEY"; // Receive API key
const char *BoardApiKey = "YOUR_BOARD_API_KEY"; // Board API key

#define LED_PIN 15  // Set the pin to which the LED is connected (D15)

void setup() {
  pinMode(LED_PIN, OUTPUT);  // Set the LED pin as an output
  digitalWrite(LED_PIN, LOW);  // Turn off the LED initially

  board.initWiFi(ssid, pass);  // Begin WiFi connection
  board.beginReceive(ReceiveApiKey, BoardApiKey);  // Initialize board to receive data from Consentium IoT cloud
}

void loop() {
  // Get sensor data from server
  auto dataPairs = board.receiveData(); 
  
  // Print sensor data from server
  for(size_t i = 0; i < dataPairs.size(); i++){
    double data = dataPairs[i].first; 
    String info = dataPairs[i].second.c_str();

    Serial.print("Data: ");
    Serial.print(data);
    Serial.print("          \t");
    Serial.print("Info: ");
    Serial.println(info);
  }
  Serial.println();

  // Test the 0th data pair (temperature) against 30°C
  if (dataPairs.size() > 0) {
    double temperature = dataPairs[0].first;  // Assume 0th data pair is temperature

    if (temperature > 30) {
      digitalWrite(LED_PIN, HIGH);  // Turn on LED if temperature > 30°C
    } else {
      digitalWrite(LED_PIN, LOW);   // Turn off LED if temperature <= 30°C
    }
  }

  delay(interval);  // Wait for the next cycle
}
```

#### Summary

* **WiFi connection** is initialized to receive sensor data.
* **LED control** is based on the temperature threshold.
* The system loops every 7 seconds, receiving and processing data.


# Sending sensor data


# WiFi Smart Connect with OLED Integration

This guide demonstrates how to integrate a standard 128x64 I2C OLED display with your ConsentiumThings Dalton board using the **U8g2** library.

By following this example, you can provide real-time visual feedback on your device's physical screen. It covers how to display the automatically generated WiFi Access Point (AP) credentials during the setup phase, show the assigned IP address upon successful connection, and indicate when data is actively being sent to the Consentium IoT Cloud.

### Prerequisites

#### Hardware Setup

* **ConsentiumThings Dalton Board** (or compatible Edge board).
* **I2C OLED Display** (e.g., SSD1306 128x64).
* Jumper wires connecting the OLED to the board's I2C pins (SDA and SCL).

#### Software & Libraries

Ensure you have the following libraries installed in your Arduino IDE:

* `ConsentiumThings`: The core library for the edge board.
* `U8g2`: A fast, highly customizable library for monochrome displays.
* `Wire`: Standard Arduino I2C library (usually built-in).

***

### Code Walkthrough

#### 1. Initialisation and Setup

First, include the necessary libraries and initialise the `U8g2` object for your specific display. You must also define your Consentium API keys.

```cpp
#include <ConsentiumThings.h>
#include <U8g2lib.h>
#include <Wire.h>

// Initialize the U8g2 object for a standard 128x64 I2C OLED
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

// Create ConsentiumThings object
ConsentiumThingsDalton board;

// Define API keys
const char *SendApiKey = "YOUR_SEND_API_KEY";      
const char *BoardApiKey = "YOUR_BOARD_API_KEY"; 
constexpr int interval = 5000; 
```

#### 2. The Display Callback Function

The board.smartConnect() function is a blocking function, meaning the code pauses while it waits for a user to connect to the generated WiFi Access Point. To display the generated SSID and Password on the OLED before the code blocks, we pass a callback function.

```cpp
void showCredentialsOnOLED(const char* ssid, const char* password) {
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr); 

  u8g2.drawStr(4, 10, "WiFi Setup Mode");
  u8g2.drawStr(4, 25, "Connect to:");

  u8g2.setCursor(4, 40);
  u8g2.print("SSID: ");
  u8g2.print(ssid);

  u8g2.setCursor(4, 55);
  u8g2.print("Pass: ");
  u8g2.print(password);

  u8g2.sendBuffer();
}
```

#### 3. The Setup Loop

In the setup() function, initialise the OLED and pass the callback function to smartConnect(). Once the connection is successful, the screen clears and displays the newly acquired IP address.

```cpp
void setup() {
  Serial.begin(115200);
  u8g2.begin(); // Start the OLED

  // Initialise WiFi, passing the OLED callback
  board.smartConnect(showCredentialsOnOLED);

  // Connection successful - Update OLED
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(4, 20, "WiFi Connected!");
  u8g2.setCursor(4, 40);
  u8g2.print("IP: ");
  u8g2.print(board.getIPAddress()); 
  u8g2.sendBuffer();

  // Initialise the board for sending data
  board.enableSend(SendApiKey, BoardApiKey);
  
  delay(2000); // Pause for 2 seconds so the user can read the IP
}
```

#### 4. The Main Loop (Data Transmission)

During normal operation, the board reads sensor data, sends it to the Consentium Cloud, and updates the OLED to confirm the transmission.

```cpp
void loop() {
  double data_0 = 1.0;  // Sample temperature data
  vector<double> sensorValues = {data_0};  
  const char* sensorInfo[] = {"Temperature"}; 

  // Send over REST
  board.pushData(sensorValues, sensorInfo, LOW_PRE);  

  // Update OLED
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(4, 20, "Data Sent to Cloud");
  u8g2.sendBuffer();

  delay(interval);
}
```

## Complete Example Code&#x20;

Copy and paste the entire block below into your Arduino IDE to get started quickly. Remember to replace the empty API keys with your actual Consentium credentials.

```cpp
#include <ConsentiumThings.h>
#include <U8g2lib.h>
#include <Wire.h>

// Initialize the U8g2 object for a standard 128x64 I2C OLED
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

// Create ConsentiumThings object
ConsentiumThingsDalton board;

// Define API keys
const char *SendApiKey = "";      // API key for sending data
const char *BoardApiKey = ""; // API key for the board

// Define the interval for data sending
constexpr int interval = 5000;  // Data transmission interval (5 seconds for free tier)

// ---------------------------------------------------------
// Callback Function: Shows AP credentials during setup
// ---------------------------------------------------------
void showCredentialsOnOLED(const char* ssid, const char* password) {
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr); 

  u8g2.drawStr(4, 10, "WiFi Setup Mode");
  u8g2.drawStr(4, 25, "Connect to:");

  u8g2.setCursor(4, 40);
  u8g2.print("SSID: ");
  u8g2.print(ssid);

  u8g2.setCursor(4, 55);
  u8g2.print("Pass: ");
  u8g2.print(password);

  u8g2.sendBuffer();
}

void setup() {
  // Start serial communication for debugging
  Serial.begin(115200);

  //Initialise the OLED display
  u8g2.begin();

  // Consentium IoT branding message
  Serial.println("Consentium IoT - Edge Board Library");
  Serial.println("------------------------------------");
  Serial.println("Initializing ConsentiumThings Board...");

  //Initialise WiFi with auto-connect feature, passing the OLED callback
  board.smartConnect(showCredentialsOnOLED);

  // Once smartConnect finishes, update the OLED to show success
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(4, 20, "WiFi Connected!");
  u8g2.setCursor(4, 40);
  u8g2.print("IP: ");
  u8g2.print(board.getIPAddress()); 
  u8g2.sendBuffer();

  //Initialise the board for sending data
  board.enableSend(SendApiKey, BoardApiKey);

  // Enable battery monitoring on ADC_IN pin (optional)
  // board.enableBatteryMonitoring(ADC_IN);

  // Enable current and voltage industrial monitoring (optional)
  // board.startSensing();
  
  Serial.println("ConsentiumThings Board Initialized!");
  Serial.println("------------------------------------");
  Serial.println();
  
  delay(2000); // Pause for 2 seconds so the user can see the IP address
}

void loop() {
  // Prepare sample sensor data
  double data_0 = 1.0;  // Sample temperature data

  // Get data from 4-20mA current sensor, returns as mA (optional)
  // double cin_1_current = board.readCurrentBus(CIN_1);
  // double cin_2_current = board.readCurrentBus(CIN_2);
  // double cin_3_current = board.readCurrentBus(CIN_3);
  // double cin_4_current = board.readCurrentBus(CIN_4);

  // Get data from 0-10v voltage sensor, returns as volts (optional)
  // double vin_1_voltage = board.readVoltageBus(VIN_1);
  // double vin_2_voltage = board.readVoltageBus(VIN_2);
  // double vin_3_voltage = board.readVoltageBus(VIN_3);
  // double vin_4_voltage = board.readVoltageBus(VIN_4);

  vector<double> sensorValues = {data_0};  // Sensor data vector
  
  // Sensor info without units can be defined as
  const char* sensorInfo[] = {"Temperature"}; 

  // Sensor info with units can be defined as
  // const char* sensorInfo[] = {"Temperature/C"};

  // Send over REST with low precision
  board.pushData(sensorValues, sensorInfo, LOW_PRE);  

  // Update OLED to show we are sending data
  u8g2.clearBuffer();
  u8g2.setFont(u8g2_font_ncenB08_tr);
  u8g2.drawStr(4, 20, "Data Sent to Cloud");
  u8g2.sendBuffer();

  // Wait before sending the next batch of data
  delay(interval);
}
```

Troubleshooting I2C & OLED Issues Hardware integrations don't always work perfectly on the first try. If your OLED screen remains blank or displays scrambled text, check the following common issues.

#### 1. Blank Screen / No Output

Wiring Check: Ensure the I2C pins are connected correctly. A very common mistake is swapping the SDA and SCL lines.

VCC -> 3.3V or 5V (Check your specific OLED module's rating)

GND -> GND

SDA -> SDA pin on your ConsentiumThings Dalton board

SCL -> SCL pin on your ConsentiumThings Dalton board

Power Supply: Ensure the board is providing enough power to the OLED. Sometimes running off a weak USB port can cause peripherals to fail.

#### 2. Incorrect I2C Address

Most 128x64 OLEDs use the I2C address 0x3C, but some use 0x3D. The U8g2 library usually handles the default 0x3C automatically based on the constructor, but if your screen has a different address or isn't being recognised, you should run an I2C Scanner sketch to verify the hardware is communicating.

I2C Scanner Code: Upload this temporary sketch to your board and open the Serial Monitor (115200 baud). It will tell you the exact address of your connected OLED.

```cpp
#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(115200);
  Serial.println("\nI2C Scanner");
}

void loop() {
  byte error, address;
  int nDevices = 0;

  Serial.println("Scanning...");

  for(address = 1; address < 127; address++ ) {
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0) {
      Serial.print("I2C device found at address 0x");
      if (address<16) Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");
      nDevices++;
    }
    else if (error==4) {
      Serial.print("Unknown error at address 0x");
      if (address<16) Serial.print("0");
      Serial.println(address,HEX);
    }    
  }
  
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           
}
```

#### 3. Scrambled Display or "Snow"

If your display lights up but the pixels look like random noise or are shifted slightly to the right, you likely have an SH1106 controller instead of an SSD1306. These modules look physically identical.

To fix this, simply change your U8g2 constructor at the top of your code:

Change this:

```cpp
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
```

To this:

```cpp
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
```

#### 4. Code Hanging / Board Restarting

If the board continuously restarts or the code freezes immediately after u8g2.begin();, it usually means the I2C bus is hanging due to missing Pull-Up resistors. Most ready-made OLED modules have these resistors built-in, but if you are using a bare screen, you may need to add 4.7kΩ resistors between SDA/3.3V and SCL/3.3V.


# Sending LM35 Sensor Data to Consentium IoT Cloud

This documentation outlines the steps and code required to read data from an LM35 temperature sensor using an ADC pin and send the data to the Consentium IoT cloud using the **ConsentiumThings** library. The code also enables firmware updates for Over-The-Air (OTA).

## Dependencies

The code relies on the `ConsentiumThings.h` library, facilitating communication with the Consentium IoT platform and enabling OTA updates.

## Features

* Connect to a WiFi network for cloud communication.
* Send sensor data to the Consentium IoT platform.
* Enable Over-The-Air (OTA) firmware updates.
* Automatically check for updates after every 100 loops.

## Constants

* **Firmware Version**: The firmware version of the board is set to `0.1`.
* **Interval**: The loop runs every 5 seconds (5000 ms).
* **Update Interval**: The firmware checks for updates every 100 loop cycles.

## Code Overview

### 1. Initialization

The program begins by creating an `ConsentiumThingsDalton` object to manage communication with the Consentium IoT platform. The initialization requires the firmware version, WiFi credentials, and Consentium IoT API keys.

```cpp
#define FIRMWARE_VERSION "0.1"

ConsentiumThingsDalton board(FIRMWARE_VERSION);
```

The following variables are set for WiFi credentials and API keys:

```cpp
const char *ssid = "YourWiFiSSID";  // Add WiFi SSID
const char *pass = "YourWiFiPassword";  // Add WiFi password

const char *SendApiKey = "YourSendKey"; // Send API key
const char *ReceiveApiKey = "YourReceiveKey"; // Receive API key
const char *BoardApiKey = "YourBoardKey"; // Board API key
```

### 2. Setup

The `setup()` function initializes the WiFi connection, sets up data transmission to the Consentium IoT cloud, and enables OTA updates.

```cpp
void setup() {
  board.initWiFi(ssid, pass);  // Begin WiFi connection
  board.beginSend(SendApiKey, BoardApiKey);  // Initialize sending data
  board.beginOTA(ReceiveApiKey, BoardApiKey);  // Enable OTA updates
}
```

### 3. Main Loop

The `loop()` function reads the temperature data from the LM35 sensor connected to an ADC pin, converts the ADC value to a voltage, and sends the data to the Consentium IoT platform.

#### a. Reading Data from LM35

The data from the LM35 sensor is read using the `analogRead(ADC_IN)` function. The value is multiplied by a constant to convert the ADC value to a corresponding temperature (depending on the calibration).

```cpp
double data_0 = analogRead(ADC_IN) * 0.322;  // read voltage data
```

#### b. Sending Sensor Data

The data is sent to the Consentium cloud using the `sendData` function. In this example, the data array consists of one temperature sensor, but the setup allows for multiple sensors to be added in the future.

```cpp
vector <double> sensorValues[] = {data_0};  // sensor data array
const char* sensorInfo[] = {"Temperature"};  // sensor information array
board.sendData(sensorValues, sensorInfo, sensorCount, LOW_PRE);  // send sensor data
```

#### c. OTA Updates

Every 100 cycles, the firmware checks for available updates and performs the update if available.

```cpp
if (loopCounter >= updateInterval) {
  board.checkAndPerformUpdate();  // Check and perform OTA updates
  loopCounter = 0;  // Reset the loop counter
}
```

### 4. Loop Control

The loop repeats every 5000 milliseconds (5 seconds).

```cpp
delay(interval);
```

## 5. Final code

```cpp
#include <ConsentiumThings.h>

#define FIRMWARE_VERSION "0.1"

ConsentiumThingsDalton board(FIRMWARE_VERSION); // Create ConsentiumThings object with firmware version

const char *ssid = "YourWiFiSSID"; // Add WiFi SSID
const char *pass = "YourWiFiPassword"; // Add WiFi password
constexpr int interval = 5000; // Wait for 5 seconds
const char *SendApiKey = "YourSendKey"; // Send API key
const char *ReceiveApiKey = "YourReceiveKey"; // Receive API key
const char *BoardApiKey = "YourBoardKey"; // Board API key
const int updateInterval = 100; // Check for update after 100 cycles

int loopCounter = 0; // Counter to keep track of loop cycles

void setup() {
  board.initWiFi(ssid, pass); // Begin WiFi connection
  board.beginSend(SendApiKey, BoardApiKey); // Initialize IoT board
  board.beginOTA(ReceiveApiKey, BoardApiKey); // Enable OTA updates
}

void loop(){
  double data_0 = analogRead(ADC_IN) * 0.322;  // read voltage data
  
  vector <double> sensorValues[] = {data_0};  // sensor data array
  const char* sensorInfo[] = {"Temperature"}; // sensor info. array
  
  board.sendData(sensorValues, sensorInfo, sensorCount, LOW_PRE); // send over REST with delay with desired prescision

  loopCounter++;
  if (loopCounter >= updateInterval) {
    board.checkAndPerformUpdate();
    loopCounter = 0; // Reset the counter after checking for an update
  }

  delay(interval);
}
```

## Summary

This program reads temperature data from an LM35 sensor, sends the data to the Consentium IoT cloud, and periodically checks for OTA firmware updates. It provides a robust real-time sensor data monitoring system and easy firmware updates.


# Sending DHT11 Sensor Data to Consentium IoT Cloud

This documentation explains how to read data from a **DHT11 sensor** using an digital pin and send the data to the **Consentium IoT cloud** using the **ConsentiumThings** library. The code also facilitates Over-The-Air (OTA) firmware updates for easy firmware management.

## Dependencies

The code leverages the `ConsentiumThings.h` library for communication with the Consentium IoT platform and the `DHT.h` library for reading data from the DHT11 sensor.

## Features

* Connect to a WiFi network to send data to the cloud.
* Read temperature and humidity from the DHT11 sensor.
* Send sensor data to the Consentium IoT platform.
* Enable Over-The-Air (OTA) firmware updates.
* Automatically check for updates after 100 loop cycles.

## Constants

* **Firmware Version**: The firmware version of the board is set to `0.1`.
* **Interval**: The main loop runs every 5 seconds (5000 ms).
* **Update Interval**: The firmware checks for updates after 100 cycles of the main loop.

## Code Overview

### 1. Initialization

The program begins by creating a `ConsentiumThingsDalton` object to manage communication with the Consentium IoT platform. The initialization requires the firmware version, WiFi credentials, and API keys.

```cpp
#define FIRMWARE_VERSION "0.1"
ConsentiumThingsDalton board(FIRMWARE_VERSION);
```

The following variables are set for WiFi credentials and API keys (hidden for security):

```cpp
const char *ssid = "YourWiFiSSID";  // WiFi SSID
const char *pass = "YourWiFiPassword";  // WiFi password
```

Additionally, a `DHT` object is initialized to interface with the DHT11 sensor:

```cpp
#include <DHT.h>
#define DHTPIN 2    // Pin where the DHT11 is connected
#define DHTTYPE DHT11   // DHT 11 sensor type
DHT dht(DHTPIN, DHTTYPE);
```

### 2. Setup

The `setup()` function initializes the WiFi connection, data transmission, OTA updates, and the DHT11 sensor.

```cpp
void setup() {
  dht.begin();  // Initialize DHT11 sensor
  board.initWiFi(ssid, pass);  // Begin WiFi connection
  board.beginSend(SendApiKey, BoardApiKey);  // Initialize data transmission to cloud
  board.beginOTA(ReceiveApiKey, BoardApiKey);  // Enable OTA updates
}
```

### 3. Main Loop

The `loop()` function reads the temperature and humidity from the DHT11 sensor, and then sends this data to the Consentium IoT platform.

#### a. Reading Data from DHT11

The temperature and humidity values are read using the `dht.readTemperature()` and `dht.readHumidity()` functions.

```cpp
float temperature = dht.readTemperature();  // Read temperature in Celsius
float humidity = dht.readHumidity();  // Read humidity in percentage
```

#### b. Sending Sensor Data

The temperature and humidity data are sent to the Consentium IoT cloud using the `sendData` function. The code is designed to handle multiple sensor values.

```cpp
vector <double> sensorValues[] = {temperature, humidity};  // sensor data array
const char* sensorInfo[] = {"Temperature", "Humidity"};  // sensor information array

board.sendData(sensorValues, sensorInfo, sensorCount, LOW_PRE);  // Send sensor data
```

#### c. OTA Updates

The firmware checks for available updates every 100 cycles. If an update is available, it will automatically perform the update.

```cpp
if (loopCounter >= updateInterval) {
  board.checkAndPerformUpdate();  // Check and perform OTA updates
  loopCounter = 0;  // Reset the loop counter
}
```

### 4. Loop Control

The loop repeats every 5000 milliseconds (5 seconds), allowing for periodic data sending and firmware update checks.

```cpp
delay(interval);
```

### Error Handling

If the sensor fails to read valid data, you can add error checking to ensure the system handles faulty sensor readings gracefully.

```cpp
if (isnan(temperature) || isnan(humidity)) {
  Serial.println("Failed to read from DHT sensor!");
  return;  // Exit loop early if reading fails
}
```

## 6. Final code

```cpp
#include <ConsentiumThings.h>
#include <DHT.h>

#define FIRMWARE_VERSION "0.1"
#define DHTPIN 2    // Pin where the DHT11 is connected
#define DHTTYPE DHT11   // DHT 11 sensor type

DHT dht(DHTPIN, DHTTYPE);  // Create DHT object

ConsentiumThingsDalton board(FIRMWARE_VERSION); // Create ConsentiumThings object with firmware version

const char *ssid = "YourWiFiSSID"; // Add WiFi SSID
const char *pass = "YourWiFiPassword"; // Add WiFi password
constexpr int interval = 5000; // Wait for 5 seconds between loops
const char *SendApiKey = "YourSendApiKey"; // Send API key
const char *ReceiveApiKey = "YourReceiveApiKey"; // Receive API key
const char *BoardApiKey = "YourBoardApiKey"; // Board API key
const int updateInterval = 100; // Check for update after 100 cycles

int loopCounter = 0; // Counter to keep track of loop cycles

void setup() {
  Serial.begin(9600);  // Initialize serial communication for debugging
  dht.begin();  // Initialize DHT11 sensor
  board.initWiFi(ssid, pass); // Begin WiFi connection
  board.beginSend(SendApiKey, BoardApiKey); // Initialize data transmission to cloud
  board.beginOTA(ReceiveApiKey, BoardApiKey); // Enable OTA updates
}

void loop() {
  // Reading temperature and humidity from the DHT11 sensor
  float temperature = dht.readTemperature();  // Read temperature in Celsius
  float humidity = dht.readHumidity();  // Read humidity in percentage

  // Check if any readings failed and exit the loop if so
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println("Failed to read from DHT sensor!");
    return;  // Exit the loop early if reading fails
  }

  // Prepare sensor values and info arrays
  vector <double> sensorValues[] = {temperature, humidity};  // Sensor data array
  const char* sensorInfo[] = {"Temperature", "Humidity"};  // Sensor information array

  // Send sensor data to the Consentium IoT cloud
  board.sendData(sensorValues, sensorInfo, sensorCount, LOW_PRE); // Send data with precision

  // Increment loop counter for OTA check
  loopCounter++;
  if (loopCounter >= updateInterval) {
    board.checkAndPerformUpdate(); // Check and perform OTA updates
    loopCounter = 0;  // Reset the counter after checking for an update
  }

  delay(interval); // Wait for the next cycle
}

```

## Summary

This code reads temperature and humidity data from a **DHT11 sensor** and sends it to the **Consentium IoT cloud** for monitoring. The system also checks for OTA updates, ensuring the firmware remains up-to-date. The design is flexible, allowing for multiple sensors to be added easily.


# Edge machine learning&#x20;


# Sine wave predictor

This document provides a guide to using Consentium's TinyML library for a continuous sine function inference example. This example uses TensorFlow Lite Micro with an Edge board compatible with ESP32/Raspberry Pi Pico W.

### Overview

This example demonstrates how to perform continuous inference on a sine function using a TensorFlow Lite model. The model predicts the sine value for a given input ( x ), and the results are compared with the actual sine value calculated using the `sin` function.

### Prerequisites

* **Hardware**: ESP32 or Raspberry Pi Pico W compatible Edge board.
* **Software**: Consentium's TinyML library, EdgeNeuron library, TensorFlow Lite Micro.

### Code Explanation

#### Includes and Constants

```cpp
#include <EdgeNeuron.h>
#include "model.h"

// Tensor arena for TensorFlow Lite to store tensors
constexpr int kTensorArenaSize = 2000;
alignas(16) uint8_t tensor_arena[kTensorArenaSize];
```

* `EdgeNeuron.h`: Include the EdgeNeuron library.
* `model.h`: Include the header file for the TensorFlow Lite model.
* `tensor_arena`: Defines the memory arena for TensorFlow Lite to manage tensor allocations.

#### Global Variables

```cpp
float x = 0.0;
float step = 0.1; // Step size for x increments
```

* `x`: The input value for the sine function.
* `step`: The increment value for `x` in each loop iteration.

#### Setup Function

```cpp
void setup() {
  Serial.begin(9600);
  while (!Serial);

  Serial.println("Continuous sine function inference example.");
  Serial.println("Initializing TensorFlow Lite Micro Interpreter...");

  // Initialize the model
  if (!initializeModel(model, tensor_arena, kTensorArenaSize)) {
    Serial.println("Model initialization failed!");
    while (true);  // Halt execution on initialization failure
  }

  Serial.println("Model initialization done.");
  Serial.println("Running continuous inference on sine function.");
}
```

* Initializes the serial communication.
* Prints initialization messages.
* Calls `initializeModel()` to load and set up the TensorFlow Lite model.

#### Loop Function

```cpp
void loop() {
  // Ensure x stays within the [0, 2π] range (reset after 2π)
  if (x > 6.28) {
    x = 0.0;
  }

  // Set input value in the model's input tensor
  setModelInput(x, 0);

  // Run the inference
  if (!runModelInference()) {
    Serial.println("Inference Failed!");
    return;
  }

  // Get the predicted output
  float y_predicted = getModelOutput(0);

  // Get the actual sine of x
  float y_actual = sin(x);

  // Print both the predicted and actual sine values
  Serial.print("Input x: ");
  Serial.print(x, 2);
  Serial.print(" | Predicted sin(x): ");
  Serial.print(y_predicted, 2);
  Serial.print(" | Actual sin(x): ");
  Serial.println(y_actual, 2);

  // Increment x by the defined step size for the next loop iteration
  x += step;

  // Add a small delay to make the output readable in the Serial Monitor
  delay(500);  // Adjust delay as needed for your use case
}
```

* Resets `x` to 0 if it exceeds (2\pi).
* Sets the input value `x` in the model.
* Runs the inference and retrieves the output.
* Calculates and prints both the predicted and actual sine values.
* Increments `x` and includes a delay to make the output readable.

### License

This code is licensed under the MIT license. All text in the license header must be included in any redistribution.


# Sine wave predictor with IoT

## Documentation for Consentium TinyML Library Integration

This guide explains the usage and functionality of the Consentium TinyML library with ESP32 or Raspberry Pi Pico W compatible Edge boards. The code demonstrates how to perform sine wave prediction using a TensorFlow Lite model, which runs on a microcontroller (ESP32 or Raspberry Pi Pico W) and interacts with IoT boards for data transmission.

### Key Components

#### Libraries Used

* **EdgeNeuron.h**: This library includes the necessary functionality to work with TensorFlow Lite on microcontroller platforms.
* **ConsentiumThings.h**: Provides support for IoT-related operations, such as WiFi initialization and data transmission.

#### Core Variables

* `ConsentiumThingsDalton board;`: Creates an object to manage IoT operations (WiFi, data transmission).
* **WiFi Credentials**:
  * `ssid`: Network SSID (WiFi name).
  * `pass`: WiFi password.
* **API Keys**:
  * `SendApiKey`: The key to authenticate sending data to a remote server.
  * `BoardApiKey`: API key for identifying the board.
* **TensorFlow Lite Variables**:
  * `tensor_arena`: Memory arena for TensorFlow Lite model execution.
  * `kTensorArenaSize`: Defines the maximum size of the tensor arena.

#### Code Breakdown

**1. Setup Function**

This function initializes both WiFi connectivity and the TensorFlow Lite model.

```cpp
void setup() {
  board.initWiFi(ssid, pass); // Initialize WiFi with the given credentials
  board.beginSend(SendApiKey, BoardApiKey); // Start sending data
  
  // Initialize the model
  if (!initializeModel(model, tensor_arena, kTensorArenaSize)) {
    while (true);  // Halt if model initialization fails
  }
}
```

* `board.initWiFi(ssid, pass);`: Connects to the specified WiFi network.
* `board.beginSend(SendApiKey, BoardApiKey);`: Authenticates the board with its unique API keys.
* `initializeModel(...)`: Loads the TensorFlow Lite model into memory using the defined tensor arena. If this fails, the execution stops.

**2. Main Loop**

The `loop` function continuously predicts the sine of `x` using the model and compares it with the actual sine value.

```cpp
void loop() {
  if (x > 6.28) {
    x = 0.0;
  }

  setModelInput(x, 0); // Set model input
  if (!runModelInference()) {
    return;  // If inference fails, exit the loop
  }

  float y_predicted = getModelOutput(0); // Retrieve the model's output
  float y_actual = sin(x); // Compute the actual sine value
  
  vector<double> sensorValues = {x, y_predicted, y_actual}; // Prepare sensor values
  const char* sensorInfo[] = {"Input", "Predicted", "Actual"}; // Metadata for each value

  board.sendData(sensorValues, sensorInfo, LOW_PRE); // Send the data with low precision

  x += step;  // Increment x by 0.1 (or any set step size)
  delay(interval); // Delay between each iteration (7 seconds)
}
```

* `setModelInput(x, 0);`: Provides the input (`x` value) to the TensorFlow Lite model.
* `runModelInference();`: Runs the inference process to predict the sine value.
* `getModelOutput(0);`: Retrieves the model's predicted output.
* `sin(x);`: Calculates the actual sine of `x` for comparison.
* `board.sendData(...)`: Sends the input, predicted, and actual sine values to a remote server with low precision (to reduce data size).

#### Additional Notes

* **WiFi Configuration**: The code connects to a WiFi network using `initWiFi()`. If there are connectivity issues, ensure the SSID and password are correct.
* **API Keys**: The API keys (`SendApiKey` and `BoardApiKey`) are essential for interacting with the server. If the keys are invalid, the data will not be sent successfully.
* **TensorFlow Lite Model**: This code assumes that a pre-trained TensorFlow Lite model is already present, loaded via `model.h`. Ensure that the model is compiled correctly and fits within the defined `tensor_arena` size.

#### Potential Modifications

* **Step Size (`x`)**: You can adjust the `step` size for `x` to change how quickly it increments. A smaller step will result in more detailed predictions.
* **Delay**: The `delay(interval);` statement controls how frequently data is sent. In this case, the delay is set to 7 seconds. Adjust it as per your use case.
* **Model Initialization**: If the model initialization frequently fails due to insufficient memory, consider increasing the `kTensorArenaSize` value or reducing the model complexity.

#### Example Use Case

This code is designed to predict the sine of values between 0 and 2π using a TinyML model on an edge device. It's a typical example for IoT projects where data is transmitted wirelessly to a remote server.

***

**License**:\
This project is licensed under the MIT License. The above information, including the text from Consentium IoT., must be included in any redistribution or modification of this code.

***

### Full Code:

```cpp
#include <EdgeNeuron.h>
#include <ConsentiumThings.h>
#include "model.h"

ConsentiumThingsDalton board; // Create ConsentiumThings object

const char *ssid = "DebjyotiFi"; // Add WiFi SSID
const char *pass = "cxa1619s";   // Add WiFi password
constexpr uint16_t interval = 7000; // Wait for 7 seconds
const char *SendApiKey = "a98a467056c590a22d5d740f89a1c2f2"; // Send API key
const char *BoardApiKey = "02fad5a5e1d39f3b"; // Board API key

// Reduced Tensor arena size for TensorFlow Lite
constexpr uint16_t kTensorArenaSize = 2000;
alignas(16) uint8_t tensor_arena[kTensorArenaSize];

// Define the range for x (between 0 and 2π)
float x = 0.0;
constexpr float step = 0.1; // Step size for x increments

void setup() {
  // Initialize WiFi and IoT board
  board.initWiFi(ssid, pass);  
  board.beginSend(SendApiKey, BoardApiKey);

  // Initialize the model
  if (!initializeModel(model, tensor_arena, kTensorArenaSize)) {
    // Reduce print messages to save space
    // Serial.println("Model initialization failed!");
    while (true);  // Halt execution on failure
  }
}

void loop() {
  // Ensure x stays within the [0, 2π] range
  if (x > 6.28) {
    x = 0.0;
  }

  // Set input value in the model's input tensor
  setModelInput(x, 0);

  // Run the inference
  if (!runModelInference()) {
    // Serial.println("Inference Failed!");
    return;
  }

  // Get the predicted output
  float y_predicted = getModelOutput(0);

  // Get the actual sine of x
  float y_actual = sin(x);

  // Use vector of sensor values for sending data
  vector <double> sensorValues = {x, y_predicted, y_actual};
  const char* sensorInfo[] = {"Input","Predicted", "Actual"};

  // Send data with low precision to save space
  board.sendData(sensorValues, sensorInfo, LOW_PRE);

  // Increment x by the defined step size
  x += step;

  // Add a delay between loop iterations
  delay(interval);  // Adjust delay as needed for your use case
}
```


# TinyML Occupancy Classification Example with Consentium IoT

This example demonstrates how to use Consentium IoT's **TinyML** and **EdgeNeuron AI** platforms to perform real-time occupancy classification using the **AMG8833 Grid-EYE thermal sensor** and **TensorFlow Lite Micro**. The project is designed for edge devices like the **ESP32** and **Raspberry Pi Pico W**.

***

## Features

* **Edge Compatibility**: Works seamlessly with ESP32 and Raspberry Pi Pico W.
* **Real-time Inference**: Employs TensorFlow Lite Micro for low-latency predictions.
* **Occupancy Classification**: Identifies room occupancy in the following categories:
  * Empty
  * One Person
  * Two Persons
  * Three Persons

***

## Prerequisites

### Hardware Requirements

1. **Edge Board**: ESP32 or Raspberry Pi Pico W
2. **Sensor**: AMG8833 Grid-EYE Thermal Sensor
3. **Connections**: I2C communication setup (SCL and SDA)

### Software Requirements

* Arduino IDE with relevant libraries:
  * `EdgeNeuron.h`
  * `EdgeMath.h`
  * `SparkFun_GridEYE_Arduino_Library.h`

***

## Code Overview

### 1. **Header Section**

The header provides essential information about the example, including its purpose, supported features, and licensing.

### 2. **Libraries and Configuration**

```cpp
#include <Wire.h>
#include <EdgeNeuron.h>
#include <EdgeMath.h>
#include <SparkFun_GridEYE_Arduino_Library.h>
#include "edge_neuron_model.h"
```

* **Wire.h**: For I2C communication.
* **EdgeNeuron.h**: Facilitates model initialization and inference.
* **EdgeMath.h**: Handles preprocessing like scaling and finding maximum probabilities.
* **SparkFun\_GridEYE\_Arduino\_Library.h**: Provides an interface for the AMG8833 sensor.

***

### 3. **Memory Allocation for TensorFlow Lite Model**

```cpp
constexpr int kTensorArenaSize = 10000;
alignas(16) uint8_t tensor_arena[kTensorArenaSize];
```

* **Tensor Arena**: Allocates memory for model inference.
* **Input and Output Tensors**:
  * `kInputSize`: 64 (8x8 thermal sensor pixels).
  * `kOutputSize`: 4 (class probabilities).

***

### 4. **Class Labels**

```cpp
String class_array[] = {"Empty", "One_person", "Two_persons", "Three_persons"};
```

Defines human-readable labels for the predicted classes.

***

### 5. **Setup Function**

```cpp
void setup() {
  // Initialize serial communication
  Serial.begin(115200);
  
  // Initialize the Grid-EYE sensor
  grideye.begin();
  
  Serial.println("[Consentium INFO] GridEYE sensor initialized successfully!");

  // Initialize the EdgeNeuron model
  if (!initializeModel(edge_neuron_model, tensor_arena, kTensorArenaSize)) {
    Serial.println("[Consentium ERROR] Model initialization failed!");
    while (true); // Halt execution
  }
  Serial.println("[Consentium INFO] Model initialized successfully!");
}
```

#### Tasks Performed:

1. Initializes the serial monitor for debugging.
2. Configures the Grid-EYE sensor for data capture.
3. Initializes the TensorFlow Lite Micro model using the **EdgeNeuron** platform.

***

### 6. **Loop Function**

#### Main Steps:

1. **Capture Data from Grid-EYE Sensor**

   ```cpp
   for (int i = 0; i < kInputSize; i++) {
     input_data[i] = grideye.getPixelTemperature(i);
     if (isnan(input_data[i])) {
       input_data[i] = 0.0; // Replace invalid sensor data
     }
   }
   ```

   * Captures the 8x8 thermal grid data from the sensor.
   * Replaces invalid data points (`NaN`) with `0.0`.

***

2. **Preprocess Input Data**

   ```cpp
   edgemath.scaler_transform(input_data, scaler_mean, scaler_scale, kInputSize);
   ```

   * Scales the input data using mean and scale values from training.

***

3. **Set Model Input Tensor**

   ```cpp
   for (int i = 0; i < kInputSize; i++) {
     setModelInput(input_data[i], i);
   }
   ```

   * Loads the preprocessed data into the model's input tensor.

***

4. **Run Model Inference**

   ```cpp
   if (!runModelInference()) {
     Serial.println("[Consentium ERROR] Inference failed!");
     return;
   }
   ```

   * Executes the TensorFlow Lite model for real-time inference.

***

5. **Retrieve Output and Predict Class**

   ```cpp
   for (int i = 0; i < kOutputSize; i++) {
     output_data[i] = getModelOutput(i);
   }
   int class_pos = edgemath.argmax(output_data, kOutputSize);
   Serial.println("[Consentium INFO] Predicted Class: " + class_array[class_pos]);
   ```

   * Retrieves the predicted probabilities for each class.
   * Uses `argmax` to identify the class with the highest probability.

***

6. **Log Class Probabilities**

   ```cpp
   for (int i = 0; i < kOutputSize; i++) {
     Serial.print("  ");
     Serial.print(class_array[i]);
     Serial.print(": ");
     Serial.println(output_data[i]);
   }
   ```

   * Outputs the predicted class probabilities to the serial monitor.

***

### 7. **Delay for the Next Cycle**

```cpp
delay(1000);
```

Introduces a 1-second delay between consecutive inferences.

***

## Example Output

### Serial Monitor Logs

```
***************************************************
*    Consentium IoT - Occupancy Classification   *
*        Powered by EdgeNeuron AI Platform       *
***************************************************

[Consentium INFO] GridEYE sensor initialized successfully!
[Consentium INFO] Model initialized successfully!
[Consentium INFO] Capturing temperature data from Grid-EYE...
[Consentium INFO] Data capture complete.
[Consentium INFO] Preprocessing input data...
[Consentium INFO] Data preprocessing complete.
[Consentium INFO] Running inference...
[Consentium INFO] Inference complete. Time taken: 23 ms
[Consentium INFO] Predicted Class: One_person
[Consentium INFO] Class probabilities:
  Empty: 0.12
  One_person: 0.85
  Two_persons: 0.03
  Three_persons: 0.00
```

***

## References

* [Consentium IoT Documentation](https://docs.consentiumiot.com)
* For additional support, email **<official@consentiumiot.com>**

***

## License

This project is licensed under the MIT License. Redistribution must include the header file.


# Adding NodeMCU support to Arduino IDE

This guide will help you program the **NodeMCU** using the **Arduino IDE**.

### Step 1: Connect Your NodeMCU to Your Computer

You need a **USB micro B cable** to connect the NodeMCU board to your computer. Once connected, a **blue LED** will start flashing.

If your computer does not detect the NodeMCU board, you may need to download the appropriate driver from the following link:

* [USB to UART Bridge VCP Drivers](https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers)

### Step 2: Open Arduino IDE

Ensure you have **Arduino IDE version 1.6.4** or later to proceed.

1. Go to **File > Preferences**.
2. In the **"Additional Boards Manager URLs"** field, type (or copy-paste) the following URL:

   ```
   http://arduino.esp8266.com/stable/package_esp8266com_index.json
   ```
3. Click **OK**.
4. Now, go to **Tools > Board > Board Manager**.
5. In the search field, type **"esp8266"**.
6. You should see an entry named **"esp8266 by ESP8266 Community"**. Click on it and press the **Install** button on the lower right.

Once the download is complete, you're ready to start coding!

### Step 3: Make an LED Blink Using NodeMCU

For our first program, we will blink an LED connected to one of the digital pins of the NodeMCU board. **Note**: The pin names printed on the board may differ from the pin names used in the program.

In this example, we'll connect the LED to **D7**, which corresponds to **GPIO13**. Below is the code (which is a modified version of the Arduino **Blink** example):

```cpp
// The setup function runs once when you press reset or power the board
void setup() {
  // Initialize digital pin 13 (D7) as an output.
  pinMode(13, OUTPUT);
}

// The loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // Turn the LED on (HIGH is the voltage level)
  delay(1000);              // Wait for one second
  digitalWrite(13, LOW);    // Turn the LED off by making the voltage LOW
  delay(1000);              // Wait for one second
}
```

#### NodeMCU Pin Mapping

* In this example, **D7** (as printed on the board) corresponds to **GPIO13** in the code.

Ensure that the LED is connected to the correct pin as per the board's pinout.


# Adding ESP32 Support to Arduino IDE

## Here's how to program the ESP32 using the Arduino IDE.

### Step 1: Connect your ESP32 to your computer

You'll need a USB micro B cable to connect your ESP32 to your computer. Once connected, the `power LED` will light up on the board. If your computer doesn't automatically recognize the ESP32, you may need to install the CP2102 driver from [this link](https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers).

### Step 2: Open Arduino IDE

Ensure you are using **Arduino IDE version 1.8.5 or later**. Here's how to set up ESP32 in the IDE:

1. Go to **File > Preferences** in the Arduino IDE.
2. In the **"Additional Boards Manager URLs"** field, paste the following URL:\
   `https://dl.espressif.com/dl/package_esp32_index.json`\
   Then, click **OK**.

   ![Preferences](https://github.com/debjyotiC/IOT_class/blob/master/images/arduino-ide-preferences-esp32.jpg)
3. Next, go to **Tools > Board > Board Manager**.
4. In the search bar, type "esp32" and select the **"esp32 by Espressif Systems"** option. Click **Install**.

   ![Board Manager](https://github.com/debjyotiC/IOT_class/blob/master/images/arduino-board-manager-esp32.jpg)

### Step 3: Make a LED Blink using ESP32

Now that your IDE is ready, let's upload a simple blink program.

Just like NodeMCU, the ESP32 has multiple GPIO pins. Refer to the ESP32 pinout below for pin naming conventions:

![ESP32 Pinout](https://randomnerdtutorials.com/wp-content/uploads/2018/08/ESP32-DOIT-DEVKIT-V1-Board-Pinout-36-GPIOs.jpg)

For this example, we'll use GPIO23 to blink an LED. Connect the LED to GPIO23 and upload the following code:

```cpp
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 23 as an output.
  pinMode(23, OUTPUT);
}
 
// the loop function runs over and over again forever
void loop() {
  digitalWrite(23, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(23, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}
```


# Programming Raspberry Pi Pico with Arduino IDE (Pico W Compatible)

Learn how to program the **Raspberry Pi Pico** and **Pico W** using the **Arduino IDE**. The Raspberry Pi Pico is a low-cost microcontroller board built around the RP2040 chip by the Raspberry Pi Foundation. In this guide, you’ll learn how to set up Arduino IDE and begin programming the Raspberry Pi Pico with C/C++.

***

## Step 1: Adding the Raspberry Pi Pico to the Boards Manager

1. **Open Arduino IDE**.
2. Go to **File > Preferences**.
3. In the **"Additional Boards Manager URLs"** field, enter the following URL:

   ```
   https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
   ```
4. Click **OK**.
5. Now, go to **Tools > Board > Boards Manager…**
6. Search for **"pico"** and install the **Raspberry Pi Pico/RP2040** boards package.
7. Once installed, go to **Tools > Board**, and you'll see a selection of **Raspberry Pi Pico** boards.

***

## Step 2: Selecting Your Pico Board

1. Go to **Tools > Board** and select the **Raspberry Pi Pico** or **Pico W** model that you are using.

***

## Step 3: Loading the Blink LED Sketch

1. Go to **File > Examples > 1. Basic > Blink**.
2. The **Blink** sketch should load, which turns an LED on and off every second.
3. You can also copy the code below:

   ```cpp
   /*
     Blink - Turns an LED on for one second, then off for one second repeatedly.
     This example code is in the public domain.
   */

   // Setup function runs once when you press reset or power the board
   void setup() {
     pinMode(LED_BUILTIN, OUTPUT);  // Initialize digital pin LED_BUILTIN as an output
   }

   // Loop function runs repeatedly
   void loop() {
     digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED on
     delay(1000);                      // Wait for a second
     digitalWrite(LED_BUILTIN, LOW);   // Turn the LED off
     delay(1000);                      // Wait for a second
   }
   ```

***

## Step 4: Connecting the Raspberry Pi Pico in BOOTLOADER Mode

1. **Put the Pico in Bootloader Mode**:

   If your Raspberry Pi Pico is currently running **MicroPython** or is new, you need to manually put it into bootloader mode.

   * Press and hold the **BOOTSEL** button on the Pico while connecting it to your computer via USB.
   * A new mass storage device will appear on your computer. You can ignore this window and close it.
2. **Upload the Code**:

   For future uploads using the Arduino IDE, the Pico board will automatically enter bootloader mode without pressing the **BOOTSEL** button.
3. In Arduino IDE, open the **Tools > Port** menu, then select **Select Other Board and Port...**.
4. **Select the Pico**: Choose **Raspberry Pi Pico** or **Raspberry Pi Pico W** as the board, and select the appropriate COM port.
5. Tick **Show All Ports** if the COM port doesn’t show up, and select **UF2 Devices** as the port option.

***

## Step 5: Upload the Code

1. After selecting the correct board and port, click on the **Upload** button in the Arduino IDE.
2. Once the code is uploaded, you should receive a success message.

***

## Step 6: Demonstration

1. If everything went as expected, the **onboard LED** of the Raspberry Pi Pico should now be blinking every second.

***


