简体中文
English
简体中文
日本語

Arduino 上手教程

2. 设备开发 & 案例程序

5. 扩展模块

6. 应用案例

Chain ENV 使用教程

1.准备工作

2.示例程序

在 Arduino IDE 的“开发板”中选择 M5ChainCaptain,并选择对应的串口。

用 Chain Bridge 连接主控 Chain Captain 和 Chain ENV。连接时需要注意方向,三角箭头从主控 Chain Captain 指向外侧,如图:

IO 引脚配置
RXD_PIN = GPIO_NUM_17(GPIO17)
TXD_PIN = GPIO_NUM_18(GPIO18)

本案例使用 Chain Captain 的 Chain 接口,GPIO17 作为 RX、GPIO18 作为 TX,对应 UART1。若改用其他主控设备,请根据实际接线修改程序中的 RXD_PIN 和 TXD_PIN。

2.1 读取环境数据

Chain ENV 内部包含 AHT20 温湿度传感器和 SPA06 气压传感器。本示例通过 getAHT20Data() 读取温度与湿度,通过 getSPA06Data() 读取温度、气压与海拔,并在 Chain Captain 的屏幕上实时显示。程序会自动等待 Chain ENV 上电,最多重试约 5 秒;仍未检测到设备时,屏幕显示 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);
}

上传程序后,屏幕会显示 AHT20 的温度、湿度,以及 SPA06 的气压和海拔。串口输出如下:

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

getAHT20Data() 返回的温度单位为 0.01°C,湿度单位为 %RH;getSPA06Data() 返回的温度单位为 0.01°C,气压单位为 0.1hPa,海拔单位为 cm。程序中对返回值做了换算。

2.2 海拔表与校准

SPA06 的海拔读数由实测气压换算得到:

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

其中 P 为 SPA06 实测气压,P0 为当地海平面气压。设备默认 P0 = 1013.3 hPa,如果与实际当地海平面气压不一致,海拔读数会产生偏差。

下面的示例是一个完整的海拔表:上电后实时显示温度、湿度、气压、海拔和当前 P0,并支持按键校准。

  • OK 短按:把当前位置的海拔记为 0 m,进入相对海拔模式;再短按 PREV 回到绝对海拔模式。
  • OK 长按 1 秒:按 REFERENCE_ALTITUDE_CM 校准,并把 P0 保存到 Chain Captain 的 NVS。
  • NEXT 短按:把 SEA_LEVEL_PRESSURE_HPA_X10 写入 ENV,并保存到 Chain Captain 的 NVS。

使用前按实际地点修改代码顶部的两个值:

  • SEA_LEVEL_PRESSURE_HPA_X10:当地实时海平面气压,单位 0.1 hPa,例如 1014.4 hPa 写成 10144。
  • REFERENCE_ALTITUDE_CM:Chain ENV 所在位置的实际海拔,单位 cm,例如 50.00 m 写成 5000。

两种绝对校准方式选一种即可。结果保存在 Chain Captain 的 NVS 中,断电不丢;每次上电后程序会自动把保存的 P0 写回 Chain ENV。OK 短按的归零只影响显示,不写 NVS,重启后自动回到绝对海拔模式。

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 -- 表示海平面气压读取失败;显示 CAL ERR 表示长按校准失败。长按 OK 校准约需 4 秒,期间请保持 Chain ENV 静止。P0 可设置范围为 300.0 ~ 1100.0 hPa;NEXT 会写入 NVS,不需要每次上电都按。

校准成功后,串口会输出:

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