我想将我的Arduino UNO从传感器读取的一个变量发送到NodeMCU,因此它可以将它作为json发送到MQTT服务器。
我已经尝试了多种在Web上看到的代码实现,但是当我以为SoftwareSerial设置的波特率观看控制台时,它只会给我随机的字符串。
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);
}
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或更小。