将整数值从 arduino uno 发送到 nodemcu

Send an integer value from arduino uno to nodemcu

我想将我的 Arduino UNO 从传感器读取的一个变量发送到 NodeMCU,以便它可以将其作为 json 发送到 MQTT 服务器。

我已经尝试了多种我在网上看到的代码实现,但是当我以我为 SoftwareSerial 设置的波特率查看控制台时,它只给我随机字符串。

Code on the uno: https://pastebin.com/fZHtEdjV

#include <SoftwareSerial.h>
#include <String.h>
SoftwareSerial toNode(2,3); // (Rx, Tx)

int sensorPin = A0;
int sensorValue;

void setup() {
 Serial.begin(9600);
 toNode.begin(115200);

 pinMode(9, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(8, OUTPUT);
}

void loop() {

 sensorValue = analogRead(sensorPin); 
 Serial.println("Analog Value : ");
 Serial.println(sensorValue);

 if (sensorValue<300) {
 digitalWrite(10, HIGH);
 digitalWrite(9, LOW);
 digitalWrite(8, LOW);
 parseJson(sensorValue);
 }
 else if(sensorValue>300 && sensorValue<450){
 digitalWrite(9, HIGH);
 digitalWrite(8, LOW);
 digitalWrite(10, LOW);
 parseJson(sensorValue);
 }
 else if(sensorValue < 300)
 {
 digitalWrite(8, HIGH);
 digitalWrite(9, LOW);
 digitalWrite(10, LOW);
 parseJson(sensorValue);
 }

 delay(1000); 
}

void parseJson(int criticidade) {
   String njs;
   njs = String(criticidade);
   toNode.println(njs);
}

Code on the NodeMCU: https://pastebin.com/SFNC5JfG

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
#include <String.h>
SoftwareSerial fromUno(D5,D6); // (Rx, Tx)

char* ssid = "B";
char* password =  "A";
const char* mqttServer = "Z";
const int mqttPort = 1;
const char* mqttUser = "Y";
const char* mqttPassword = "X;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {

  Serial.begin(9600);
  fromUno.begin(115200);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

  client.setServer(mqttServer, mqttPort);

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }
}

void loop() {
   char json[100];
   json[0] = fromUno.read();
   String json2 = "{\"planta\":{\"umidade\":200,\"criticidade\":1}}";

  Serial.println("Sending message to MQTT topic..");

  if (client.publish("test", json2) == true) {
    Serial.println("Success sending message");
  } else {
    Serial.println("Error sending message");
  }

  client.loop();
  Serial.println("-------------");

  delay(10000);
}

我预计当从 NodeMCU 读取串行端口时,它会将我从 UNO 发送的整数值设置为一个变量。

SoftwareSerial不支持115200波特率。您可能可以获得 57600,但最好尝试 9600 或更少。