Skip to content
Flyght
Sign in

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

  1. Declare it at the top with its pins, for example fn::Ultrasonic tank(18, 19, "tank");.
  2. Set it up in setup() with its builders, for example tank.tank(150, 20).every(1000);.
  3. Give it to the device before begin(): dev.use(tank);. Calls chain: dev.use(a).use(b).
  4. 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.
The smallest sketch with a deviceC++
#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

DeviceClassBusPins (the name of each in the pins API)Page on the board
Relay boardRelayGPIO outputch1, ch2 … (a latching channel also ch1r)Relays
Solenoid valveSolenoidGPIO outputch1Relays
DC motor (H-bridge)DcMotorPWM and two GPIOpwm, in1, in2Motors
Brushless motor (ESC)EscServo pulse, 50 HzpwmMotors
Stepper (step/dir driver)StepperGPIOstep, dir, enMotors
Hobby servoServoPWM, 50 HzpwmServos
DHT11 / DHT22DhtOne GPIOdataSensors
DS18B20Ds18b201-WiredataSensors
Ultrasonic (trig + echo)UltrasonicGPIO out + GPIO intrig, echoSensors
Analog sensorAnalogSensorADC1pinSensors
On/off sensorDigitalSensorGPIO inputpinSensors
MH-Z19 (CO2)Mhz19UART, 9600 baudrx, txSensors
PZEM-004T (mains)PzemUART, 9600 baudrx, txSensors
INA219 (DC power)Ina219I2C, 0x40sda, sclSensors
GPS receiverGpsUART, 9600 baudthe constructor: rxPin, txPinMap
BNO055 IMUBno055I2C, 0x28pins(sda, scl)Motion
Character LCDLcdI2cI2C, 0x27 / 0x3Fpins(sda, scl)LCD
External microcontrollerMcuLinkUART, 115200 baudthe constructor: rxPin, txPinSerial
SD cardSdCardSPI (or SDMMC)cs, pins(sck, miso, mosi)Files
TFT screenTftSpi + TftSPIcs, dc, rst, pins(sck, mosi, miso)Screen

The pages of this group

Devices · 02

Supported devices

The chips, boards, sensors, actuators and links that work today, and where each is documented.

Every chip of the ESP32 family the library builds forC++
// 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

ChipStatusWhat it isGood for
ESP32SupportedDual-core Xtensa, Wi-Fi and classic BluetoothThe all-rounder: the most pins, three UARTs, the widest choice of boards
ESP32-S2SupportedSingle-core Xtensa, Wi-Fi, native USBSmall devices that need USB and no Bluetooth
ESP32-S3SupportedDual-core Xtensa, Wi-Fi and BLE, native USB, PSRAM boardsGateways, screens and anything that needs memory and speed
ESP32-C3SupportedSingle-core RISC-V, Wi-Fi and BLECheap, small nodes: a relay, a sensor, a switch
ESP32-C5SupportedRISC-V, dual-band Wi-Fi 6 (2.4 and 5 GHz)Sites where the 2.4 GHz band is crowded
ESP32-C6SupportedRISC-V, Wi-Fi 6, BLE and 802.15.4New 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

DeviceClassBusDocs
DHT11, DHT22Dht1 GPIODevices → Sensors
DS18B20 probeDs18b201-WireDevices → Sensors
HC-SR04, JSN-SR04T and other trig + echo modulesUltrasonic2 GPIODevices → Ultrasonic distance
Anything analog: water level 4–20 mA or 0.5–4.5 V, MQ gas, O2, ACS712 currentAnalogSensorADC1Devices → Sensors
Float switch, water leak, flame, doorDigitalSensor1 GPIODevices → Sensors
MH-Z19 CO2Mhz19UARTDevices → Sensors
PZEM-004T v3 mains meterPzemUARTDevices → Sensors
INA219 DC powerIna219I2CDevices → Sensors
BNO055 orientationBno055I2CDevices → IMU
GPS receivers (NMEA)GpsUARTDevices → GPS

Outputs and actuators

DeviceClassBusDocs
Relay boards up to 16 channels: active high or low, latching, interlock, timersRelayGPIODevices → Relays and actuators
Solenoid valveSolenoidGPIODevices → Relays and actuators
DC motor on an H-bridge (L298N, TB6612, L9110, DRV8871)DcMotorPWM + GPIODevices → Relays and actuators
Brushless motor through an ESCEscPWM 50 HzDevices → Relays and actuators
Stepper on a step/dir driver (A4988, DRV8825, TB6600)StepperGPIODevices → Relays and actuators
Hobby servo, positional or 360 continuousServoPWM 50 HzDevices → Servo
Plain LED, RGB LED, onboard WS2812Led, RgbLedGPIOComponents → Light

Screens, storage and other boards

DeviceClassBusDocs
HD44780 LCD on a PCF8574 backpack (16×2, 20×4)LcdI2cI2CDevices → LCD
ST7789 and ILI9341 TFT screens; any other through Adafruit_GFX, TFT_eSPI or LovyanGFXTftSpi, GfxTarget, TftSPIDevices → TFT screen
SD card (FAT32)SdCardSPI or SDMMCDevices → SD card
Another microcontroller: Arduino Uno, STM32, RP2040, another ESPMcuLinkUARTDevices → External microcontroller

What the devices talk to

WhereStatusNotes
The board’s own dashboard and HTTP APISupportedRoles viewer, operator, admin; tokens for scripts. See Local API.
Local MQTT and Home Assistant discoverySupportedEvery widget of a device is an entity; webhooks and visual flows run on the board.
Flyght CloudSupportedClaim 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 airSupportedAn 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.

What a scan findsC++
# 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

ItemDetail
Used byIna219 (0x40), Bno055 (0x28, or 0x29), LcdI2c (0x27 or 0x3F, found by itself).
PinsThe 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.
Speed400 kHz, unless you start the bus yourself with another value (fn::i2c::begin).
Started onceA 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

ChipI2C SDA, SCLSPI SCK, MISO, MOSIUART RX, TX (GPS)
ESP3221, 2218, 19, 2316, 17
ESP32-S38, 912, 13, 1118, 17
ESP32-S28, 936, 37, 3518, 17
ESP32-C38, 94, 5, 610, 0
ESP32-C623, 2221, 20, 194, 5
ESP32-C50, 110, 9, 84, 5

The helpers: fn::i2c

CallMeaning
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.
Your own I2C device: find it, read its id registerC++
#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).

Terminal
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, 0x3FLCD backpack / PCF8574
0x23BH1750
0x28, 0x29BNO055 IMU / VL53L0X
0x3C, 0x3DOLED SSD1306
0x40PCA9685 / INA219 / HTU21D
0x48 to 0x4BADS1115 / TMP102
0x50 to 0x57EEPROM AT24Cxx
0x5AMLX90614
0x5CAM2320 / BH1750 (alt)
0x68, 0x69MPU6050 / DS3231 RTC (0x69: MPU6050 alt)
0x76, 0x77BME280 / BMP280

SPI: clock, MISO, MOSI and a chip-select

DevicePins and settings
SdCardSdCard(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.
TftSpiTftSpi(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

DeviceSpeedDefault portConstructor
Gps9600 (a parameter)Serial1Gps(int rxPin, int txPin = -1, uint32_t baud = 9600, HardwareSerial& port = Serial1)
McuLink115200 (a parameter)Serial1McuLink(int rxPin, int txPin, uint32_t baud = 115200, HardwareSerial& port = Serial1)
Mhz199600Serial2Mhz19(int rxPin, int txPin, HardwareSerial& port = Serial2, const char* id = "co2")
Pzem9600Serial2Pzem(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: Serial1 exists on every chip, Serial2 on 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.

A water tankC++
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 pinGoes toNotes
VCCThe supply your module needs (usually 5 V)Check the module: the HC-SR04 is a 5 V part.
GNDGND, shared with the board—
TRIGThe trigPin (a GPIO output)A 3.3 V pulse is enough.
ECHOThe 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

C++
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

ParameterTypeDefault / rangeMeaning
trigPininta GPIOThe output pin that starts a measurement.
echoPininta GPIOThe input pin the echo comes back on (3.3 V).
idconst char*"distance"The prefix of the widgets: <id>_cm, <id>_level.
airTemperature(float celsius)float20 °CThe speed of sound depends on the air: give the temperature if you know it.
tank(float emptyCm, float fullCm)float, floatnoneThe 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 Ultrasonic per firmware: the echo interrupt keeps its pin in one place.

Widgets and readings

WhereWhat
Widget <id>_cmThe distance in cm, a gauge from 0 to 400, one decimal.
Widget <id>_levelThe 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.
A tank that fills itself: the alarm switches a pumpC++
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.

Several sensors on one boardC++
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

CallMeaning
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

SensorConstructorPeriod (default, minimum)Readings (widgets)
DhtDht(int pin, Type type = Dht22, const char* id = "dht")DHT22 2000, 2000 ms; DHT11 1000, 1000 msdht_temp (°C), dht_hum (%)
Ds18b20Ds18b20(int pin, const char* id = "ds18b20")2000, 1000 msds18b20_temp (°C)
UltrasonicUltrasonic(int trigPin, int echoPin, const char* id = "distance")500, 60 ms<id>_cm, <id>_level
AnalogSensorAnalogSensor(int pin, const char* id, const char* title, const char* unit)1000, 100 ms<id>_v
DigitalSensorDigitalSensor(int pin, const char* id, const char* title)20, 10 ms<id>_state
Mhz19Mhz19(int rxPin, int txPin, HardwareSerial& port = Serial2, const char* id = "co2")5000, 2000 msco2_ppm
PzemPzem(int rxPin, int txPin, HardwareSerial& port = Serial2, uint8_t address = 0xF8, const char* id = "mains")2000, 1000 msmains_v, _a, _w, _kwh, _hz, _pf
Ina219Ina219(uint8_t address = 0x40, float shuntOhm = 0.1f, TwoWire& wire = Wire, int sda = -1, int scl = -1, const char* id = "ina219")1000, 100 msina219_v, _a, _w

DHT11 and DHT22: temperature and humidity

Module pinGoes to
VCC / + 3.3 V (a DHT works from 3.3 to 5 V)
DATA / OUTThe pin you give (a pull-up to VCC is on most breakout boards; add 10 kΩ if it is the bare part)
GNDGND
C++
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.
C++
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.

CallMeaning
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).
C++
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

CallMeaning
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.
C++
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 pinGoes to
Vin5 V (the module is a 5 V part; its TX answers at 3.3 V logic)
GNDGND
TXThe board’s rxPin
RXThe board’s txPin
C++
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 its txPin. 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).
  • address is 0xF8 (the general address) unless you set another one on the module.
C++
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.
  • shuntOhm is 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.
C++
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.

A relay board with a pump and two interlocked channelsC++
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 pinGoes to
VCCThe supply of the board’s coils (5 V on most boards)
GNDGND, shared with the board
IN1, IN2 …One GPIO per channel, the pin of channel()
COM, NO, NCThe load side: COM and NO close when the relay is on
CallMeaning
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() and pulse() switch a channel off by themselves, even if the network is gone.
Relays from code, and from a sensor alarmC++
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)).

C++
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 code

DC motor on an H-bridge

H-bridge pinGoes to
ENA / PWM / ENpwmPin: the speed (20 kHz PWM by default)
IN1in1Pin: the direction input
IN2in2Pin: the other direction input. With in2Pin = -1 only one direction pin is used (forward = high)
Motor supply and GNDIts own supply; join its GND to the board’s GND
CallMeaning
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.
C++
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.
CallMeaning
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.
C++
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().

CallMeaning
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.
C++
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.

A servo on the Servos pageC++
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.

PresetPulse windowTravel
mg90s500 – 2400 µs180°
mg9951000 – 2000 µs180°
mg996r500 – 2500 µs180°
sg90500 – 2400 µs180°
universal500 – 2500 µs180°
cont3601000 – 2000 µscontinuous, 360

Calls

CallMeaning
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

RouteRoleMeaning
GET /fn/api/v1/servosviewerEvery 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.

A GPS on UART1C++
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());
}

The Map page: a map with the track and the position, the coordinates and the satellites
Map: position, track, coordinates and satellites. Map © OpenStreetMap contributors.

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 pinGoes to
VCC3.3 V or 5 V, as your module says
GNDGND
TXThe board’s rxPin (the data you read)
RXThe board’s txPin: only if you want to send commands to the receiver; leave it -1 otherwise

Constructor and builders

CallMeaning
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` fieldMeaning
validRMC status A.
qualityGGA: 0 none, 1 GPS, 2 DGPS, 4 RTK fixed, 5 RTK float.
satsSatellites in use.
lat, lonDegrees.
altM, hdopAltitude in metres, horizontal dilution of precision.
speedKmh, courseSpeed in km/h and heading in degrees.
hh, mm, ss, day, month, yearThe UTC date and time of the fix.
sentences, badSentences accepted, and rejected for a bad checksum.

Routes

RouteRoleMeaning
GET /fn/api/v1/gpsviewerThe 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/trackviewerThe track as [[lat,lon],…], six decimals.
DELETE /fn/api/v1/gps/trackoperatorEmpties 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.

Orientation on the default I2C pinsC++
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 Motion page: an artificial horizon, a compass, a 3D box, the numbers and the calibration status
Motion: horizon, compass, 3D box, the numbers, calibration, “Set as level”.

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 pinGoes to
VIN3.3 V (a breakout with a regulator also takes 5 V)
GNDGND
SDA, SCLThe board’s I2C pins (see I2C, SPI and UART)
ADR / COM3Low = address 0x28 (the default), high = 0x29

Constructor and calls

CallMeaning
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

RouteRoleMeaning
GET /fn/api/v1/imuviewerok, y, p, r (degrees), t (°C), c (the four calibration values), addr, hz, savedCal, leveled.
POST /fn/api/v1/imu/leveloperatorMakes the current attitude the zero. Body {"clear":true} removes the offset instead.
POST /fn/api/v1/imu/calibrationadminSaves the sensor’s calibration offsets, used at the next start. 409 when the sensor is not connected.
DELETE /fn/api/v1/imu/calibrationadminForgets the saved calibration.
  1. Power the board with the sensor still for a few seconds: the gyroscope calibrates first.
  2. 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.
  3. Press “save calibration” (or call POST /imu/calibration). The next start begins calibrated.
  4. 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.

Show the address of the boardC++
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
}

The LCD page: the real screen, a box to write a row, and the I2C devices found by a scan
LCD: the screen live, write a row from the phone, and “Scan bus” lists the I2C devices.

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 pinGoes to
VCC5 V (the screen needs it; the backpack’s I2C lines are pulled up to it)
GNDGND
SDA, SCLThe board’s I2C pins

Constructor and calls

CallMeaning
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

RouteRoleMeaning
GET /fn/api/v1/lcdviewerfound, cols, rows, bl (backlight), addr (as “0x27”) and text (the rows now).
POST /fn/api/v1/lcdoperatorA 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.
Terminal
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/lcd

Devices · 11

External microcontroller

A line-based UART link to an Arduino Uno, STM32, RP2040 or another ESP.

Two boards, one dashboardC++
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();
}

The Serial page: the console, the latest values, the quick buttons and the connection settings
Serial: the console, the values, the quick buttons, the baud rate and the line ending.

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 boardThe other board
rxPinTX of the other board
txPinRX of the other board (a 5 V board needs a divider or level shifter on its TX)
GNDGND (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 key temp into the widget temp. forward("light") sends light=1 (or the value) to the other board when the widget light changes; the second argument names a different key.
  • A line is at most 256 characters; \r is ignored.
The other board: an Arduino sketchC++
// 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

CallMeaning
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

RouteRoleMeaning
GET /fn/api/v1/mcu?since=<seq>vieweronline, 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/sendoperator{"line":"LED=BLINK"}: sends a line, 1 to 256 characters (422 otherwise).
PUT /fn/api/v1/mcu/configadmin{"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.

A card on the SPI pins, logging to a fileC++
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 Files page: folders and files of the SD card with upload, download, rename and delete
Files: the card, folders, upload, download, rename, delete.
A text file of the card opened in a preview with a download button
A file opened in the preview.

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 pinGoes to
VCC5 V on a module with a regulator, or 3.3 V on one without: read its label
GNDGND
SCK, MISO, MOSIThe board’s SPI pins, or the ones you give to pins()
CSThe cs of the constructor (default SS)

Constructor and calls

CallMeaning
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

RouteRoleMeaning
GET /fn/api/v1/sdviewermounted, mode (spi or sdmmc), type, total and used in bytes.
POST /fn/api/v1/sd/mountadminMounts again. 503 when no card is found.
GET /fn/api/v1/sd/ls?path=/viewerThe 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]viewerThe file, streamed. dl=1 downloads it as an attachment.
POST /fn/api/v1/sd/file?path=/a.csvadminUploads: 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.csvadminDeletes a file or an empty folder. 409 when a folder is not empty.
POST /fn/api/v1/sd/mkdir?path=/logsadminMakes a folder. 409 when it cannot.
POST /fn/api/v1/sd/renameadmin{"from":"/a.csv","to":"/b.csv"}. 409 when the new name exists.
Terminal
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.

A 240×240 ST7789C++
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 Screen page: the TFT mirrored in the browser, drawing tools, colours, rotation and brightness
Screen: the same picture as on the TFT, with drawing tools, colours, rotation and brightness.

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 pinGoes to
VCC, GND3.3 V and GND
SCL / SCK, SDA / MOSIThe sck and mosi of pins()
CScs: the chip-select of the screen
DC / RSdc: the data/command pin
RES / RSTrst (or -1 when the module has no reset pin, or it is tied high)
BL / LEDThe pin of backlight(pin), or 3.3 V for a screen that is always bright

Constructors and calls

CallMeaning
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

RouteRoleMeaning
GET /fn/api/v1/tftviewerok, driver, w, h, rot, bright, backlight, inverted and the ops drawn so far (what the browser mirrors).
POST /fn/api/v1/tft/drawoperatorOne 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/settingsadminrot, bright, inverted or "splash":true, in any combination.
Terminal
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/draw

Devices · 14

Moving pins

An admin changes a pin from a card or the API, without compiling again.

Moving the pin of a relay channelC++
# PUT /fn/api/v1/devices/relay/pins     (admin)
{"pins":{"ch1":4,"ch2":null},"confirm":"relay-board"}

The Settings dialog of a relay card: a drop-down per pin and a field to type the device name
A relay: a pin per channel; the device name is asked because the pins switch a load.
The Settings dialog of a CO2 sensor: the RX and TX pins and a note that UART pins are used after the restart
A UART sensor: the pins are saved now and used from the next start.
The Settings dialog of a DC motor: the PWM and the two direction pins, and a message that the device needs a restart
A DC motor: PWM and direction pins.

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

DeviceKeys
Relay, Solenoidch1, ch2 … (the channel counted from 1); a latching channel also ch1r for its reset pin
DcMotorpwm, in1, in2
Escpwm
Stepperstep, dir, en
Dht, Ds18b20data
Ultrasonictrig, echo
AnalogSensor, DigitalSensorpin
Mhz19, Pzemrx, tx (restart)
Ina219sda, scl (restart)
Servopwm

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

RouteRoleMeaning
GET /fn/api/v1/devicesadminchip, 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>/pinsadmin{"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.
Terminal
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/pins

For 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.

Two of our top picksC++
// 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-485

How 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

  1. BME280 and BMP280 (I2C): temperature, humidity and pressure from one cheap chip; the scan already recognises its address.
  2. A pulse counter (one GPIO): water flow meters, rain gauges, wind sensors and energy meters with a pulse output.
  3. ADS1115 (I2C): four clean 16-bit inputs for 4–20 mA loops and pressure or level sensors, better than the ESP32’s own converter.
  4. Modbus RTU master (RS-485): read PLCs, power meters and drives as points. The biggest step, and the one that opens industrial sites.
  5. BH1750 (I2C): light level in lux, tiny and cheap, a good first step toward lighting rules.

The full list

DeviceInterfaceWhat it addsOur pick
BME280, BMP280I2C 0x76 / 0x77Temperature, humidity (BME280), pressureRecommended
Pulse counter (flow, rain, wind, energy)1 GPIO interruptFlow, rain and energy from pulsesRecommended
ADS1115I2C 0x484 precise analog inputsRecommended
Modbus RTU masterUART + RS-485 (MAX485)PLCs, meters and drives as pointsRecommended
BH1750I2C 0x23Light level in luxRecommended
WS2812 strips (many LEDs)1 GPIOStatus bars and indicatorsGood next
SSD1306 OLEDI2C 0x3CA small status screenGood next
DS3231 RTCI2C 0x68Time that survives a power cutGood next
VL53L0X, VL53L1XI2C 0x29Short-range distance by laserGood next
MPU6050I2C 0x68Acceleration and rotation, cheaper than the BNO055Good next
PCF8574, MCP23017I2CMore relays and inputs from two pinsGood next
HX711 load cell2 GPIOWeightGood next
Ethernet W5500SPIA wired network for industrial sitesLater
MLX90614I2C 0x5ATemperature without touchingLater
MFRC522 RFIDSPICards and tags for accessLater
LoRa SX127xSPILong range, low rateLater
CAN bus (with a transceiver)2 GPIOVehicles and machinesLater
Camera (ESP32-CAM, S3 boards)Camera busPictures for AI visionLater

“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.