Getting Started
First, download the NinjaIoT_esp32 or NinjaIoT_esp8266 library.
Add it via Sketch > Include Library > Add .ZIP Library.
Then get your Project API Key from the Ninja IoT Dashboard.
#include <NinjaIoT.h>
NinjaIoT iot;
void setup() {
Serial.begin(115200);
// Use your Project API Key from https://iot.roboninja.in/
iot.connect("your-wifi-name", "your-wifi-pass", "Your_Project_API");
}
void loop() {
iot.ReadAll(); // Keep the connection alive & sync variables
delay(50);
}
Simple LED Control
Control a digital output pin directly from the cloud. In your dashboard, create a Switch Widget mapped to D27.
The iot.SyncOut("D27") function automatically fetches the state of D27 from the server and writes it to GPIO 27.
#include <NinjaIoT.h>
NinjaIoT iot;
void setup() {
Serial.begin(115200);
iot.connect("wifi-name", "wifi-pass", "Your_Project_API");
}
void loop() {
// Control LED on GPIO27 according to server value (ON/OFF)
iot.SyncOut("D27");
delay(50); // wait 50 milliseconds to respect rate limits
}
LED Brightness Control (PWM)
You can seamlessly map a Slider Widget on your dashboard to an ESP's PWM output.
Using iot.SyncPWM("D14") will read the slider value (0-255) from the cloud and adjust the brightness of the LED connected to GPIO 14.
#include <NinjaIoT.h>
NinjaIoT iot;
void setup() {
Serial.begin(115200);
iot.connect("wifi-name", "wifi-pass", "Your_Project_API");
}
void loop() {
// Adjust PWM brightness on GPIO14 from server value (0-255)
iot.SyncPWM("D14");
delay(50); // wait 50 milliseconds
}
Read Analog Sensor to Cloud
Learn how to read an analog sensor (like a Soil Moisture sensor) and send its value to a custom variable in your Ninja IoT dashboard using WriteVar.
Create a Gauge Widget mapped to the variable SoilMoisture to visualize this data.
#include <NinjaIoT.h>
NinjaIoT iot;
int SoilMoisture = 0;
void setup() {
Serial.begin(115200);
iot.connect("wifi-name", "wifi-pass", "Your_Project_API");
}
void loop() {
SoilMoisture = analogRead(36); // Read analog value from VP pin (GPIO36)
iot.WriteVar("SoilMoisture", SoilMoisture); // Send value to the cloud
delay(1500); // Wait 1.5 seconds before sending the next value
}
DHT11 Temperature & Humidity
Use the popular DHT sensor library by Adafruit to read temperature and humidity, then upload multiple variables at once to the cloud.
Map these variables (Temperature and Humidity) to Gauge or Text Widgets on your dashboard.
#include <NinjaIoT.h>
#include "DHT.h"
NinjaIoT iot;
#define DHTPIN 12 // connect DHT11 to GPIO12 (D12)
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
iot.connect("wifi-name", "wifi-pass", "Your_Project_API");
dht.begin();
}
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
iot.WriteVar("Temperature", t);
iot.WriteVar("Humidity", h);
delay(1500); // Respect rate limits
}