English
English
简体中文
日本語

Arduino Quick Start

2. Devices & Examples

5. Extensions

6. Applications

Chain ENV Tutorial

1. Preparation

2. Example Program

Build Requirements
M5Stack Board Manager Version >= 3.3.10-a (must include Chain Captain)
M5Chain Library Version >= 1.0.10
M5Unified Library Version >= 0.3.0
M5GFX Library Version >= 0.3.0

In Arduino IDE, select M5ChainCaptain from the Board menu and select the corresponding serial port.

Use the Chain Bridge connector to link the main controller Chain Captain with Chain ENV. Pay attention to the orientation: the triangular arrow points outward from the main controller Chain Captain, as shown below:

IO Pin Configuration
RXD_PIN = GPIO_NUM_17 (GPIO17)
TXD_PIN = GPIO_NUM_18 (GPIO18)

This example uses the Chain port on Chain Captain, with GPIO17 as RX and GPIO18 as TX, which corresponds to UART1. If you use a different host device, modify RXD_PIN and TXD_PIN in the program according to the actual wiring.

2.1 Read Environment Data

Chain ENV integrates an AHT20 temperature and humidity sensor and an SPA06 barometric pressure sensor. This example reads temperature and humidity through getAHT20Data(), and temperature, pressure and altitude through getSPA06Data(), then displays them on the Chain Captain screen in real time. The program automatically waits for Chain ENV to power up and retries for up to about 5 seconds; if the device is still not detected, the screen shows ENV ERROR.

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
#include <M5Chain.h>
#include <M5Unified.h>

#define RXD_PIN GPIO_NUM_17  // Chain Captain Chain RX
#define TXD_PIN GPIO_NUM_18  // Chain Captain Chain TX

// Maximum number of devices handled by this demo.
constexpr uint8_t MAX_DEVICES = 16;

Chain M5Chain;
uint8_t env_id = 0;

void applyTitleFont()
{
    // FreeSans is rounder and softer than the default bitmap font.
    M5.Display.setFont(&fonts::FreeSans18pt7b);
    M5.Display.setTextSize(1);
}

void applyBodyFont()
{
    M5.Display.setFont(&fonts::FreeSans12pt7b);
    M5.Display.setTextSize(1);
}

void showStatus(const char *text, uint16_t color)
{
    // Show one centered status message on the Chain Captain display.
    M5.Display.fillScreen(TFT_BLACK);
    M5.Display.setTextDatum(middle_center);
    M5.Display.setTextColor(color, TFT_BLACK);
    applyBodyFont();
    M5.Display.drawString(text, M5.Display.width() / 2, M5.Display.height() / 2);
}

bool findENV()
{
    // The ENV node needs a short startup time after Chain 5V is enabled.
    // Retry for about 5 seconds before reporting an error.
    for (uint8_t attempt = 0; attempt < 10; ++attempt) {
        if (M5Chain.isDeviceConnected(3)) {
            uint16_t device_count = 0;
            if (M5Chain.getDeviceNum(&device_count) == CHAIN_OK &&
                device_count > 0 && device_count <= MAX_DEVICES) {
                device_info_t devices[MAX_DEVICES];
                device_list_t device_list{device_count, devices};
                if (M5Chain.getDeviceList(&device_list)) {
                    for (uint16_t i = 0; i < device_count; ++i) {
                        if (devices[i].device_type == CHAIN_ENV_TYPE_CODE) {
                            env_id = devices[i].id;
                            return true;
                        }
                    }
                }
            }
        }
        delay(500);
    }
    return false;
}

void showEnvironment(float aht_temp, uint8_t humidity,
                     float pressure, float altitude)
{
    char line[32];
    const int cx = M5.Display.width() / 2;

    M5.Display.fillScreen(TFT_BLACK);
    M5.Display.setTextDatum(middle_center);

    M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
    applyTitleFont();
    M5.Display.drawString("CHAIN ENV", cx, 24);

    M5.Display.setTextColor(TFT_GREEN, TFT_BLACK);
    applyBodyFont();
    snprintf(line, sizeof(line), "TEMP  %.2f C", aht_temp);
    M5.Display.drawString(line, cx, 72);

    snprintf(line, sizeof(line), "HUMI  %u %%RH", (unsigned)humidity);
    M5.Display.drawString(line, cx, 108);

    M5.Display.setTextColor(TFT_CYAN, TFT_BLACK);
    snprintf(line, sizeof(line), "PRESS %.1f hPa", pressure);
    M5.Display.drawString(line, cx, 152);

    snprintf(line, sizeof(line), "ALT   %.1f m", altitude);
    M5.Display.drawString(line, cx, 188);
}

void setup()
{
    // Chain Captain uses M5IOE1 for display and power control.
    // Wait for the expander to finish booting before M5.begin().
    delay(520);

    auto cfg = M5.config();
    cfg.serial_baudrate = 115200;
    M5.begin(cfg);
    Serial.begin(115200);

    M5Chain.begin(&Serial1, 115200, RXD_PIN, TXD_PIN);

    // Chain power-up resets the panel; run the same init as M5.begin().
    M5.Display.init();
    M5.Display.setBrightness(255);

    showStatus("STARTING", TFT_WHITE);

    if (!findENV()) {
        Serial.println("Chain ENV not found");
        showStatus("ENV ERROR", TFT_RED);
        return;
    }

    Serial.printf("Chain ENV found, id=%u\n", (unsigned)env_id);
}

void loop()
{
    if (env_id == 0) {
        delay(1000);
        return;
    }

    int16_t aht_temp = 0;
    uint8_t humidity = 0;
    int16_t spa_temp = 0;
    uint16_t pressure = 0;
    int32_t altitude = 0;

    chain_status_t aht_status = M5Chain.getAHT20Data(env_id, &aht_temp, &humidity);
    chain_status_t spa_status = M5Chain.getSPA06Data(env_id, &spa_temp, &pressure, &altitude);

    if (aht_status != CHAIN_OK || spa_status != CHAIN_OK) {
        Serial.printf("Read failed: AHT20=%d SPA06=%d\n", aht_status, spa_status);
        showStatus("READ ERROR", TFT_RED);
        delay(1000);
        return;
    }

    float temp_c = aht_temp / 100.0f;
    float pressure_hpa = pressure / 10.0f;
    float altitude_m = altitude / 100.0f;

    Serial.printf("AHT20: %.2f C, %u %%RH\n", temp_c, (unsigned)humidity);
    Serial.printf("SPA06: %.2f C, %.1f hPa, %.2f m\n",
                  spa_temp / 100.0f, pressure_hpa, altitude_m);

    showEnvironment(temp_c, humidity, pressure_hpa, altitude_m);
    delay(1000);
}

After uploading the program, the screen displays the AHT20 temperature and humidity along with the SPA06 pressure and altitude. The serial output is as follows:

Chain ENV found, id=1
AHT20: 26.32 C, 66 %RH
SPA06: 27.76 C, 1009.5 hPa, 32.10 m

The temperature returned by getAHT20Data() is in units of 0.01°C and the humidity is in %RH; the temperature returned by getSPA06Data() is in units of 0.01°C, the pressure in 0.1hPa and the altitude in cm. The program converts these raw values accordingly.

2.2 Altitude Meter and Calibration

The SPA06 altitude reading is derived from the measured pressure:

Altitude_m = 44330 * [1 - (P / P0)^0.1903]

where P is the pressure measured by SPA06 and P0 is the local sea-level pressure. The device defaults to P0 = 1013.3 hPa; if this value differs from the actual local sea-level pressure, the altitude reading will be offset.

The following example is a complete altitude meter: after power-on it displays temperature, humidity, pressure, altitude and the current P0 in real time, and supports calibration with the buttons.

  • Short press OK: record the current altitude as 0 m and enter relative altitude mode; short press PREV again to return to absolute altitude mode.
  • Long press OK for 1 second: calibrate against REFERENCE_ALTITUDE_CM and save P0 to the NVS of Chain Captain.
  • Short press NEXT: write SEA_LEVEL_PRESSURE_HPA_X10 to ENV and save it to the NVS of Chain Captain.

Before use, change the two values at the top of the code according to your actual location:

  • SEA_LEVEL_PRESSURE_HPA_X10: the current local sea-level pressure in units of 0.1 hPa; for example, 1014.4 hPa is written as 10144.
  • REFERENCE_ALTITUDE_CM: the actual altitude of the Chain ENV location in cm; for example, 50.00 m is written as 5000.

Choose either of the two absolute calibration methods. The result is stored in the NVS of Chain Captain and survives power loss; on every power-on the program automatically writes the saved P0 back to Chain ENV. The zeroing performed by a short press of OK only affects the display and is not written to NVS, so the device returns to absolute altitude mode after a restart.

cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
#include <M5Chain.h>
#include <M5Unified.h>
#include <Preferences.h>
#include <math.h>
#include <type_traits>

#define RXD_PIN GPIO_NUM_17  // Chain Captain Chain RX
#define TXD_PIN GPIO_NUM_18  // Chain Captain Chain TX

// Local sea-level pressure in hPa x10. 1013.3 hPa -> 10133.
constexpr uint16_t SEA_LEVEL_PRESSURE_HPA_X10 = 10133;

// Known altitude of the sensor in cm, used by the long-press calibration.
constexpr int32_t REFERENCE_ALTITUDE_CM = 3210;

static_assert(SEA_LEVEL_PRESSURE_HPA_X10 >= 3000 &&
                  SEA_LEVEL_PRESSURE_HPA_X10 <= 11000,
              "Sea-level pressure must be 300.0 ~ 1100.0 hPa");


constexpr uint8_t MAX_DEVICES = 16;
constexpr uint32_t READ_INTERVAL_MS = 1000;
constexpr uint32_t HOLD_MS = 1000;

template <typename T>
struct FourthArg;

template <typename R, typename C, typename A1, typename A2, typename A3,
          typename A4, typename... Rest>
struct FourthArg<R (C::*)(A1, A2, A3, A4, Rest...)> {
    using type = A4;
};

using SetP0Arg = typename FourthArg<decltype(&Chain::setSPA06SeaLevelPressure)>::type;

Chain M5Chain;
Preferences prefs;
uint8_t env_id = 0;

int16_t aht_temp = 0;
uint8_t humidity = 0;
int16_t spa_temp = 0;
uint16_t pressure = 0;
int32_t altitude_cm = 0;

bool relative_mode = false;
int32_t zero_offset_cm = 0;
uint16_t sea_level_pressure = 0;

char status_text[24] = "ABS MODE";
uint32_t status_until = 0;
bool hold_done = false;

void setStatus(const char *text, uint32_t duration = 3000)
{
    strncpy(status_text, text, sizeof(status_text) - 1);
    status_text[sizeof(status_text) - 1] = '\0';
    status_until = millis() + duration;
}

const char *currentStatus()
{
    if (millis() < status_until) {
        return status_text;
    }
    return relative_mode ? "REL MODE" : "ABS MODE";
}

bool findENV()
{
    // The ENV node needs a short startup time after Chain 5V is enabled.
    for (uint8_t attempt = 0; attempt < 10; ++attempt) {
        if (M5Chain.isDeviceConnected(3)) {
            uint16_t device_count = 0;
            if (M5Chain.getDeviceNum(&device_count) == CHAIN_OK &&
                device_count > 0 && device_count <= MAX_DEVICES) {
                device_info_t devices[MAX_DEVICES];
                device_list_t device_list{device_count, devices};
                if (M5Chain.getDeviceList(&device_list)) {
                    for (uint16_t i = 0; i < device_count; ++i) {
                        if (devices[i].device_type == CHAIN_ENV_TYPE_CODE) {
                            env_id = devices[i].id;
                            return true;
                        }
                    }
                }
            }
        }
        delay(500);
    }
    return false;
}

bool readP0()
{
    uint16_t p0 = 0;
    if (M5Chain.getSPA06SeaLevelPressure(env_id, &p0) != CHAIN_OK) {
        return false;
    }
    sea_level_pressure = p0;
    return true;
}

bool readSensors()
{
    bool ok = true;
    if (M5Chain.getAHT20Data(env_id, &aht_temp, &humidity) != CHAIN_OK) {
        ok = false;
    }
    if (M5Chain.getSPA06Data(env_id, &spa_temp, &pressure, &altitude_cm) != CHAIN_OK) {
        ok = false;
    }
    return ok;
}

uint16_t loadP0()
{
    if (!prefs.begin("chain_env", true)) {
        return SEA_LEVEL_PRESSURE_HPA_X10;
    }
    uint16_t p0 = prefs.getUShort("p0", SEA_LEVEL_PRESSURE_HPA_X10);
    prefs.end();
    return p0;
}

void saveP0(uint16_t p0)
{
    if (!prefs.begin("chain_env", false)) {
        return;
    }
    prefs.putUShort("p0", p0);
    prefs.end();
}

bool setP0(uint16_t p0)
{
    uint8_t operation_status = 0;
    // 1.0.10 uses the fourth argument as timeout; 1.0.11 uses it as save flag.
    const SetP0Arg arg = std::is_same<SetP0Arg, unsigned long>::value
                             ? SetP0Arg(100)
                             : SetP0Arg(0);
    chain_status_t status = M5Chain.setSPA06SeaLevelPressure(
        env_id, p0, &operation_status, arg);
    return status == CHAIN_OK && operation_status == 1;
}

bool calibrateByReference()
{
    uint32_t pressure_sum = 0;
    uint8_t samples = 0;

    for (uint8_t i = 0; i < 16; ++i) {
        int16_t sample_temp = 0;
        uint16_t sample_pressure = 0;
        int32_t sample_altitude = 0;
        if (M5Chain.getSPA06Data(env_id, &sample_temp, &sample_pressure,
                                 &sample_altitude) == CHAIN_OK) {
            pressure_sum += sample_pressure;
            ++samples;
        }
        delay(250);
    }

    if (samples == 0) {
        return false;
    }

    const float average_hpa = pressure_sum / (10.0f * samples);
    const float reference_m = REFERENCE_ALTITUDE_CM / 100.0f;
    const float base = 1.0f - reference_m / 44330.0f;
    if (base <= 0.0f) {
        return false;
    }

    const float p0_hpa = average_hpa / powf(base, 1.0f / 0.1903f);
    const long p0_x10 = lroundf(p0_hpa * 10.0f);
    if (p0_x10 < 3000 || p0_x10 > 11000) {
        return false;
    }

    if (!setP0((uint16_t)p0_x10)) {
        return false;
    }
    saveP0((uint16_t)p0_x10);
    return true;
}

void drawScreen()
{
    char line[32];
    M5.Display.fillScreen(TFT_BLACK);

    M5.Display.setTextDatum(middle_center);
    M5.Display.setFont(&fonts::FreeSans12pt7b);
    M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
    M5.Display.drawString("CHAIN ENV", 120, 18);

    M5.Display.setTextDatum(middle_left);
    M5.Display.setFont(&fonts::FreeSans9pt7b);

    M5.Display.setTextColor(TFT_GREEN, TFT_BLACK);
    snprintf(line, sizeof(line), "TEMP  %.2f C", aht_temp / 100.0f);
    M5.Display.drawString(line, 16, 50);

    snprintf(line, sizeof(line), "HUMI  %u %%RH", (unsigned)humidity);
    M5.Display.drawString(line, 16, 80);

    M5.Display.setTextColor(TFT_CYAN, TFT_BLACK);
    snprintf(line, sizeof(line), "PRESS %.1f hPa", pressure / 10.0f);
    M5.Display.drawString(line, 16, 110);

    const int32_t shown_altitude = relative_mode ? (altitude_cm - zero_offset_cm) : altitude_cm;
    M5.Display.setTextDatum(middle_center);
    M5.Display.setFont(&fonts::FreeSans12pt7b);
    M5.Display.setTextColor(TFT_YELLOW, TFT_BLACK);
    snprintf(line, sizeof(line), "ALT %.2f m", shown_altitude / 100.0f);
    M5.Display.drawString(line, 120, 150);

    M5.Display.setFont(&fonts::FreeSans9pt7b);
    M5.Display.setTextColor(TFT_DARKGREY, TFT_BLACK);
    if (sea_level_pressure != 0) {
        snprintf(line, sizeof(line), "%s  P0 %.1f", relative_mode ? "REL" : "ABS",
                 sea_level_pressure / 10.0f);
    } else {
        snprintf(line, sizeof(line), "%s  P0 --", relative_mode ? "REL" : "ABS");
    }
    M5.Display.drawString(line, 120, 188);

    M5.Display.setTextColor(TFT_YELLOW, TFT_BLACK);
    M5.Display.drawString(currentStatus(), 120, 214);
}

void setup()
{
    // Chain Captain uses M5IOE1 for display and power control.
    // Wait for the expander to finish booting before M5.begin().
    delay(520);

    auto cfg = M5.config();
    cfg.serial_baudrate = 115200;
    M5.begin(cfg);
    Serial.begin(115200);

    M5Chain.begin(&Serial1, 115200, RXD_PIN, TXD_PIN);

    // Chain power-up resets the panel; run the same init as M5.begin().
    M5.Display.init();
    M5.Display.setBrightness(255);

    M5.Display.fillScreen(TFT_BLACK);
    M5.Display.setTextDatum(middle_center);
    M5.Display.setFont(&fonts::FreeSans12pt7b);
    M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
    M5.Display.drawString("STARTING", 120, 120);

    if (!findENV()) {
        Serial.println("Chain ENV not found");
        M5.Display.fillScreen(TFT_BLACK);
        M5.Display.setTextColor(TFT_RED, TFT_BLACK);
        M5.Display.drawString("ENV ERROR", 120, 120);
        return;
    }
    Serial.printf("Chain ENV found, id=%u\n", (unsigned)env_id);

    const uint16_t boot_p0 = loadP0();
    if (setP0(boot_p0)) {
        Serial.printf("P0 applied: %.1f hPa\n", boot_p0 / 10.0f);
    } else {
        Serial.println("P0 apply failed");
    }
    if (readP0()) {
        Serial.printf("P0: %.1f hPa\n", sea_level_pressure / 10.0f);
    } else {
        Serial.println("P0 read failed");
    }
    if (!readSensors()) {
        Serial.println("Sensor read failed");
    }
    drawScreen();

    M5.BtnA.setHoldThresh(HOLD_MS);
}

void loop()
{
    M5.update();

    static uint32_t last_read = 0;
    if (millis() - last_read >= READ_INTERVAL_MS) {
        last_read = millis();
        if (!readSensors()) {
            setStatus("READ ERR");
        }
        drawScreen();
    }

    if (M5.BtnA.isPressed()) {
        if (!hold_done && M5.BtnA.pressedFor(HOLD_MS)) {
            hold_done = true;
            setStatus("CALIBRATING", 8000);
            drawScreen();
            Serial.printf("Calibrating to %.2f m...\n", REFERENCE_ALTITUDE_CM / 100.0f);
            if (calibrateByReference()) {
                Serial.println("Calibration OK");
                relative_mode = false;
                readP0();
                readSensors();
                setStatus("CAL OK");
            } else {
                Serial.println("Calibration failed");
                setStatus("CAL ERR");
            }
            drawScreen();
        }
    } else {
        if (!hold_done && M5.BtnA.wasClicked()) {
            zero_offset_cm = altitude_cm;
            relative_mode = true;
            setStatus("REL ZERO");
            drawScreen();
        }
        hold_done = false;
    }

    if (M5.BtnB.wasClicked()) {
        relative_mode = false;
        setStatus("ABS MODE");
        drawScreen();
    }

    if (M5.BtnC.wasClicked()) {
        Serial.printf("Setting P0 to %.1f hPa...\n", SEA_LEVEL_PRESSURE_HPA_X10 / 10.0f);
        if (setP0(SEA_LEVEL_PRESSURE_HPA_X10)) {
            saveP0(SEA_LEVEL_PRESSURE_HPA_X10);
            Serial.println("P0 applied and stored");
            sea_level_pressure = SEA_LEVEL_PRESSURE_HPA_X10;
            relative_mode = false;
            readSensors();
            setStatus("P0 OK");
        } else {
            setStatus("P0 ERR");
        }
        drawScreen();
    }
}

P0 -- on the screen means the sea-level pressure read failed; CAL ERR means the long-press calibration failed. Long-press calibration with OK takes about 4 seconds, during which Chain ENV should be kept still. P0 can be set in the range of 300.0 ~ 1100.0 hPa; NEXT writes the value to NVS, so it does not need to be pressed on every power-on.

After successful calibration, the serial output is as follows:

Chain ENV found, id=1
P0 applied: 1013.3 hPa
P0: 1013.3 hPa
Calibrating to 32.10 m...
Calibration OK
Page Tools
PDF
On This Page