NodeMCU 使用 Wire 库读取 MQ135 传感器 I2C 数据

本教程将指导您如何将 MQ135 传感器连接到 NodeMCU 的 I2C 接口,并使用 Wire 库读取传感器数据。

代码示例

#include <Wire.h>

#define MQ135_I2C_ADDRESS 0x48   // MQ135 传感器的 I2C 地址

void setup() {
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
  Wire.beginTransmission(MQ135_I2C_ADDRESS);
  Wire.write(0x00);
  Wire.endTransmission();

  Wire.requestFrom(MQ135_I2C_ADDRESS, 2);
  if (Wire.available() == 2) {
    int msb = Wire.read();
    int lsb = Wire.read();
    int value = (msb << 8) | lsb;
    Serial.println('MQ135 Sensor Value: ' + String(value));
  }

  delay(1000);   // 每 1 秒读取一次传感器数据
}

说明:

  • 该代码示例是基于 MQ135 传感器使用 I2C 通信协议的情况下编写的。
  • 若使用其他通信协议,需根据具体情况修改代码。
  • 请确保您已正确连接了 MQ135 传感器和 NodeMCU。
  • SDA 和 SCL 引脚分别连接到 NodeMCU 的 D1 和 D2 引脚。

总结

本教程展示了如何使用 Wire 库读取 MQ135 传感器的数据。您可以根据需要修改代码,以实现不同的功能。

NodeMCU 使用 Wire 库读取 MQ135 传感器 I2C 数据

原文地址: https://www.cveoy.top/t/topic/ngMd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录