以下是一个示例代码,可以读取 MG811 传感器的数字信号并将其打印到串口监视器上:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX pins for communication with MG811 sensor

void setup() {
  Serial.begin(9600); // initialize Serial communication
  mySerial.begin(9600); // initialize SoftwareSerial communication with MG811 sensor
}

void loop() {
  if (mySerial.available()) { // if data is available on SoftwareSerial
    int value = mySerial.parseInt(); // read the integer value from SoftwareSerial
    Serial.println(value); // print the value to Serial monitor
  }
}

在上面的代码中,我们使用了 SoftwareSerial 库,将 NodeMCU 的 GPIO2 和 GPIO3 引脚用作软件串口,用于与 MG811 传感器通信。在 setup() 函数中,我们初始化了 Serial 和 mySerial 对象,并设置了波特率为 9600。在 loop() 函数中,我们使用 mySerial.parseInt() 函数读取 MG811 传感器发送的整数值,并将其打印到串口监视器上。


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

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