Evening all !
I've constructed a box of electronics and I'm using a NodeMCU ESP8266 connected to a temperature sensor in order to control a pair of PWM fans. The idea is that the temperature in the box will be measured and the fans will speed up or slow down as required to maintain the temperature.
This all works fine.
As the box of electronics is on a remote hilltop I'd like to send a JSON message containing the current temperature and fan speed via UDP to a remote server for logging purposes.
I just cannot get this to work. Here is my code:
// Libraries for sending UDP over Wifi
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <SPI.h>
// Library for JSON
#include <ArduinoJson.h>
// Create a UDP object
WiFiUDP Udp;
// Define server that we'll send temperature and fan data to
IPAddress serverIP (A, B, C, D);
unsigned short serverPort = 50000;
// Create the JSON object
StaticJsonDocument<128> doc;
// Build the object values
doc["source"] = "ESP8266";
doc["temp"] = sensorTemp; // Value from elsewhere
doc["fan"] = fanSpeedPercent; // Value from elsewhere
Serial.println("Pretty JSON message: "); // This works
serializeJsonPretty(doc, Serial);
// Create and send UDP packet
Udp.beginPacket(serverIP, serverPort);
char payload[] = "";
// Serialize the JSON directly to the udp port and send a newline character at the end
serializeJson(doc, payload) + "\n";
Udp.write(payload);
Udp.endPacket();
Unfortunately absolutely nothing is sent to the server. The code on the server works as it receives JSON sent via UDP from some of the electronics in the box.
What am I doing wrong ? I'm sure that there's just one obvious thing that I've missed but after several hours of going around in circles I still can't see it.