FlyghtEdge · Flyght Cloud
Documentation
From installing the library to a device you watch and control from anywhere, step by step.
Devices · 01
Devices and wiring
Sensors, relays, motors, buses and screens: how to wire and call each one.
Every device the library knows is a module of its own: you create the object, set it up, and pass it to dev.use(...) before dev.begin(). Only the modules you create end up in the firmware. Each one adds cards or a page to the board’s own dashboard, and its readings and switches are widgets that MQTT, Home Assistant, flows and Flyght Cloud see like any other.
How a device is used
- Declare it at the top with its pins, for example
fn::Ultrasonic tank(18, 19, "tank");. - Set it up in
setup()with its builders, for exampletank.tank(150, 20).every(1000);. - Give it to the device before
begin():dev.use(tank);. Calls chain:dev.use(a).use(b). - Let
dev.loop()run it. Read a value when you need one (tank.distanceCm()), or leave it to the dashboard, MQTT and flows, which use its widgets.
#include <FlyghtEdge.h>
fn::Device dev("water-tank");
fn::Ultrasonic tank(18, 19, "tank"); // trig pin, echo pin, id
void setup() {
tank.tank(150, 20).every(1000); // 150 cm = empty, 20 cm = full
dev.use(tank);
dev.begin();
}
void loop() { dev.loop(); }Which module uses which bus and pins
| Device | Class | Bus | Pins (the name of each in the pins API) | Page on the board |
|---|---|---|---|---|
| Relay board | Relay | GPIO output | ch1, ch2 … (a latching channel also ch1r) | Relays |
| Solenoid valve | Solenoid | GPIO output | ch1 | Relays |
| DC motor (H-bridge) | DcMotor | PWM and two GPIO | pwm, in1, in2 | Motors |
| Brushless motor (ESC) | Esc | Servo pulse, 50 Hz | pwm | Motors |
| Stepper (step/dir driver) | Stepper | GPIO | step, dir, en | Motors |
| Hobby servo | Servo | PWM, 50 Hz | pwm | Servos |
| DHT11 / DHT22 | Dht | One GPIO | data | Sensors |
| DS18B20 | Ds18b20 | 1-Wire | data | Sensors |
| Ultrasonic (trig + echo) | Ultrasonic | GPIO out + GPIO in | trig, echo | Sensors |
| Analog sensor | AnalogSensor | ADC1 | pin | Sensors |
| On/off sensor | DigitalSensor | GPIO input | pin | Sensors |
| MH-Z19 (CO2) | Mhz19 | UART, 9600 baud | rx, tx | Sensors |
| PZEM-004T (mains) | Pzem | UART, 9600 baud | rx, tx | Sensors |
| INA219 (DC power) | Ina219 | I2C, 0x40 | sda, scl | Sensors |
| GPS receiver | Gps | UART, 9600 baud | the constructor: rxPin, txPin | Map |
| BNO055 IMU | Bno055 | I2C, 0x28 | pins(sda, scl) | Motion |
| Character LCD | LcdI2c | I2C, 0x27 / 0x3F | pins(sda, scl) | LCD |
| External microcontroller | McuLink | UART, 115200 baud | the constructor: rxPin, txPin | Serial |
| SD card | SdCard | SPI (or SDMMC) | cs, pins(sck, miso, mosi) | Files |
| TFT screen | TftSpi + Tft | SPI | cs, dc, rst, pins(sck, mosi, miso) | Screen |
The pages of this group
- Supported devicesEvery chip, sensor, actuator and link that works today.
- I2C, SPI and UARTPins, speeds, addresses, the scan call and the helpers.
- Ultrasonic distanceTrig and echo wiring, tank level, an alarm.
- Sensors: wiring and useDHT, DS18B20, analog, digital, CO2, mains power, INA219.
- Relays and actuatorsRelay boards, valves, DC motors, ESCs and steppers.
- ServoA hobby servo: an angle, or a speed for a 360 one, calibrated in the browser.
- GPSPosition, track and a map over UART.
- IMU (BNO055)Orientation over I2C.
- LCD (I2C)A character screen you can write to.
- External microcontrollerA line-based link over UART to another board.
- SD cardFiles over SPI, and a file manager.
- TFT screenDraw on an SPI display, mirrored in the browser.
- Moving pinsChange a pin from the dashboard, no re-flash.
- Next upWhat we propose to add next, our picks, and how to tell us.
Devices · 02
Supported devices
The chips, boards, sensors, actuators and links that work today, and where each is documented.
// Arduino IDE: Tools > Board > esp32 (Arduino-ESP32 core 3.x), then pick your chip.
// Tools > Partition Scheme > "No FS 4MB (2MB APP x2)"
#include <FlyghtEdge.h>“Supported” here means: it is in the library today, with a page in these docs that shows its wiring, its calls and its widgets. A device that is not listed is not promised (see Next up for what we propose to add).
Chips
| Chip | Status | What it is | Good for |
|---|---|---|---|
| ESP32 | Supported | Dual-core Xtensa, Wi-Fi and classic Bluetooth | The all-rounder: the most pins, three UARTs, the widest choice of boards |
| ESP32-S2 | Supported | Single-core Xtensa, Wi-Fi, native USB | Small devices that need USB and no Bluetooth |
| ESP32-S3 | Supported | Dual-core Xtensa, Wi-Fi and BLE, native USB, PSRAM boards | Gateways, screens and anything that needs memory and speed |
| ESP32-C3 | Supported | Single-core RISC-V, Wi-Fi and BLE | Cheap, small nodes: a relay, a sensor, a switch |
| ESP32-C5 | Supported | RISC-V, dual-band Wi-Fi 6 (2.4 and 5 GHz) | Sites where the 2.4 GHz band is crowded |
| ESP32-C6 | Supported | RISC-V, Wi-Fi 6, BLE and 802.15.4 | New designs that want Wi-Fi 6 |
- All of them need the Arduino-ESP32 core 3.x. The library ships one precompiled archive per chip, so you only choose the board.
- Not supported: ESP8266 (another architecture), ESP32-H2 and ESP32-P4 (no Wi-Fi radio of their own).
- Default pins differ per chip: the table in I2C, SPI and UART lists the ones the library’s example uses.
Sensors and inputs
| Device | Class | Bus | Docs |
|---|---|---|---|
| DHT11, DHT22 | Dht | 1 GPIO | Devices → Sensors |
| DS18B20 probe | Ds18b20 | 1-Wire | Devices → Sensors |
| HC-SR04, JSN-SR04T and other trig + echo modules | Ultrasonic | 2 GPIO | Devices → Ultrasonic distance |
| Anything analog: water level 4–20 mA or 0.5–4.5 V, MQ gas, O2, ACS712 current | AnalogSensor | ADC1 | Devices → Sensors |
| Float switch, water leak, flame, door | DigitalSensor | 1 GPIO | Devices → Sensors |
| MH-Z19 CO2 | Mhz19 | UART | Devices → Sensors |
| PZEM-004T v3 mains meter | Pzem | UART | Devices → Sensors |
| INA219 DC power | Ina219 | I2C | Devices → Sensors |
| BNO055 orientation | Bno055 | I2C | Devices → IMU |
| GPS receivers (NMEA) | Gps | UART | Devices → GPS |
Outputs and actuators
| Device | Class | Bus | Docs |
|---|---|---|---|
| Relay boards up to 16 channels: active high or low, latching, interlock, timers | Relay | GPIO | Devices → Relays and actuators |
| Solenoid valve | Solenoid | GPIO | Devices → Relays and actuators |
| DC motor on an H-bridge (L298N, TB6612, L9110, DRV8871) | DcMotor | PWM + GPIO | Devices → Relays and actuators |
| Brushless motor through an ESC | Esc | PWM 50 Hz | Devices → Relays and actuators |
| Stepper on a step/dir driver (A4988, DRV8825, TB6600) | Stepper | GPIO | Devices → Relays and actuators |
| Hobby servo, positional or 360 continuous | Servo | PWM 50 Hz | Devices → Servo |
| Plain LED, RGB LED, onboard WS2812 | Led, RgbLed | GPIO | Components → Light |
Screens, storage and other boards
| Device | Class | Bus | Docs |
|---|---|---|---|
| HD44780 LCD on a PCF8574 backpack (16×2, 20×4) | LcdI2c | I2C | Devices → LCD |
| ST7789 and ILI9341 TFT screens; any other through Adafruit_GFX, TFT_eSPI or LovyanGFX | TftSpi, GfxTarget, Tft | SPI | Devices → TFT screen |
| SD card (FAT32) | SdCard | SPI or SDMMC | Devices → SD card |
| Another microcontroller: Arduino Uno, STM32, RP2040, another ESP | McuLink | UART | Devices → External microcontroller |
What the devices talk to
| Where | Status | Notes |
|---|---|---|
| The board’s own dashboard and HTTP API | Supported | Roles viewer, operator, admin; tokens for scripts. See Local API. |
| Local MQTT and Home Assistant discovery | Supported | Every widget of a device is an entity; webhooks and visual flows run on the board. |
| Flyght Cloud | Supported | Claim with a license key, then MQTT or HTTPS. Brokers: EMQX 5 (also EMQX Cloud Serverless) and Mosquitto with dynamic security; the in-process broker for hosts that accept WebSocket. |
| Updates over the air | Supported | An administrator uploads a firmware to the board (POST /sys/ota). |
Devices · 03
I2C, SPI and UART
Which pins, which speed, which address; the scan call and the helpers.
# GET /fn/api/v1/i2c/scan
{"devices":[
{"addr":39,"hex":"0x27","guess":"LCD backpack / PCF8574"},
{"addr":40,"hex":"0x28","guess":"BNO055 IMU / VL53L0X"},
{"addr":64,"hex":"0x40","guess":"PCA9685 / INA219 / HTU21D"}
]}Three buses carry the devices of this group. I2C uses two wires and an address, SPI uses a clock, two data lines and a chip-select per device, UART uses two crossed wires and a speed. All of them are 3.3 V on the board’s pins.
I2C: SDA and SCL
| Item | Detail |
|---|---|
| Used by | Ina219 (0x40), Bno055 (0x28, or 0x29), LcdI2c (0x27 or 0x3F, found by itself). |
| Pins | The board’s default SDA and SCL, or the pins you give: imu.pins(sda, scl), lcd.pins(sda, scl), or the sda and scl arguments of Ina219. Modules on one bus must be given the same pins. |
| Speed | 400 kHz, unless you start the bus yourself with another value (fn::i2c::begin). |
| Started once | A bus is started once; a later call for the same bus changes nothing, so a module and your own code can both call begin. |
The pins the library’s example uses, per chip
| Chip | I2C SDA, SCL | SPI SCK, MISO, MOSI | UART RX, TX (GPS) |
|---|---|---|---|
| ESP32 | 21, 22 | 18, 19, 23 | 16, 17 |
| ESP32-S3 | 8, 9 | 12, 13, 11 | 18, 17 |
| ESP32-S2 | 8, 9 | 36, 37, 35 | 18, 17 |
| ESP32-C3 | 8, 9 | 4, 5, 6 | 10, 0 |
| ESP32-C6 | 23, 22 | 21, 20, 19 | 4, 5 |
| ESP32-C5 | 0, 1 | 10, 9, 8 | 4, 5 |
The helpers: fn::i2c
| Call | Meaning |
|---|---|
bool begin(TwoWire& wire, int sda = -1, int scl = -1, uint32_t freq = 400000) | Starts a bus once, on the pins you give (or the board’s defaults with -1). false when it cannot start. |
bool probe(TwoWire& wire, uint8_t addr) | true when a device answers at the address. |
const char* guess(uint8_t addr) | A guess for well-known addresses (see the table below); an empty text when unknown. |
bool writeReg(TwoWire& wire, uint8_t addr, uint8_t reg, uint8_t value) | Writes one register. true on success. |
bool readRegs(TwoWire& wire, uint8_t addr, uint8_t reg, uint8_t* out, size_t len) | Reads len registers starting at reg. true when all of them arrived. |
#include <FlyghtEdge.h>
fn::Device dev("i2c-lab");
const uint8_t ADDR = 0x76; // a BME280 / BMP280
void setup() {
fn::i2c::begin(Wire, 21, 22); // SDA, SCL (400 kHz)
dev.page("Bus").value("chip", "Chip id", "");
dev.begin();
if (fn::i2c::probe(Wire, ADDR)) {
uint8_t id;
if (fn::i2c::readRegs(Wire, ADDR, 0xD0, &id, 1)) dev.ui().set("chip", (float)id); // 0x60 = BME280
}
}
void loop() { dev.loop(); }Scanning the bus
GET /fn/api/v1/i2c/scan (role Viewer) probes every address from 0x08 to 0x77 and answers with the devices found, each with its address, its hex form and a guess. The route is registered once per firmware by the first module that uses I2C and has a web page (Bno055 or LcdI2c).
H=smart-lamp-c2d3.local # or the device IP
TOKEN=fn_... # a session or API token, see "Local API"
curl -s -H "Authorization: Bearer $TOKEN" http://$H/fn/api/v1/i2c/scan| Address | `guess()` says |
|---|---|
| 0x20, 0x27, 0x38, 0x3F | LCD backpack / PCF8574 |
| 0x23 | BH1750 |
| 0x28, 0x29 | BNO055 IMU / VL53L0X |
| 0x3C, 0x3D | OLED SSD1306 |
| 0x40 | PCA9685 / INA219 / HTU21D |
| 0x48 to 0x4B | ADS1115 / TMP102 |
| 0x50 to 0x57 | EEPROM AT24Cxx |
| 0x5A | MLX90614 |
| 0x5C | AM2320 / BH1750 (alt) |
| 0x68, 0x69 | MPU6050 / DS3231 RTC (0x69: MPU6050 alt) |
| 0x76, 0x77 | BME280 / BMP280 |
SPI: clock, MISO, MOSI and a chip-select
| Device | Pins and settings |
|---|---|
SdCard | SdCard(int cs = SS, SPIClass& spi = SPI), pins(sck, miso, mosi), frequency(hz) (default 20 MHz). On a chip with an SDMMC host, mmc(oneBit = true, clk, cmd, d0) uses that instead of SPI. |
TftSpi | TftSpi(chip, w, h, cs, dc, rst = -1, spi = SPI, hz = 40000000), pins(sck, mosi, miso = -1). dc is the data/command pin, rst the reset pin (-1 when it has none). |
The SD card and the TFT screen can share the bus: give both the same sck, miso and mosi, and each its own chip-select. The library’s 05_Devices example does exactly that.
UART: RX, TX and a speed
| Device | Speed | Default port | Constructor |
|---|---|---|---|
Gps | 9600 (a parameter) | Serial1 | Gps(int rxPin, int txPin = -1, uint32_t baud = 9600, HardwareSerial& port = Serial1) |
McuLink | 115200 (a parameter) | Serial1 | McuLink(int rxPin, int txPin, uint32_t baud = 115200, HardwareSerial& port = Serial1) |
Mhz19 | 9600 | Serial2 | Mhz19(int rxPin, int txPin, HardwareSerial& port = Serial2, const char* id = "co2") |
Pzem | 9600 | Serial2 | Pzem(int rxPin, int txPin, HardwareSerial& port = Serial2, uint8_t address = 0xF8, const char* id = "mains") |
- Cross the wires: the board’s RX goes to the device’s TX and the board’s TX to the device’s RX. The pin names in the dashboard say it (“RX (from the sensor TX)”). Share the ground.
- The
HardwareSerial&argument picks the port:Serial1exists on every chip,Serial2on chips with a third UART. Give each module its own port. - On a chip with two UARTs the MCU link can use UART0 (
Serial0) when “USB CDC On Boot” is enabled, because the USB is then the serial monitor. - A UART is started once: when an admin moves its pins from the dashboard they are saved at once and used from the next start.
Devices · 04
Ultrasonic distance (trig and echo)
HC-SR04, JSN-SR04T or any trig and echo module: distance, tank level and an alarm.
fn::Ultrasonic tank(18, 19, "tank"); // trig pin, echo pin, id
void setup() {
tank.tank(150, 20).every(1000); // 150 cm = empty, 20 cm = full
dev.use(tank);
dev.begin();
}Wiring
| Module pin | Goes to | Notes |
|---|---|---|
| VCC | The supply your module needs (usually 5 V) | Check the module: the HC-SR04 is a 5 V part. |
| GND | GND, shared with the board | — |
| TRIG | The trigPin (a GPIO output) | A 3.3 V pulse is enough. |
| ECHO | The echoPin (a GPIO input) | It must reach the pin at 3.3 V. A module that answers at 5 V needs a divider (for example 1 kΩ in series and 2 kΩ to ground). The dashboard labels the pin “Echo (3.3 V!)”. |
Constructor and builders
Ultrasonic(int trigPin, int echoPin, const char* id = "distance");
Ultrasonic& airTemperature(float celsius); // default 20 C
Ultrasonic& tank(float emptyCm, float fullCm); // adds the level in percent
float distanceCm() const; // NaN when there is no echo| Parameter | Type | Default / range | Meaning |
|---|---|---|---|
trigPin | int | a GPIO | The output pin that starts a measurement. |
echoPin | int | a GPIO | The input pin the echo comes back on (3.3 V). |
id | const char* | "distance" | The prefix of the widgets: <id>_cm, <id>_level. |
airTemperature(float celsius) | float | 20 °C | The speed of sound depends on the air: give the temperature if you know it. |
tank(float emptyCm, float fullCm) | float, float | none | The sensor on top of a tank: adds a level in percent between the two distances. |
What it does
- Every period it sends a 10 µs pulse on the trig pin; an interrupt on the echo pin measures the width of the pulse that comes back.
loop()never waits for it. - No echo within 40 ms means nothing is in range: the card shows “—”, never a made-up number.
- The period is 500 ms by default and at least 60 ms (
every(ms)). - Only one
Ultrasonicper firmware: the echo interrupt keeps its pin in one place.
Widgets and readings
| Where | What |
|---|---|
Widget <id>_cm | The distance in cm, a gauge from 0 to 400, one decimal. |
Widget <id>_level | The level in percent (a gauge from 0 to 100), only after tank(). |
distanceCm() | The last valid distance in cm (NaN when there is none). |
value(int reading) | value(0) is the distance, value(1) the level (when tank() was called). |
alarm(high, low, cb) | An alarm on the distance (the first reading): ALARM at high or more, OK again at low or less. Adds the widget <id>_alarm. |
fn::Ultrasonic tank(18, 19, "tank");
fn::Relay pump("pump", "Fill pump");
void setup() {
pump.channel(4, "Fill pump").maxOn(600); // never longer than 10 minutes
tank.tank(150, 20).every(1000) // 150 cm = empty, 20 cm = full
.alarm(130, 100, [](bool nearlyEmpty) { // ALARM at 130 cm or more, OK again at 100 cm or less
pump.set(0, nearlyEmpty); // the callback runs on the loop task
});
dev.use(tank).use(pump);
dev.begin();
}
void loop() {
dev.loop();
if (!isnan(tank.distanceCm())) Serial.println(tank.distanceCm());
}Devices · 05
Sensors: wiring and use
DHT, DS18B20, analog, on/off, CO2, mains power and INA219: pins, calls and widgets.
fn::Dht dht(4, fn::Dht::Type::Dht22);
fn::Ds18b20 probe(5);
fn::AnalogSensor pressure(34, "pressure", "Tank pressure", "m");
void setup() {
dht.every(5000).alarm(35, 32); // an alarm card: on at 35 C, off again at 32 C
probe.every(5000);
pressure.map(500, 4500, 0, 3).range(0, 3, 2); // 0.5-4.5 V = 0-3 m of water
dev.use(dht).use(probe).use(pressure);
dev.begin();
}Every sensor is a module with the same behaviour: one card per reading, “—” while there is no trustworthy value (never a made-up number), health “degraded” when a reading is missing for too long, and pins an admin can move from the card menu. Create it, set it up, dev.use(...) it, and dev.loop() does the rest without blocking.
What every sensor has
| Call | Meaning |
|---|---|
every(ms) | The period between readings. Each sensor has a minimum (the table below): a smaller value is raised to it. |
staleAfter(ms) | How long a reading may be missing before the sensor is “degraded”. Default: five periods; 0 = never. |
alarm(high, low, cb) | An alarm on the first reading: ALARM at high or more, OK again at low or less (default: the same value). Adds a card <id>_alarm. cb(bool) runs on the loop task when it changes, for example to switch a relay. |
alarmOn() | Whether the alarm is on now. |
value(int reading) | The last valid value of a reading, in the order the sensor declares them (NaN when there is none). |
page("Name") | Puts the cards on a page of your choice (default “Sensors”). |
The widget of a reading is <id>_<key>, for example dht_temp. Its topics, its Home Assistant entity and its place in a flow follow from it.
The eight sensors at a glance
| Sensor | Constructor | Period (default, minimum) | Readings (widgets) |
|---|---|---|---|
Dht | Dht(int pin, Type type = Dht22, const char* id = "dht") | DHT22 2000, 2000 ms; DHT11 1000, 1000 ms | dht_temp (°C), dht_hum (%) |
Ds18b20 | Ds18b20(int pin, const char* id = "ds18b20") | 2000, 1000 ms | ds18b20_temp (°C) |
Ultrasonic | Ultrasonic(int trigPin, int echoPin, const char* id = "distance") | 500, 60 ms | <id>_cm, <id>_level |
AnalogSensor | AnalogSensor(int pin, const char* id, const char* title, const char* unit) | 1000, 100 ms | <id>_v |
DigitalSensor | DigitalSensor(int pin, const char* id, const char* title) | 20, 10 ms | <id>_state |
Mhz19 | Mhz19(int rxPin, int txPin, HardwareSerial& port = Serial2, const char* id = "co2") | 5000, 2000 ms | co2_ppm |
Pzem | Pzem(int rxPin, int txPin, HardwareSerial& port = Serial2, uint8_t address = 0xF8, const char* id = "mains") | 2000, 1000 ms | mains_v, _a, _w, _kwh, _hz, _pf |
Ina219 | Ina219(uint8_t address = 0x40, float shuntOhm = 0.1f, TwoWire& wire = Wire, int sda = -1, int scl = -1, const char* id = "ina219") | 1000, 100 ms | ina219_v, _a, _w |
DHT11 and DHT22: temperature and humidity
| Module pin | Goes to |
|---|---|
| VCC / + | 3.3 V (a DHT works from 3.3 to 5 V) |
| DATA / OUT | The pin you give (a pull-up to VCC is on most breakout boards; add 10 kΩ if it is the bare part) |
| GND | GND |
fn::Dht dht(4, fn::Dht::Type::Dht22); // or fn::Dht::Type::Dht11
void setup() {
dht.every(5000).alarm(35, 32); // temperature alarm: on at 35 C, off at 32 C
dev.use(dht);
dev.begin();
}
void loop() {
dev.loop();
static uint32_t t;
if (millis() - t > 10000) {
t = millis();
Serial.printf("%.1f C %.0f %%\n", dht.temperature(), dht.humidity()); // NaN when there is no reading
}
}DS18B20: a temperature probe
- Wire the three leads: red to 3.3 V, black to GND, yellow (data) to the pin, and a 4.7 kΩ resistor between data and 3.3 V. The dashboard labels the pin “Data (4.7 k to 3.3 V)”.
- One probe per pin. The conversion is a small state machine, so
loop()is not held for the 750 ms it takes. - The range of the card is −20 to 80 °C.
probe.temperature()is NaN until the first good reading.
fn::Ds18b20 probe(5, "boiler"); // data pin, id -> widget boiler_temp
void setup() {
probe.every(5000).alarm(80, 70); // too hot at 80 C, fine again at 70 C
dev.use(probe);
dev.begin();
}AnalogSensor: anything with an analog output
The pin must be an ADC1 pin: the library refuses the others, because ADC2 stops working while Wi-Fi is on. The ADC reads up to about 3.3 V: put a divider in front of a 5 V output. The reading is in millivolts; one of the builders turns it into your unit.
| Call | Meaning |
|---|---|
map(mvLo, mvHi, outLo, outHi) | Linear: the sensor gives mvLo to mvHi millivolts for outLo to outHi (the value is clamped). A 0.5–4.5 V level sensor of 0–3 m: map(500, 4500, 0, 3). |
range(lo, hi, decimals) | The scale of the gauge and the number of decimals. |
hall(zeroMv, mvPerAmp) | A Hall current sensor (ACS712 and kin): amps = (mV − zeroMv) / mvPerAmp. Mind the divider if the board runs at 5 V. |
mq(supplyV, loadOhm, r0Ohm, a, b) | A metal-oxide gas sensor on a divider: ppm = a × (Rs/R0)^b, with Rs = RL × (Vc − Vout) / Vout. The curve (a, b) is from the sensor’s datasheet. |
millivolts() | The last voltage at the pin, in mV (NaN when there is none). |
fn::AnalogSensor level(34, "level", "Tank level", "m"); // an ADC1 pin
fn::AnalogSensor amps(35, "pump_a", "Pump current", "A");
fn::AnalogSensor gas(32, "gas", "LPG", "ppm");
void setup() {
level.map(500, 4500, 0, 3).range(0, 3, 2); // 0.5-4.5 V (after a divider) = 0-3 m
amps.hall(1650, 66).range(0, 20, 2); // ACS712-30A: 66 mV per A, zero at 1650 mV
gas.mq(5.0f, 10000, 9500, 574.25f, -2.222f).range(0, 2000, 0); // an MQ-6 curve; calibrate R0 in clean air
dev.use(level).use(amps).use(gas);
dev.begin();
}DigitalSensor: a float switch, a leak or a flame sensor
| Call | Meaning |
|---|---|
activeLow(bool on = true) | The sensor pulls the pin to ground when it is active (a switch to GND). |
pullUp(bool on = true) | The internal pull-up (default on). |
labels(active, idle) | The words on the card (default “Active” and “Idle”). |
debounce(ms) | The time a level must hold before it counts (default 50 ms). |
onChange(cb) | cb(bool active) runs on the loop task when the state changes. At start the card takes what the pin says, without a change. |
active() | The debounced state now. |
fn::DigitalSensor leak(23, "leak", "Water leak");
void setup() {
leak.activeLow().labels("WET", "dry") // switch to GND, internal pull-up
.onChange([](bool wet) { if (wet) Serial.println("water!"); });
dev.use(leak);
dev.begin();
}MH-Z19: CO2 over UART
| Module pin | Goes to |
|---|---|
| Vin | 5 V (the module is a 5 V part; its TX answers at 3.3 V logic) |
| GND | GND |
| TX | The board’s rxPin |
| RX | The board’s txPin |
fn::Mhz19 co2(16, 17); // rx, tx; Serial2 at 9600 baud
void setup() {
co2.every(10000).alarm(1200, 1000); // ventilate at 1200 ppm
dev.use(co2);
dev.begin();
}
void loop() {
dev.loop();
int ppm = co2.ppm(); // -1 until the first valid reading
}A fresh MH-Z19 needs a few minutes to warm up and calibrates itself over days; the card shows “—” until a valid reading arrives.
PZEM-004T v3: mains voltage, current and energy
- The module’s TTL side has 5 V, TX, RX and GND. TX goes to the board’s
rxPin, RX to itstxPin. The mains side has a live voltage: wire it with the power off, in a closed enclosure, and use the current clamp (CT) that comes with it. - Six readings: voltage (
_v), current (_a), power (_w), energy (_kwh), frequency (_hz) and power factor (_pf). addressis 0xF8 (the general address) unless you set another one on the module.
fn::Pzem mains(16, 17); // rx, tx; Serial2 at 9600 baud
void setup() {
mains.every(2000);
dev.use(mains);
dev.begin();
}
void loop() {
dev.loop();
float v = mains.volts(), a = mains.amps(), w = mains.watts(); // NaN when there is none
float kwh = mains.value(3); // the fourth reading
}INA219: DC voltage, current and power over I2C
- Wire VCC to 3.3 V, GND, SDA and SCL to the board’s I2C pins. The load goes through VIN+ and VIN− (the shunt), in series with the positive wire.
shuntOhmis the resistor on your board: 0.1 Ω on most breakouts, 0.01 Ω on the 8 A ones. A wrong value gives wrong amps.- The address is 0x40 unless the A0 and A1 pads were bridged. Check with the I2C scan.
fn::Ina219 batt(0x40, 0.1f, Wire, 21, 22); // address, shunt (ohm), bus, SDA, SCL
void setup() {
batt.every(1000);
dev.use(batt);
dev.begin();
}
void loop() {
dev.loop();
if (batt.volts() < 11.5f) { /* the battery is low: shed the load */ } // NaN < x is false
}Devices · 06
Relays and actuators
Relay boards, solenoid valves, DC motors, ESCs and steppers: wiring, calls and safety.
fn::Relay relays("relay", "Relay board");
void setup() {
relays.channel(4, "Pump").maxOn(600); // off by itself after 10 minutes
relays.channel(16, "Valve", fn::Relay::Type::ActiveLow); // low-level trigger board
relays.latching(17, 18, "Gate"); // set pin, reset pin
relays.channel(19, "Forward").interlock(1);
relays.channel(21, "Reverse").interlock(1); // never on together with Forward
dev.use(relays);
dev.begin();
}Relay board
| Relay board pin | Goes to |
|---|---|
| VCC | The supply of the board’s coils (5 V on most boards) |
| GND | GND, shared with the board |
| IN1, IN2 … | One GPIO per channel, the pin of channel() |
| COM, NO, NC | The load side: COM and NO close when the relay is on |
| Call | Meaning |
|---|---|
Relay(const char* id = "relay", const char* title = "Relays") | The module. id is at most 15 characters and, like title, must outlive the object (a string literal). Up to 16 channels (Relay::kMaxChannels). |
channel(int pin, const char* name = nullptr, Type type = ActiveHigh) | Adds a channel before begin(). pin -1 means “not wired yet”. Type::ActiveLow is for low-level trigger boards. |
latching(int setPin, int resetPin, const char* name = nullptr) | A bistable relay: a 50 ms pulse on setPin turns it on, one on resetPin turns it off. Its second pin is the slot ch<n>r. |
bootOn(bool on = true) | The channel added last starts on (default: off). |
maxOn(uint32_t seconds) | It switches off by itself after this long (0 = never). |
pulse(uint32_t milliseconds) | Every ON lasts this long, then goes OFF (a door strike, a doorbell). 0 = stays on. |
interlock(uint8_t group) | Group 1–255: channels of one group are never on together. A blocked command is refused and said so in the log. |
minOff(uint32_t seconds) | A rest time: after it switches off it cannot be switched on again for this long (a compressor, a coil). |
page("Name") | The page of the cards (default “Relays”). |
channels(), isOn(ch), set(ch, on) | The number of channels, whether channel ch (counted from 0) is on, and switching it from code. set returns false when the channel does not exist, has no pin, or its interlock group is busy. |
The widgets are toggles named relay_1, relay_2 … (the id and the position counted from 1): a switch on the dashboard, a command on <prefix>/<device_id>/set/relay_1 over MQTT, a switch entity in Home Assistant. The Settings of a card lets an admin move the pin; the dialog asks for the device name first, because the pin switches a load.
- A channel starts in its boot state (off unless
bootOn()), a pin is written before it becomes an output, so a load does not twitch at start. maxOn()andpulse()switch a channel off by themselves, even if the network is gone.
fn::Relay relays("relay", "Fan and light");
fn::Dht dht(4);
void setup() {
relays.channel(26, "Fan").minOff(30); // channel 0: rests 30 s between runs
relays.channel(27, "Light"); // channel 1
dht.every(5000).alarm(32, 29, [](bool hot) {
relays.set(0, hot); // the fan follows the alarm
});
dev.use(relays).use(dht);
dev.begin();
}
void loop() {
dev.loop();
static bool last = false;
if (relays.isOn(1) != last) { last = relays.isOn(1); Serial.println(last ? "light on" : "light off"); }
}Solenoid valve
Solenoid(int pin, const char* id = "valve", const char* name = "Valve", uint32_t maxOnSeconds = 60, uint32_t minOffSeconds = 2, Type type = ActiveHigh) is a relay with one channel that closes by itself after maxOnSeconds (a coil overheats when it stays on) and rests minOffSeconds before it opens again. It uses the relay’s page and calls (set(0, true)).
fn::Solenoid valve(33, "valve", "Water valve", 30, 5); // closes after 30 s, rests 5 s
// dev.use(valve); ... valve.set(0, true); // open it from codeDC motor on an H-bridge
| H-bridge pin | Goes to |
|---|---|
| ENA / PWM / EN | pwmPin: the speed (20 kHz PWM by default) |
| IN1 | in1Pin: the direction input |
| IN2 | in2Pin: the other direction input. With in2Pin = -1 only one direction pin is used (forward = high) |
| Motor supply and GND | Its own supply; join its GND to the board’s GND |
| Call | Meaning |
|---|---|
DcMotor(int pwmPin, int in1Pin, int in2Pin = -1, const char* id = "motor", const char* title = "DC motor") | The module. Widgets: <id>_speed (a slider −100 to 100 %), <id>_stop (a button), <id>_now (the speed now). |
ramp(float percentPerSecond) | How fast the speed changes. Default 100 (1 s to full speed); 0 = no ramp. A reversal always goes through zero. |
maxRun(uint32_t seconds) | It stops by itself after this long (0 = never). |
pwmFrequency(uint32_t hz) | The PWM frequency (default 20 kHz, silent). |
speed(float percent) / speed() | Sets the speed to ramp to, −100 to 100, and reads the speed now. |
stop() | To zero at once, with no ramp. |
fn::DcMotor motor(25, 26, 27); // pwm, in1, in2
void setup() {
motor.ramp(50).maxRun(600); // 2 s to full speed, stops itself after 10 minutes
dev.use(motor);
dev.begin();
}
void loop() {
dev.loop();
// motor.speed(60); // 60 % forward motor.speed(-30); // 30 % in reverse motor.stop();
}Brushless motor on an ESC
- The ESC’s signal wire goes to the pin and its ground to the board’s ground; the motor power goes only through the ESC, never through the board. The signal is a 50 Hz servo pulse.
- The ESC arms first: the library sends the idle pulse for
armTime(3 s by default) and ignores a throttle until then.armed()tells when. - Take the propeller off while you test.
| Call | Meaning |
|---|---|
Esc(int pin, const char* id = "esc", const char* title = "Brushless motor") | The module. Widgets: <id>_thr (a slider 0 to 100 %), <id>_stop. |
pulse(uint16_t minUs, uint16_t maxUs) | The pulse for 0 % and 100 %. Default 1000 and 2000 µs. |
ramp(float percentPerSecond) | Default 50; 0 = none. |
armTime(uint32_t ms) | The idle pulse before it accepts a throttle. Default 3000. |
maxRun(uint32_t seconds) | It stops by itself after this long. |
throttle(float percent) / throttle() | 0 to 100, ignored while the ESC is arming; reads the throttle now. |
stop(), armed() | The idle pulse at once; whether the ESC has armed. |
fn::Esc esc(32);
void setup() {
esc.ramp(30).maxRun(300); // slow ramp, stops itself after 5 minutes
dev.use(esc);
dev.begin();
}
void loop() {
dev.loop();
if (esc.armed()) { /* esc.throttle(25); */ }
}Stepper (step and dir driver)
For A4988, DRV8825, TB6600 and other step/dir drivers. STEP and DIR go to the two pins, EN to the optional third (a low level enables the driver unless you call enableActiveHigh()). The motor’s coils and supply belong to the driver, not the board. The steps are generated by a hardware timer, so a move does not depend on loop().
| Call | Meaning |
|---|---|
Stepper(int stepPin, int dirPin, int enablePin = -1, const char* id = "stepper", const char* title = "Stepper") | The module. Widgets: <id>_target (a slider over the limits, in steps), <id>_pos (the position now), <id>_stop (a button). |
maxSpeed(float stepsPerSecond) | Default 800, up to about 5000. |
acceleration(float stepsPerSecond2) | Default 1600. |
limits(long minPosition, long maxPosition) | The range a move may reach. Default −10000 to 10000. |
enableActiveHigh(bool on = true), reverse(bool on = true) | A driver enabled by a high level; the direction turned around. |
releaseAfter(uint32_t ms) | Disable the driver this long after a move (default 2000, 0 = keep it on). |
moveTo(long position), moveBy(long steps) | Move with acceleration. false when the position is outside the limits. |
stop(), setPosition(long p) | Stops at once (the position stays right); tells it where it is (only while it does not move). |
position(), moving() | The position in steps from power-on; whether it is moving. |
fn::Stepper stepper(14, 12, 13); // step, dir, enable
void setup() {
stepper.maxSpeed(1000).acceleration(2000).limits(-4000, 4000);
dev.use(stepper);
dev.begin();
}
void loop() {
dev.loop();
// stepper.moveTo(2000); stepper.moveBy(-500); if (!stepper.moving()) { /* arrived */ }
}Devices · 07
Servo
A hobby servo on one pin: an angle, or a speed for a 360 one, calibrated from the browser.
New in 2.3.0. fn::Servo drives a hobby servo with a 50 Hz signal. A positional servo (the usual kind) goes to an angle; a continuous 360 servo has no angle, it turns at a speed and stops when you hold it. Both get a card on the Servos page of the board, with a calibration dialog that saves the pulse window for each servo.
fn::Servo arm(10, "arm", "Robot arm"); // positional
fn::Servo wheel(11, "wheel", "Drive wheel"); // continuous, 360
void setup() {
arm.preset("mg996r").speed(90); // moves at 90 degrees a second
wheel.continuous();
dev.use(arm).use(wheel);
dev.begin();
}
void loop() {
dev.loop();
// arm.angle(45); wheel.move(60); wheel.hold();
}Wiring
- The signal wire (usually yellow or white) goes to the pin; it must be a pin that can do PWM. Only a pin that can work is offered when you move it.
- Power the servo from its own 5 V supply that can give the current it needs, and join its ground to the board’s ground. A servo that pulls hard can reset the board when it is powered from the board.
- The pin drives a load, so moving it from the card asks you to type the device name.
Presets
A preset sets the pulse window and the travel. “Universal” is the wide, safe window; if your servo is not listed, start from it and calibrate.
| Preset | Pulse window | Travel |
|---|---|---|
mg90s | 500 – 2400 µs | 180° |
mg995 | 1000 – 2000 µs | 180° |
mg996r | 500 – 2500 µs | 180° |
sg90 | 500 – 2400 µs | 180° |
universal | 500 – 2500 µs | 180° |
cont360 | 1000 – 2000 µs | continuous, 360 |
Calls
| Call | Meaning |
|---|---|
Servo(int pin, const char* id = "servo", const char* title = "Servo") | The module. Pin −1 means “set it later in Settings”. |
continuous(bool on = true) | A 360 continuous-rotation servo: a speed instead of an angle. |
range(float degrees) | The travel of a positional servo. Default 180. |
pulse(uint16_t minUs, uint16_t maxUs) | The pulse for 0 and for the full travel. Default 500 and 2500 µs. |
center(uint16_t stopUs) | Continuous: the pulse that holds it still. Default 1500 µs. |
preset(const char* name) | One of the presets above. |
speed(float degPerSecond) | Positional: how fast it moves to a new angle. Default 0 = as fast as it can. |
page(const char* name) | The name of the page. Default “Servos”. |
angle(float degrees) / angle() | Positional: go to 0 to range; reads the target (0 for a continuous servo). |
move(float speedPct) | Continuous: −100 to 100 %, the sign is the direction. |
hold() | Continuous: the stop pulse. |
The Servos page and the calibration
- Each servo has a card: an Angle with Move here or, for a continuous servo, a Speed and a stop. Calibrate opens the dialog Calibrate the servo: Pick your servo (the presets), the Travel, the pulse of each end, the stop point of a continuous one, and Save calibration.
- Until a servo has a working pin, its health in Settings reads “pin missing: set it in Settings”.
- An operator can set the angle or the speed. Everything that changes the hardware (a preset, the travel, positional or continuous, the calibration, a test pulse) is for an admin.
- The calibration dialog fits the pulse window to your servo (and, for a continuous one, the pulse that holds it still). It is saved on the board, for that servo, and wins over what the sketch says.
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/servos | viewer | Every servo (value, pin, pulse window, travel, continuous or not) and the presets. |
PUT /fn/api/v1/servos/<id> | operator | {"angle": 45} or {"speed": 60} or {"hold": true}. |
PUT /fn/api/v1/servos/<id> | admin | {"preset": "mg996r"}, {"range": 270} (1 to 360), {"cont": true}, {"testUs": 1500} (400 to 2600) or {"cal": {"min": 600, "max": 2400, "stop": 1500}}. |
A calibration is refused with 422 unless the pulses are between 400 and 2600 µs, in order, and at least 200 µs apart. The example 09_Motors has a positional servo and a continuous one.
Devices · 08
GPS
An NMEA receiver over UART: position, speed, a track and a map on the board.
fn::Gps gps(16, 17); // rx, tx; Serial1 at 9600 baud
void setup() {
gps.track(400, 3); // up to 400 points, a new one every 3 m
dev.use(gps);
dev.begin();
}
void loop() {
dev.loop();
if (gps.hasFix()) Serial.printf("%.6f, %.6f\n", gps.lat(), gps.lon());
}Any receiver that talks NMEA 0183 works (u-blox, ATGM336H, Quectel …). The module reads GGA and RMC sentences whose checksum is good, adds a Map page (Leaflet, served from the device) with position, track, speed, altitude and satellites, and sets the board’s clock from the satellites. Map tiles need the phone to have internet; the numbers and the track always work offline.
Wiring
| GPS pin | Goes to |
|---|---|
| VCC | 3.3 V or 5 V, as your module says |
| GND | GND |
| TX | The board’s rxPin (the data you read) |
| RX | The board’s txPin: only if you want to send commands to the receiver; leave it -1 otherwise |
Constructor and builders
| Call | Meaning |
|---|---|
Gps(int rxPin, int txPin = -1, uint32_t baud = 9600, HardwareSerial& port = Serial1) | Serial1 exists on every ESP32; pass Serial2 on chips that have it when Serial1 is busy. Many receivers speak 9600 baud; some 38400 or 115200. |
track(uint16_t maxPoints, float minMeters = 3) | The track kept in RAM: up to maxPoints (default 400; when full, the oldest tenth goes), a new point every minMeters, or after 10 s with a move of at least half a metre. |
setClock(bool on) | Whether the satellites set the board’s clock once (default on). |
hasFix() | True when the receiver has a position (RMC status A, or a GGA quality above 0). |
fix() | The last fix (a GpsFix), see below. |
lat(), lon() | Degrees, south and west negative. |
clearTrack() | Empties the track. |
| `GpsFix` field | Meaning |
|---|---|
valid | RMC status A. |
quality | GGA: 0 none, 1 GPS, 2 DGPS, 4 RTK fixed, 5 RTK float. |
sats | Satellites in use. |
lat, lon | Degrees. |
altM, hdop | Altitude in metres, horizontal dilution of precision. |
speedKmh, course | Speed in km/h and heading in degrees. |
hh, mm, ss, day, month, year | The UTC date and time of the fix. |
sentences, bad | Sentences accepted, and rejected for a bad checksum. |
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/gps | viewer | The snapshot: fix, lat, lon, alt, speed, course, sats, hdop, q, utc, live (bytes in the last 3 s), sentences, bad, points, and the wiring: baud, rx, tx. |
GET /fn/api/v1/gps/track | viewer | The track as [[lat,lon],…], six decimals. |
DELETE /fn/api/v1/gps/track | operator | Empties the track. |
- No data from the receiver for 5 s makes the module “degraded” with the hint to check the RX pin and the baud. A receiver that is searching is “ok” with the number of satellites; the first fix outdoors can take minutes.
- Indoors there is no fix. Put the antenna with a view of the sky.
Devices · 09
IMU (BNO055)
Absolute orientation over I2C: yaw, pitch, roll, calibration and a level offset.
fn::Bno055 imu; // 0x28 on Wire
void setup() {
imu.pins(21, 22).rate(50); // optional: SDA, SCL, 50 readings a second
dev.use(imu);
dev.begin();
}
void loop() {
dev.loop();
if (imu.ready()) Serial.printf("%.1f %.1f %.1f\n", imu.yaw(), imu.pitch(), imu.roll());
}The Bosch BNO055 fuses its own accelerometer, gyroscope and magnetometer and reports an absolute orientation, so no extra library is needed. The module adds a Motion page with an artificial horizon, a compass, a 3D box, the calibration status, “set as level” and “save calibration”.
Wiring
| BNO055 pin | Goes to |
|---|---|
| VIN | 3.3 V (a breakout with a regulator also takes 5 V) |
| GND | GND |
| SDA, SCL | The board’s I2C pins (see I2C, SPI and UART) |
| ADR / COM3 | Low = address 0x28 (the default), high = 0x29 |
Constructor and calls
| Call | Meaning |
|---|---|
Bno055(uint8_t addr = 0x28, TwoWire& wire = Wire) | The module. Use 0x29 when the address pin is high. |
pins(int sda, int scl) | Which pins the bus uses (default: the board’s). |
rate(uint16_t hz) | Readings per second, at most 100 (default 50). |
externalCrystal(bool on) | Use the crystal of the breakout (default on; most boards have one). |
ready() | True when the sensor is found and running. |
yaw(), pitch(), roll() | Degrees after the level offset. Yaw 0 to 360, pitch and roll −180 to 180. |
temperature() | The chip’s temperature in °C. |
calibration(uint8_t which) | 0 to 3 for 0 = system, 1 = gyro, 2 = accelerometer, 3 = magnetometer. 3 means calibrated. |
level(), clearLevel() | The current attitude becomes 0/0/0 (kept over restarts); remove that offset again. |
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/imu | viewer | ok, y, p, r (degrees), t (°C), c (the four calibration values), addr, hz, savedCal, leveled. |
POST /fn/api/v1/imu/level | operator | Makes the current attitude the zero. Body {"clear":true} removes the offset instead. |
POST /fn/api/v1/imu/calibration | admin | Saves the sensor’s calibration offsets, used at the next start. 409 when the sensor is not connected. |
DELETE /fn/api/v1/imu/calibration | admin | Forgets the saved calibration. |
- Power the board with the sensor still for a few seconds: the gyroscope calibrates first.
- Move it slowly through a few positions for the accelerometer, and draw a figure of eight in the air for the magnetometer, until the Motion page shows 3 for each.
- Press “save calibration” (or call
POST /imu/calibration). The next start begins calibrated. - Put the board in the position you call level and press “set as level”.
Devices · 10
LCD (I2C)
A 16×2 or 20×4 character screen on a PCF8574 backpack: write to it from code or the dashboard.
fn::LcdI2c lcd(16, 2); // 16 columns, 2 rows, address found by itself
void setup() {
lcd.pins(21, 22); // optional: SDA, SCL
dev.use(lcd);
dev.begin();
}
void loop() {
dev.loop();
lcd.line(0, "Hello!"); // a whole row, padded
lcd.print(1, 0, String(millis() / 1000) + " s"); // row, column, text
}For HD44780 character screens on a PCF8574 I2C backpack (16×2, 20×4 …). The module adds an LCD page that shows the real screen live, and lets an operator type a row from the phone.
Wiring
| Backpack pin | Goes to |
|---|---|
| VCC | 5 V (the screen needs it; the backpack’s I2C lines are pulled up to it) |
| GND | GND |
| SDA, SCL | The board’s I2C pins |
Constructor and calls
| Call | Meaning |
|---|---|
LcdI2c(uint8_t cols = 16, uint8_t rows = 2, uint8_t addr = 0, TwoWire& wire = Wire) | addr 0 looks for 0x27 and then 0x3F. At most 4 rows. |
pins(int sda, int scl) | The pins of the bus. |
clear() | Empties the screen. |
print(uint8_t row, uint8_t col, const String& text) | Writes text at a position. |
line(uint8_t row, const String& text) | Writes a whole row, padded with spaces. |
backlight(bool on) / backlight() | Switches the backlight; reads it. |
text(uint8_t row), cols(), rows() | The text of a row now, and the size. |
Call the writing functions from the loop task (loop(), a widget callback, an alarm callback), not from an interrupt or another task. The character ROM of the screen is ASCII: anything outside 32 to 126 shows as “?” when typed from the dashboard.
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/lcd | viewer | found, cols, rows, bl (backlight), addr (as “0x27”) and text (the rows now). |
POST /fn/api/v1/lcd | operator | A body of one of {"row":0,"text":"Hello"}, {"clear":true}, {"backlight":false} or {"preset":"ip"} (name, IP address, host name and a greeting on the rows). 422 when the row is out of range. |
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"row":0,"text":"Pump is ON"}' http://$H/fn/api/v1/lcdDevices · 11
External microcontroller
A line-based UART link to an Arduino Uno, STM32, RP2040 or another ESP.
fn::McuLink mcu(18, 19, 9600); // rx, tx, baud (Serial1); the default is 115200
void setup() {
mcu.bind("temp", "temp") // "temp=23.4" from the MCU -> the widget "temp"
.forward("light") // the widget "light" changes -> "light=1\n" to the MCU
.quick("Blink", "LED=BLINK"); // a one-tap button in the console
dev.use(mcu);
dev.begin();
}Use it to put a board that is not an ESP32 on the dashboard, MQTT and the cloud. The link is plain text, line by line, so it can be tried with any serial monitor. The module adds a Serial page with a console, the live values and quick buttons.
Wiring
| This board | The other board |
|---|---|
rxPin | TX of the other board |
txPin | RX of the other board (a 5 V board needs a divider or level shifter on its TX) |
| GND | GND (always shared) |
The lines
- The other board sends lines that end in a newline:
temp=23.4,hum=60(pairs separated by commas) or JSON such as{"temp":23.4}. Every key becomes a live value. bind("temp", "temp")copies the value of the keytempinto the widgettemp.forward("light")sendslight=1(or the value) to the other board when the widgetlightchanges; the second argument names a different key.- A line is at most 256 characters;
\ris ignored.
// An Arduino Uno / Nano, wired to the ESP32 (its TX, RX and GND). Uses SoftwareSerial on pins 10 and 11.
#include <SoftwareSerial.h>
SoftwareSerial link(10, 11); // rx, tx
void setup() {
link.begin(9600); // the same baud as McuLink(..., 9600)
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
static unsigned long t;
if (millis() - t > 2000) {
t = millis();
link.print("temp=");
link.println(analogRead(A0) * 0.1); // -> "temp=23.4\n"
}
if (link.available()) {
String s = link.readStringUntil('\n'); // "light=1" from the ESP32
if (s.startsWith("light=")) digitalWrite(LED_BUILTIN, s.endsWith("1"));
}
}Constructor and calls
| Call | Meaning |
|---|---|
McuLink(int rxPin, int txPin, uint32_t baud = 115200, HardwareSerial& port = Serial1) | Serial1 exists on every chip. On a chip with two UARTs and “USB CDC On Boot”, UART0 (Serial0) is free for this link. |
bind(const char* key, const char* widgetId) | A key from the other board drives a widget of yours. |
forward(const char* widgetId, const char* key = nullptr) | A change of the widget is sent as key=value (the key is the widget id unless you name one). |
quick(const char* label, const char* command) | A button in the console that sends command. |
onLine(std::function<void(const String&)> cb) | Your own handler for every line received, on the loop task. |
lineEnding(const char* eol) | What ends a line you send: "\n" (default), "\r" or "\r\n". |
send(const String& line) | Sends a line to the other board. |
value(const char* key) | The last value received for a key (an empty text when none). |
online() | True while a line arrived in the last 5 s. |
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/mcu?since=<seq> | viewer | online, baud, rx, tx, the byte and line counters, eol, values, the quick buttons and the log of lines after since. |
POST /fn/api/v1/mcu/send | operator | {"line":"LED=BLINK"}: sends a line, 1 to 256 characters (422 otherwise). |
PUT /fn/api/v1/mcu/config | admin | {"baud":115200,"eol":"lf"}: the baud (1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800 or 921600) and the line ending (lf, cr or crlf). The baud is kept over restarts. |
Devices · 12
SD card
A card on SPI or SDMMC: files from your code and a file manager in the browser.
fn::SdCard sd(5); // SPI, chip-select on GPIO 5
void setup() {
sd.pins(18, 19, 23); // optional: SCK, MISO, MOSI
dev.use(sd);
dev.begin();
}
void loop() {
dev.loop();
static uint32_t t;
if (sd.mounted() && millis() - t > 10000) {
t = millis();
fn::SdCard::Lock lock(sd); // while people browse the files, the two never collide
File f = sd.fs().open("/log.csv", FILE_APPEND);
if (f) { f.printf("%lu\n", millis()); f.close(); }
}
}The module mounts a FAT32 card and adds a Files page: folders, upload, download, rename, delete and a preview. Your own code reads and writes through sd.fs() like any Arduino file system.
Wiring (SPI)
| SD module pin | Goes to |
|---|---|
| VCC | 5 V on a module with a regulator, or 3.3 V on one without: read its label |
| GND | GND |
| SCK, MISO, MOSI | The board’s SPI pins, or the ones you give to pins() |
| CS | The cs of the constructor (default SS) |
Constructor and calls
| Call | Meaning |
|---|---|
SdCard(int cs = SS, SPIClass& spi = SPI) | The module on an SPI bus. |
pins(int sck, int miso, int mosi) | The pins of the bus (default: the board’s). |
frequency(uint32_t hz) | The bus speed, default 20 MHz. Lower it for long wires. |
mmc(bool oneBit = true, int clk = -1, int cmd = -1, int d0 = -1) | Only on chips with an SDMMC host (ESP32, ESP32-S3): use that instead of SPI. On the S3 the pins are free to choose; on the ESP32 they are fixed (pass -1). |
mounted() | True when a card is mounted. |
fs() | The file system (fs::FS&): open, exists, mkdir, remove and the rest. |
remount() | Tries to mount again (after the card was put back). |
SdCard::Lock | { fn::SdCard::Lock l(sd); … } holds the card for your code while the web files page may be reading it. |
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/sd | viewer | mounted, mode (spi or sdmmc), type, total and used in bytes. |
POST /fn/api/v1/sd/mount | admin | Mounts again. 503 when no card is found. |
GET /fn/api/v1/sd/ls?path=/ | viewer | The entries of a folder (at most 500): name, dir, size, mtime. 404 when it is not a folder. |
GET /fn/api/v1/sd/file?path=/a.csv[&dl=1] | viewer | The file, streamed. dl=1 downloads it as an attachment. |
POST /fn/api/v1/sd/file?path=/a.csv | admin | Uploads: the raw bytes are the body. 413 when the card has no room, 500 when the folder does not exist or the upload broke (the half file is removed). |
DELETE /fn/api/v1/sd/file?path=/a.csv | admin | Deletes a file or an empty folder. 409 when a folder is not empty. |
POST /fn/api/v1/sd/mkdir?path=/logs | admin | Makes a folder. 409 when it cannot. |
POST /fn/api/v1/sd/rename | admin | {"from":"/a.csv","to":"/b.csv"}. 409 when the new name exists. |
curl -s -H "Authorization: Bearer $TOKEN" "http://$H/fn/api/v1/sd/ls?path=/"
curl -s -H "Authorization: Bearer $TOKEN" -o log.csv "http://$H/fn/api/v1/sd/file?path=/log.csv&dl=1"
curl -s -X POST -H "Authorization: Bearer $TOKEN" --data-binary @config.json "http://$H/fn/api/v1/sd/file?path=/config.json"A path starts with / and is checked on the device: a path with .. or a character that is not allowed is a 422. A card that is missing makes the module “degraded” and it tries again by itself.
Devices · 13
TFT screen
An ST7789 or ILI9341 on SPI, or any library’s display: draw from code or the browser.
fn::TftSpi panel(fn::TftSpi::ST7789, 240, 240, /*cs*/ 10, /*dc*/ 9, /*rst*/ 8);
fn::Tft tft(panel);
void setup() {
panel.pins(12, 11); // SCK, MOSI (MISO is not needed)
tft.backlight(7); // a PWM pin: brightness slider in the UI
dev.use(tft);
dev.begin();
tft.clear(fn::Tft::rgb(15, 23, 42));
tft.text(10, 10, "Hello!", 0xFFFF, 2);
}
void loop() { dev.loop(); }The built-in drivers need no extra library: ST7789 (240×240, 240×320, 135×240, 170×320) and ILI9341 (240×320). Any other display works through GfxTarget, which wraps an Adafruit_GFX, TFT_eSPI or LovyanGFX object. The module adds a Screen page with the same picture in the browser and drawing tools: text, rectangle, circle and line, colours, rotation and brightness.
Wiring (SPI)
| Screen pin | Goes to |
|---|---|
| VCC, GND | 3.3 V and GND |
| SCL / SCK, SDA / MOSI | The sck and mosi of pins() |
| CS | cs: the chip-select of the screen |
| DC / RS | dc: the data/command pin |
| RES / RST | rst (or -1 when the module has no reset pin, or it is tied high) |
| BL / LED | The pin of backlight(pin), or 3.3 V for a screen that is always bright |
Constructors and calls
| Call | Meaning |
|---|---|
TftSpi(Chip chip, uint16_t w, uint16_t h, int8_t cs, int8_t dc, int8_t rst = -1, SPIClass& spi = SPI, uint32_t hz = 40000000) | The built-in driver. Chip is fn::TftSpi::ST7789 or fn::TftSpi::ILI9341; w and h are the panel’s size; hz is the SPI speed. |
pins(int8_t sck, int8_t mosi, int8_t miso = -1) | The SPI pins of the screen. |
GfxTarget<G>(G& g, std::function<bool()> init = nullptr) | Wraps another display object; G needs width(), height(), setRotation(), fillRect() and drawPixel(). init starts it. |
Tft(TftTarget& target) | The module on a target (a TftSpi or a GfxTarget). |
backlight(int pin, bool activeHigh = true) | The backlight on a PWM pin; the brightness slider uses it. |
Tft::rgb(r, g, b) | An RGB565 colour from three 0–255 values. Colours are RGB565. |
clear(color = 0) | Fills the screen. |
text(x, y, s, color = 0xFFFF, size = 1, bg = -1) | Text at a position; size is the multiple of the 5×7 font; bg a background colour (-1 = transparent). |
rect(x, y, w, h, color, fill = false) | A rectangle, outline or filled. |
line(x0, y0, x1, y1, color) | A line. |
circle(x, y, r, color, fill = false) | A circle around a centre. |
rotation(r), brightness(percent) | The rotation 0–3 and the brightness 5–100 (both kept over restarts). |
splash(), width(), height() | The name, the address and a friendly face; the size of the screen. |
Call the drawing functions from the loop task. A flow can also draw: the node Screen text (tft.text) takes x, y, text, color, size and “clear first”.
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/tft | viewer | ok, driver, w, h, rot, bright, backlight, inverted and the ops drawn so far (what the browser mirrors). |
POST /fn/api/v1/tft/draw | operator | One drawing operation. k is c (clear), t (text), r (rectangle), l (line) or o (circle), otherwise 422. a, b, cc, d are the numbers: text a, b = x, y; rectangle a, b, cc, d = x, y, w, h; line a, b, cc, d = x0, y0, x1, y1; circle a, b = x, y and cc = the radius. c is the colour as "#rrggbb", z the text size 1–8, f fills, s the text (60 characters at most), bg a background colour. |
POST /fn/api/v1/tft/settings | admin | rot, bright, inverted or "splash":true, in any combination. |
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"k":"t","a":10,"b":40,"s":"Pump ON","c":"#22c55e","z":3}' http://$H/fn/api/v1/tft/draw
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"k":"r","a":5,"b":5,"cc":100,"d":60,"c":"#2563eb","f":true}' http://$H/fn/api/v1/tft/drawDevices · 14
Moving pins
An admin changes a pin from a card or the API, without compiling again.
# PUT /fn/api/v1/devices/relay/pins (admin)
{"pins":{"ch1":4,"ch2":null},"confirm":"relay-board"}The wiring in a sketch is a default. On a card of a relay, sensor or motor an admin opens the three dots, then Settings, picks another pin and saves it: a saved pin wins over the sketch, the way every other setting does. The dialog offers only the pins that can do the job (no flash or USB pins, no input-only pin for an output), and asks for the device name before it moves a pin that switches a load. A motor is stopped before its pin moves.
- A GPIO pin (a relay, a motor, a DHT, a trig pin …) applies at once on the loop task.
- A bus pin (UART, I2C) is saved at once and used from the next start; the answer says so.
- The sketch’s own
-1(no pin) is a pin that is not wired yet: you can give it a pin from the dashboard later.
The names of the pins
| Device | Keys |
|---|---|
Relay, Solenoid | ch1, ch2 … (the channel counted from 1); a latching channel also ch1r for its reset pin |
DcMotor | pwm, in1, in2 |
Esc | pwm |
Stepper | step, dir, en |
Dht, Ds18b20 | data |
Ultrasonic | trig, echo |
AnalogSensor, DigitalSensor | pin |
Mhz19, Pzem | rx, tx (restart) |
Ina219 | sda, scl (restart) |
Servo | pwm |
What the cloud sees
New in 2.3.0. Once per connect, after the claim, the device publishes how it is wired on <base>/hw (retained): the chip, every device with its pins, roles and protocols, and the pins still free for each role. It is the same inventory GET /fn/api/v1/devices returns, and Flyght Cloud shows it on the Hardware page of the device.
Routes
| Route | Role | Meaning |
|---|---|---|
GET /fn/api/v1/devices | admin | chip, the devices (id, title, load when it switches a load, restart when its pins need one, and its slots: key, label, role, proto, pin now, def of the sketch) and, per role, the pins that may be used: pins with out, in, adc, pwm, each a list of {p, warn?, by?} (by = who has the pin already). |
PUT /fn/api/v1/devices/<id>/pins | admin | {"pins":{"ch1":4,"ch2":null},"confirm":"<device name>"}. A number is a GPIO, null clears the pin. 400 for bad JSON, 404 for an unknown device, 422 for an unknown key, a pin that cannot do the job (the message says why) or a missing confirm on a device that switches a load. |
curl -s -H "Authorization: Bearer $TOKEN" http://$H/fn/api/v1/devices # what can be moved, and to where
curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"pins":{"ch1":4,"ch2":null},"confirm":"relay-board"}' http://$H/fn/api/v1/devices/relay/pinsFor a module of your own
A module that drives or reads pins can offer them too: inherit PinDevice next to Module, return pinDeviceId() (at most 15 characters, it is the storage key) and pinDeviceTitle(), list the pins in pinSlots(), put the pins in a safe state and take the new ones in pinApply(), and call fn::pins::add(app, this) in begin(). Read a saved pin with fn::pins::saved(id, key, def). Return pinsDriveLoad() true when a wrong pin can switch a load, and pinsNeedRestart() true for a bus.
Devices · 15
Next up: what we propose to support
Devices we could add in later versions, in the order we recommend, and how to tell us what you need.
// A proposal, not in the library today:
// fn::Bme280 air(0x76); // temperature, humidity, pressure over I2C
// fn::ModbusRtu plc(Serial1, 9600); // read a PLC or a meter over RS-485How we choose what comes next
- A bus we already have. An I2C or UART device reuses the code of the buses and needs no new hardware layer.
- It fits a card. Its readings are numbers or states a card, a chart, a flow or a rule can use.
- Many people use it. A sensor in every project beats a rare one.
- It costs little flash. Every module is linked only when a sketch creates it, so a new one never grows a sketch that does not use it.
Our five picks, in order
- BME280 and BMP280 (I2C): temperature, humidity and pressure from one cheap chip; the scan already recognises its address.
- A pulse counter (one GPIO): water flow meters, rain gauges, wind sensors and energy meters with a pulse output.
- ADS1115 (I2C): four clean 16-bit inputs for 4–20 mA loops and pressure or level sensors, better than the ESP32’s own converter.
- Modbus RTU master (RS-485): read PLCs, power meters and drives as points. The biggest step, and the one that opens industrial sites.
- BH1750 (I2C): light level in lux, tiny and cheap, a good first step toward lighting rules.
The full list
| Device | Interface | What it adds | Our pick |
|---|---|---|---|
| BME280, BMP280 | I2C 0x76 / 0x77 | Temperature, humidity (BME280), pressure | Recommended |
| Pulse counter (flow, rain, wind, energy) | 1 GPIO interrupt | Flow, rain and energy from pulses | Recommended |
| ADS1115 | I2C 0x48 | 4 precise analog inputs | Recommended |
| Modbus RTU master | UART + RS-485 (MAX485) | PLCs, meters and drives as points | Recommended |
| BH1750 | I2C 0x23 | Light level in lux | Recommended |
| WS2812 strips (many LEDs) | 1 GPIO | Status bars and indicators | Good next |
| SSD1306 OLED | I2C 0x3C | A small status screen | Good next |
| DS3231 RTC | I2C 0x68 | Time that survives a power cut | Good next |
| VL53L0X, VL53L1X | I2C 0x29 | Short-range distance by laser | Good next |
| MPU6050 | I2C 0x68 | Acceleration and rotation, cheaper than the BNO055 | Good next |
| PCF8574, MCP23017 | I2C | More relays and inputs from two pins | Good next |
| HX711 load cell | 2 GPIO | Weight | Good next |
| Ethernet W5500 | SPI | A wired network for industrial sites | Later |
| MLX90614 | I2C 0x5A | Temperature without touching | Later |
| MFRC522 RFID | SPI | Cards and tags for access | Later |
| LoRa SX127x | SPI | Long range, low rate | Later |
| CAN bus (with a transceiver) | 2 GPIO | Vehicles and machines | Later |
| Camera (ESP32-CAM, S3 boards) | Camera bus | Pictures for AI vision | Later |
“Recommended” means first in line. “Good next” is useful but waits for the five picks. “Later” needs more than a module: more flash, a new bus, or work on the cloud side.
Tell us what you need
Which device would you use first? Pick one from the list, or name another. Your message goes to the developer, and every answer changes the order above.












